@niledatabase/server 1.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,9 @@
1
+ import syncFetch from 'sync-fetch';
2
+ import 'dotenv/config';
1
3
  import isEmpty from 'lodash-es/isEmpty';
2
4
  import isObject from 'lodash-es/isObject';
3
5
  import { decodeJwt } from 'jose';
4
- import knex from 'knex';
6
+ import { Pool } from 'pg';
5
7
 
6
8
  function _regeneratorRuntime() {
7
9
  _regeneratorRuntime = function () {
@@ -391,6 +393,18 @@ function _setPrototypeOf(o, p) {
391
393
  };
392
394
  return _setPrototypeOf(o, p);
393
395
  }
396
+ function _objectWithoutPropertiesLoose(source, excluded) {
397
+ if (source == null) return {};
398
+ var target = {};
399
+ var sourceKeys = Object.keys(source);
400
+ var key, i;
401
+ for (i = 0; i < sourceKeys.length; i++) {
402
+ key = sourceKeys[i];
403
+ if (excluded.indexOf(key) >= 0) continue;
404
+ target[key] = source[key];
405
+ }
406
+ return target;
407
+ }
394
408
  function _unsupportedIterableToArray(o, minLen) {
395
409
  if (!o) return;
396
410
  if (typeof o === "string") return _arrayLikeToArray(o, minLen);
@@ -423,6 +437,189 @@ function _createForOfIteratorHelperLoose(o, allowArrayLike) {
423
437
  throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
424
438
  }
425
439
 
440
+ function Logger(config) {
441
+ for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
442
+ params[_key - 1] = arguments[_key];
443
+ }
444
+ return {
445
+ info: function info() {
446
+ if (config != null && config.debug) {
447
+ var _console;
448
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
449
+ args[_key2] = arguments[_key2];
450
+ }
451
+ // eslint-disable-next-line no-console
452
+ (_console = console).info.apply(_console, ['[niledb]'].concat(params, args));
453
+ }
454
+ },
455
+ warn: function warn() {
456
+ if (config != null && config.debug) {
457
+ var _console2;
458
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
459
+ args[_key3] = arguments[_key3];
460
+ }
461
+ // eslint-disable-next-line no-console
462
+ (_console2 = console).warn.apply(_console2, ['[niledb]'].concat(params, args));
463
+ }
464
+ },
465
+ error: function error() {
466
+ if (config != null && config.debug) {
467
+ var _console3;
468
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
469
+ args[_key4] = arguments[_key4];
470
+ }
471
+ // eslint-disable-next-line no-console
472
+ (_console3 = console).error.apply(_console3, ['[niledb]', '[ERROR]'].concat(params, args));
473
+ }
474
+ }
475
+ };
476
+ }
477
+
478
+ var getDatbaseId = function getDatbaseId(cfg) {
479
+ var config = cfg.config,
480
+ logger = cfg.logger;
481
+ var _Logger = Logger(config, '[databaseId]'),
482
+ info = _Logger.info;
483
+ if (config != null && config.databaseId) {
484
+ logger && info(logger, 'config', config.databaseId);
485
+ return String(config == null ? void 0 : config.databaseId);
486
+ }
487
+ logger && info(logger, 'env', process.env.NILEDB_ID);
488
+ return process.env.NILEDB_ID;
489
+ };
490
+ var getUsername = function getUsername(cfg) {
491
+ var config = cfg.config,
492
+ logger = cfg.logger;
493
+ var _Logger2 = Logger(config, '[username]'),
494
+ info = _Logger2.info;
495
+ if (config != null && config.user) {
496
+ logger && info(logger, 'config', config.user);
497
+ return String(config == null ? void 0 : config.user);
498
+ }
499
+ logger && info(logger, '.env', process.env.NILEDB_USER);
500
+ return process.env.NILEDB_USER;
501
+ };
502
+ var getPassword = function getPassword(cfg) {
503
+ var config = cfg.config,
504
+ logger = cfg.logger;
505
+ var log = logProtector(logger);
506
+ var _Logger3 = Logger(config, '[password]'),
507
+ info = _Logger3.info;
508
+ if (config != null && config.password) {
509
+ log && info(logger, 'config', config.password);
510
+ return String(config.password);
511
+ }
512
+ log && info(logger, '.env', process.env.NILEDB_PASSWORD);
513
+ return process.env.NILEDB_PASSWORD;
514
+ };
515
+ var getInfoBearer = function getInfoBearer(cfg) {
516
+ return getUsername(cfg) + ":" + getPassword(cfg);
517
+ };
518
+ var getToken = function getToken(cfg) {
519
+ var _config$api;
520
+ var config = cfg.config,
521
+ logger = cfg.logger;
522
+ var _Logger4 = Logger(config, '[token]'),
523
+ info = _Logger4.info;
524
+ if (config != null && (_config$api = config.api) != null && _config$api.token) {
525
+ var _config$api2, _config$api3;
526
+ logger && info(logger, 'config', (_config$api2 = config.api) == null ? void 0 : _config$api2.token);
527
+ return String((_config$api3 = config.api) == null ? void 0 : _config$api3.token);
528
+ }
529
+ if (process.env.NILEDB_TOKEN) {
530
+ logger && info(logger, '.env', process.env.NILEDB_TOKEN);
531
+ return process.env.NILEDB_TOKEN;
532
+ }
533
+ return undefined;
534
+ };
535
+ var getDatabaseName = function getDatabaseName(cfg) {
536
+ var config = cfg.config,
537
+ logger = cfg.logger;
538
+ var _Logger5 = Logger(config, '[databaseName]'),
539
+ info = _Logger5.info;
540
+ if (config != null && config.databaseName) {
541
+ logger && info(logger, 'config', config.databaseName);
542
+ return String(config.databaseName);
543
+ }
544
+ if (process.env.NILEDB_NAME) {
545
+ logger && info(logger, 'config', process.env.NILEDB_NAME);
546
+ return process.env.NILEDB_NAME;
547
+ }
548
+ return null;
549
+ };
550
+ var getTenantId = function getTenantId(cfg) {
551
+ var config = cfg.config,
552
+ logger = cfg.logger;
553
+ var _Logger6 = Logger(config, '[tenantId]'),
554
+ info = _Logger6.info;
555
+ if (config != null && config.tenantId) {
556
+ logger && info(logger, 'config', config.tenantId);
557
+ return config.tenantId;
558
+ }
559
+ if (process.env.NILEDB_TENANT) {
560
+ logger && info(logger, '.env', process.env.NILEDB_TENANT);
561
+ return process.env.NILEDB_TENANT;
562
+ }
563
+ return null;
564
+ };
565
+ var getBasePath = function getBasePath(cfg) {
566
+ var _config$api4;
567
+ var config = cfg.config,
568
+ logger = cfg.logger;
569
+ var _Logger7 = Logger(config, '[basePath]'),
570
+ info = _Logger7.info;
571
+ var basePath = config == null || (_config$api4 = config.api) == null ? void 0 : _config$api4.basePath;
572
+ if (basePath) {
573
+ var _config$api5;
574
+ logger && info(logger, 'config', config == null || (_config$api5 = config.api) == null ? void 0 : _config$api5.basePath);
575
+ return basePath;
576
+ }
577
+ if (process.env.NILEDB_API) {
578
+ logger && info(logger, '.env', process.env.NILEDB_API);
579
+ return "https://" + process.env.NILEDB_API;
580
+ }
581
+ logger && info(logger, 'default', process.env.NILEDB_API);
582
+ return 'https://api.thenile.dev';
583
+ };
584
+ function getDbHost(cfg) {
585
+ var config = cfg.config,
586
+ logger = cfg.logger;
587
+ var _Logger8 = Logger(config, '[db.host]'),
588
+ info = _Logger8.info;
589
+ if (config != null && config.db && config.db.host) {
590
+ logger && info(logger, 'config', config == null ? void 0 : config.db.host);
591
+ return config.db.host;
592
+ }
593
+ if (process.env.NILEDB_HOST) {
594
+ logger && info(logger, '.env', process.env.NILEDB_HOST);
595
+ return process.env.NILEDB_HOST;
596
+ }
597
+ logger && info(logger, 'default', 'db.thenile.dev');
598
+ return 'db.thenile.dev';
599
+ }
600
+ function getDbPort(cfg) {
601
+ var _config$db;
602
+ var config = cfg.config,
603
+ logger = cfg.logger;
604
+ var _Logger9 = Logger(config, '[db.port]'),
605
+ info = _Logger9.info;
606
+ if (config != null && (_config$db = config.db) != null && _config$db.port && config.db.port != null) {
607
+ var _config$db2;
608
+ logger && info(logger, 'config', config == null ? void 0 : config.db.port);
609
+ return Number((_config$db2 = config.db) == null ? void 0 : _config$db2.port);
610
+ }
611
+ if (process.env.NILEDB_PORT) {
612
+ logger && info(logger, 'config', process.env.NILEDB_PORT);
613
+ return Number(process.env.NILEDB_PORT);
614
+ }
615
+ logger && info(logger, 'default', 5432);
616
+ return 5432;
617
+ }
618
+ // don't let people accidentally log secrets to production
619
+ var logProtector = function logProtector(logger) {
620
+ return process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test' ? logger : null;
621
+ };
622
+
426
623
  var ApiConfig = /*#__PURE__*/function () {
427
624
  function ApiConfig(_ref) {
428
625
  var basePath = _ref.basePath,
@@ -445,39 +642,81 @@ var ApiConfig = /*#__PURE__*/function () {
445
642
  }
446
643
  }]);
447
644
  }();
448
- var niledatabase_url = 'thenile.dev';
449
645
  var Config = /*#__PURE__*/function () {
450
- function Config(_config) {
451
- var _config$api$basePath, _config$api, _config$api$cookieKey, _config$api2, _config$api3, _config$db, _config$db2, _config$db3, _config$db4, _config$db5;
452
- this.database = void 0;
453
- this.workspace = void 0;
646
+ function Config(config, allowPhoneHome) {
647
+ var _config$api$cookieKey, _config$api;
648
+ this.user = void 0;
649
+ this.password = void 0;
650
+ this.databaseId = void 0;
651
+ this.databaseName = void 0;
652
+ this.debug = void 0;
454
653
  this.db = void 0;
455
654
  this.api = void 0;
456
655
  this._tenantId = void 0;
457
656
  this._userId = void 0;
458
- // always provided
459
- this.database = String(_config == null ? void 0 : _config.database);
460
- this.workspace = String(_config == null ? void 0 : _config.workspace);
461
- // set the context
462
- this._tenantId = _config == null ? void 0 : _config.tenantId;
463
- this._userId = _config == null ? void 0 : _config.userId;
464
- // api config
657
+ var _Logger = Logger(config, '[config]'),
658
+ info = _Logger.info,
659
+ error = _Logger.error;
660
+ var envVarConfig = {
661
+ config: config
662
+ };
663
+ if (allowPhoneHome) {
664
+ envVarConfig.logger = '[config]';
665
+ }
666
+ this.databaseId = getDatbaseId(envVarConfig);
667
+ this.user = getUsername(envVarConfig);
668
+ this.password = getPassword(envVarConfig);
669
+ this.databaseName = getDatabaseName(envVarConfig);
670
+ this._tenantId = getTenantId(envVarConfig);
671
+ this.debug = Boolean(config == null ? void 0 : config.debug);
672
+ var basePath = getBasePath(envVarConfig);
673
+ var host = getDbHost(envVarConfig);
674
+ var port = getDbPort(envVarConfig);
675
+ this._userId = config == null ? void 0 : config.userId;
676
+ if (allowPhoneHome && (!host || !this.databaseName || !this.databaseId)) {
677
+ var database = getInfo(config);
678
+ info('[fetched database]', database);
679
+ if (process.env.NODE_ENV !== 'TEST') {
680
+ if ('message' in database) {
681
+ if ('statusCode' in database) {
682
+ error(database);
683
+ throw new Error('HTTP error has occured');
684
+ } else {
685
+ throw new Error('Unable to auto-configure. Please set or remove NILEDB_API, NILEDB_NAME, and NILEDB_HOST in your .env file.');
686
+ }
687
+ }
688
+ if (typeof database === 'object') {
689
+ var apiHost = database.apiHost,
690
+ dbHost = database.dbHost,
691
+ name = database.name,
692
+ id = database.id;
693
+ this.databaseId = id;
694
+ this.databaseName = name;
695
+ // gotta do something dumb here
696
+ var dburl = new URL(dbHost);
697
+ var apiurl = new URL(apiHost);
698
+ host = dburl.host;
699
+ basePath = apiurl.origin;
700
+ }
701
+ }
702
+ }
465
703
  this.api = new ApiConfig({
466
- basePath: (_config$api$basePath = _config == null || (_config$api = _config.api) == null ? void 0 : _config$api.basePath) != null ? _config$api$basePath : "https://api." + niledatabase_url,
467
- cookieKey: (_config$api$cookieKey = _config == null || (_config$api2 = _config.api) == null ? void 0 : _config$api2.cookieKey) != null ? _config$api$cookieKey : 'token',
468
- token: _config == null || (_config$api3 = _config.api) == null ? void 0 : _config$api3.token
704
+ basePath: basePath,
705
+ cookieKey: (_config$api$cookieKey = config == null || (_config$api = config.api) == null ? void 0 : _config$api.cookieKey) != null ? _config$api$cookieKey : 'token',
706
+ token: getToken({
707
+ config: config
708
+ })
469
709
  });
470
- // db config
471
- var host = _config != null && _config.db && _config.db.connection && typeof ((_config$db = _config.db) == null ? void 0 : _config$db.connection) !== 'string' && 'host' in _config.db.connection ? String(_config.db.connection.host) : "db." + niledatabase_url;
472
- var port = _config != null && (_config$db2 = _config.db) != null && _config$db2.connection && typeof ((_config$db3 = _config.db) == null ? void 0 : _config$db3.connection) !== 'string' && 'port' in _config.db.connection ? Number((_config$db4 = _config.db) == null || (_config$db4 = _config$db4.connection) == null ? void 0 : _config$db4.port) : 5432;
473
- var connection = _extends({
710
+ this.db = _extends({
711
+ user: this.user,
712
+ password: this.password,
474
713
  host: host,
475
714
  port: port,
476
- database: _config == null ? void 0 : _config.database
477
- }, typeof (_config == null || (_config$db5 = _config.db) == null ? void 0 : _config$db5.connection) === 'object' ? _config.db.connection : {});
478
- this.db = _extends({}, _config == null ? void 0 : _config.db, {
479
- connection: connection
480
- });
715
+ database: this.databaseName
716
+ }, typeof (config == null ? void 0 : config.db) === 'object' ? config.db : {});
717
+ if (allowPhoneHome) {
718
+ info(this);
719
+ }
481
720
  }
482
721
  return _createClass(Config, [{
483
722
  key: "tenantId",
@@ -497,6 +736,49 @@ var Config = /*#__PURE__*/function () {
497
736
  }
498
737
  }]);
499
738
  }();
739
+ function getInfo(config) {
740
+ var basePath = getBasePath({
741
+ config: config
742
+ });
743
+ var databaseName = getDatabaseName({
744
+ config: config,
745
+ logger: 'getInfo'
746
+ });
747
+ var url = new URL(basePath + "/databases/configure");
748
+ if (databaseName) {
749
+ url.searchParams.set('databaseName', databaseName);
750
+ }
751
+ var _Logger2 = Logger(config, '[getInfo]'),
752
+ info = _Logger2.info,
753
+ error = _Logger2.error;
754
+ info(url.href);
755
+ var res = syncFetch(url, {
756
+ headers: {
757
+ Authorization: "Bearer " + getInfoBearer({
758
+ config: config
759
+ })
760
+ }
761
+ });
762
+ var possibleError = res.clone();
763
+ try {
764
+ var json = res.json();
765
+ if (res.status === 404) {
766
+ info('is the configured databaseName correct?');
767
+ }
768
+ if (json.status && json.status !== 'READY') {
769
+ return {
770
+ message: 'Database is not ready yet'
771
+ };
772
+ }
773
+ return json;
774
+ } catch (e) {
775
+ var message = possibleError.text();
776
+ error(message);
777
+ return {
778
+ message: message
779
+ };
780
+ }
781
+ }
500
782
 
501
783
  var ResponseError = function ResponseError(body, init) {
502
784
  this.response = void 0;
@@ -614,10 +896,11 @@ function _fetch(_x, _x2, _x3) {
614
896
  function _fetch2() {
615
897
  _fetch2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config, path, opts) {
616
898
  var _config$api, _config$api2, _response$status;
617
- var url, cookieKey, headers, basicHeaders, authHeader, _config$api3, token, _config$api4, tenantId, userId, useableUrl, response, res, _res, message, _res2, _res2$errors, _message;
899
+ var _Logger, info, error, url, cookieKey, headers, basicHeaders, authHeader, token, tenantId, userId, useableUrl, response, res, errorHandler, msg, _res, message, _res2, _res2$errors, _message;
618
900
  return _regeneratorRuntime().wrap(function _callee$(_context) {
619
901
  while (1) switch (_context.prev = _context.next) {
620
902
  case 0:
903
+ _Logger = Logger(config, '[server]'), info = _Logger.info, error = _Logger.error;
621
904
  url = "" + ((_config$api = config.api) == null ? void 0 : _config$api.basePath) + path;
622
905
  cookieKey = (_config$api2 = config.api) == null ? void 0 : _config$api2.cookieKey;
623
906
  headers = new Headers(opts == null ? void 0 : opts.headers);
@@ -628,8 +911,12 @@ function _fetch2() {
628
911
  token = getTokenFromCookie(headers, cookieKey);
629
912
  if (token) {
630
913
  basicHeaders.set('Authorization', "Bearer " + token);
631
- } else if ((_config$api3 = config.api) != null && _config$api3.token) {
632
- basicHeaders.set('Authorization', "Bearer " + ((_config$api4 = config.api) == null ? void 0 : _config$api4.token));
914
+ } else if (getToken({
915
+ config: config
916
+ })) {
917
+ basicHeaders.set('Authorization', "Bearer " + getToken({
918
+ config: config
919
+ }));
633
920
  }
634
921
  }
635
922
  tenantId = getTenantFromHttp(headers, config);
@@ -637,66 +924,105 @@ function _fetch2() {
637
924
  userId = getUserFromHttp(headers, config);
638
925
  updateUserId(userId);
639
926
  if (!(url.includes('{tenantId}') && !tenantId)) {
640
- _context.next = 13;
927
+ _context.next = 14;
641
928
  break;
642
929
  }
643
930
  return _context.abrupt("return", new ResponseError('tenantId is not set for request', {
644
931
  status: 400
645
932
  }));
646
- case 13:
933
+ case 14:
647
934
  useableUrl = url.replace('{tenantId}', encodeURIComponent(String(tenantId))).replace('{userId}', encodeURIComponent(String(userId)));
648
- _context.next = 16;
935
+ info('[fetch]', useableUrl);
936
+ _context.next = 18;
649
937
  return fetch(useableUrl, _extends({}, opts, {
650
938
  headers: basicHeaders
651
939
  }))["catch"](function (e) {
652
- // eslint-disable-next-line no-console
653
- console.log(e);
940
+ error('[fetch]', '[response]', e);
654
941
  });
655
- case 16:
942
+ case 18:
656
943
  response = _context.sent;
657
944
  if (!(response && response.status >= 200 && response.status < 300)) {
658
- _context.next = 19;
945
+ _context.next = 27;
946
+ break;
947
+ }
948
+ if (!(typeof response.clone === 'function')) {
949
+ _context.next = 26;
659
950
  break;
660
951
  }
952
+ _context.t0 = info;
953
+ _context.next = 24;
954
+ return response.clone().json();
955
+ case 24:
956
+ _context.t1 = _context.sent;
957
+ (0, _context.t0)('[fetch]', '[response]', _context.t1);
958
+ case 26:
661
959
  return _context.abrupt("return", response);
662
- case 19:
663
- _context.prev = 19;
664
- _context.next = 22;
960
+ case 27:
961
+ errorHandler = typeof (response == null ? void 0 : response.clone) === 'function' ? response.clone() : null;
962
+ msg = '';
963
+ _context.prev = 29;
964
+ _context.next = 32;
665
965
  return response == null ? void 0 : response.json();
666
- case 22:
966
+ case 32:
667
967
  res = _context.sent;
668
- _context.next = 27;
968
+ _context.next = 43;
669
969
  break;
670
- case 25:
671
- _context.prev = 25;
672
- _context.t0 = _context["catch"](19);
673
- case 27:
970
+ case 35:
971
+ _context.prev = 35;
972
+ _context.t2 = _context["catch"](29);
973
+ if (!errorHandler) {
974
+ _context.next = 42;
975
+ break;
976
+ }
977
+ _context.next = 40;
978
+ return errorHandler.text();
979
+ case 40:
980
+ msg = _context.sent;
981
+ if (msg) {
982
+ error('[fetch]', '[response]', "[status: " + errorHandler.status + "]", msg);
983
+ }
984
+ case 42:
985
+ if (!msg) {
986
+ error('[fetch]', '[response]', _context.t2);
987
+ }
988
+ case 43:
989
+ if (!msg) {
990
+ _context.next = 45;
991
+ break;
992
+ }
993
+ return _context.abrupt("return", new ResponseError(msg, {
994
+ status: errorHandler == null ? void 0 : errorHandler.status
995
+ }));
996
+ case 45:
674
997
  if (!(res && 'message' in res)) {
675
- _context.next = 30;
998
+ _context.next = 49;
676
999
  break;
677
1000
  }
678
1001
  _res = res, message = _res.message;
1002
+ error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", message);
679
1003
  return _context.abrupt("return", new ResponseError(message, {
680
1004
  status: 400
681
1005
  }));
682
- case 30:
1006
+ case 49:
683
1007
  if (!(res && 'errors' in res)) {
684
- _context.next = 33;
1008
+ _context.next = 53;
685
1009
  break;
686
1010
  }
687
1011
  _res2 = res, _res2$errors = _res2.errors, _message = _res2$errors[0];
1012
+ error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", _message);
688
1013
  return _context.abrupt("return", new ResponseError(_message, {
689
1014
  status: 400
690
1015
  }));
691
- case 33:
1016
+ case 53:
1017
+ error('[fetch]', '[response]', "[status: " + (errorHandler == null ? void 0 : errorHandler.status) + "]", 'UNHANDLED ERROR');
692
1018
  return _context.abrupt("return", new ResponseError(null, {
693
1019
  status: (_response$status = response == null ? void 0 : response.status) != null ? _response$status : 500
694
1020
  }));
695
- case 34:
1021
+ case 55:
696
1022
  case "end":
697
1023
  return _context.stop();
698
1024
  }
699
- }, _callee, null, [[19, 25]]);
1025
+ }, _callee, null, [[29, 35]]);
700
1026
  }));
701
1027
  return _fetch2.apply(this, arguments);
702
1028
  }
@@ -1040,7 +1366,7 @@ var Auth = /*#__PURE__*/function (_Config) {
1040
1366
  };
1041
1367
  _this.loginSSOUrl = function (provider) {
1042
1368
  var _this$tenantId;
1043
- return "/workspaces/" + encodeURIComponent(_this.workspace) + "/databases/" + encodeURIComponent(_this.database) + "/tenants/" + ((_this$tenantId = _this.tenantId) != null ? _this$tenantId : '{tenantId}') + "/auth/oidc/providers/" + provider + "/login";
1369
+ return "/databases/" + encodeURIComponent(_this.databaseId) + "/tenants/" + ((_this$tenantId = _this.tenantId) != null ? _this$tenantId : '{tenantId}') + "/auth/oidc/providers/" + provider + "/login";
1044
1370
  };
1045
1371
  _this.signUp = /*#__PURE__*/function () {
1046
1372
  var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(req, init) {
@@ -1192,32 +1518,32 @@ var Auth = /*#__PURE__*/function (_Config) {
1192
1518
  } else if (param instanceof Headers) {
1193
1519
  tenantId = getTenantFromHttp(param, _this);
1194
1520
  }
1195
- return _this.api.basePath + "/workspaces/" + _this.workspace + "/databases/" + _this.database + "/tenants/" + tenantId + "/auth/oidc/callback";
1521
+ return "/databases/" + _this.databaseId + "/tenants/" + tenantId + "/auth/oidc/callback";
1196
1522
  };
1197
1523
  return _this;
1198
1524
  }
1199
1525
  _inheritsLoose(Auth, _Config);
1200
1526
  var _proto = Auth.prototype;
1201
1527
  _proto.updateProviderUrl = function updateProviderUrl(providerName) {
1202
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/tenants/" + (this.tenantId ? encodeURIComponent(this.tenantId) : '{tenantId}') + "/auth/oidc/providers/" + encodeURIComponent(providerName);
1528
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants/" + (this.tenantId ? encodeURIComponent(this.tenantId) : '{tenantId}') + "/auth/oidc/providers/" + encodeURIComponent(providerName);
1203
1529
  };
1204
1530
  _proto.providerUrl = function providerUrl(email) {
1205
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/tenants/auth/oidc/providers" + (email ? "?email=" + encodeURIComponent(email) : '');
1531
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants/auth/oidc/providers" + (email ? "?email=" + encodeURIComponent(email) : '');
1206
1532
  };
1207
1533
  return _createClass(Auth, [{
1208
1534
  key: "loginUrl",
1209
1535
  get: function get() {
1210
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/users/login";
1536
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/users/login";
1211
1537
  }
1212
1538
  }, {
1213
1539
  key: "signUpUrl",
1214
1540
  get: function get() {
1215
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/users";
1541
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/users";
1216
1542
  }
1217
1543
  }, {
1218
1544
  key: "listTenantProvidersUrl",
1219
1545
  get: function get() {
1220
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/tenants/" + (this.tenantId ? encodeURIComponent(this.tenantId) : '{tenantId}') + "/auth/oidc/providers";
1546
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants/" + (this.tenantId ? encodeURIComponent(this.tenantId) : '{tenantId}') + "/auth/oidc/providers";
1221
1547
  }
1222
1548
  }]);
1223
1549
  }(Config);
@@ -1337,7 +1663,7 @@ var Users = /*#__PURE__*/function (_Config) {
1337
1663
  return _createClass(Users, [{
1338
1664
  key: "baseUrl",
1339
1665
  get: function get() {
1340
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database);
1666
+ return "/databases/" + encodeURIComponent(this.databaseId);
1341
1667
  }
1342
1668
  }, {
1343
1669
  key: "usersUrl",
@@ -1353,7 +1679,7 @@ var Users = /*#__PURE__*/function (_Config) {
1353
1679
  }, {
1354
1680
  key: "meUrl",
1355
1681
  get: function get() {
1356
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/users/me";
1682
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/users/me";
1357
1683
  }
1358
1684
  }]);
1359
1685
  }(Config);
@@ -1404,66 +1730,87 @@ var Tenants = /*#__PURE__*/function (_Config) {
1404
1730
  return _createClass(Tenants, [{
1405
1731
  key: "tenantsUrl",
1406
1732
  get: function get() {
1407
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/tenants";
1733
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants";
1408
1734
  }
1409
1735
  }, {
1410
1736
  key: "tenantUrl",
1411
1737
  get: function get() {
1412
1738
  var _this$tenantId;
1413
- return "/workspaces/" + encodeURIComponent(this.workspace) + "/databases/" + encodeURIComponent(this.database) + "/tenants/" + ((_this$tenantId = this.tenantId) != null ? _this$tenantId : '{tenantId}');
1739
+ return "/databases/" + encodeURIComponent(this.databaseId) + "/tenants/" + ((_this$tenantId = this.tenantId) != null ? _this$tenantId : '{tenantId}');
1414
1740
  }
1415
1741
  }]);
1416
1742
  }(Config);
1417
1743
 
1744
+ var _excluded = ["afterCreate"];
1418
1745
  var NileDatabase = /*#__PURE__*/function () {
1419
1746
  function NileDatabase(config, id) {
1420
- var _config$db$connection,
1421
- _config$db$connection2,
1422
- _config$db$pool,
1423
- _this = this;
1424
- this.knex = void 0;
1747
+ var _this = this;
1748
+ this.pool = void 0;
1425
1749
  this.tenantId = void 0;
1426
1750
  this.userId = void 0;
1427
1751
  this.id = void 0;
1428
1752
  this.config = void 0;
1429
1753
  this.timer = void 0;
1754
+ var _Logger = Logger(config, '[NileInstance]'),
1755
+ warn = _Logger.warn,
1756
+ info = _Logger.info;
1430
1757
  this.id = id;
1431
1758
  var poolConfig = _extends({
1432
1759
  min: 0,
1433
1760
  max: 10,
1434
1761
  idleTimeoutMillis: 30000
1435
- }, config.db.pool);
1436
- var database = (_config$db$connection = (_config$db$connection2 = config.db.connection) == null ? void 0 : _config$db$connection2.database) != null ? _config$db$connection : config.database;
1437
- this.config = _extends({}, config, {
1438
- db: _extends({}, config.db, {
1439
- connection: _extends({}, config.db.connection, {
1440
- database: database
1441
- }),
1442
- pool: poolConfig
1443
- })
1444
- });
1445
- this.knex = knex(_extends({}, this.config.db, {
1446
- client: 'pg'
1447
- }));
1448
- if ((_config$db$pool = config.db.pool) != null && _config$db$pool.afterCreate) {
1449
- console.log('Providing an pool configuration will stop automatic tenant context setting.');
1450
- } else {
1451
- var afterCreate = makeAfterCreate(config);
1452
- poolConfig.afterCreate = afterCreate;
1762
+ }, config.db);
1763
+ var afterCreate = poolConfig.afterCreate,
1764
+ remaining = _objectWithoutPropertiesLoose(poolConfig, _excluded);
1765
+ config.db = poolConfig;
1766
+ this.config = config;
1767
+ info(this.config);
1768
+ this.pool = new Pool(remaining);
1769
+ if (typeof afterCreate === 'function') {
1770
+ warn('Providing an pool configuration will stop automatic tenant context setting.');
1453
1771
  }
1454
1772
  // start the timer for cleanup
1455
1773
  this.startTimeout();
1456
- this.knex.on('query', /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
1457
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1458
- while (1) switch (_context.prev = _context.next) {
1459
- case 0:
1460
- _this.startTimeout();
1461
- case 1:
1462
- case "end":
1463
- return _context.stop();
1464
- }
1465
- }, _callee);
1466
- })));
1774
+ this.pool.on('connect', /*#__PURE__*/function () {
1775
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(client) {
1776
+ var afterCreate;
1777
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1778
+ while (1) switch (_context.prev = _context.next) {
1779
+ case 0:
1780
+ info('pool connected');
1781
+ afterCreate = makeAfterCreate(config);
1782
+ afterCreate(client, function (err, _client) {
1783
+ if (err) {
1784
+ _client.release();
1785
+ }
1786
+ });
1787
+ _this.startTimeout();
1788
+ case 4:
1789
+ case "end":
1790
+ return _context.stop();
1791
+ }
1792
+ }, _callee);
1793
+ }));
1794
+ return function (_x) {
1795
+ return _ref.apply(this, arguments);
1796
+ };
1797
+ }());
1798
+ this.pool.on('error', /*#__PURE__*/function () {
1799
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(e) {
1800
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1801
+ while (1) switch (_context2.prev = _context2.next) {
1802
+ case 0:
1803
+ info('pool failed', e);
1804
+ case 1:
1805
+ case "end":
1806
+ return _context2.stop();
1807
+ }
1808
+ }, _callee2);
1809
+ }));
1810
+ return function (_x2) {
1811
+ return _ref2.apply(this, arguments);
1812
+ };
1813
+ }());
1467
1814
  }
1468
1815
  var _proto = NileDatabase.prototype;
1469
1816
  _proto.startTimeout = function startTimeout() {
@@ -1471,43 +1818,48 @@ var NileDatabase = /*#__PURE__*/function () {
1471
1818
  if (this.timer) {
1472
1819
  clearTimeout(this.timer);
1473
1820
  }
1474
- this.timer = setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
1475
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1476
- while (1) switch (_context2.prev = _context2.next) {
1821
+ this.timer = setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
1822
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1823
+ while (1) switch (_context3.prev = _context3.next) {
1477
1824
  case 0:
1478
- _context2.next = 2;
1479
- return _this2.knex.client.pool.destroy();
1825
+ _context3.next = 2;
1826
+ return _this2.pool.end();
1480
1827
  case 2:
1481
- _context2.next = 4;
1482
- return _this2.knex.destroy();
1483
- case 4:
1484
1828
  evictPool(_this2.id);
1485
- case 5:
1829
+ case 3:
1486
1830
  case "end":
1487
- return _context2.stop();
1831
+ return _context3.stop();
1488
1832
  }
1489
- }, _callee2);
1490
- })), this.config.db.pool.idleTimeoutMillis);
1833
+ }, _callee3);
1834
+ })), this.config.db.idleTimeoutMillis);
1491
1835
  };
1492
1836
  return NileDatabase;
1493
1837
  }();
1494
1838
  function makeAfterCreate(config) {
1839
+ var _Logger2 = Logger(config, '[afterCreate]'),
1840
+ warn = _Logger2.warn,
1841
+ info = _Logger2.info;
1495
1842
  return function (conn, done) {
1496
1843
  conn.on('error', function errorHandler(error) {
1497
- console.log('Connection was terminated by server', error);
1844
+ warn('Connection was terminated by server', error);
1498
1845
  done(error, conn);
1499
1846
  });
1500
1847
  if (config.tenantId) {
1501
1848
  var query = ["SET nile.tenant_id = '" + config.tenantId + "'"];
1502
1849
  if (config.userId) {
1503
1850
  if (!config.tenantId) {
1504
- console.warn('A user id cannot be set in context without a tenant id');
1851
+ warn('A user id cannot be set in context without a tenant id');
1505
1852
  }
1506
1853
  query.push("SET nile.user_id = '" + config.userId + "'");
1507
1854
  }
1508
1855
  // in this example we use pg driver's connection API
1509
1856
  conn.query(query.join(';'), function (err) {
1510
- console.log('tenant id and user id set', config.userId, config.tenantId);
1857
+ if (config.tenantId) {
1858
+ info('[tenant id]', config.tenantId);
1859
+ }
1860
+ if (config.userId) {
1861
+ info('[user id]', config.userId);
1862
+ }
1511
1863
  done(err, conn);
1512
1864
  });
1513
1865
  }
@@ -1519,9 +1871,12 @@ var DBManager = /*#__PURE__*/function () {
1519
1871
  function DBManager(config) {
1520
1872
  var _this = this;
1521
1873
  this.connections = void 0;
1874
+ var _Logger = Logger(config, '[DBManager]'),
1875
+ info = _Logger.info;
1522
1876
  this.connections = new Map();
1523
1877
  // add the base one, so you can at least query
1524
1878
  var id = this.makeId();
1879
+ info('constructor', id);
1525
1880
  this.connections.set(id, new NileDatabase(new Config(config), id));
1526
1881
  watchEvictPool(function (id) {
1527
1882
  if (id && _this.connections.has(id)) {
@@ -1540,13 +1895,20 @@ var DBManager = /*#__PURE__*/function () {
1540
1895
  return 'base';
1541
1896
  };
1542
1897
  _proto.getConnection = function getConnection(config) {
1898
+ var _Logger2 = Logger(config, '[DBManager]'),
1899
+ info = _Logger2.info;
1543
1900
  var id = this.makeId(config.tenantId, config.userId);
1544
1901
  var existing = this.connections.get(id);
1902
+ info('# of instances:', this.connections.size);
1545
1903
  if (existing) {
1546
- return existing;
1904
+ info('returning existing', id);
1905
+ return existing.pool;
1547
1906
  }
1548
- this.connections.set(id, new NileDatabase(new Config(config), id));
1549
- return this.connections.get(id);
1907
+ var newOne = new NileDatabase(new Config(config), id);
1908
+ this.connections.set(id, newOne);
1909
+ info('created new', id);
1910
+ info('# of instances:', this.connections.size);
1911
+ return newOne.pool;
1550
1912
  };
1551
1913
  return DBManager;
1552
1914
  }();
@@ -1576,7 +1938,7 @@ var Server = /*#__PURE__*/function () {
1576
1938
  this.api = void 0;
1577
1939
  this.manager = void 0;
1578
1940
  this.servers = void 0;
1579
- this.config = new Config(config);
1941
+ this.config = new Config(config, true);
1580
1942
  this.servers = new Map();
1581
1943
  var _init = init(this.config),
1582
1944
  api = _init[0];
@@ -1594,7 +1956,7 @@ var Server = /*#__PURE__*/function () {
1594
1956
  }
1595
1957
  var _proto = Server.prototype;
1596
1958
  _proto.setConfig = function setConfig(cfg) {
1597
- this.config = new Config(cfg);
1959
+ this.config = new Config(cfg, false);
1598
1960
  };
1599
1961
  /**
1600
1962
  * A utility function if you want to manage different NileDB instances yourself
@@ -1611,38 +1973,26 @@ var Server = /*#__PURE__*/function () {
1611
1973
  var existing = this.servers.get(serverId);
1612
1974
  if (existing) {
1613
1975
  // be sure the config is up to date
1614
- var updatedConfig = new Config(_config);
1976
+ var updatedConfig = new Config(_config, false);
1615
1977
  existing.setConfig(updatedConfig);
1616
1978
  // propagage special config items
1617
1979
  existing.tenantId = updatedConfig.tenantId;
1618
1980
  existing.userId = updatedConfig.userId;
1619
1981
  existing.token = updatedConfig.api.token;
1620
- existing.workspace = updatedConfig.workspace;
1621
- existing.database = updatedConfig.database;
1982
+ existing.databaseId = updatedConfig.databaseId;
1622
1983
  return existing;
1623
1984
  }
1624
1985
  this.servers.set(serverId, new Server(_config));
1625
1986
  return this.servers.get(serverId);
1626
1987
  };
1627
1988
  return _createClass(Server, [{
1628
- key: "database",
1629
- set: function set(val) {
1630
- if (val) {
1631
- this.config.database = val;
1632
- this.config.db.connection.database = val;
1633
- this.api.auth.database = val;
1634
- this.api.users.database = val;
1635
- this.api.tenants.database = val;
1636
- }
1637
- }
1638
- }, {
1639
- key: "workspace",
1989
+ key: "databaseId",
1640
1990
  set: function set(val) {
1641
1991
  if (val) {
1642
- this.config.workspace = val;
1643
- this.api.auth.workspace = val;
1644
- this.api.users.workspace = val;
1645
- this.api.tenants.workspace = val;
1992
+ this.config.databaseId = val;
1993
+ this.api.auth.databaseId = val;
1994
+ this.api.users.databaseId = val;
1995
+ this.api.tenants.databaseId = val;
1646
1996
  }
1647
1997
  }
1648
1998
  }, {
@@ -1651,7 +2001,7 @@ var Server = /*#__PURE__*/function () {
1651
2001
  return this.config.userId;
1652
2002
  },
1653
2003
  set: function set(userId) {
1654
- this.database = this.config.database;
2004
+ this.databaseId = this.config.databaseId;
1655
2005
  this.config.userId = userId;
1656
2006
  if (this.api) {
1657
2007
  this.api.auth.userId = this.config.userId;
@@ -1665,7 +2015,7 @@ var Server = /*#__PURE__*/function () {
1665
2015
  return this.config.tenantId;
1666
2016
  },
1667
2017
  set: function set(tenantId) {
1668
- this.database = this.config.database;
2018
+ this.databaseId = this.config.databaseId;
1669
2019
  this.config.tenantId = tenantId;
1670
2020
  if (this.api) {
1671
2021
  this.api.auth.tenantId = tenantId;
@@ -1693,14 +2043,13 @@ var Server = /*#__PURE__*/function () {
1693
2043
  key: "db",
1694
2044
  get: function get() {
1695
2045
  // only need to interact with the knex object
1696
- //@ts-expect-error - because that's where it is in the proxy
1697
- return this.manager.getConnection(this.config).knex;
2046
+ return this.manager.getConnection(this.config);
1698
2047
  }
1699
2048
  }]);
1700
2049
  }(); // export default Server;
1701
2050
  function Nile(config) {
1702
2051
  var server = new Server(config);
1703
- server.setConfig(new Config(config));
2052
+ // server.setConfig(new Config(config as ServerConfig, false));
1704
2053
  return server;
1705
2054
  }
1706
2055