@niledatabase/server 3.0.0-alpha.4 → 3.0.0-alpha.6

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.
@@ -1,6 +1,6 @@
1
1
  import 'dotenv/config';
2
- import { decodeJwt } from 'jose';
3
2
  import { Pool } from 'pg';
3
+ import { decodeJwt } from 'jose';
4
4
 
5
5
  function _regeneratorRuntime() {
6
6
  _regeneratorRuntime = function () {
@@ -899,11 +899,6 @@ var Config = /*#__PURE__*/function () {
899
899
  }]);
900
900
  }();
901
901
 
902
- var ResponseError = function ResponseError(body, init) {
903
- this.response = void 0;
904
- this.response = new Response(body, init);
905
- };
906
-
907
902
  var Events;
908
903
  (function (Events) {
909
904
  Events["User"] = "userId";
@@ -974,1351 +969,707 @@ var evictPool = function evictPool(val) {
974
969
  eventer.publish(Events.EvictPool, val);
975
970
  };
976
971
 
977
- var X_NILE_TENANT = 'niledb-tenant-id';
978
- var X_NILE_USER_ID = 'niledb-user-id';
979
- function getTokenFromCookie(headers, cookieKey) {
980
- var _headers$get;
981
- var cookie = (_headers$get = headers.get('cookie')) == null ? void 0 : _headers$get.split('; ');
982
- var _cookies = {};
983
- if (cookie) {
984
- for (var _iterator = _createForOfIteratorHelperLoose(cookie), _step; !(_step = _iterator()).done;) {
985
- var parts = _step.value;
986
- var cookieParts = parts.split('=');
987
- var _cookie = cookieParts.slice(1).join('=');
988
- var name = cookieParts[0];
989
- _cookies[name] = _cookie;
990
- }
991
- }
992
- if (cookie) {
993
- for (var _iterator2 = _createForOfIteratorHelperLoose(cookie), _step2; !(_step2 = _iterator2()).done;) {
994
- var _parts = _step2.value;
995
- var _cookieParts = _parts.split('=');
996
- var _cookie2 = _cookieParts.slice(1).join('=');
997
- var _name = _cookieParts[0];
998
- _cookies[_name] = _cookie2;
972
+ function createProxyForPool(pool, config) {
973
+ var _Logger = Logger(config, '[pool]'),
974
+ info = _Logger.info,
975
+ error = _Logger.error;
976
+ return new Proxy(pool, {
977
+ get: function get(target, property) {
978
+ if (property === 'query') {
979
+ // give connection string a pass for these problems
980
+ if (!config.db.connectionString) {
981
+ if (!config.user || !config.password) {
982
+ error('Cannot connect to the database. User and/or password are missing. Generate them at https://console.thenile.dev');
983
+ } else if (!config.db.database) {
984
+ error('Database name is missing from the config. Call `nile.init()` or set NILEDB_ID in your .env');
985
+ }
986
+ }
987
+ var caller = target[property];
988
+ return function query() {
989
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
990
+ args[_key] = arguments[_key];
991
+ }
992
+ info.apply(void 0, args);
993
+ // @ts-expect-error - not mine
994
+ var called = caller.apply(this, args);
995
+ return called;
996
+ };
997
+ }
998
+ return target[property];
999
999
  }
1000
- }
1001
- if (cookieKey) {
1002
- return _cookies[cookieKey];
1003
- }
1004
- return null;
1005
- }
1006
- function getTenantFromHttp(headers, config) {
1007
- var _ref;
1008
- var cookieTenant = getTokenFromCookie(headers, X_NILE_TENANT);
1009
- return (_ref = cookieTenant != null ? cookieTenant : headers == null ? void 0 : headers.get(X_NILE_TENANT)) != null ? _ref : config == null ? void 0 : config.tenantId;
1000
+ });
1010
1001
  }
1011
- function getUserFromHttp(headers, config) {
1012
- var _headers$get2;
1013
- var token = getTokenFromCookie(headers, config.api.cookieKey);
1014
- if (token) {
1015
- var jwt = decodeJwt(token);
1016
- return jwt.sub;
1002
+
1003
+ function isUUID(value) {
1004
+ if (!value) {
1005
+ return false;
1017
1006
  }
1018
- return (_headers$get2 = headers == null ? void 0 : headers.get(X_NILE_USER_ID)) != null ? _headers$get2 : config.userId;
1019
- }
1020
- function _fetch(_x, _x2, _x3) {
1021
- return _fetch2.apply(this, arguments);
1007
+ var regex = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
1008
+ return regex.test(value);
1022
1009
  }
1023
- function _fetch2() {
1024
- _fetch2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config, path, opts) {
1025
- var _config$api, _config$api2, _response$status;
1026
- var _Logger, info, error, url, cookieKey, headers, basicHeaders, creds, authHeader, token, tenantId, userId, useableUrl, response, res, errorHandler, msg, _res, message, _res2, _res2$errors, _message;
1027
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1028
- while (1) switch (_context.prev = _context.next) {
1029
- case 0:
1030
- _Logger = Logger(config, '[server]'), info = _Logger.info, error = _Logger.error;
1031
- url = "" + ((_config$api = config.api) == null ? void 0 : _config$api.basePath) + path;
1032
- cookieKey = (_config$api2 = config.api) == null ? void 0 : _config$api2.cookieKey;
1033
- headers = new Headers(opts == null ? void 0 : opts.headers);
1034
- basicHeaders = new Headers(opts == null ? void 0 : opts.headers);
1035
- basicHeaders.set('content-type', 'application/json; charset=utf-8');
1036
- creds = Buffer.from(process.env.NILEDB_USER + ":" + process.env.NILEDB_PASSWORD, 'utf8').toString('base64');
1037
- basicHeaders.set('niledb-creds', creds);
1038
- authHeader = headers.get('Authorization');
1039
- if (!authHeader) {
1040
- token = getTokenFromCookie(headers, cookieKey);
1041
- if (token) {
1042
- basicHeaders.set('Authorization', "Bearer " + token);
1043
- } else if (getToken({
1044
- config: config
1045
- })) {
1046
- basicHeaders.set('Authorization', "Bearer " + getToken({
1047
- config: config
1048
- }));
1049
- }
1050
- }
1051
- tenantId = getTenantFromHttp(headers, config);
1052
- updateTenantId(tenantId);
1053
- userId = getUserFromHttp(headers, config);
1054
- updateUserId(userId);
1055
- if (!(url.includes('{tenantId}') && !tenantId)) {
1056
- _context.next = 16;
1057
- break;
1058
- }
1059
- return _context.abrupt("return", new ResponseError('tenantId is not set for request', {
1060
- status: 400
1061
- }));
1062
- case 16:
1063
- useableUrl = url.replace('{tenantId}', encodeURIComponent(String(tenantId))).replace('{userId}', encodeURIComponent(String(userId)));
1064
- info('[fetch]', useableUrl);
1065
- _context.next = 20;
1066
- return fetch(useableUrl, _extends({}, opts, {
1067
- headers: basicHeaders
1068
- }))["catch"](function (e) {
1069
- error('[fetch]', '[response]', e);
1070
- });
1071
- case 20:
1072
- response = _context.sent;
1073
- if (!(response && response.status >= 200 && response.status < 300)) {
1074
- _context.next = 39;
1075
- break;
1076
- }
1077
- if (!(typeof response.clone === 'function')) {
1078
- _context.next = 38;
1079
- break;
1080
- }
1081
- _context.prev = 23;
1082
- _context.t0 = info;
1083
- _context.next = 27;
1084
- return response.clone().json();
1085
- case 27:
1086
- _context.t1 = _context.sent;
1087
- (0, _context.t0)('[fetch]', '[response]', _context.t1);
1088
- _context.next = 38;
1089
- break;
1090
- case 31:
1091
- _context.prev = 31;
1092
- _context.t2 = _context["catch"](23);
1093
- _context.t3 = info;
1094
- _context.next = 36;
1095
- return response.clone().text();
1096
- case 36:
1097
- _context.t4 = _context.sent;
1098
- (0, _context.t3)('[fetch]', '[response]', _context.t4);
1099
- case 38:
1100
- return _context.abrupt("return", response);
1101
- case 39:
1102
- if (!((response == null ? void 0 : response.status) === 401)) {
1103
- _context.next = 41;
1104
- break;
1010
+
1011
+ var _excluded$1 = ["afterCreate"];
1012
+ var NileDatabase = /*#__PURE__*/function () {
1013
+ function NileDatabase(config, id) {
1014
+ var _this = this;
1015
+ this.pool = void 0;
1016
+ this.tenantId = void 0;
1017
+ this.userId = void 0;
1018
+ this.id = void 0;
1019
+ this.config = void 0;
1020
+ this.timer = void 0;
1021
+ var _Logger = Logger(config, '[NileInstance]'),
1022
+ warn = _Logger.warn,
1023
+ info = _Logger.info;
1024
+ this.id = id;
1025
+ var poolConfig = _extends({
1026
+ min: 0,
1027
+ max: 10,
1028
+ idleTimeoutMillis: 30000
1029
+ }, config.db);
1030
+ var afterCreate = poolConfig.afterCreate,
1031
+ remaining = _objectWithoutPropertiesLoose(poolConfig, _excluded$1);
1032
+ config.db = poolConfig;
1033
+ this.config = config;
1034
+ info(this.config.db);
1035
+ this.pool = createProxyForPool(new Pool(remaining), this.config);
1036
+ if (typeof afterCreate === 'function') {
1037
+ warn('Providing an pool configuration will stop automatic tenant context setting.');
1038
+ }
1039
+ // start the timer for cleanup
1040
+ this.startTimeout();
1041
+ this.pool.on('connect', /*#__PURE__*/function () {
1042
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(client) {
1043
+ var afterCreate;
1044
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1045
+ while (1) switch (_context.prev = _context.next) {
1046
+ case 0:
1047
+ info('pool connected');
1048
+ afterCreate = makeAfterCreate(config);
1049
+ afterCreate(client, function (err) {
1050
+ var _Logger2 = Logger(config, '[after create callback]'),
1051
+ error = _Logger2.error;
1052
+ if (err) {
1053
+ error('after create failed', err);
1054
+ evictPool(_this.id);
1055
+ }
1056
+ });
1057
+ _this.startTimeout();
1058
+ case 4:
1059
+ case "end":
1060
+ return _context.stop();
1105
1061
  }
1106
- return _context.abrupt("return", new ResponseError('Unauthorized', {
1107
- status: 401
1108
- }));
1109
- case 41:
1110
- if (!((response == null ? void 0 : response.status) === 405)) {
1111
- _context.next = 43;
1112
- break;
1113
- }
1114
- return _context.abrupt("return", new ResponseError('Method not allowed', {
1115
- status: 405
1116
- }));
1117
- case 43:
1118
- errorHandler = typeof (response == null ? void 0 : response.clone) === 'function' ? response.clone() : null;
1119
- msg = '';
1120
- _context.prev = 45;
1121
- _context.next = 48;
1122
- return response == null ? void 0 : response.json();
1123
- case 48:
1124
- res = _context.sent;
1125
- _context.next = 59;
1126
- break;
1127
- case 51:
1128
- _context.prev = 51;
1129
- _context.t5 = _context["catch"](45);
1130
- if (!errorHandler) {
1131
- _context.next = 58;
1132
- break;
1133
- }
1134
- _context.next = 56;
1135
- return errorHandler.text();
1136
- case 56:
1137
- msg = _context.sent;
1138
- if (msg) {
1139
- error('[fetch]', '[response]', "[status: " + errorHandler.status + "]", msg);
1140
- }
1141
- case 58:
1142
- if (!msg) {
1143
- error('[fetch]', '[response]', _context.t5);
1144
- }
1145
- case 59:
1146
- if (!msg) {
1147
- _context.next = 61;
1148
- break;
1149
- }
1150
- return _context.abrupt("return", new ResponseError(msg, {
1151
- status: errorHandler == null ? void 0 : errorHandler.status
1152
- }));
1153
- case 61:
1154
- if (!(res && 'message' in res)) {
1155
- _context.next = 65;
1156
- break;
1157
- }
1158
- _res = res, message = _res.message;
1159
- error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", message);
1160
- return _context.abrupt("return", new ResponseError(message, {
1161
- status: 400
1162
- }));
1163
- case 65:
1164
- if (!(res && 'errors' in res)) {
1165
- _context.next = 69;
1166
- break;
1167
- }
1168
- _res2 = res, _res2$errors = _res2.errors, _message = _res2$errors[0];
1169
- error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", _message);
1170
- return _context.abrupt("return", new ResponseError(_message, {
1171
- status: 400
1172
- }));
1173
- case 69:
1174
- error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", 'UNHANDLED ERROR');
1175
- return _context.abrupt("return", new ResponseError(null, {
1176
- status: (_response$status = response == null ? void 0 : response.status) != null ? _response$status : 500
1177
- }));
1178
- case 71:
1179
- case "end":
1180
- return _context.stop();
1181
- }
1182
- }, _callee, null, [[23, 31], [45, 51]]);
1183
- }));
1184
- return _fetch2.apply(this, arguments);
1185
- }
1186
-
1187
- var Requester = /*#__PURE__*/function (_Config) {
1188
- function Requester(config) {
1189
- var _this;
1190
- _this = _Config.call(this, config) || this;
1191
- _this.post = /*#__PURE__*/function () {
1192
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, url, init) {
1193
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1194
- while (1) switch (_context.prev = _context.next) {
1195
- case 0:
1196
- _context.next = 2;
1197
- return _this.request('POST', url, req, init);
1198
- case 2:
1199
- return _context.abrupt("return", _context.sent);
1200
- case 3:
1201
- case "end":
1202
- return _context.stop();
1203
- }
1204
- }, _callee);
1205
- }));
1206
- return function (_x, _x2, _x3) {
1207
- return _ref.apply(this, arguments);
1208
- };
1209
- }();
1210
- _this.get = /*#__PURE__*/function () {
1211
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(req, url, init) {
1212
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1213
- while (1) switch (_context2.prev = _context2.next) {
1214
- case 0:
1215
- _context2.next = 2;
1216
- return _this.request('GET', url, req, init);
1217
- case 2:
1218
- return _context2.abrupt("return", _context2.sent);
1219
- case 3:
1220
- case "end":
1221
- return _context2.stop();
1062
+ }, _callee);
1063
+ }));
1064
+ return function (_x) {
1065
+ return _ref.apply(this, arguments);
1066
+ };
1067
+ }());
1068
+ this.pool.on('error', /*#__PURE__*/function () {
1069
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(e) {
1070
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1071
+ while (1) switch (_context2.prev = _context2.next) {
1072
+ case 0:
1073
+ info('pool failed', e);
1074
+ if (_this.timer) {
1075
+ clearTimeout(_this.timer);
1076
+ }
1077
+ evictPool(_this.id);
1078
+ case 3:
1079
+ case "end":
1080
+ return _context2.stop();
1222
1081
  }
1223
1082
  }, _callee2);
1224
1083
  }));
1225
- return function (_x4, _x5, _x6) {
1084
+ return function (_x2) {
1226
1085
  return _ref2.apply(this, arguments);
1227
1086
  };
1228
- }();
1229
- _this.put = /*#__PURE__*/function () {
1230
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, url, init) {
1231
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1232
- while (1) switch (_context3.prev = _context3.next) {
1233
- case 0:
1234
- _context3.next = 2;
1235
- return _this.request('PUT', url, req, init);
1236
- case 2:
1237
- return _context3.abrupt("return", _context3.sent);
1238
- case 3:
1239
- case "end":
1240
- return _context3.stop();
1241
- }
1242
- }, _callee3);
1243
- }));
1244
- return function (_x7, _x8, _x9) {
1245
- return _ref3.apply(this, arguments);
1246
- };
1247
- }();
1248
- _this["delete"] = /*#__PURE__*/function () {
1249
- var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(req, url, init) {
1250
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1251
- while (1) switch (_context4.prev = _context4.next) {
1252
- case 0:
1253
- _context4.next = 2;
1254
- return _this.request('DELETE', url, req, init);
1255
- case 2:
1256
- return _context4.abrupt("return", _context4.sent);
1257
- case 3:
1258
- case "end":
1259
- return _context4.stop();
1260
- }
1261
- }, _callee4);
1262
- }));
1263
- return function (_x10, _x11, _x12) {
1264
- return _ref4.apply(this, arguments);
1265
- };
1266
- }();
1267
- return _this;
1087
+ }());
1268
1088
  }
1269
- _inheritsLoose(Requester, _Config);
1270
- var _proto = Requester.prototype;
1271
- _proto.rawRequest = /*#__PURE__*/function () {
1272
- var _rawRequest = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(method, url, init, body) {
1273
- var _init, res;
1274
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1275
- while (1) switch (_context5.prev = _context5.next) {
1089
+ var _proto = NileDatabase.prototype;
1090
+ _proto.startTimeout = function startTimeout() {
1091
+ var _this2 = this;
1092
+ var _Logger3 = Logger(this.config, '[NileInstance]'),
1093
+ info = _Logger3.info;
1094
+ if (this.timer) {
1095
+ clearTimeout(this.timer);
1096
+ }
1097
+ this.timer = setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
1098
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1099
+ while (1) switch (_context3.prev = _context3.next) {
1276
1100
  case 0:
1277
- _init = _extends({}, init, {
1278
- body: body,
1279
- method: method
1101
+ info('Pool reached idleTimeoutMillis.', _this2.id, 'evicted after', _this2.config.db.idleTimeoutMillis, 'ms');
1102
+ _context3.next = 3;
1103
+ return _this2.pool.end(function () {
1104
+ info('Pool end called');
1105
+ // something odd going on here. Without the callback, pool.end() is flakey
1280
1106
  });
1281
- _context5.next = 3;
1282
- return _fetch(this, url, _init);
1283
1107
  case 3:
1284
- res = _context5.sent;
1285
- if (!(res instanceof ResponseError)) {
1286
- _context5.next = 6;
1287
- break;
1288
- }
1289
- return _context5.abrupt("return", res.response);
1290
- case 6:
1291
- return _context5.abrupt("return", res);
1292
- case 7:
1108
+ evictPool(_this2.id);
1109
+ case 4:
1293
1110
  case "end":
1294
- return _context5.stop();
1111
+ return _context3.stop();
1295
1112
  }
1296
- }, _callee5, this);
1297
- }));
1298
- function rawRequest(_x13, _x14, _x15, _x16) {
1299
- return _rawRequest.apply(this, arguments);
1300
- }
1301
- return rawRequest;
1302
- }()
1303
- /**
1304
- * three optios here
1305
- * 1) pass in headers for a server side request
1306
- * 2) pass in the payload that matches the api
1307
- * 3) pass in the request object sent by a browser
1308
- * @param method
1309
- * @param url
1310
- * @param req
1311
- * @param init
1312
- * @returns
1313
- */
1314
- ;
1315
- _proto.request =
1316
- /*#__PURE__*/
1317
- function () {
1318
- var _request = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(method, url, req, init) {
1319
- var headers, tenantId, cookie, _headers, _tenantId, _cookie, body, _init;
1320
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1321
- while (1) switch (_context6.prev = _context6.next) {
1322
- case 0:
1323
- // set the headers
1324
- headers = new Headers(init ? init == null ? void 0 : init.headers : {});
1325
- if (req instanceof Headers) {
1326
- tenantId = req.get(X_NILE_TENANT);
1327
- cookie = req.get('cookie');
1328
- if (tenantId) {
1329
- headers.set(X_NILE_TENANT, tenantId);
1330
- }
1331
- if (cookie) {
1332
- headers.set('cookie', cookie);
1333
- }
1334
- } else if (req instanceof Request) {
1335
- // pass back the X_NILE_TENANT
1336
- _headers = new Headers(req == null ? void 0 : req.headers);
1337
- _tenantId = _headers.get(X_NILE_TENANT);
1338
- _cookie = _headers.get('cookie');
1339
- if (_tenantId) {
1340
- headers.set(X_NILE_TENANT, _tenantId);
1341
- }
1342
- if (_cookie) {
1343
- headers.set('cookie', _cookie);
1344
- }
1345
- }
1346
- // default the body - may be the actual payload for the API
1347
- body = JSON.stringify(req); // comes from next/some server
1348
- if (!(method === 'GET')) {
1349
- _context6.next = 7;
1350
- break;
1351
- }
1352
- body = undefined;
1353
- _context6.next = 14;
1354
- break;
1355
- case 7:
1356
- if (!(req instanceof Request)) {
1357
- _context6.next = 13;
1358
- break;
1359
- }
1360
- _context6.next = 10;
1361
- return new Response(req.body).text();
1362
- case 10:
1363
- body = _context6.sent;
1364
- _context6.next = 14;
1365
- break;
1366
- case 13:
1367
- if (
1368
- // is just headers for a GET request
1369
- req instanceof Headers || JSON.stringify(req) === '{}' || req && typeof req === 'object' && Object.values(req).length === 0) {
1370
- body = undefined;
1371
- }
1372
- case 14:
1373
- _init = _extends({}, init, {
1374
- headers: headers
1375
- });
1376
- _context6.next = 17;
1377
- return this.rawRequest(method, url, _init, body);
1378
- case 17:
1379
- return _context6.abrupt("return", _context6.sent);
1380
- case 18:
1381
- case "end":
1382
- return _context6.stop();
1113
+ }, _callee3);
1114
+ })), this.config.db.idleTimeoutMillis);
1115
+ };
1116
+ return NileDatabase;
1117
+ }();
1118
+ function makeAfterCreate(config) {
1119
+ var _Logger4 = Logger(config, '[afterCreate]'),
1120
+ warn = _Logger4.warn,
1121
+ info = _Logger4.info;
1122
+ return function (conn, done) {
1123
+ conn.on('error', function errorHandler(error) {
1124
+ warn('Connection was terminated by server', error);
1125
+ done(error, conn);
1126
+ });
1127
+ if (isUUID(config.tenantId)) {
1128
+ var query = ["SET nile.tenant_id = '" + config.tenantId + "'"];
1129
+ if (isUUID(config.userId)) {
1130
+ if (!config.tenantId) {
1131
+ warn('A user id cannot be set in context without a tenant id');
1383
1132
  }
1384
- }, _callee6, this);
1385
- }));
1386
- function request(_x17, _x18, _x19, _x20) {
1387
- return _request.apply(this, arguments);
1133
+ query.push("SET nile.user_id = '" + config.userId + "'");
1134
+ }
1135
+ // in this example we use pg driver's connection API
1136
+ conn.query(query.join(';'), function (err) {
1137
+ if (query.length === 1) {
1138
+ info('[tenant id]', config.tenantId);
1139
+ }
1140
+ if (query.length === 2) {
1141
+ info('[user id]', config.userId);
1142
+ }
1143
+ done(err, conn);
1144
+ });
1388
1145
  }
1389
- return request;
1390
- }();
1391
- return Requester;
1392
- }(Config);
1146
+ done(null, conn);
1147
+ };
1148
+ }
1393
1149
 
1394
- var Users = /*#__PURE__*/function (_Config) {
1395
- function Users(config, headers) {
1396
- var _this;
1397
- _this = _Config.call(this, config) || this;
1398
- _this.headers = void 0;
1399
- _this.createUser = /*#__PURE__*/function () {
1400
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, init) {
1401
- var _requester, _init;
1402
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1403
- while (1) switch (_context.prev = _context.next) {
1404
- case 0:
1405
- _requester = new Requester(_this);
1406
- _init = _this.handleHeaders(init);
1407
- _context.next = 4;
1408
- return _requester.post(req, _this.usersUrl, _init);
1409
- case 4:
1410
- return _context.abrupt("return", _context.sent);
1411
- case 5:
1412
- case "end":
1413
- return _context.stop();
1414
- }
1415
- }, _callee);
1416
- }));
1417
- return function (_x, _x2) {
1418
- return _ref.apply(this, arguments);
1419
- };
1420
- }();
1421
- _this.updateUser = /*#__PURE__*/function () {
1422
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(userId, req, init) {
1423
- var _requester, _init;
1424
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1425
- while (1) switch (_context2.prev = _context2.next) {
1426
- case 0:
1427
- _requester = new Requester(_this);
1428
- _init = _this.handleHeaders(init);
1429
- _context2.next = 4;
1430
- return _requester.put(req, _this.usersUrl + "/" + userId, _init);
1431
- case 4:
1432
- return _context2.abrupt("return", _context2.sent);
1433
- case 5:
1434
- case "end":
1435
- return _context2.stop();
1436
- }
1437
- }, _callee2);
1438
- }));
1439
- return function (_x3, _x4, _x5) {
1440
- return _ref2.apply(this, arguments);
1441
- };
1442
- }();
1443
- _this.listUsers = /*#__PURE__*/function () {
1444
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, init) {
1445
- var _requester, _init;
1446
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1447
- while (1) switch (_context3.prev = _context3.next) {
1448
- case 0:
1449
- _requester = new Requester(_this);
1450
- _init = _this.handleHeaders(init);
1451
- _context3.next = 4;
1452
- return _requester.get(req, _this.tenantUsersUrl, _init);
1453
- case 4:
1454
- return _context3.abrupt("return", _context3.sent);
1455
- case 5:
1456
- case "end":
1457
- return _context3.stop();
1458
- }
1459
- }, _callee3);
1460
- }));
1461
- return function (_x6, _x7) {
1462
- return _ref3.apply(this, arguments);
1463
- };
1464
- }();
1465
- _this.linkUser = /*#__PURE__*/function () {
1466
- var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(req, init) {
1467
- var _requester, _init;
1468
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1469
- while (1) switch (_context4.prev = _context4.next) {
1470
- case 0:
1471
- _requester = new Requester(_this);
1472
- _init = _this.handleHeaders(init);
1473
- _context4.next = 4;
1474
- return _requester.put(req, _this.tenantUsersUrl, _init);
1475
- case 4:
1476
- return _context4.abrupt("return", _context4.sent);
1477
- case 5:
1478
- case "end":
1479
- return _context4.stop();
1480
- }
1481
- }, _callee4);
1482
- }));
1483
- return function (_x8, _x9) {
1484
- return _ref4.apply(this, arguments);
1150
+ var DBManager = /*#__PURE__*/function () {
1151
+ function DBManager(_config) {
1152
+ var _this = this;
1153
+ this.connections = void 0;
1154
+ this.cleared = void 0;
1155
+ this.poolWatcher = function (config) {
1156
+ return function (id) {
1157
+ var _Logger = Logger(config, '[DBManager]'),
1158
+ info = _Logger.info;
1159
+ if (id && _this.connections.has(id)) {
1160
+ info('Removing', id, 'from db connection pool.');
1161
+ _this.connections["delete"](id);
1162
+ }
1485
1163
  };
1486
- }();
1487
- _this.tenantUsersDeleteUrl = function (userId) {
1488
- var _this$tenantId;
1489
- return "/tenants/" + ((_this$tenantId = _this.tenantId) != null ? _this$tenantId : '{tenantId}') + "/users/" + (userId != null ? userId : '{userId}');
1490
1164
  };
1491
- _this.getUserId = /*#__PURE__*/function () {
1492
- var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(req) {
1493
- var body;
1494
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1495
- while (1) switch (_context5.prev = _context5.next) {
1496
- case 0:
1497
- if (!(req instanceof Request)) {
1498
- _context5.next = 6;
1499
- break;
1500
- }
1501
- _context5.next = 3;
1502
- return new Response(req == null ? void 0 : req.body).json();
1503
- case 3:
1504
- body = _context5.sent;
1505
- if (!body) {
1506
- _context5.next = 6;
1507
- break;
1508
- }
1509
- return _context5.abrupt("return", body.id);
1510
- case 6:
1511
- if (!('id' in req)) {
1512
- _context5.next = 8;
1513
- break;
1514
- }
1515
- return _context5.abrupt("return", req.id);
1516
- case 8:
1517
- return _context5.abrupt("return", null);
1518
- case 9:
1519
- case "end":
1520
- return _context5.stop();
1521
- }
1522
- }, _callee5);
1523
- }));
1524
- return function (_x10) {
1525
- return _ref5.apply(this, arguments);
1526
- };
1527
- }();
1528
- _this.unlinkUser = /*#__PURE__*/function () {
1529
- var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(req, init) {
1530
- var _requester, userId, _init;
1531
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1532
- while (1) switch (_context6.prev = _context6.next) {
1533
- case 0:
1534
- _requester = new Requester(_this);
1535
- _context6.next = 3;
1536
- return _this.getUserId(req);
1537
- case 3:
1538
- userId = _context6.sent;
1539
- _init = _this.handleHeaders(init);
1540
- _context6.next = 7;
1541
- return _requester["delete"](req, _this.tenantUsersDeleteUrl(userId), _init);
1542
- case 7:
1543
- return _context6.abrupt("return", _context6.sent);
1544
- case 8:
1545
- case "end":
1546
- return _context6.stop();
1547
- }
1548
- }, _callee6);
1549
- }));
1550
- return function (_x11, _x12) {
1551
- return _ref6.apply(this, arguments);
1552
- };
1553
- }();
1554
- _this.me = /*#__PURE__*/function () {
1555
- var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(req, init) {
1556
- var _requester, _init;
1557
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1558
- while (1) switch (_context7.prev = _context7.next) {
1559
- case 0:
1560
- _requester = new Requester(_this);
1561
- _init = _this.handleHeaders(init);
1562
- _context7.next = 4;
1563
- return _requester.get(req, _this.meUrl, _init);
1564
- case 4:
1565
- return _context7.abrupt("return", _context7.sent);
1566
- case 5:
1567
- case "end":
1568
- return _context7.stop();
1569
- }
1570
- }, _callee7);
1571
- }));
1572
- return function (_x13, _x14) {
1573
- return _ref7.apply(this, arguments);
1574
- };
1575
- }();
1576
- _this.headers = headers;
1577
- return _this;
1578
- }
1579
- _inheritsLoose(Users, _Config);
1580
- var _proto = Users.prototype;
1581
- _proto.handleHeaders = function handleHeaders(init) {
1582
- if (this.headers) {
1583
- if (init) {
1584
- var _init2;
1585
- init.headers = new Headers(_extends({}, this.headers, (_init2 = init) == null ? void 0 : _init2.headers));
1586
- return init;
1587
- } else {
1588
- init = {
1589
- headers: this.headers
1590
- };
1591
- return init;
1165
+ this.getConnection = function (config) {
1166
+ var _Logger2 = Logger(config, '[DBManager]'),
1167
+ info = _Logger2.info;
1168
+ var id = _this.makeId(config.tenantId, config.userId);
1169
+ var existing = _this.connections.get(id);
1170
+ info('# of instances:', _this.connections.size);
1171
+ if (existing) {
1172
+ info('returning existing', id);
1173
+ existing.startTimeout();
1174
+ return existing.pool;
1175
+ }
1176
+ var newOne = new NileDatabase(new Config(config), id);
1177
+ _this.connections.set(id, newOne);
1178
+ info('created new', id);
1179
+ info('# of instances:', _this.connections.size);
1180
+ // resume listening to the evict pool if a connection is requested.
1181
+ if (_this.cleared) {
1182
+ _this.cleared = false;
1183
+ watchEvictPool(_this.poolWatcher(config));
1592
1184
  }
1185
+ return newOne.pool;
1186
+ };
1187
+ this.clear = function (config) {
1188
+ var _Logger3 = Logger(config, '[DBManager]'),
1189
+ info = _Logger3.info;
1190
+ info('Clearing all connections', _this.connections.size);
1191
+ closeEvictPool(_this.poolWatcher(config));
1192
+ _this.cleared = true;
1193
+ _this.connections.clear();
1194
+ };
1195
+ var _Logger4 = Logger(_config, '[DBManager]'),
1196
+ _info = _Logger4.info;
1197
+ this.cleared = false;
1198
+ this.connections = new Map();
1199
+ // add the base one, so you can at least query
1200
+ var _id = this.makeId();
1201
+ _info('constructor', _id);
1202
+ this.connections.set(_id, new NileDatabase(new Config(_config), _id));
1203
+ watchEvictPool(this.poolWatcher(_config));
1204
+ }
1205
+ var _proto = DBManager.prototype;
1206
+ _proto.makeId = function makeId(tenantId, userId) {
1207
+ if (isUUID(tenantId) && isUUID(userId)) {
1208
+ return tenantId + ":" + userId;
1593
1209
  }
1594
- return undefined;
1595
- };
1596
- return _createClass(Users, [{
1597
- key: "usersUrl",
1598
- get: function get() {
1599
- return '/users';
1600
- }
1601
- }, {
1602
- key: "tenantUsersUrl",
1603
- get: function get() {
1604
- var _this$tenantId2;
1605
- return "/tenants/" + ((_this$tenantId2 = this.tenantId) != null ? _this$tenantId2 : '{tenantId}') + "/users";
1606
- }
1607
- }, {
1608
- key: "meUrl",
1609
- get: function get() {
1610
- return '/me';
1210
+ if (isUUID(tenantId)) {
1211
+ return "" + tenantId;
1611
1212
  }
1612
- }]);
1613
- }(Config);
1213
+ return 'base';
1214
+ };
1215
+ return DBManager;
1216
+ }();
1614
1217
 
1615
- var Tenants = /*#__PURE__*/function (_Config) {
1616
- function Tenants(config, headers) {
1617
- var _this;
1618
- _this = _Config.call(this, config) || this;
1619
- _this.headers = void 0;
1620
- _this.createTenant = /*#__PURE__*/function () {
1621
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, init) {
1622
- var _requester, _init;
1623
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1624
- while (1) switch (_context.prev = _context.next) {
1625
- case 0:
1626
- _requester = new Requester(_this);
1627
- _init = _this.handleHeaders(init);
1628
- return _context.abrupt("return", _requester.post(req, _this.tenantsUrl, _init));
1629
- case 3:
1630
- case "end":
1631
- return _context.stop();
1632
- }
1633
- }, _callee);
1634
- }));
1635
- return function (_x, _x2) {
1636
- return _ref.apply(this, arguments);
1637
- };
1638
- }();
1639
- _this.getTenant = /*#__PURE__*/function () {
1640
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(req, init) {
1641
- var _requester, _init;
1642
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1643
- while (1) switch (_context2.prev = _context2.next) {
1644
- case 0:
1645
- _requester = new Requester(_this);
1646
- _init = _this.handleHeaders(init);
1647
- return _context2.abrupt("return", _requester.get(req, _this.tenantUrl, _init));
1648
- case 3:
1649
- case "end":
1650
- return _context2.stop();
1651
- }
1652
- }, _callee2);
1653
- }));
1654
- return function (_x3, _x4) {
1655
- return _ref2.apply(this, arguments);
1656
- };
1657
- }();
1658
- _this.listTenants = /*#__PURE__*/function () {
1659
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, init) {
1660
- var _requester, _init;
1661
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1662
- while (1) switch (_context3.prev = _context3.next) {
1663
- case 0:
1664
- _requester = new Requester(_this);
1665
- _init = _this.handleHeaders(init);
1666
- return _context3.abrupt("return", _requester.get(req, _this.tenantListUrl, _init));
1667
- case 3:
1668
- case "end":
1669
- return _context3.stop();
1670
- }
1671
- }, _callee3);
1672
- }));
1673
- return function (_x5, _x6) {
1674
- return _ref3.apply(this, arguments);
1675
- };
1676
- }();
1677
- _this.headers = headers;
1678
- return _this;
1218
+ var getServerId = function getServerId(config) {
1219
+ var cfg = new Config(config);
1220
+ return makeServerId(cfg);
1221
+ };
1222
+ var makeServerId = function makeServerId(config) {
1223
+ return Buffer.from(JSON.stringify(config), 'utf8').toString('base64');
1224
+ };
1225
+
1226
+ var NILEDB_API_URL = process.env.NILEDB_API_URL;
1227
+ function makeRestUrl(path, qp) {
1228
+ if (!NILEDB_API_URL) {
1229
+ throw new Error('An API url is required. Set it via NILEDB_API_URL.');
1679
1230
  }
1680
- _inheritsLoose(Tenants, _Config);
1681
- var _proto = Tenants.prototype;
1682
- _proto.handleHeaders = function handleHeaders(init) {
1683
- if (this.headers) {
1684
- if (init) {
1685
- var _init2;
1686
- init.headers = new Headers(_extends({}, this.headers, (_init2 = init) == null ? void 0 : _init2.headers));
1687
- return init;
1688
- } else {
1689
- init = {
1690
- headers: this.headers
1691
- };
1692
- return init;
1693
- }
1694
- }
1695
- return undefined;
1696
- };
1697
- return _createClass(Tenants, [{
1698
- key: "tenantsUrl",
1699
- get: function get() {
1700
- return '/tenants';
1701
- }
1702
- }, {
1703
- key: "tenantUrl",
1704
- get: function get() {
1705
- var _this$tenantId;
1706
- return "/tenants/" + ((_this$tenantId = this.tenantId) != null ? _this$tenantId : '{tenantId}');
1707
- }
1708
- }, {
1709
- key: "tenantListUrl",
1710
- get: function get() {
1711
- var _this$userId;
1712
- return "/users/" + ((_this$userId = this.userId) != null ? _this$userId : '{userId}') + "/tenants";
1713
- }
1714
- }]);
1715
- }(Config);
1231
+ var params = new URLSearchParams(qp);
1232
+ return "" + [NILEDB_API_URL, path.substring(1, path.length)].join('/') + (qp ? "?" + params.toString() : '');
1233
+ }
1716
1234
 
1717
- function createProxyForPool(pool, config) {
1718
- var _Logger = Logger(config, '[pool]'),
1719
- info = _Logger.info,
1720
- error = _Logger.error;
1721
- return new Proxy(pool, {
1722
- get: function get(target, property) {
1723
- if (property === 'query') {
1724
- // give connection string a pass for these problems
1725
- if (!config.db.connectionString) {
1726
- if (!config.user || !config.password) {
1727
- error('Cannot connect to the database. User and/or password are missing. Generate them at https://console.thenile.dev');
1728
- } else if (!config.db.database) {
1729
- error('Database name is missing from the config. Call `nile.init()` or set NILEDB_ID in your .env');
1730
- }
1731
- }
1732
- var caller = target[property];
1733
- return function query() {
1734
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1735
- args[_key] = arguments[_key];
1235
+ var apiRoutes = {
1236
+ ME: /*#__PURE__*/makeRestUrl('/me'),
1237
+ USERS: function USERS(tenantId) {
1238
+ return makeRestUrl('/users', tenantId ? {
1239
+ tenantId: tenantId
1240
+ } : undefined);
1241
+ },
1242
+ USER: function USER(userId) {
1243
+ return makeRestUrl("/users/" + userId);
1244
+ },
1245
+ TENANTS: /*#__PURE__*/makeRestUrl('/tenants'),
1246
+ TENANT: function TENANT(tenantId) {
1247
+ return makeRestUrl("/tenants/" + tenantId);
1248
+ },
1249
+ SIGNUP: /*#__PURE__*/makeRestUrl('/signup'),
1250
+ TENANT_USERS: function TENANT_USERS(tenantId) {
1251
+ return makeRestUrl("/tenants/" + tenantId + "/users");
1252
+ },
1253
+ TENANT_USER: function TENANT_USER(tenantId, userId) {
1254
+ return makeRestUrl("/tenants/" + tenantId + "/users/" + userId);
1255
+ },
1256
+ USER_TENANTS: function USER_TENANTS(userId) {
1257
+ return makeRestUrl("/users/" + userId + "/tenants");
1258
+ }
1259
+ };
1260
+
1261
+ function urlMatches(requestUrl, route) {
1262
+ var url = new URL(requestUrl);
1263
+ return url.pathname.startsWith(route);
1264
+ }
1265
+
1266
+ var _excluded = ["request"];
1267
+ var _console$1 = console,
1268
+ log$1 = _console$1.log;
1269
+ function request(_x, _x2, _x3) {
1270
+ return _request.apply(this, arguments);
1271
+ }
1272
+ function _request() {
1273
+ _request = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(url, _init, config) {
1274
+ var _params$method;
1275
+ var _Logger, info, error, request, init, requestUrl, updatedHeaders, params, _init$body, res, loggingRes;
1276
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1277
+ while (1) switch (_context.prev = _context.next) {
1278
+ case 0:
1279
+ _Logger = Logger(_extends({}, config, {
1280
+ debug: config == null ? void 0 : config.debug
1281
+ }), '[REQUEST]', "[" + url + "]"), info = _Logger.info, error = _Logger.error;
1282
+ request = _init.request, init = _objectWithoutPropertiesLoose(_init, _excluded);
1283
+ requestUrl = new URL(request.url);
1284
+ updatedHeaders = new Headers(request.headers);
1285
+ updatedHeaders.set('host', requestUrl.host);
1286
+ updatedHeaders.set('niledb-origin', requestUrl.origin);
1287
+ updatedHeaders.set('niledb-creds', Buffer.from(process.env.NILEDB_USER + ":" + process.env.NILEDB_PASSWORD).toString('base64'));
1288
+ params = _extends({}, init, {
1289
+ headers: updatedHeaders
1290
+ });
1291
+ if (params.method === 'POST' || params.method === 'PUT') {
1292
+ params.body = (_init$body = init.body) != null ? _init$body : request.body;
1293
+ // @ts-expect-error - its there
1294
+ params.duplex = 'half';
1736
1295
  }
1737
- info.apply(void 0, args);
1738
- // @ts-expect-error - not mine
1739
- var called = caller.apply(this, args);
1740
- return called;
1741
- };
1296
+ log$1("[" + ((_params$method = params.method) != null ? _params$method : 'GET') + "]", url);
1297
+ _context.next = 12;
1298
+ return fetch(url, _extends({}, params))["catch"](function (e) {
1299
+ error('An error has occurred in the fetch', e);
1300
+ return new Response('An unexpected (most likely configuration) problem has occurred', {
1301
+ status: 500
1302
+ });
1303
+ });
1304
+ case 12:
1305
+ res = _context.sent;
1306
+ loggingRes = typeof (res == null ? void 0 : res.clone) === 'function' ? res == null ? void 0 : res.clone() : null;
1307
+ _context.t0 = info;
1308
+ _context.t1 = res == null ? void 0 : res.status;
1309
+ _context.t2 = res == null ? void 0 : res.statusText;
1310
+ _context.next = 19;
1311
+ return loggingRes == null ? void 0 : loggingRes.text();
1312
+ case 19:
1313
+ _context.t3 = _context.sent;
1314
+ (0, _context.t0)('[Response]', _context.t1, _context.t2, _context.t3);
1315
+ return _context.abrupt("return", res);
1316
+ case 22:
1317
+ case "end":
1318
+ return _context.stop();
1742
1319
  }
1743
- return target[property];
1744
- }
1745
- });
1320
+ }, _callee);
1321
+ }));
1322
+ return _request.apply(this, arguments);
1746
1323
  }
1747
1324
 
1748
- var _excluded$1 = ["afterCreate"];
1749
- var NileDatabase = /*#__PURE__*/function () {
1750
- function NileDatabase(config, id) {
1751
- var _this = this;
1752
- this.pool = void 0;
1753
- this.tenantId = void 0;
1754
- this.userId = void 0;
1755
- this.id = void 0;
1756
- this.config = void 0;
1757
- this.timer = void 0;
1758
- var _Logger = Logger(config, '[NileInstance]'),
1759
- warn = _Logger.warn,
1760
- info = _Logger.info;
1761
- this.id = id;
1762
- var poolConfig = _extends({
1763
- min: 0,
1764
- max: 10,
1765
- idleTimeoutMillis: 30000
1766
- }, config.db);
1767
- var afterCreate = poolConfig.afterCreate,
1768
- remaining = _objectWithoutPropertiesLoose(poolConfig, _excluded$1);
1769
- config.db = poolConfig;
1770
- this.config = config;
1771
- info(this.config.db);
1772
- this.pool = createProxyForPool(new Pool(remaining), this.config);
1773
- if (typeof afterCreate === 'function') {
1774
- warn('Providing an pool configuration will stop automatic tenant context setting.');
1775
- }
1776
- // start the timer for cleanup
1777
- this.startTimeout();
1778
- this.pool.on('connect', /*#__PURE__*/function () {
1779
- var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(client) {
1780
- var afterCreate;
1781
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1782
- while (1) switch (_context.prev = _context.next) {
1783
- case 0:
1784
- info('pool connected');
1785
- afterCreate = makeAfterCreate(config);
1786
- afterCreate(client, function (err) {
1787
- var _Logger2 = Logger(config, '[after create callback]'),
1788
- error = _Logger2.error;
1789
- if (err) {
1790
- error('after create failed', err);
1791
- evictPool(_this.id);
1792
- }
1793
- });
1794
- _this.startTimeout();
1795
- case 4:
1796
- case "end":
1797
- return _context.stop();
1798
- }
1799
- }, _callee);
1800
- }));
1801
- return function (_x) {
1802
- return _ref.apply(this, arguments);
1803
- };
1804
- }());
1805
- this.pool.on('error', /*#__PURE__*/function () {
1806
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(e) {
1807
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1808
- while (1) switch (_context2.prev = _context2.next) {
1809
- case 0:
1810
- info('pool failed', e);
1811
- if (_this.timer) {
1812
- clearTimeout(_this.timer);
1813
- }
1814
- evictPool(_this.id);
1815
- case 3:
1816
- case "end":
1817
- return _context2.stop();
1325
+ var key$6 = 'ME';
1326
+ var url = apiRoutes[key$6];
1327
+ /**
1328
+ * @swagger
1329
+ * /api/me:
1330
+ * get:
1331
+ * summary: Identify the principal
1332
+ * description: Returns information about the principal associated with the session
1333
+ * provided
1334
+ * operationId: me
1335
+ * responses:
1336
+ * "200":
1337
+ * description: Identified user
1338
+ * content:
1339
+ * application/json:
1340
+ * schema:
1341
+ * $ref: '#/components/schemas/User'
1342
+ * "400":
1343
+ * description: API/Database failures
1344
+ * content:
1345
+ * text/plain:
1346
+ * schema:
1347
+ * type: string
1348
+ * "404":
1349
+ * description: Not found
1350
+ * content: {}
1351
+ * "401":
1352
+ * description: Unauthorized
1353
+ * content: {}
1354
+ */
1355
+ function GET$3(_x, _x2) {
1356
+ return _GET$3.apply(this, arguments);
1357
+ }
1358
+ function _GET$3() {
1359
+ _GET$3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(init, log) {
1360
+ var res;
1361
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1362
+ while (1) switch (_context.prev = _context.next) {
1363
+ case 0:
1364
+ log('[GET]', url);
1365
+ _context.next = 3;
1366
+ return request(url, init);
1367
+ case 3:
1368
+ res = _context.sent;
1369
+ return _context.abrupt("return", res);
1370
+ case 5:
1371
+ case "end":
1372
+ return _context.stop();
1373
+ }
1374
+ }, _callee);
1375
+ }));
1376
+ return _GET$3.apply(this, arguments);
1377
+ }
1378
+ function route$a(_x3, _x4) {
1379
+ return _route$a.apply(this, arguments);
1380
+ }
1381
+ function _route$a() {
1382
+ _route$a = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(request, config) {
1383
+ var _Logger, info;
1384
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1385
+ while (1) switch (_context2.prev = _context2.next) {
1386
+ case 0:
1387
+ _Logger = Logger(_extends({}, config, {
1388
+ debug: config.debug
1389
+ }), '[ROUTES]', "[" + key$6 + "]"), info = _Logger.info;
1390
+ _context2.t0 = request.method;
1391
+ _context2.next = _context2.t0 === 'GET' ? 4 : 7;
1392
+ break;
1393
+ case 4:
1394
+ _context2.next = 6;
1395
+ return GET$3({
1396
+ request: request
1397
+ }, info);
1398
+ case 6:
1399
+ return _context2.abrupt("return", _context2.sent);
1400
+ case 7:
1401
+ return _context2.abrupt("return", new Response('method not allowed', {
1402
+ status: 405
1403
+ }));
1404
+ case 8:
1405
+ case "end":
1406
+ return _context2.stop();
1407
+ }
1408
+ }, _callee2);
1409
+ }));
1410
+ return _route$a.apply(this, arguments);
1411
+ }
1412
+ function matches$a(configRoutes, request) {
1413
+ return urlMatches(request.url, configRoutes[key$6]);
1414
+ }
1415
+
1416
+ function auth(_x, _x2) {
1417
+ return _auth.apply(this, arguments);
1418
+ }
1419
+ function _auth() {
1420
+ _auth = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, config) {
1421
+ var _Logger, info, sessionUrl, res;
1422
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1423
+ while (1) switch (_context.prev = _context.next) {
1424
+ case 0:
1425
+ _Logger = Logger(_extends({}, config, {
1426
+ debug: config.debug
1427
+ }), '[nileauth]'), info = _Logger.info;
1428
+ info('checking auth');
1429
+ sessionUrl = config.api.basePath + "/auth/session";
1430
+ info('using session', sessionUrl);
1431
+ // handle the pass through with posts
1432
+ req.headers["delete"]('content-length');
1433
+ _context.next = 7;
1434
+ return request(sessionUrl, {
1435
+ request: req
1436
+ });
1437
+ case 7:
1438
+ res = _context.sent;
1439
+ if (res) {
1440
+ _context.next = 11;
1441
+ break;
1818
1442
  }
1819
- }, _callee2);
1820
- }));
1821
- return function (_x2) {
1822
- return _ref2.apply(this, arguments);
1823
- };
1824
- }());
1825
- }
1826
- var _proto = NileDatabase.prototype;
1827
- _proto.startTimeout = function startTimeout() {
1828
- var _this2 = this;
1829
- var _Logger3 = Logger(this.config, '[NileInstance]'),
1830
- info = _Logger3.info;
1831
- if (this.timer) {
1832
- clearTimeout(this.timer);
1833
- }
1834
- this.timer = setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
1835
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1836
- while (1) switch (_context3.prev = _context3.next) {
1837
- case 0:
1838
- info('Pool reached idleTimeoutMillis.', _this2.id, 'evicted after', _this2.config.db.idleTimeoutMillis, 'ms');
1839
- _context3.next = 3;
1840
- return _this2.pool.end(function () {
1841
- info('Pool end called');
1842
- // something odd going on here. Without the callback, pool.end() is flakey
1843
- });
1844
- case 3:
1845
- evictPool(_this2.id);
1846
- case 4:
1847
- case "end":
1848
- return _context3.stop();
1849
- }
1850
- }, _callee3);
1851
- })), this.config.db.idleTimeoutMillis);
1852
- };
1853
- return NileDatabase;
1854
- }();
1855
- function makeAfterCreate(config) {
1856
- var _Logger4 = Logger(config, '[afterCreate]'),
1857
- warn = _Logger4.warn,
1858
- info = _Logger4.info;
1859
- return function (conn, done) {
1860
- conn.on('error', function errorHandler(error) {
1861
- warn('Connection was terminated by server', error);
1862
- done(error, conn);
1863
- });
1864
- if (config.tenantId) {
1865
- var query = ["SET nile.tenant_id = '" + config.tenantId + "'"];
1866
- if (config.userId) {
1867
- if (!config.tenantId) {
1868
- warn('A user id cannot be set in context without a tenant id');
1869
- }
1870
- query.push("SET nile.user_id = '" + config.userId + "'");
1443
+ info('no session found');
1444
+ return _context.abrupt("return", undefined);
1445
+ case 11:
1446
+ info('session active');
1447
+ _context.next = 14;
1448
+ return new Response(res.body).json();
1449
+ case 14:
1450
+ return _context.abrupt("return", _context.sent);
1451
+ case 15:
1452
+ case "end":
1453
+ return _context.stop();
1871
1454
  }
1872
- // in this example we use pg driver's connection API
1873
- conn.query(query.join(';'), function (err) {
1874
- if (config.tenantId) {
1875
- info('[tenant id]', config.tenantId);
1876
- }
1877
- if (config.userId) {
1878
- info('[user id]', config.userId);
1879
- }
1880
- done(err, conn);
1881
- });
1882
- }
1883
- done(null, conn);
1884
- };
1455
+ }, _callee);
1456
+ }));
1457
+ return _auth.apply(this, arguments);
1885
1458
  }
1886
1459
 
1887
- var DBManager = /*#__PURE__*/function () {
1888
- function DBManager(_config) {
1889
- var _this = this;
1890
- this.connections = void 0;
1891
- this.cleared = void 0;
1892
- this.poolWatcher = function (config) {
1893
- return function (id) {
1894
- var _Logger = Logger(config, '[DBManager]'),
1895
- info = _Logger.info;
1896
- if (id && _this.connections.has(id)) {
1897
- info('Removing', id, 'from db connection pool.');
1898
- _this.connections["delete"](id);
1899
- }
1900
- };
1901
- };
1902
- this.getConnection = function (config) {
1903
- var _Logger2 = Logger(config, '[DBManager]'),
1904
- info = _Logger2.info;
1905
- var id = _this.makeId(config.tenantId, config.userId);
1906
- var existing = _this.connections.get(id);
1907
- info('# of instances:', _this.connections.size);
1908
- if (existing) {
1909
- info('returning existing', id);
1910
- existing.startTimeout();
1911
- return existing.pool;
1912
- }
1913
- var newOne = new NileDatabase(new Config(config), id);
1914
- _this.connections.set(id, newOne);
1915
- info('created new', id);
1916
- info('# of instances:', _this.connections.size);
1917
- // resume listening to the evict pool if a connection is requested.
1918
- if (_this.cleared) {
1919
- _this.cleared = false;
1920
- watchEvictPool(_this.poolWatcher(config));
1921
- }
1922
- return newOne.pool;
1923
- };
1924
- this.clear = function (config) {
1925
- var _Logger3 = Logger(config, '[DBManager]'),
1926
- info = _Logger3.info;
1927
- info('Clearing all connections', _this.connections.size);
1928
- closeEvictPool(_this.poolWatcher(config));
1929
- _this.cleared = true;
1930
- _this.connections.clear();
1931
- };
1932
- var _Logger4 = Logger(_config, '[DBManager]'),
1933
- _info = _Logger4.info;
1934
- this.cleared = false;
1935
- this.connections = new Map();
1936
- // add the base one, so you can at least query
1937
- var _id = this.makeId();
1938
- _info('constructor', _id);
1939
- this.connections.set(_id, new NileDatabase(new Config(_config), _id));
1940
- watchEvictPool(this.poolWatcher(_config));
1941
- }
1942
- var _proto = DBManager.prototype;
1943
- _proto.makeId = function makeId(tenantId, userId) {
1944
- if (tenantId && userId) {
1945
- return tenantId + ":" + userId;
1946
- }
1947
- if (tenantId) {
1948
- return "" + tenantId;
1949
- }
1950
- return 'base';
1951
- };
1952
- return DBManager;
1953
- }();
1954
-
1955
- var getServerId = function getServerId(config) {
1956
- var cfg = new Config(config);
1957
- return makeServerId(cfg);
1958
- };
1959
- var makeServerId = function makeServerId(config) {
1960
- return Buffer.from(JSON.stringify(config), 'base64').toString();
1460
+ var ResponseError = function ResponseError(body, init) {
1461
+ this.response = void 0;
1462
+ this.response = new Response(body, init);
1961
1463
  };
1962
1464
 
1963
- /**
1964
- * a helper function to log in server side.
1965
- */
1966
- function serverAuth(config, handlers) {
1967
- return /*#__PURE__*/function () {
1968
- var _login = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
1969
- var _yield$csrfRes$json, _exec;
1970
- var email, password, sessionUrl, sessionReq, sessionRes, providers, csrf, csrfReq, csrfRes, _ref2, csrfToken, credentials, csrfCookie, signInUrl, postReq, loginRes, authCookie, _ref3, token;
1971
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1972
- while (1) switch (_context.prev = _context.next) {
1973
- case 0:
1974
- email = _ref.email, password = _ref.password;
1975
- sessionUrl = new URL(config.api.localPath + "/api/auth/providers");
1976
- sessionReq = new Request(sessionUrl, {
1977
- method: 'GET',
1978
- headers: new Headers({
1979
- host: sessionUrl.host
1980
- })
1981
- });
1982
- _context.next = 5;
1983
- return handlers.POST(sessionReq);
1984
- case 5:
1985
- sessionRes = _context.sent;
1986
- _context.next = 8;
1987
- return sessionRes == null ? void 0 : sessionRes.json();
1988
- case 8:
1989
- providers = _context.sent;
1990
- csrf = new URL(config.api.localPath + "/api/auth/csrf");
1991
- csrfReq = new Request(csrf, {
1992
- method: 'GET',
1993
- headers: new Headers({
1994
- host: sessionUrl.host
1995
- })
1996
- });
1997
- _context.next = 13;
1998
- return handlers.POST(csrfReq);
1999
- case 13:
2000
- csrfRes = _context.sent;
2001
- _context.next = 16;
2002
- return csrfRes == null ? void 0 : csrfRes.json();
2003
- case 16:
2004
- _context.t0 = _yield$csrfRes$json = _context.sent;
2005
- if (!(_context.t0 != null)) {
2006
- _context.next = 21;
2007
- break;
2008
- }
2009
- _context.t1 = _yield$csrfRes$json;
2010
- _context.next = 22;
2011
- break;
2012
- case 21:
2013
- _context.t1 = {};
2014
- case 22:
2015
- _ref2 = _context.t1;
2016
- csrfToken = _ref2.csrfToken;
2017
- credentials = providers.credentials;
2018
- csrfCookie = csrfRes == null ? void 0 : csrfRes.headers.get('set-cookie');
2019
- expect(csrfCookie).toContain('nile.csrf-token=');
2020
- signInUrl = new URL(credentials.callbackUrl);
2021
- if (csrfCookie) {
2022
- _context.next = 30;
2023
- break;
2024
- }
2025
- throw new Error('unable to authenticate REST');
2026
- case 30:
2027
- postReq = new Request(signInUrl, {
2028
- method: 'POST',
2029
- headers: new Headers({
2030
- 'content-type': 'application/json',
2031
- cookie: csrfCookie
2032
- }),
2033
- body: JSON.stringify({
2034
- email: email,
2035
- password: password,
2036
- csrfToken: csrfToken,
2037
- callbackUrl: credentials.callbackUrl
2038
- })
2039
- });
2040
- _context.next = 33;
2041
- return handlers.POST(postReq);
2042
- case 33:
2043
- loginRes = _context.sent;
2044
- authCookie = loginRes == null ? void 0 : loginRes.headers.get('set-cookie');
2045
- if (authCookie) {
2046
- _context.next = 37;
2047
- break;
2048
- }
2049
- throw new Error('authentication failed');
2050
- case 37:
2051
- expect(authCookie).toContain('nile.session-token=');
2052
- _ref3 = (_exec = /(nile\.session-token=.+?);/.exec(authCookie)) != null ? _exec : [], token = _ref3[1];
2053
- return _context.abrupt("return", new Headers({
2054
- cookie: [token, csrfCookie].join('; ')
2055
- }));
2056
- case 40:
2057
- case "end":
2058
- return _context.stop();
2059
- }
2060
- }, _callee);
2061
- }));
2062
- function login(_x) {
2063
- return _login.apply(this, arguments);
1465
+ var X_NILE_TENANT = 'niledb-tenant-id';
1466
+ var X_NILE_USER_ID = 'niledb-user-id';
1467
+ function getTokenFromCookie(headers, cookieKey) {
1468
+ var _headers$get;
1469
+ var cookie = (_headers$get = headers.get('cookie')) == null ? void 0 : _headers$get.split('; ');
1470
+ var _cookies = {};
1471
+ if (cookie) {
1472
+ for (var _iterator = _createForOfIteratorHelperLoose(cookie), _step; !(_step = _iterator()).done;) {
1473
+ var parts = _step.value;
1474
+ var cookieParts = parts.split('=');
1475
+ var _cookie = cookieParts.slice(1).join('=');
1476
+ var name = cookieParts[0];
1477
+ _cookies[name] = _cookie;
2064
1478
  }
2065
- return login;
2066
- }();
2067
- }
2068
-
2069
- var appRoutes = function appRoutes(prefix) {
2070
- if (prefix === void 0) {
2071
- prefix = '/api';
2072
1479
  }
2073
- return {
2074
- SIGNIN: prefix + "/auth/signin",
2075
- PROVIDERS: prefix + "/auth/providers",
2076
- SESSION: prefix + "/auth/session",
2077
- CSRF: prefix + "/auth/csrf",
2078
- CALLBACK: prefix + "/auth/callback",
2079
- SIGNOUT: prefix + "/auth/signout",
2080
- ERROR: prefix + "/auth/error",
2081
- ME: prefix + "/me",
2082
- USERS: prefix + "/users",
2083
- TENANTS: prefix + "/tenants",
2084
- TENANT_USER: prefix + "/tenants/{tenantId}/users/{userId}",
2085
- TENANT_USERS: prefix + "/tenants/{tenantId}/users",
2086
- SIGNUP: prefix + "/signup"
2087
- };
2088
- };
2089
-
2090
- var NILEDB_API_URL = process.env.NILEDB_API_URL;
2091
- function makeRestUrl(path, qp) {
2092
- if (!NILEDB_API_URL) {
2093
- throw new Error('An API url is required. Set it via NILEDB_API_URL.');
1480
+ if (cookie) {
1481
+ for (var _iterator2 = _createForOfIteratorHelperLoose(cookie), _step2; !(_step2 = _iterator2()).done;) {
1482
+ var _parts = _step2.value;
1483
+ var _cookieParts = _parts.split('=');
1484
+ var _cookie2 = _cookieParts.slice(1).join('=');
1485
+ var _name = _cookieParts[0];
1486
+ _cookies[_name] = _cookie2;
1487
+ }
2094
1488
  }
2095
- var params = new URLSearchParams(qp);
2096
- return "" + [NILEDB_API_URL, path.substring(1, path.length)].join('/') + (qp ? "?" + params.toString() : '');
2097
- }
2098
-
2099
- var apiRoutes = {
2100
- ME: /*#__PURE__*/makeRestUrl('/me'),
2101
- USERS: function USERS(tenantId) {
2102
- return makeRestUrl('/users', tenantId ? {
2103
- tenantId: tenantId
2104
- } : undefined);
2105
- },
2106
- USER: function USER(userId) {
2107
- return makeRestUrl("/users/" + userId);
2108
- },
2109
- TENANTS: /*#__PURE__*/makeRestUrl('/tenants'),
2110
- TENANT: function TENANT(tenantId) {
2111
- return makeRestUrl("/tenants/" + tenantId);
2112
- },
2113
- SIGNUP: /*#__PURE__*/makeRestUrl('/signup'),
2114
- TENANT_USERS: function TENANT_USERS(tenantId) {
2115
- return makeRestUrl("/tenants/" + tenantId + "/users");
2116
- },
2117
- TENANT_USER: function TENANT_USER(tenantId, userId) {
2118
- return makeRestUrl("/tenants/" + tenantId + "/users/" + userId);
2119
- },
2120
- USER_TENANTS: function USER_TENANTS(userId) {
2121
- return makeRestUrl("/users/" + userId + "/tenants");
1489
+ if (cookieKey) {
1490
+ return _cookies[cookieKey];
2122
1491
  }
2123
- };
2124
-
2125
- function urlMatches(requestUrl, route) {
2126
- var url = new URL(requestUrl);
2127
- return url.pathname.startsWith(route);
1492
+ return null;
2128
1493
  }
2129
-
2130
- var _excluded = ["request"];
2131
- var _console$1 = console,
2132
- log$1 = _console$1.log;
2133
- function request(_x, _x2, _x3) {
2134
- return _request.apply(this, arguments);
1494
+ function getTenantFromHttp(headers, config) {
1495
+ var _ref;
1496
+ var cookieTenant = getTokenFromCookie(headers, X_NILE_TENANT);
1497
+ return (_ref = cookieTenant != null ? cookieTenant : headers == null ? void 0 : headers.get(X_NILE_TENANT)) != null ? _ref : config == null ? void 0 : config.tenantId;
2135
1498
  }
2136
- function _request() {
2137
- _request = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(url, _init, config) {
2138
- var _params$method;
2139
- var _Logger, info, error, request, init, requestUrl, updatedHeaders, params, _init$body, res, loggingRes;
1499
+ function getUserFromHttp(headers, config) {
1500
+ var _headers$get2;
1501
+ var token = getTokenFromCookie(headers, config.api.cookieKey);
1502
+ if (token) {
1503
+ var jwt = decodeJwt(token);
1504
+ return jwt.sub;
1505
+ }
1506
+ return (_headers$get2 = headers == null ? void 0 : headers.get(X_NILE_USER_ID)) != null ? _headers$get2 : config.userId;
1507
+ }
1508
+ function _fetch(_x, _x2, _x3) {
1509
+ return _fetch2.apply(this, arguments);
1510
+ }
1511
+ function _fetch2() {
1512
+ _fetch2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config, path, opts) {
1513
+ var _config$api, _config$api2, _response$status;
1514
+ var _Logger, info, error, url, cookieKey, headers, basicHeaders, creds, authHeader, token, tenantId, userId, useableUrl, response, res, errorHandler, msg, _res, message, _res2, _res2$errors, _message;
2140
1515
  return _regeneratorRuntime().wrap(function _callee$(_context) {
2141
1516
  while (1) switch (_context.prev = _context.next) {
2142
1517
  case 0:
2143
- _Logger = Logger(_extends({}, config, {
2144
- debug: config == null ? void 0 : config.debug
2145
- }), '[REQUEST]', "[" + url + "]"), info = _Logger.info, error = _Logger.error;
2146
- request = _init.request, init = _objectWithoutPropertiesLoose(_init, _excluded);
2147
- requestUrl = new URL(request.url);
2148
- updatedHeaders = new Headers(request.headers);
2149
- updatedHeaders.set('host', requestUrl.host);
2150
- updatedHeaders.set('niledb-origin', requestUrl.origin);
2151
- updatedHeaders.set('niledb-creds', Buffer.from(process.env.NILEDB_USER + ":" + process.env.NILEDB_PASSWORD).toString('base64'));
2152
- params = _extends({}, init, {
2153
- headers: updatedHeaders
2154
- });
2155
- if (params.method === 'POST' || params.method === 'PUT') {
2156
- params.body = (_init$body = init.body) != null ? _init$body : request.body;
2157
- // @ts-expect-error - its there
2158
- params.duplex = 'half';
1518
+ _Logger = Logger(config, '[server]'), info = _Logger.info, error = _Logger.error;
1519
+ url = "" + ((_config$api = config.api) == null ? void 0 : _config$api.basePath) + path;
1520
+ cookieKey = (_config$api2 = config.api) == null ? void 0 : _config$api2.cookieKey;
1521
+ headers = new Headers(opts == null ? void 0 : opts.headers);
1522
+ basicHeaders = new Headers(opts == null ? void 0 : opts.headers);
1523
+ basicHeaders.set('content-type', 'application/json; charset=utf-8');
1524
+ creds = Buffer.from(process.env.NILEDB_USER + ":" + process.env.NILEDB_PASSWORD, 'utf8').toString('base64');
1525
+ basicHeaders.set('niledb-creds', creds);
1526
+ authHeader = headers.get('Authorization');
1527
+ if (!authHeader) {
1528
+ token = getTokenFromCookie(headers, cookieKey);
1529
+ if (token) {
1530
+ basicHeaders.set('Authorization', "Bearer " + token);
1531
+ } else if (getToken({
1532
+ config: config
1533
+ })) {
1534
+ basicHeaders.set('Authorization', "Bearer " + getToken({
1535
+ config: config
1536
+ }));
1537
+ }
2159
1538
  }
2160
- log$1("[" + ((_params$method = params.method) != null ? _params$method : 'GET') + "]", url);
2161
- _context.next = 12;
2162
- return fetch(url, _extends({}, params))["catch"](function (e) {
2163
- error('An error has occurred in the fetch', e);
2164
- return new Response('An unexpected (most likely configuration) problem has occurred', {
2165
- status: 500
2166
- });
1539
+ tenantId = getTenantFromHttp(headers, config);
1540
+ updateTenantId(tenantId);
1541
+ userId = getUserFromHttp(headers, config);
1542
+ updateUserId(userId);
1543
+ if (!(url.includes('{tenantId}') && !tenantId)) {
1544
+ _context.next = 16;
1545
+ break;
1546
+ }
1547
+ return _context.abrupt("return", new ResponseError('tenantId is not set for request', {
1548
+ status: 400
1549
+ }));
1550
+ case 16:
1551
+ useableUrl = url.replace('{tenantId}', encodeURIComponent(String(tenantId))).replace('{userId}', encodeURIComponent(String(userId)));
1552
+ info('[fetch]', useableUrl);
1553
+ _context.next = 20;
1554
+ return fetch(useableUrl, _extends({}, opts, {
1555
+ headers: basicHeaders
1556
+ }))["catch"](function (e) {
1557
+ error('[fetch]', '[response]', e);
2167
1558
  });
2168
- case 12:
2169
- res = _context.sent;
2170
- loggingRes = typeof (res == null ? void 0 : res.clone) === 'function' ? res == null ? void 0 : res.clone() : null;
1559
+ case 20:
1560
+ response = _context.sent;
1561
+ if (!(response && response.status >= 200 && response.status < 300)) {
1562
+ _context.next = 39;
1563
+ break;
1564
+ }
1565
+ if (!(typeof response.clone === 'function')) {
1566
+ _context.next = 38;
1567
+ break;
1568
+ }
1569
+ _context.prev = 23;
2171
1570
  _context.t0 = info;
2172
- _context.t1 = res == null ? void 0 : res.status;
2173
- _context.t2 = res == null ? void 0 : res.statusText;
2174
- _context.next = 19;
2175
- return loggingRes == null ? void 0 : loggingRes.text();
2176
- case 19:
2177
- _context.t3 = _context.sent;
2178
- (0, _context.t0)('[Response]', _context.t1, _context.t2, _context.t3);
2179
- return _context.abrupt("return", res);
2180
- case 22:
1571
+ _context.next = 27;
1572
+ return response.clone().json();
1573
+ case 27:
1574
+ _context.t1 = _context.sent;
1575
+ (0, _context.t0)('[fetch]', '[response]', _context.t1);
1576
+ _context.next = 38;
1577
+ break;
1578
+ case 31:
1579
+ _context.prev = 31;
1580
+ _context.t2 = _context["catch"](23);
1581
+ _context.t3 = info;
1582
+ _context.next = 36;
1583
+ return response.clone().text();
1584
+ case 36:
1585
+ _context.t4 = _context.sent;
1586
+ (0, _context.t3)('[fetch]', '[response]', _context.t4);
1587
+ case 38:
1588
+ return _context.abrupt("return", response);
1589
+ case 39:
1590
+ if (!((response == null ? void 0 : response.status) === 401)) {
1591
+ _context.next = 41;
1592
+ break;
1593
+ }
1594
+ return _context.abrupt("return", new ResponseError('Unauthorized', {
1595
+ status: 401
1596
+ }));
1597
+ case 41:
1598
+ if (!((response == null ? void 0 : response.status) === 405)) {
1599
+ _context.next = 43;
1600
+ break;
1601
+ }
1602
+ return _context.abrupt("return", new ResponseError('Method not allowed', {
1603
+ status: 405
1604
+ }));
1605
+ case 43:
1606
+ errorHandler = typeof (response == null ? void 0 : response.clone) === 'function' ? response.clone() : null;
1607
+ msg = '';
1608
+ _context.prev = 45;
1609
+ _context.next = 48;
1610
+ return response == null ? void 0 : response.json();
1611
+ case 48:
1612
+ res = _context.sent;
1613
+ _context.next = 59;
1614
+ break;
1615
+ case 51:
1616
+ _context.prev = 51;
1617
+ _context.t5 = _context["catch"](45);
1618
+ if (!errorHandler) {
1619
+ _context.next = 58;
1620
+ break;
1621
+ }
1622
+ _context.next = 56;
1623
+ return errorHandler.text();
1624
+ case 56:
1625
+ msg = _context.sent;
1626
+ if (msg) {
1627
+ error('[fetch]', '[response]', "[status: " + errorHandler.status + "]", msg);
1628
+ }
1629
+ case 58:
1630
+ if (!msg) {
1631
+ error('[fetch]', '[response]', _context.t5);
1632
+ }
1633
+ case 59:
1634
+ if (!msg) {
1635
+ _context.next = 61;
1636
+ break;
1637
+ }
1638
+ return _context.abrupt("return", new ResponseError(msg, {
1639
+ status: errorHandler == null ? void 0 : errorHandler.status
1640
+ }));
1641
+ case 61:
1642
+ if (!(res && 'message' in res)) {
1643
+ _context.next = 65;
1644
+ break;
1645
+ }
1646
+ _res = res, message = _res.message;
1647
+ error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", message);
1648
+ return _context.abrupt("return", new ResponseError(message, {
1649
+ status: 400
1650
+ }));
1651
+ case 65:
1652
+ if (!(res && 'errors' in res)) {
1653
+ _context.next = 69;
1654
+ break;
1655
+ }
1656
+ _res2 = res, _res2$errors = _res2.errors, _message = _res2$errors[0];
1657
+ error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", _message);
1658
+ return _context.abrupt("return", new ResponseError(_message, {
1659
+ status: 400
1660
+ }));
1661
+ case 69:
1662
+ error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", 'UNHANDLED ERROR');
1663
+ return _context.abrupt("return", new ResponseError(null, {
1664
+ status: (_response$status = response == null ? void 0 : response.status) != null ? _response$status : 500
1665
+ }));
1666
+ case 71:
2181
1667
  case "end":
2182
1668
  return _context.stop();
2183
1669
  }
2184
- }, _callee);
1670
+ }, _callee, null, [[23, 31], [45, 51]]);
2185
1671
  }));
2186
- return _request.apply(this, arguments);
2187
- }
2188
-
2189
- var key$6 = 'ME';
2190
- var url = apiRoutes[key$6];
2191
- /**
2192
- * @swagger
2193
- * /api/me:
2194
- * get:
2195
- * summary: Identify the principal
2196
- * description: Returns information about the principal associated with the session
2197
- * provided
2198
- * operationId: me
2199
- * responses:
2200
- * "200":
2201
- * description: Identified user
2202
- * content:
2203
- * application/json:
2204
- * schema:
2205
- * $ref: '#/components/schemas/User'
2206
- * "400":
2207
- * description: API/Database failures
2208
- * content:
2209
- * text/plain:
2210
- * schema:
2211
- * type: string
2212
- * "404":
2213
- * description: Not found
2214
- * content: {}
2215
- * "401":
2216
- * description: Unauthorized
2217
- * content: {}
2218
- */
2219
- function GET$3(_x, _x2) {
2220
- return _GET$3.apply(this, arguments);
2221
- }
2222
- function _GET$3() {
2223
- _GET$3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(init, log) {
2224
- var res;
2225
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2226
- while (1) switch (_context.prev = _context.next) {
2227
- case 0:
2228
- log('[GET]', url);
2229
- _context.next = 3;
2230
- return request(url, init);
2231
- case 3:
2232
- res = _context.sent;
2233
- return _context.abrupt("return", res);
2234
- case 5:
2235
- case "end":
2236
- return _context.stop();
2237
- }
2238
- }, _callee);
2239
- }));
2240
- return _GET$3.apply(this, arguments);
2241
- }
2242
- function route$a(_x3, _x4) {
2243
- return _route$a.apply(this, arguments);
2244
- }
2245
- function _route$a() {
2246
- _route$a = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(request, config) {
2247
- var _Logger, info;
2248
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
2249
- while (1) switch (_context2.prev = _context2.next) {
2250
- case 0:
2251
- _Logger = Logger(_extends({}, config, {
2252
- debug: config.debug
2253
- }), '[ROUTES]', "[" + key$6 + "]"), info = _Logger.info;
2254
- _context2.t0 = request.method;
2255
- _context2.next = _context2.t0 === 'GET' ? 4 : 7;
2256
- break;
2257
- case 4:
2258
- _context2.next = 6;
2259
- return GET$3({
2260
- request: request
2261
- }, info);
2262
- case 6:
2263
- return _context2.abrupt("return", _context2.sent);
2264
- case 7:
2265
- return _context2.abrupt("return", new Response('method not allowed', {
2266
- status: 405
2267
- }));
2268
- case 8:
2269
- case "end":
2270
- return _context2.stop();
2271
- }
2272
- }, _callee2);
2273
- }));
2274
- return _route$a.apply(this, arguments);
2275
- }
2276
- function matches$a(configRoutes, request) {
2277
- return urlMatches(request.url, configRoutes[key$6]);
2278
- }
2279
-
2280
- function auth(_x, _x2) {
2281
- return _auth.apply(this, arguments);
2282
- }
2283
- function _auth() {
2284
- _auth = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, config) {
2285
- var _Logger, info, sessionUrl, res;
2286
- return _regeneratorRuntime().wrap(function _callee$(_context) {
2287
- while (1) switch (_context.prev = _context.next) {
2288
- case 0:
2289
- _Logger = Logger(_extends({}, config, {
2290
- debug: config.debug
2291
- }), '[nileauth]'), info = _Logger.info;
2292
- info('checking auth');
2293
- sessionUrl = config.api.basePath + "/auth/session";
2294
- info('using session', sessionUrl);
2295
- // handle the pass through with posts
2296
- req.headers["delete"]('content-length');
2297
- _context.next = 7;
2298
- return request(sessionUrl, {
2299
- request: req
2300
- });
2301
- case 7:
2302
- res = _context.sent;
2303
- if (res) {
2304
- _context.next = 11;
2305
- break;
2306
- }
2307
- info('no session found');
2308
- return _context.abrupt("return", undefined);
2309
- case 11:
2310
- info('session active');
2311
- _context.next = 14;
2312
- return new Response(res.body).json();
2313
- case 14:
2314
- return _context.abrupt("return", _context.sent);
2315
- case 15:
2316
- case "end":
2317
- return _context.stop();
2318
- }
2319
- }, _callee);
2320
- }));
2321
- return _auth.apply(this, arguments);
1672
+ return _fetch2.apply(this, arguments);
2322
1673
  }
2323
1674
 
2324
1675
  /**
@@ -3538,172 +2889,876 @@ function GETTER(configRoutes, config) {
3538
2889
  function GET(_x) {
3539
2890
  return _GET.apply(this, arguments);
3540
2891
  }
3541
- return GET;
3542
- }();
3543
- }
3544
-
3545
- function POSTER(configRoutes, config) {
3546
- return /*#__PURE__*/function () {
3547
- var _POST = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3548
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3549
- while (1) switch (_context.prev = _context.next) {
3550
- case 0:
3551
- if (!matches$8(configRoutes, req)) {
3552
- _context.next = 2;
3553
- break;
3554
- }
3555
- return _context.abrupt("return", route$8(req, config));
3556
- case 2:
3557
- if (!matches$9(configRoutes, req)) {
3558
- _context.next = 4;
3559
- break;
3560
- }
3561
- return _context.abrupt("return", route$9(req, config));
3562
- case 4:
3563
- if (!matches$7(configRoutes, req)) {
3564
- _context.next = 6;
3565
- break;
3566
- }
3567
- return _context.abrupt("return", route$7(req, config));
3568
- case 6:
3569
- if (!matches$5(configRoutes, req)) {
3570
- _context.next = 8;
3571
- break;
3572
- }
3573
- return _context.abrupt("return", route$5(req, config));
3574
- case 8:
3575
- if (!matches$6(configRoutes, req)) {
3576
- _context.next = 10;
3577
- break;
3578
- }
3579
- return _context.abrupt("return", route$6(req));
3580
- case 10:
3581
- if (!matches$4(configRoutes, req)) {
3582
- _context.next = 12;
3583
- break;
3584
- }
3585
- return _context.abrupt("return", route$4(req));
3586
- case 12:
3587
- if (!matches$3(configRoutes, req)) {
3588
- _context.next = 14;
3589
- break;
3590
- }
3591
- return _context.abrupt("return", route$3(req));
3592
- case 14:
3593
- if (!matches$2(configRoutes, req)) {
3594
- _context.next = 16;
3595
- break;
3596
- }
3597
- return _context.abrupt("return", route$2(req));
3598
- case 16:
3599
- if (!matches$1(configRoutes, req)) {
3600
- _context.next = 18;
3601
- break;
3602
- }
3603
- return _context.abrupt("return", route$1(req));
3604
- case 18:
3605
- return _context.abrupt("return", new Response(null, {
3606
- status: 404
3607
- }));
3608
- case 19:
3609
- case "end":
3610
- return _context.stop();
3611
- }
3612
- }, _callee);
3613
- }));
3614
- function POST(_x) {
3615
- return _POST.apply(this, arguments);
2892
+ return GET;
2893
+ }();
2894
+ }
2895
+
2896
+ function POSTER(configRoutes, config) {
2897
+ return /*#__PURE__*/function () {
2898
+ var _POST = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2899
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2900
+ while (1) switch (_context.prev = _context.next) {
2901
+ case 0:
2902
+ if (!matches$8(configRoutes, req)) {
2903
+ _context.next = 2;
2904
+ break;
2905
+ }
2906
+ return _context.abrupt("return", route$8(req, config));
2907
+ case 2:
2908
+ if (!matches$9(configRoutes, req)) {
2909
+ _context.next = 4;
2910
+ break;
2911
+ }
2912
+ return _context.abrupt("return", route$9(req, config));
2913
+ case 4:
2914
+ if (!matches$7(configRoutes, req)) {
2915
+ _context.next = 6;
2916
+ break;
2917
+ }
2918
+ return _context.abrupt("return", route$7(req, config));
2919
+ case 6:
2920
+ if (!matches$5(configRoutes, req)) {
2921
+ _context.next = 8;
2922
+ break;
2923
+ }
2924
+ return _context.abrupt("return", route$5(req, config));
2925
+ case 8:
2926
+ if (!matches$6(configRoutes, req)) {
2927
+ _context.next = 10;
2928
+ break;
2929
+ }
2930
+ return _context.abrupt("return", route$6(req));
2931
+ case 10:
2932
+ if (!matches$4(configRoutes, req)) {
2933
+ _context.next = 12;
2934
+ break;
2935
+ }
2936
+ return _context.abrupt("return", route$4(req));
2937
+ case 12:
2938
+ if (!matches$3(configRoutes, req)) {
2939
+ _context.next = 14;
2940
+ break;
2941
+ }
2942
+ return _context.abrupt("return", route$3(req));
2943
+ case 14:
2944
+ if (!matches$2(configRoutes, req)) {
2945
+ _context.next = 16;
2946
+ break;
2947
+ }
2948
+ return _context.abrupt("return", route$2(req));
2949
+ case 16:
2950
+ if (!matches$1(configRoutes, req)) {
2951
+ _context.next = 18;
2952
+ break;
2953
+ }
2954
+ return _context.abrupt("return", route$1(req));
2955
+ case 18:
2956
+ return _context.abrupt("return", new Response(null, {
2957
+ status: 404
2958
+ }));
2959
+ case 19:
2960
+ case "end":
2961
+ return _context.stop();
2962
+ }
2963
+ }, _callee);
2964
+ }));
2965
+ function POST(_x) {
2966
+ return _POST.apply(this, arguments);
2967
+ }
2968
+ return POST;
2969
+ }();
2970
+ }
2971
+
2972
+ function DELETER(configRoutes, config) {
2973
+ return /*#__PURE__*/function () {
2974
+ var _DELETE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
2975
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2976
+ while (1) switch (_context.prev = _context.next) {
2977
+ case 0:
2978
+ if (!matches$8(configRoutes, req)) {
2979
+ _context.next = 2;
2980
+ break;
2981
+ }
2982
+ return _context.abrupt("return", route$8(req, config));
2983
+ case 2:
2984
+ if (!matches$7(configRoutes, req)) {
2985
+ _context.next = 4;
2986
+ break;
2987
+ }
2988
+ return _context.abrupt("return", route$7(req, config));
2989
+ case 4:
2990
+ return _context.abrupt("return", new Response(null, {
2991
+ status: 404
2992
+ }));
2993
+ case 5:
2994
+ case "end":
2995
+ return _context.stop();
2996
+ }
2997
+ }, _callee);
2998
+ }));
2999
+ function DELETE(_x) {
3000
+ return _DELETE.apply(this, arguments);
3001
+ }
3002
+ return DELETE;
3003
+ }();
3004
+ }
3005
+
3006
+ function PUTER(configRoutes, config) {
3007
+ return /*#__PURE__*/function () {
3008
+ var _PUT = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3009
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3010
+ while (1) switch (_context.prev = _context.next) {
3011
+ case 0:
3012
+ if (!matches$8(configRoutes, req)) {
3013
+ _context.next = 2;
3014
+ break;
3015
+ }
3016
+ return _context.abrupt("return", route$8(req, config));
3017
+ case 2:
3018
+ if (!matches$9(configRoutes, req)) {
3019
+ _context.next = 4;
3020
+ break;
3021
+ }
3022
+ return _context.abrupt("return", route$9(req, config));
3023
+ case 4:
3024
+ if (!matches$7(configRoutes, req)) {
3025
+ _context.next = 6;
3026
+ break;
3027
+ }
3028
+ return _context.abrupt("return", route$7(req, config));
3029
+ case 6:
3030
+ return _context.abrupt("return", new Response(null, {
3031
+ status: 404
3032
+ }));
3033
+ case 7:
3034
+ case "end":
3035
+ return _context.stop();
3036
+ }
3037
+ }, _callee);
3038
+ }));
3039
+ function PUT(_x) {
3040
+ return _PUT.apply(this, arguments);
3041
+ }
3042
+ return PUT;
3043
+ }();
3044
+ }
3045
+
3046
+ function Handlers(configRoutes, config) {
3047
+ var GET = GETTER(configRoutes, config);
3048
+ var POST = POSTER(configRoutes, config);
3049
+ var DELETE = DELETER(configRoutes, config);
3050
+ var PUT = PUTER(configRoutes, config);
3051
+ return {
3052
+ GET: GET,
3053
+ POST: POST,
3054
+ DELETE: DELETE,
3055
+ PUT: PUT
3056
+ };
3057
+ }
3058
+
3059
+ var appRoutes = function appRoutes(prefix) {
3060
+ if (prefix === void 0) {
3061
+ prefix = '/api';
3062
+ }
3063
+ return {
3064
+ SIGNIN: prefix + "/auth/signin",
3065
+ PROVIDERS: prefix + "/auth/providers",
3066
+ SESSION: prefix + "/auth/session",
3067
+ CSRF: prefix + "/auth/csrf",
3068
+ CALLBACK: prefix + "/auth/callback",
3069
+ SIGNOUT: prefix + "/auth/signout",
3070
+ ERROR: prefix + "/auth/error",
3071
+ ME: prefix + "/me",
3072
+ USERS: prefix + "/users",
3073
+ TENANTS: prefix + "/tenants",
3074
+ TENANT_USER: prefix + "/tenants/{tenantId}/users/{userId}",
3075
+ TENANT_USERS: prefix + "/tenants/{tenantId}/users",
3076
+ SIGNUP: prefix + "/signup"
3077
+ };
3078
+ };
3079
+
3080
+ /**
3081
+ * a helper function to log in server side.
3082
+ */
3083
+ function serverAuth(config, handlers) {
3084
+ return /*#__PURE__*/function () {
3085
+ var _login = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
3086
+ var _yield$csrfRes$json, _exec;
3087
+ var email, password, sessionUrl, sessionReq, sessionRes, providers, csrf, csrfReq, csrfRes, _ref2, csrfToken, credentials, csrfCookie, signInUrl, postReq, loginRes, authCookie, _ref3, token;
3088
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3089
+ while (1) switch (_context.prev = _context.next) {
3090
+ case 0:
3091
+ email = _ref.email, password = _ref.password;
3092
+ sessionUrl = new URL(config.api.localPath + "/api/auth/providers");
3093
+ sessionReq = new Request(sessionUrl, {
3094
+ method: 'GET',
3095
+ headers: new Headers({
3096
+ host: sessionUrl.host
3097
+ })
3098
+ });
3099
+ _context.next = 5;
3100
+ return handlers.POST(sessionReq);
3101
+ case 5:
3102
+ sessionRes = _context.sent;
3103
+ _context.next = 8;
3104
+ return sessionRes == null ? void 0 : sessionRes.json();
3105
+ case 8:
3106
+ providers = _context.sent;
3107
+ csrf = new URL(config.api.localPath + "/api/auth/csrf");
3108
+ csrfReq = new Request(csrf, {
3109
+ method: 'GET',
3110
+ headers: new Headers({
3111
+ host: sessionUrl.host
3112
+ })
3113
+ });
3114
+ _context.next = 13;
3115
+ return handlers.POST(csrfReq);
3116
+ case 13:
3117
+ csrfRes = _context.sent;
3118
+ _context.next = 16;
3119
+ return csrfRes == null ? void 0 : csrfRes.json();
3120
+ case 16:
3121
+ _context.t0 = _yield$csrfRes$json = _context.sent;
3122
+ if (!(_context.t0 != null)) {
3123
+ _context.next = 21;
3124
+ break;
3125
+ }
3126
+ _context.t1 = _yield$csrfRes$json;
3127
+ _context.next = 22;
3128
+ break;
3129
+ case 21:
3130
+ _context.t1 = {};
3131
+ case 22:
3132
+ _ref2 = _context.t1;
3133
+ csrfToken = _ref2.csrfToken;
3134
+ credentials = providers.credentials;
3135
+ csrfCookie = csrfRes == null ? void 0 : csrfRes.headers.get('set-cookie');
3136
+ expect(csrfCookie).toContain('nile.csrf-token=');
3137
+ signInUrl = new URL(credentials.callbackUrl);
3138
+ if (csrfCookie) {
3139
+ _context.next = 30;
3140
+ break;
3141
+ }
3142
+ throw new Error('unable to authenticate REST');
3143
+ case 30:
3144
+ postReq = new Request(signInUrl, {
3145
+ method: 'POST',
3146
+ headers: new Headers({
3147
+ 'content-type': 'application/json',
3148
+ cookie: csrfCookie
3149
+ }),
3150
+ body: JSON.stringify({
3151
+ email: email,
3152
+ password: password,
3153
+ csrfToken: csrfToken,
3154
+ callbackUrl: credentials.callbackUrl
3155
+ })
3156
+ });
3157
+ _context.next = 33;
3158
+ return handlers.POST(postReq);
3159
+ case 33:
3160
+ loginRes = _context.sent;
3161
+ authCookie = loginRes == null ? void 0 : loginRes.headers.get('set-cookie');
3162
+ if (authCookie) {
3163
+ _context.next = 37;
3164
+ break;
3165
+ }
3166
+ throw new Error('authentication failed');
3167
+ case 37:
3168
+ expect(authCookie).toContain('nile.session-token=');
3169
+ _ref3 = (_exec = /(nile\.session-token=.+?);/.exec(authCookie)) != null ? _exec : [], token = _ref3[1];
3170
+ return _context.abrupt("return", new Headers({
3171
+ cookie: [token, csrfCookie].join('; ')
3172
+ }));
3173
+ case 40:
3174
+ case "end":
3175
+ return _context.stop();
3176
+ }
3177
+ }, _callee);
3178
+ }));
3179
+ function login(_x) {
3180
+ return _login.apply(this, arguments);
3181
+ }
3182
+ return login;
3183
+ }();
3184
+ }
3185
+
3186
+ var Requester = /*#__PURE__*/function (_Config) {
3187
+ function Requester(config) {
3188
+ return _Config.call(this, config) || this;
3189
+ }
3190
+ _inheritsLoose(Requester, _Config);
3191
+ var _proto = Requester.prototype;
3192
+ _proto.rawRequest = /*#__PURE__*/function () {
3193
+ var _rawRequest = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(method, url, init, body) {
3194
+ var _init, res;
3195
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3196
+ while (1) switch (_context.prev = _context.next) {
3197
+ case 0:
3198
+ _init = _extends({}, init, {
3199
+ body: body,
3200
+ method: method
3201
+ });
3202
+ _context.next = 3;
3203
+ return _fetch(this, url, _init);
3204
+ case 3:
3205
+ res = _context.sent;
3206
+ if (!(res instanceof ResponseError)) {
3207
+ _context.next = 6;
3208
+ break;
3209
+ }
3210
+ return _context.abrupt("return", res.response);
3211
+ case 6:
3212
+ return _context.abrupt("return", res);
3213
+ case 7:
3214
+ case "end":
3215
+ return _context.stop();
3216
+ }
3217
+ }, _callee, this);
3218
+ }));
3219
+ function rawRequest(_x, _x2, _x3, _x4) {
3220
+ return _rawRequest.apply(this, arguments);
3221
+ }
3222
+ return rawRequest;
3223
+ }()
3224
+ /**
3225
+ * three options here
3226
+ * 1) pass in headers for a server side request
3227
+ * 2) pass in the payload that matches the api
3228
+ * 3) pass in the request object sent by a browser
3229
+ * @param method
3230
+ * @param url
3231
+ * @param req
3232
+ * @param init
3233
+ * @returns
3234
+ */
3235
+ ;
3236
+ _proto.request =
3237
+ /*#__PURE__*/
3238
+ function () {
3239
+ var _request = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(method, url, req, init) {
3240
+ var headers, tenantId, cookie, _headers, _tenantId, _cookie, body, _init;
3241
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3242
+ while (1) switch (_context2.prev = _context2.next) {
3243
+ case 0:
3244
+ // set the headers
3245
+ headers = new Headers(init ? init == null ? void 0 : init.headers : {});
3246
+ if (req instanceof Headers) {
3247
+ tenantId = req.get(X_NILE_TENANT);
3248
+ cookie = req.get('cookie');
3249
+ if (tenantId) {
3250
+ headers.set(X_NILE_TENANT, tenantId);
3251
+ }
3252
+ if (cookie) {
3253
+ headers.set('cookie', cookie);
3254
+ }
3255
+ } else if (req instanceof Request) {
3256
+ // pass back the X_NILE_TENANT
3257
+ _headers = new Headers(req == null ? void 0 : req.headers);
3258
+ _tenantId = _headers.get(X_NILE_TENANT);
3259
+ _cookie = _headers.get('cookie');
3260
+ if (_tenantId) {
3261
+ headers.set(X_NILE_TENANT, _tenantId);
3262
+ }
3263
+ if (_cookie) {
3264
+ headers.set('cookie', _cookie);
3265
+ }
3266
+ }
3267
+ // default the body - may be the actual payload for the API
3268
+ body = JSON.stringify(req); // comes from next/some server
3269
+ if (!(method === 'GET')) {
3270
+ _context2.next = 7;
3271
+ break;
3272
+ }
3273
+ body = undefined;
3274
+ _context2.next = 14;
3275
+ break;
3276
+ case 7:
3277
+ if (!(req instanceof Request)) {
3278
+ _context2.next = 13;
3279
+ break;
3280
+ }
3281
+ _context2.next = 10;
3282
+ return new Response(req.body).text();
3283
+ case 10:
3284
+ body = _context2.sent;
3285
+ _context2.next = 14;
3286
+ break;
3287
+ case 13:
3288
+ if (
3289
+ // is just headers for a GET request
3290
+ req instanceof Headers || JSON.stringify(req) === '{}' || req && typeof req === 'object' && Object.values(req).length === 0) {
3291
+ body = undefined;
3292
+ }
3293
+ case 14:
3294
+ _init = _extends({}, init, {
3295
+ headers: headers
3296
+ });
3297
+ _context2.next = 17;
3298
+ return this.rawRequest(method, url, _init, body);
3299
+ case 17:
3300
+ return _context2.abrupt("return", _context2.sent);
3301
+ case 18:
3302
+ case "end":
3303
+ return _context2.stop();
3304
+ }
3305
+ }, _callee2, this);
3306
+ }));
3307
+ function request(_x5, _x6, _x7, _x8) {
3308
+ return _request.apply(this, arguments);
3309
+ }
3310
+ return request;
3311
+ }();
3312
+ _proto.post = /*#__PURE__*/function () {
3313
+ var _post = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, url, init) {
3314
+ var response;
3315
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
3316
+ while (1) switch (_context3.prev = _context3.next) {
3317
+ case 0:
3318
+ _context3.next = 2;
3319
+ return this.request('POST', url, req, init);
3320
+ case 2:
3321
+ response = _context3.sent;
3322
+ if (!(response && response.status >= 200 && response.status < 300)) {
3323
+ _context3.next = 5;
3324
+ break;
3325
+ }
3326
+ return _context3.abrupt("return", response.json());
3327
+ case 5:
3328
+ return _context3.abrupt("return", response);
3329
+ case 6:
3330
+ case "end":
3331
+ return _context3.stop();
3332
+ }
3333
+ }, _callee3, this);
3334
+ }));
3335
+ function post(_x9, _x10, _x11) {
3336
+ return _post.apply(this, arguments);
3337
+ }
3338
+ return post;
3339
+ }();
3340
+ _proto.get = /*#__PURE__*/function () {
3341
+ var _get = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(req, url, init) {
3342
+ var response;
3343
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
3344
+ while (1) switch (_context4.prev = _context4.next) {
3345
+ case 0:
3346
+ _context4.next = 2;
3347
+ return this.request('GET', url, req, init);
3348
+ case 2:
3349
+ response = _context4.sent;
3350
+ if (!(response && response.status >= 200 && response.status < 300)) {
3351
+ _context4.next = 5;
3352
+ break;
3353
+ }
3354
+ return _context4.abrupt("return", response.json());
3355
+ case 5:
3356
+ return _context4.abrupt("return", response);
3357
+ case 6:
3358
+ case "end":
3359
+ return _context4.stop();
3360
+ }
3361
+ }, _callee4, this);
3362
+ }));
3363
+ function get(_x12, _x13, _x14) {
3364
+ return _get.apply(this, arguments);
3365
+ }
3366
+ return get;
3367
+ }();
3368
+ _proto.put = /*#__PURE__*/function () {
3369
+ var _put = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(req, url, init) {
3370
+ var response;
3371
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
3372
+ while (1) switch (_context5.prev = _context5.next) {
3373
+ case 0:
3374
+ _context5.next = 2;
3375
+ return this.request('PUT', url, req, init);
3376
+ case 2:
3377
+ response = _context5.sent;
3378
+ if (!(response && response.status >= 200 && response.status < 300)) {
3379
+ _context5.next = 5;
3380
+ break;
3381
+ }
3382
+ return _context5.abrupt("return", response.json());
3383
+ case 5:
3384
+ return _context5.abrupt("return", response);
3385
+ case 6:
3386
+ case "end":
3387
+ return _context5.stop();
3388
+ }
3389
+ }, _callee5, this);
3390
+ }));
3391
+ function put(_x15, _x16, _x17) {
3392
+ return _put.apply(this, arguments);
3393
+ }
3394
+ return put;
3395
+ }();
3396
+ _proto["delete"] = /*#__PURE__*/function () {
3397
+ var _delete2 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(req, url, init) {
3398
+ var response;
3399
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
3400
+ while (1) switch (_context6.prev = _context6.next) {
3401
+ case 0:
3402
+ _context6.next = 2;
3403
+ return this.request('DELETE', url, req, init);
3404
+ case 2:
3405
+ response = _context6.sent;
3406
+ if (!(response && response.status >= 200 && response.status < 300)) {
3407
+ _context6.next = 5;
3408
+ break;
3409
+ }
3410
+ return _context6.abrupt("return", response.json());
3411
+ case 5:
3412
+ return _context6.abrupt("return", response);
3413
+ case 6:
3414
+ case "end":
3415
+ return _context6.stop();
3416
+ }
3417
+ }, _callee6, this);
3418
+ }));
3419
+ function _delete(_x18, _x19, _x20) {
3420
+ return _delete2.apply(this, arguments);
3421
+ }
3422
+ return _delete;
3423
+ }();
3424
+ return Requester;
3425
+ }(Config);
3426
+
3427
+ var Tenants = /*#__PURE__*/function (_Config) {
3428
+ function Tenants(config, headers) {
3429
+ var _this;
3430
+ _this = _Config.call(this, config) || this;
3431
+ _this.headers = void 0;
3432
+ _this.createTenant = /*#__PURE__*/function () {
3433
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, init) {
3434
+ var _req, _requester, _init;
3435
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3436
+ while (1) switch (_context.prev = _context.next) {
3437
+ case 0:
3438
+ if (typeof req === 'string') {
3439
+ _req = new Request("" + _this.api.basePath + _this.tenantsUrl, {
3440
+ body: JSON.stringify({
3441
+ name: req
3442
+ }),
3443
+ method: 'POST'
3444
+ });
3445
+ } else {
3446
+ _req = req;
3447
+ }
3448
+ _requester = new Requester(_this);
3449
+ _init = _this.handleHeaders(init);
3450
+ return _context.abrupt("return", _requester.post(_req, _this.tenantsUrl, _init));
3451
+ case 4:
3452
+ case "end":
3453
+ return _context.stop();
3454
+ }
3455
+ }, _callee);
3456
+ }));
3457
+ return function (_x, _x2) {
3458
+ return _ref.apply(this, arguments);
3459
+ };
3460
+ }();
3461
+ _this.getTenant = /*#__PURE__*/function () {
3462
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(req, init) {
3463
+ var _requester, _init;
3464
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3465
+ while (1) switch (_context2.prev = _context2.next) {
3466
+ case 0:
3467
+ if (typeof req === 'string') {
3468
+ _this.tenantId = req;
3469
+ }
3470
+ _requester = new Requester(_this);
3471
+ _init = _this.handleHeaders(init);
3472
+ return _context2.abrupt("return", _requester.get(req, _this.tenantUrl, _init));
3473
+ case 4:
3474
+ case "end":
3475
+ return _context2.stop();
3476
+ }
3477
+ }, _callee2);
3478
+ }));
3479
+ return function (_x3, _x4) {
3480
+ return _ref2.apply(this, arguments);
3481
+ };
3482
+ }();
3483
+ _this.listTenants = /*#__PURE__*/function () {
3484
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, init) {
3485
+ var _requester, _init;
3486
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
3487
+ while (1) switch (_context3.prev = _context3.next) {
3488
+ case 0:
3489
+ _requester = new Requester(_this);
3490
+ _init = _this.handleHeaders(init);
3491
+ return _context3.abrupt("return", _requester.get(req, _this.tenantListUrl, _init));
3492
+ case 3:
3493
+ case "end":
3494
+ return _context3.stop();
3495
+ }
3496
+ }, _callee3);
3497
+ }));
3498
+ return function (_x5, _x6) {
3499
+ return _ref3.apply(this, arguments);
3500
+ };
3501
+ }();
3502
+ _this.headers = headers;
3503
+ return _this;
3504
+ }
3505
+ _inheritsLoose(Tenants, _Config);
3506
+ var _proto = Tenants.prototype;
3507
+ _proto.handleHeaders = function handleHeaders(init) {
3508
+ if (this.headers) {
3509
+ if (init) {
3510
+ var _init2;
3511
+ init.headers = new Headers(_extends({}, this.headers, (_init2 = init) == null ? void 0 : _init2.headers));
3512
+ return init;
3513
+ } else {
3514
+ init = {
3515
+ headers: this.headers
3516
+ };
3517
+ return init;
3518
+ }
3519
+ }
3520
+ return undefined;
3521
+ };
3522
+ return _createClass(Tenants, [{
3523
+ key: "tenantsUrl",
3524
+ get: function get() {
3525
+ return '/tenants';
3526
+ }
3527
+ }, {
3528
+ key: "tenantUrl",
3529
+ get: function get() {
3530
+ var _this$tenantId;
3531
+ return "/tenants/" + ((_this$tenantId = this.tenantId) != null ? _this$tenantId : '{tenantId}');
3532
+ }
3533
+ }, {
3534
+ key: "tenantListUrl",
3535
+ get: function get() {
3536
+ var _this$userId;
3537
+ return "/users/" + ((_this$userId = this.userId) != null ? _this$userId : '{userId}') + "/tenants";
3538
+ }
3539
+ }]);
3540
+ }(Config);
3541
+
3542
+ var Users = /*#__PURE__*/function (_Config) {
3543
+ function Users(config, headers) {
3544
+ var _this;
3545
+ _this = _Config.call(this, config) || this;
3546
+ _this.headers = void 0;
3547
+ _this.createUser = /*#__PURE__*/function () {
3548
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, init) {
3549
+ var _requester, _init;
3550
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3551
+ while (1) switch (_context.prev = _context.next) {
3552
+ case 0:
3553
+ _requester = new Requester(_this);
3554
+ _init = _this.handleHeaders(init);
3555
+ _context.next = 4;
3556
+ return _requester.post(req, _this.usersUrl, _init);
3557
+ case 4:
3558
+ return _context.abrupt("return", _context.sent);
3559
+ case 5:
3560
+ case "end":
3561
+ return _context.stop();
3562
+ }
3563
+ }, _callee);
3564
+ }));
3565
+ return function (_x, _x2) {
3566
+ return _ref.apply(this, arguments);
3567
+ };
3568
+ }();
3569
+ _this.updateUser = /*#__PURE__*/function () {
3570
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(userId, req, init) {
3571
+ var _requester, _init;
3572
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3573
+ while (1) switch (_context2.prev = _context2.next) {
3574
+ case 0:
3575
+ _requester = new Requester(_this);
3576
+ _init = _this.handleHeaders(init);
3577
+ _context2.next = 4;
3578
+ return _requester.put(req, _this.usersUrl + "/" + userId, _init);
3579
+ case 4:
3580
+ return _context2.abrupt("return", _context2.sent);
3581
+ case 5:
3582
+ case "end":
3583
+ return _context2.stop();
3584
+ }
3585
+ }, _callee2);
3586
+ }));
3587
+ return function (_x3, _x4, _x5) {
3588
+ return _ref2.apply(this, arguments);
3589
+ };
3590
+ }();
3591
+ _this.listUsers = /*#__PURE__*/function () {
3592
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, init) {
3593
+ var _requester, _init;
3594
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
3595
+ while (1) switch (_context3.prev = _context3.next) {
3596
+ case 0:
3597
+ _requester = new Requester(_this);
3598
+ _init = _this.handleHeaders(init);
3599
+ _context3.next = 4;
3600
+ return _requester.get(req, _this.tenantUsersUrl, _init);
3601
+ case 4:
3602
+ return _context3.abrupt("return", _context3.sent);
3603
+ case 5:
3604
+ case "end":
3605
+ return _context3.stop();
3606
+ }
3607
+ }, _callee3);
3608
+ }));
3609
+ return function (_x6, _x7) {
3610
+ return _ref3.apply(this, arguments);
3611
+ };
3612
+ }();
3613
+ _this.linkUser = /*#__PURE__*/function () {
3614
+ var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(req, init) {
3615
+ var _requester, _init;
3616
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
3617
+ while (1) switch (_context4.prev = _context4.next) {
3618
+ case 0:
3619
+ _requester = new Requester(_this);
3620
+ _init = _this.handleHeaders(init);
3621
+ _context4.next = 4;
3622
+ return _requester.put(req, _this.tenantUsersUrl, _init);
3623
+ case 4:
3624
+ return _context4.abrupt("return", _context4.sent);
3625
+ case 5:
3626
+ case "end":
3627
+ return _context4.stop();
3628
+ }
3629
+ }, _callee4);
3630
+ }));
3631
+ return function (_x8, _x9) {
3632
+ return _ref4.apply(this, arguments);
3633
+ };
3634
+ }();
3635
+ _this.tenantUsersDeleteUrl = function (userId) {
3636
+ var _this$tenantId;
3637
+ return "/tenants/" + ((_this$tenantId = _this.tenantId) != null ? _this$tenantId : '{tenantId}') + "/users/" + (userId != null ? userId : '{userId}');
3638
+ };
3639
+ _this.getUserId = /*#__PURE__*/function () {
3640
+ var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(req) {
3641
+ var body;
3642
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
3643
+ while (1) switch (_context5.prev = _context5.next) {
3644
+ case 0:
3645
+ if (!(req instanceof Request)) {
3646
+ _context5.next = 6;
3647
+ break;
3648
+ }
3649
+ _context5.next = 3;
3650
+ return new Response(req == null ? void 0 : req.body).json();
3651
+ case 3:
3652
+ body = _context5.sent;
3653
+ if (!body) {
3654
+ _context5.next = 6;
3655
+ break;
3656
+ }
3657
+ return _context5.abrupt("return", body.id);
3658
+ case 6:
3659
+ if (!('id' in req)) {
3660
+ _context5.next = 8;
3661
+ break;
3662
+ }
3663
+ return _context5.abrupt("return", req.id);
3664
+ case 8:
3665
+ return _context5.abrupt("return", null);
3666
+ case 9:
3667
+ case "end":
3668
+ return _context5.stop();
3669
+ }
3670
+ }, _callee5);
3671
+ }));
3672
+ return function (_x10) {
3673
+ return _ref5.apply(this, arguments);
3674
+ };
3675
+ }();
3676
+ _this.unlinkUser = /*#__PURE__*/function () {
3677
+ var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(req, init) {
3678
+ var _requester, userId, _init;
3679
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
3680
+ while (1) switch (_context6.prev = _context6.next) {
3681
+ case 0:
3682
+ _requester = new Requester(_this);
3683
+ _context6.next = 3;
3684
+ return _this.getUserId(req);
3685
+ case 3:
3686
+ userId = _context6.sent;
3687
+ _init = _this.handleHeaders(init);
3688
+ _context6.next = 7;
3689
+ return _requester["delete"](req, _this.tenantUsersDeleteUrl(userId), _init);
3690
+ case 7:
3691
+ return _context6.abrupt("return", _context6.sent);
3692
+ case 8:
3693
+ case "end":
3694
+ return _context6.stop();
3695
+ }
3696
+ }, _callee6);
3697
+ }));
3698
+ return function (_x11, _x12) {
3699
+ return _ref6.apply(this, arguments);
3700
+ };
3701
+ }();
3702
+ _this.me = /*#__PURE__*/function () {
3703
+ var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(req, init) {
3704
+ var _requester, _init;
3705
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
3706
+ while (1) switch (_context7.prev = _context7.next) {
3707
+ case 0:
3708
+ _requester = new Requester(_this);
3709
+ _init = _this.handleHeaders(init);
3710
+ _context7.next = 4;
3711
+ return _requester.get(req, _this.meUrl, _init);
3712
+ case 4:
3713
+ return _context7.abrupt("return", _context7.sent);
3714
+ case 5:
3715
+ case "end":
3716
+ return _context7.stop();
3717
+ }
3718
+ }, _callee7);
3719
+ }));
3720
+ return function (_x13, _x14) {
3721
+ return _ref7.apply(this, arguments);
3722
+ };
3723
+ }();
3724
+ _this.headers = headers;
3725
+ return _this;
3726
+ }
3727
+ _inheritsLoose(Users, _Config);
3728
+ var _proto = Users.prototype;
3729
+ _proto.handleHeaders = function handleHeaders(init) {
3730
+ if (this.headers) {
3731
+ if (init) {
3732
+ var _init2;
3733
+ init.headers = new Headers(_extends({}, this.headers, (_init2 = init) == null ? void 0 : _init2.headers));
3734
+ return init;
3735
+ } else {
3736
+ init = {
3737
+ headers: this.headers
3738
+ };
3739
+ return init;
3740
+ }
3741
+ }
3742
+ return undefined;
3743
+ };
3744
+ return _createClass(Users, [{
3745
+ key: "usersUrl",
3746
+ get: function get() {
3747
+ return '/users';
3616
3748
  }
3617
- return POST;
3618
- }();
3619
- }
3620
-
3621
- function DELETER(configRoutes, config) {
3622
- return /*#__PURE__*/function () {
3623
- var _DELETE = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3624
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3625
- while (1) switch (_context.prev = _context.next) {
3626
- case 0:
3627
- if (!matches$8(configRoutes, req)) {
3628
- _context.next = 2;
3629
- break;
3630
- }
3631
- return _context.abrupt("return", route$8(req, config));
3632
- case 2:
3633
- if (!matches$7(configRoutes, req)) {
3634
- _context.next = 4;
3635
- break;
3636
- }
3637
- return _context.abrupt("return", route$7(req, config));
3638
- case 4:
3639
- return _context.abrupt("return", new Response(null, {
3640
- status: 404
3641
- }));
3642
- case 5:
3643
- case "end":
3644
- return _context.stop();
3645
- }
3646
- }, _callee);
3647
- }));
3648
- function DELETE(_x) {
3649
- return _DELETE.apply(this, arguments);
3749
+ }, {
3750
+ key: "tenantUsersUrl",
3751
+ get: function get() {
3752
+ var _this$tenantId2;
3753
+ return "/tenants/" + ((_this$tenantId2 = this.tenantId) != null ? _this$tenantId2 : '{tenantId}') + "/users";
3650
3754
  }
3651
- return DELETE;
3652
- }();
3653
- }
3654
-
3655
- function PUTER(configRoutes, config) {
3656
- return /*#__PURE__*/function () {
3657
- var _PUT = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req) {
3658
- return _regeneratorRuntime().wrap(function _callee$(_context) {
3659
- while (1) switch (_context.prev = _context.next) {
3660
- case 0:
3661
- if (!matches$8(configRoutes, req)) {
3662
- _context.next = 2;
3663
- break;
3664
- }
3665
- return _context.abrupt("return", route$8(req, config));
3666
- case 2:
3667
- if (!matches$9(configRoutes, req)) {
3668
- _context.next = 4;
3669
- break;
3670
- }
3671
- return _context.abrupt("return", route$9(req, config));
3672
- case 4:
3673
- if (!matches$7(configRoutes, req)) {
3674
- _context.next = 6;
3675
- break;
3676
- }
3677
- return _context.abrupt("return", route$7(req, config));
3678
- case 6:
3679
- return _context.abrupt("return", new Response(null, {
3680
- status: 404
3681
- }));
3682
- case 7:
3683
- case "end":
3684
- return _context.stop();
3685
- }
3686
- }, _callee);
3687
- }));
3688
- function PUT(_x) {
3689
- return _PUT.apply(this, arguments);
3755
+ }, {
3756
+ key: "meUrl",
3757
+ get: function get() {
3758
+ return '/me';
3690
3759
  }
3691
- return PUT;
3692
- }();
3693
- }
3694
-
3695
- function Handlers(configRoutes, config) {
3696
- var GET = GETTER(configRoutes, config);
3697
- var POST = POSTER(configRoutes, config);
3698
- var DELETE = DELETER(configRoutes, config);
3699
- var PUT = PUTER(configRoutes, config);
3700
- return {
3701
- GET: GET,
3702
- POST: POST,
3703
- DELETE: DELETE,
3704
- PUT: PUT
3705
- };
3706
- }
3760
+ }]);
3761
+ }(Config);
3707
3762
 
3708
3763
  var Api = /*#__PURE__*/function () {
3709
3764
  function Api(config) {
@@ -3747,6 +3802,7 @@ var Api = /*#__PURE__*/function () {
3747
3802
  }
3748
3803
  }]);
3749
3804
  }();
3805
+
3750
3806
  var Server = /*#__PURE__*/function () {
3751
3807
  function Server(config) {
3752
3808
  var _this = this;
@@ -3768,32 +3824,32 @@ var Server = /*#__PURE__*/function () {
3768
3824
  _this.token = token;
3769
3825
  });
3770
3826
  }
3771
- var _proto2 = Server.prototype;
3772
- _proto2.setConfig = function setConfig(cfg) {
3827
+ var _proto = Server.prototype;
3828
+ _proto.setConfig = function setConfig(cfg) {
3773
3829
  this.config = new Config(cfg);
3774
3830
  };
3775
- _proto2.init = /*#__PURE__*/function () {
3776
- var _init = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(cfg) {
3831
+ _proto.init = /*#__PURE__*/function () {
3832
+ var _init = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(cfg) {
3777
3833
  var updatedConfig;
3778
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3779
- while (1) switch (_context2.prev = _context2.next) {
3834
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3835
+ while (1) switch (_context.prev = _context.next) {
3780
3836
  case 0:
3781
- _context2.next = 2;
3837
+ _context.next = 2;
3782
3838
  return this.config.configure(_extends({}, this.config, cfg));
3783
3839
  case 2:
3784
- updatedConfig = _context2.sent;
3840
+ updatedConfig = _context.sent;
3785
3841
  this.setConfig(updatedConfig);
3786
3842
  this.manager.clear(this.config);
3787
3843
  this.manager = new DBManager(this.config);
3788
3844
  this.api = new Api(this.config);
3789
- return _context2.abrupt("return", this);
3845
+ return _context.abrupt("return", this);
3790
3846
  case 8:
3791
3847
  case "end":
3792
- return _context2.stop();
3848
+ return _context.stop();
3793
3849
  }
3794
- }, _callee2, this);
3850
+ }, _callee, this);
3795
3851
  }));
3796
- function init(_x2) {
3852
+ function init(_x) {
3797
3853
  return _init.apply(this, arguments);
3798
3854
  }
3799
3855
  return init;
@@ -3803,7 +3859,7 @@ var Server = /*#__PURE__*/function () {
3803
3859
  * returns the global Server object, an existing server that's already been configured,
3804
3860
  * or a new one if the config isn't in the cache
3805
3861
  */
3806
- _proto2.getInstance = function getInstance(config) {
3862
+ _proto.getInstance = function getInstance(config) {
3807
3863
  var _config = _extends({}, this.config, config);
3808
3864
  var serverId = getServerId(_config);
3809
3865
  var currentServerId = makeServerId(this.config);
@@ -3822,8 +3878,9 @@ var Server = /*#__PURE__*/function () {
3822
3878
  existing.databaseId = updatedConfig.databaseId;
3823
3879
  return existing;
3824
3880
  }
3825
- this.servers.set(serverId, new Server(_config));
3826
- return this.servers.get(serverId);
3881
+ var newServer = new Server(_config);
3882
+ this.servers.set(serverId, newServer);
3883
+ return newServer;
3827
3884
  };
3828
3885
  return _createClass(Server, [{
3829
3886
  key: "databaseId",
@@ -3878,30 +3935,29 @@ var Server = /*#__PURE__*/function () {
3878
3935
  }, {
3879
3936
  key: "db",
3880
3937
  get: function get() {
3881
- // only need to interact with the knex object
3882
3938
  return this.manager.getConnection(this.config);
3883
3939
  }
3884
3940
  }]);
3885
3941
  }();
3886
- function create(_x3) {
3942
+ function create(_x2) {
3887
3943
  return _create.apply(this, arguments);
3888
3944
  }
3889
3945
  function _create() {
3890
- _create = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(config) {
3946
+ _create = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(config) {
3891
3947
  var server;
3892
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
3893
- while (1) switch (_context3.prev = _context3.next) {
3948
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3949
+ while (1) switch (_context2.prev = _context2.next) {
3894
3950
  case 0:
3895
3951
  server = new Server(config);
3896
- _context3.next = 3;
3952
+ _context2.next = 3;
3897
3953
  return server.init();
3898
3954
  case 3:
3899
- return _context3.abrupt("return", _context3.sent);
3955
+ return _context2.abrupt("return", _context2.sent);
3900
3956
  case 4:
3901
3957
  case "end":
3902
- return _context3.stop();
3958
+ return _context2.stop();
3903
3959
  }
3904
- }, _callee3);
3960
+ }, _callee2);
3905
3961
  }));
3906
3962
  return _create.apply(this, arguments);
3907
3963
  }