@carbonorm/carbonnode 3.5.9 → 3.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/api/orm/builders/ConditionBuilder.d.ts +1 -0
  2. package/dist/index.cjs.js +1252 -1002
  3. package/dist/index.cjs.js.map +1 -1
  4. package/dist/index.esm.js +1254 -1004
  5. package/dist/index.esm.js.map +1 -1
  6. package/package.json +2 -5
  7. package/scripts/generateRestBindings.cjs +1 -1
  8. package/scripts/generateRestBindings.ts +1 -1
  9. package/src/api/convertForRequestBody.ts +1 -7
  10. package/src/api/executors/HttpExecutor.ts +1 -3
  11. package/src/api/executors/SqlExecutor.ts +2 -1
  12. package/src/api/orm/builders/ConditionBuilder.ts +20 -9
  13. package/src/api/orm/queries/DeleteQueryBuilder.ts +1 -0
  14. package/src/api/orm/queries/PostQueryBuilder.ts +1 -0
  15. package/src/api/orm/queries/SelectQueryBuilder.ts +1 -0
  16. package/src/api/orm/queries/UpdateQueryBuilder.ts +1 -0
  17. package/dist/api/builders/queryHelpers.d.ts +0 -4
  18. package/dist/api/builders/sqlBuilder.d.ts +0 -33
  19. package/dist/api/carbonSqlExecutor.d.ts +0 -17
  20. package/dist/api/interfaces/ormInterfaces.d.ts +0 -87
  21. package/dist/api/orm/SqlBuilder.d.ts +0 -17
  22. package/dist/api/rest/Blog_Categories.d.ts +0 -37
  23. package/dist/api/rest/Blog_Categories.test.d.ts +0 -11
  24. package/dist/api/rest/Blog_Images.d.ts +0 -37
  25. package/dist/api/rest/Blog_Images.test.d.ts +0 -15
  26. package/dist/api/rest/Blog_Post_Categories.d.ts +0 -37
  27. package/dist/api/rest/Blog_Post_Categories.test.d.ts +0 -13
  28. package/dist/api/rest/Blog_Post_Tags.d.ts +0 -37
  29. package/dist/api/rest/Blog_Post_Tags.test.d.ts +0 -13
  30. package/dist/api/rest/Blog_Posts.d.ts +0 -37
  31. package/dist/api/rest/Blog_Posts.test.d.ts +0 -21
  32. package/dist/api/rest/Blog_Tags.d.ts +0 -37
  33. package/dist/api/rest/Blog_Tags.test.d.ts +0 -11
  34. package/dist/api/rest/C6.d.ts +0 -1000
  35. package/dist/api/rest/Cache.d.ts +0 -37
  36. package/dist/api/rest/Cache.test.d.ts +0 -12
  37. package/dist/api/rest/Cities.d.ts +0 -37
  38. package/dist/api/rest/Cities.test.d.ts +0 -17
  39. package/dist/api/rest/Counties.d.ts +0 -37
  40. package/dist/api/rest/Counties.test.d.ts +0 -18
  41. package/dist/api/rest/Countries.d.ts +0 -37
  42. package/dist/api/rest/Countries.test.d.ts +0 -24
  43. package/dist/api/rest/Geometries.d.ts +0 -37
  44. package/dist/api/rest/Geometries.test.d.ts +0 -16
  45. package/dist/api/rest/Images.d.ts +0 -37
  46. package/dist/api/rest/Images.test.d.ts +0 -16
  47. package/dist/api/rest/Land_Section_Info.d.ts +0 -37
  48. package/dist/api/rest/Land_Section_Info.test.d.ts +0 -15
  49. package/dist/api/rest/Neighborhoods.d.ts +0 -37
  50. package/dist/api/rest/Neighborhoods.test.d.ts +0 -12
  51. package/dist/api/rest/Parcel_Building_Details.d.ts +0 -37
  52. package/dist/api/rest/Parcel_Building_Details.test.d.ts +0 -40
  53. package/dist/api/rest/Parcel_Neighborhoods.d.ts +0 -37
  54. package/dist/api/rest/Parcel_Neighborhoods.test.d.ts +0 -15
  55. package/dist/api/rest/Parcel_Owners.d.ts +0 -37
  56. package/dist/api/rest/Parcel_Owners.test.d.ts +0 -23
  57. package/dist/api/rest/Parcel_Sales.d.ts +0 -37
  58. package/dist/api/rest/Parcel_Sales.test.d.ts +0 -19
  59. package/dist/api/rest/Parcel_Tax_History.d.ts +0 -37
  60. package/dist/api/rest/Parcel_Tax_History.test.d.ts +0 -24
  61. package/dist/api/rest/Parcels.d.ts +0 -37
  62. package/dist/api/rest/Parcels.test.d.ts +0 -42
  63. package/dist/api/rest/Payment_Charge_Logs.d.ts +0 -37
  64. package/dist/api/rest/Payment_Charge_Logs.test.d.ts +0 -17
  65. package/dist/api/rest/Payment_Subscriptions.d.ts +0 -37
  66. package/dist/api/rest/Payment_Subscriptions.test.d.ts +0 -20
  67. package/dist/api/rest/Property_Units.d.ts +0 -37
  68. package/dist/api/rest/Property_Units.test.d.ts +0 -55
  69. package/dist/api/rest/Sources.d.ts +0 -37
  70. package/dist/api/rest/Sources.test.d.ts +0 -17
  71. package/dist/api/rest/States.d.ts +0 -37
  72. package/dist/api/rest/States.test.d.ts +0 -20
  73. package/dist/api/rest/Tax_Districts.d.ts +0 -37
  74. package/dist/api/rest/Tax_Districts.test.d.ts +0 -12
  75. package/dist/api/rest/Users.d.ts +0 -37
  76. package/dist/api/rest/Users.test.d.ts +0 -14
  77. package/dist/api/rest/Valuation_Reports.d.ts +0 -37
  78. package/dist/api/rest/Valuation_Reports.test.d.ts +0 -36
  79. package/dist/api/rest/Zip_Codes.d.ts +0 -37
  80. package/dist/api/rest/Zip_Codes.test.d.ts +0 -15
package/dist/index.esm.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import axios from 'axios';
2
2
  import Qs from 'qs';
3
+ import { __assign, __awaiter, __generator, __extends, __spreadArray } from 'tslib';
3
4
  import { toast } from 'react-toastify';
4
5
  import namedPlaceholders from 'named-placeholders';
5
6
  import { Buffer as Buffer$1 } from 'buffer';
6
7
 
7
- const C6Constants = {
8
+ var C6Constants = {
8
9
  // try to 1=1 match the Rest abstract class
9
10
  ADDDATE: 'ADDDATE',
10
11
  ADDTIME: 'ADDTIME',
@@ -162,7 +163,7 @@ const C6Constants = {
162
163
  FINISH: 'FINISH',
163
164
  VALIDATE_C6_ENTITY_ID_REGEX: '#^([a-fA-F0-9]{20,35})$#',
164
165
  };
165
- const C6C = C6Constants;
166
+ var C6C = C6Constants;
166
167
 
167
168
  // @link https://www.npmjs.com/package/axios-cache-adapter
168
169
  // updating these values
@@ -267,100 +268,109 @@ var axiosInstance = (axios.create({
267
268
  */
268
269
  }));
269
270
 
270
- function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler = alert) {
271
- const payload = {};
272
- const tableNames = Array.isArray(tableName) ? tableName : [tableName];
273
- const tableDefinitions = tableNames.map((name) => {
274
- const tableDefinition = Object.values(C6.TABLES).find((t) => t.TABLE_NAME === name);
271
+ function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler) {
272
+ if (regexErrorHandler === void 0) { regexErrorHandler = alert; }
273
+ var payload = {};
274
+ var tableNames = Array.isArray(tableName) ? tableName : [tableName];
275
+ var tableDefinitions = tableNames.map(function (name) {
276
+ var tableDefinition = Object.values(C6.TABLES).find(function (t) { return t.TABLE_NAME === name; });
275
277
  if (!tableDefinition) {
276
- console.error(`Table name (${name}) is not found in the C6.TABLES object.`, C6.TABLES);
277
- throw new Error(`Table name (${name}) is not found in the C6.TABLES object.`);
278
+ console.error("Table name (".concat(name, ") is not found in the C6.TABLES object."), C6.TABLES);
279
+ throw new Error("Table name (".concat(name, ") is not found in the C6.TABLES object."));
278
280
  }
279
281
  return tableDefinition;
280
282
  });
281
- for (const tableDefinition of tableDefinitions) {
282
- for (const value of Object.keys(restfulObject)) {
283
- const shortReference = value.toUpperCase();
283
+ for (var _i = 0, tableDefinitions_1 = tableDefinitions; _i < tableDefinitions_1.length; _i++) {
284
+ var tableDefinition = tableDefinitions_1[_i];
285
+ var _loop_1 = function (value) {
286
+ var shortReference = value.toUpperCase();
284
287
  if ([
285
288
  C6Constants.GET,
286
- C6Constants.SELECT,
287
- C6Constants.INSERT,
288
289
  C6Constants.POST,
289
290
  C6Constants.UPDATE,
290
- C6Constants.PUT,
291
291
  C6Constants.REPLACE,
292
292
  C6Constants.DELETE,
293
293
  C6Constants.WHERE,
294
294
  C6Constants.JOIN,
295
295
  C6Constants.PAGINATION
296
296
  ].includes(value)) {
297
- // TODO - pretty sure we could validate this better on the FED
298
- const val = restfulObject[value];
299
- if (Array.isArray(val)) {
300
- payload[value] = val.sort();
297
+ var val_1 = restfulObject[value];
298
+ if (Array.isArray(val_1)) {
299
+ payload[value] = val_1.sort();
301
300
  }
302
- else if (typeof val === 'object' && val !== null) {
303
- payload[value] = Object.keys(val)
301
+ else if (typeof val_1 === 'object' && val_1 !== null) {
302
+ payload[value] = Object.keys(val_1)
304
303
  .sort()
305
- .reduce((acc, key) => ({ ...acc, [key]: val[key] }), {});
304
+ .reduce(function (acc, key) {
305
+ var _a;
306
+ return (__assign(__assign({}, acc), (_a = {}, _a[key] = val_1[key], _a)));
307
+ }, {});
306
308
  }
307
- continue;
309
+ return "continue";
308
310
  }
309
311
  if (shortReference in tableDefinition) {
310
- const longName = tableDefinition[shortReference];
311
- const columnValue = restfulObject[value];
312
+ var longName = tableDefinition[shortReference];
313
+ var columnValue = restfulObject[value];
312
314
  payload[longName] = columnValue;
313
- const regexValidations = tableDefinition.REGEX_VALIDATION[longName];
315
+ var regexValidations = tableDefinition.REGEX_VALIDATION[longName];
314
316
  if (regexValidations instanceof RegExp) {
315
317
  if (!regexValidations.test(columnValue)) {
316
- regexErrorHandler(`Failed to match regex (${regexValidations}) for column (${longName})`);
317
- throw new Error(`Failed to match regex (${regexValidations}) for column (${longName})`);
318
+ regexErrorHandler("Failed to match regex (".concat(regexValidations, ") for column (").concat(longName, ")"));
319
+ throw new Error("Failed to match regex (".concat(regexValidations, ") for column (").concat(longName, ")"));
318
320
  }
319
321
  }
320
322
  else if (typeof regexValidations === 'object' && regexValidations !== null) {
321
- for (const errorMessage in regexValidations) {
322
- const regex = regexValidations[errorMessage];
323
+ for (var errorMessage in regexValidations) {
324
+ var regex = regexValidations[errorMessage];
323
325
  if (!regex.test(columnValue)) {
324
- const devErrorMessage = `Failed to match regex (${regex}) for column (${longName})`;
326
+ var devErrorMessage = "Failed to match regex (".concat(regex, ") for column (").concat(longName, ")");
325
327
  regexErrorHandler(errorMessage || devErrorMessage);
326
328
  throw new Error(devErrorMessage);
327
329
  }
328
330
  }
329
331
  }
330
332
  }
331
- else if (value in Object.values(tableDefinition.COLUMNS)) {
333
+ else if (Object.values(tableDefinition.COLUMNS).includes(value)) {
332
334
  // Already a fully qualified column name
333
- const columnValue = restfulObject[value];
335
+ var columnValue = restfulObject[value];
334
336
  payload[value] = columnValue;
335
- const regexValidations = tableDefinition.REGEX_VALIDATION[value];
337
+ var regexValidations = tableDefinition.REGEX_VALIDATION[value];
336
338
  if (regexValidations instanceof RegExp) {
337
339
  if (!regexValidations.test(columnValue)) {
338
- regexErrorHandler(`Failed to match regex (${regexValidations}) for column (${value})`);
339
- throw new Error(`Failed to match regex (${regexValidations}) for column (${value})`);
340
+ regexErrorHandler("Failed to match regex (".concat(regexValidations, ") for column (").concat(value, ")"));
341
+ throw new Error("Failed to match regex (".concat(regexValidations, ") for column (").concat(value, ")"));
340
342
  }
341
343
  }
342
344
  else if (typeof regexValidations === 'object' && regexValidations !== null) {
343
- for (const errorMessage in regexValidations) {
344
- const regex = regexValidations[errorMessage];
345
+ for (var errorMessage in regexValidations) {
346
+ var regex = regexValidations[errorMessage];
345
347
  if (!regex.test(columnValue)) {
346
- const devErrorMessage = `Failed to match regex (${regex}) for column (${value})`;
348
+ var devErrorMessage = "Failed to match regex (".concat(regex, ") for column (").concat(value, ")");
347
349
  regexErrorHandler(errorMessage || devErrorMessage);
348
350
  throw new Error(devErrorMessage);
349
351
  }
350
352
  }
351
353
  }
352
354
  }
355
+ };
356
+ for (var _a = 0, _b = Object.keys(restfulObject); _a < _b.length; _a++) {
357
+ var value = _b[_a];
358
+ _loop_1(value);
353
359
  }
354
360
  }
355
361
  return Object.keys(payload)
356
362
  .sort()
357
- .reduce((acc, key) => ({ ...acc, [key]: payload[key] }), {});
363
+ .reduce(function (acc, key) {
364
+ var _a;
365
+ return (__assign(__assign({}, acc), (_a = {}, _a[key] = payload[key], _a)));
366
+ }, {});
358
367
  }
359
368
 
360
- const isNode = () => {
369
+ var isNode = function () {
370
+ var _a;
361
371
  console.log('Checking if running in Node.js environment...');
362
- const isNodeEnv = typeof process !== 'undefined' && !!process.versions?.node;
363
- console.log(`Is Node.js environment: ${isNodeEnv}`);
372
+ var isNodeEnv = typeof process !== 'undefined' && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
373
+ console.log("Is Node.js environment: ".concat(isNodeEnv));
364
374
  return isNodeEnv;
365
375
  };
366
376
 
@@ -368,94 +378,112 @@ const isNode = () => {
368
378
  * Facade: routes API calls to SQL or HTTP executors based on runtime context.
369
379
  */
370
380
  function restRequest(configX) {
371
- return async (request) => {
372
- const config = typeof configX === "function" ? configX() : configX;
373
- config.verbose ??= true; // Default to verbose logging if not set
374
- // SQL path if on Node with a provided pool
375
- if (isNode() && config.mysqlPool) {
376
- const { SqlExecutor } = await Promise.resolve().then(function () { return SqlExecutor$1; });
377
- const executor = new SqlExecutor(config, request);
378
- return executor.execute();
379
- }
380
- // HTTP path fallback
381
- const { HttpExecutor } = await Promise.resolve().then(function () { return HttpExecutor$1; });
382
- const http = new HttpExecutor(config, request);
383
- return http.execute();
384
- };
381
+ var _this = this;
382
+ return function (request) { return __awaiter(_this, void 0, void 0, function () {
383
+ var config, SqlExecutor, executor, HttpExecutor, http;
384
+ var _a;
385
+ return __generator(this, function (_b) {
386
+ switch (_b.label) {
387
+ case 0:
388
+ config = typeof configX === "function" ? configX() : configX;
389
+ (_a = config.verbose) !== null && _a !== void 0 ? _a : (config.verbose = true); // Default to verbose logging if not set
390
+ if (!(isNode() && config.mysqlPool)) return [3 /*break*/, 2];
391
+ return [4 /*yield*/, Promise.resolve().then(function () { return SqlExecutor$1; })];
392
+ case 1:
393
+ SqlExecutor = (_b.sent()).SqlExecutor;
394
+ executor = new SqlExecutor(config, request);
395
+ return [2 /*return*/, executor.execute()];
396
+ case 2: return [4 /*yield*/, Promise.resolve().then(function () { return HttpExecutor$1; })];
397
+ case 3:
398
+ HttpExecutor = (_b.sent()).HttpExecutor;
399
+ http = new HttpExecutor(config, request);
400
+ return [2 /*return*/, http.execute()];
401
+ }
402
+ });
403
+ }); };
385
404
  }
386
405
 
387
406
  function restOrm(configFn) {
388
407
  return {
389
- Get: restRequest(() => ({
390
- ...configFn(),
391
- requestMethod: "GET"
392
- })),
393
- Put: restRequest(() => ({
394
- ...configFn(),
395
- requestMethod: "PUT"
396
- })),
397
- Post: restRequest(() => ({
398
- ...configFn(),
399
- requestMethod: "POST"
400
- })),
401
- Delete: restRequest(() => ({
402
- ...configFn(),
403
- requestMethod: "DELETE"
404
- }))
408
+ Get: restRequest(function () { return (__assign(__assign({}, configFn()), { requestMethod: "GET" })); }),
409
+ Put: restRequest(function () { return (__assign(__assign({}, configFn()), { requestMethod: "PUT" })); }),
410
+ Post: restRequest(function () { return (__assign(__assign({}, configFn()), { requestMethod: "POST" })); }),
411
+ Delete: restRequest(function () { return (__assign(__assign({}, configFn()), { requestMethod: "DELETE" })); })
405
412
  };
406
413
  }
407
414
 
408
- function timeout(shouldContinueAfterTimeout, cb, timeoutMs = 3000) {
409
- const timer = () => setTimeout(() => {
415
+ function timeout(shouldContinueAfterTimeout, cb, timeoutMs) {
416
+ if (timeoutMs === void 0) { timeoutMs = 3000; }
417
+ var timer = function () { return setTimeout(function () {
410
418
  if (false === shouldContinueAfterTimeout()) {
411
419
  return;
412
420
  }
413
421
  cb();
414
- }, timeoutMs);
415
- const timerId = timer();
416
- return () => {
422
+ }, timeoutMs); };
423
+ var timerId = timer();
424
+ return function () {
417
425
  clearTimeout(timerId);
418
426
  };
419
427
  }
420
428
 
421
- class Executor {
422
- config;
423
- request;
424
- useNamedParams;
425
- constructor(config, request, useNamedParams = false) {
429
+ var Executor = /** @class */ (function () {
430
+ function Executor(config, request, useNamedParams) {
431
+ if (useNamedParams === void 0) { useNamedParams = false; }
426
432
  this.config = config;
427
433
  this.request = request;
428
434
  this.useNamedParams = useNamedParams;
429
435
  }
430
- async runLifecycleHooks(phase, args) {
431
- const lifecycleGroup = this.config.restModel.LIFECYCLE_HOOKS[this.config.requestMethod]?.[phase];
432
- if (!lifecycleGroup)
433
- return;
434
- for (const [key, fn] of Object.entries(lifecycleGroup)) {
435
- if (typeof fn === "function") {
436
- if (this.config.verbose || args.request.debug) {
437
- console.groupCollapsed(`[LIFECYCLE] ${this.config.requestMethod}.${String(phase)}:${key}`);
438
- console.log("config:", args.config);
439
- console.log("request:", args.request);
440
- if ("response" in args) {
441
- console.log("response:", args.response);
442
- }
443
- console.groupEnd();
444
- }
445
- try {
446
- // todo - this
447
- await fn(args);
448
- }
449
- catch (err) {
450
- console.error(`[LIFECYCLE ERROR] ${this.config.requestMethod}.${String(phase)}:${key}`, err);
451
- throw err;
436
+ Executor.prototype.runLifecycleHooks = function (phase, args) {
437
+ return __awaiter(this, void 0, void 0, function () {
438
+ var lifecycleGroup, _i, _a, _b, key, fn, err_1;
439
+ var _c;
440
+ return __generator(this, function (_d) {
441
+ switch (_d.label) {
442
+ case 0:
443
+ lifecycleGroup = (_c = this.config.restModel.LIFECYCLE_HOOKS[this.config.requestMethod]) === null || _c === void 0 ? void 0 : _c[phase];
444
+ if (!lifecycleGroup)
445
+ return [2 /*return*/];
446
+ _i = 0, _a = Object.entries(lifecycleGroup);
447
+ _d.label = 1;
448
+ case 1:
449
+ if (!(_i < _a.length)) return [3 /*break*/, 6];
450
+ _b = _a[_i], key = _b[0], fn = _b[1];
451
+ if (!(typeof fn === "function")) return [3 /*break*/, 5];
452
+ if (this.config.verbose || args.request.debug) {
453
+ console.groupCollapsed("[LIFECYCLE] ".concat(this.config.requestMethod, ".").concat(String(phase), ":").concat(key));
454
+ console.log("config:", args.config);
455
+ console.log("request:", args.request);
456
+ if ("response" in args) {
457
+ console.log("response:", args.response);
458
+ }
459
+ console.groupEnd();
460
+ }
461
+ _d.label = 2;
462
+ case 2:
463
+ _d.trys.push([2, 4, , 5]);
464
+ // todo - this
465
+ return [4 /*yield*/, fn(args)];
466
+ case 3:
467
+ // todo - this
468
+ _d.sent();
469
+ return [3 /*break*/, 5];
470
+ case 4:
471
+ err_1 = _d.sent();
472
+ console.error("[LIFECYCLE ERROR] ".concat(this.config.requestMethod, ".").concat(String(phase), ":").concat(key), err_1);
473
+ throw err_1;
474
+ case 5:
475
+ _i++;
476
+ return [3 /*break*/, 1];
477
+ case 6: return [2 /*return*/];
452
478
  }
453
- }
454
- }
455
- }
456
- }
479
+ });
480
+ });
481
+ };
482
+ return Executor;
483
+ }());
457
484
 
458
- function getEnvVar(key, fallback = '') {
485
+ function getEnvVar(key, fallback) {
486
+ if (fallback === void 0) { fallback = ''; }
459
487
  // Vite-style injection
460
488
  // @ts-ignore
461
489
  if (typeof import.meta !== 'undefined' && import.meta.env && key in import.meta.env) {
@@ -492,12 +520,12 @@ var eFetchDependencies;
492
520
  })(eFetchDependencies || (eFetchDependencies = {}));
493
521
 
494
522
  // Refined TypeScript types for CarbonORM
495
- const POST = 'POST';
496
- const PUT = 'PUT';
497
- const GET = 'GET';
498
- const DELETE = 'DELETE';
523
+ var POST = 'POST';
524
+ var PUT = 'PUT';
525
+ var GET = 'GET';
526
+ var DELETE = 'DELETE';
499
527
 
500
- const toastOptions = {
528
+ var toastOptions = {
501
529
  position: "bottom-left",
502
530
  autoClose: 10000,
503
531
  hideProgressBar: false,
@@ -506,7 +534,7 @@ const toastOptions = {
506
534
  draggable: true,
507
535
  theme: "dark",
508
536
  };
509
- const toastOptionsDevs = {
537
+ var toastOptionsDevs = {
510
538
  position: "bottom-right",
511
539
  autoClose: 3000,
512
540
  hideProgressBar: false,
@@ -518,19 +546,20 @@ const toastOptionsDevs = {
518
546
 
519
547
  // When we capture DropExceptions and display them as a custom page, this will change.
520
548
  function TestRestfulResponse(response, success, error) {
521
- if (undefined === response.data?.['ERROR TYPE']
522
- && (undefined !== response?.data?.rest
523
- || undefined !== response.data?.created
524
- || undefined !== response.data?.updated
525
- || undefined !== response.data?.deleted)) {
526
- let successReturn = 'function' === typeof success ? success?.(response) : success;
549
+ var _a, _b, _c, _d, _e, _f, _g, _h;
550
+ if (undefined === ((_a = response.data) === null || _a === void 0 ? void 0 : _a['ERROR TYPE'])
551
+ && (undefined !== ((_b = response === null || response === void 0 ? void 0 : response.data) === null || _b === void 0 ? void 0 : _b.rest)
552
+ || undefined !== ((_c = response.data) === null || _c === void 0 ? void 0 : _c.created)
553
+ || undefined !== ((_d = response.data) === null || _d === void 0 ? void 0 : _d.updated)
554
+ || undefined !== ((_e = response.data) === null || _e === void 0 ? void 0 : _e.deleted))) {
555
+ var successReturn = 'function' === typeof success ? success === null || success === void 0 ? void 0 : success(response) : success;
527
556
  if (typeof successReturn === 'string') {
528
557
  toast.success(successReturn, toastOptions);
529
558
  }
530
559
  // this could end up with bad results for deleting id's === 0
531
- return response.data.created ?? response.data.updated ?? response.data.deleted ?? true;
560
+ return (_h = (_g = (_f = response.data.created) !== null && _f !== void 0 ? _f : response.data.updated) !== null && _g !== void 0 ? _g : response.data.deleted) !== null && _h !== void 0 ? _h : true;
532
561
  }
533
- let errorReturn = 'function' === typeof error ? error?.(response) : error;
562
+ var errorReturn = 'function' === typeof error ? error === null || error === void 0 ? void 0 : error(response) : error;
534
563
  if (typeof errorReturn === 'string') {
535
564
  toast.error(errorReturn, toastOptions);
536
565
  }
@@ -543,15 +572,15 @@ function removePrefixIfExists(tableName, prefix) {
543
572
  return tableName;
544
573
  }
545
574
  function removeInvalidKeys(request, c6Tables) {
546
- let intersection = {};
547
- let restfulObjectKeys = [];
548
- const tableList = Object.values(c6Tables);
549
- tableList.forEach(table => Object.values(table.COLUMNS).forEach(column => {
575
+ var intersection = {};
576
+ var restfulObjectKeys = [];
577
+ var tableList = Object.values(c6Tables);
578
+ tableList.forEach(function (table) { return Object.values(table.COLUMNS).forEach(function (column) {
550
579
  if (false === restfulObjectKeys.includes(column)) {
551
580
  restfulObjectKeys.push(column);
552
581
  }
553
- }));
554
- Object.keys(request).forEach(key => {
582
+ }); });
583
+ Object.keys(request).forEach(function (key) {
555
584
  if (restfulObjectKeys.includes(key)) {
556
585
  intersection[key] = request[key];
557
586
  }
@@ -562,13 +591,13 @@ function removeInvalidKeys(request, c6Tables) {
562
591
 
563
592
  // do not remove entries from this array. It is used to track the progress of API requests.
564
593
  // position in array is important. Do not sort. To not add to begging.
565
- let apiRequestCache = [];
566
- let userCustomClearCache = [];
594
+ var apiRequestCache = [];
595
+ var userCustomClearCache = [];
567
596
  function clearCache(props) {
568
- if (false === props?.ignoreWarning) {
597
+ if (false === (props === null || props === void 0 ? void 0 : props.ignoreWarning)) {
569
598
  console.warn('The rest api clearCache should only be used with extreme care! Avoid using this in favor of using `cacheResults : boolean`.');
570
599
  }
571
- userCustomClearCache.map((f) => 'function' === typeof f && f());
600
+ userCustomClearCache.map(function (f) { return 'function' === typeof f && f(); });
572
601
  userCustomClearCache = apiRequestCache = [];
573
602
  }
574
603
  function checkCache(cacheResult, requestMethod, tableName, request) {
@@ -583,551 +612,601 @@ function checkCache(cacheResult, requestMethod, tableName, request) {
583
612
  }
584
613
 
585
614
  function sortAndSerializeQueryObject(tables, query) {
586
- const orderedQuery = Object.keys(query).sort().reduce((obj, key) => {
615
+ var orderedQuery = Object.keys(query).sort().reduce(function (obj, key) {
587
616
  obj[key] = query[key];
588
617
  return obj;
589
618
  }, {});
590
619
  return tables + ' ' + JSON.stringify(orderedQuery);
591
620
  }
592
621
 
593
- class HttpExecutor extends Executor {
594
- putState(response, request, callback) {
595
- this.config.reactBootstrap?.updateRestfulObjectArrays({
596
- callback,
622
+ var HttpExecutor = /** @class */ (function (_super) {
623
+ __extends(HttpExecutor, _super);
624
+ function HttpExecutor() {
625
+ return _super !== null && _super.apply(this, arguments) || this;
626
+ }
627
+ HttpExecutor.prototype.putState = function (response, request, callback) {
628
+ var _a, _b;
629
+ (_a = this.config.reactBootstrap) === null || _a === void 0 ? void 0 : _a.updateRestfulObjectArrays({
630
+ callback: callback,
597
631
  dataOrCallback: [
598
- removeInvalidKeys({
599
- ...request,
600
- ...response?.data?.rest,
601
- }, this.config.C6.TABLES)
632
+ removeInvalidKeys(__assign(__assign({}, request), (_b = response === null || response === void 0 ? void 0 : response.data) === null || _b === void 0 ? void 0 : _b.rest), this.config.C6.TABLES)
602
633
  ],
603
634
  stateKey: this.config.restModel.TABLE_NAME,
604
635
  uniqueObjectId: this.config.restModel.PRIMARY_SHORT
605
636
  });
606
- }
607
- postState(response, request, callback) {
637
+ };
638
+ HttpExecutor.prototype.postState = function (response, request, callback) {
639
+ var _this = this;
640
+ var _a, _b, _c;
608
641
  if (1 !== this.config.restModel.PRIMARY_SHORT.length) {
609
642
  console.error("C6 received unexpected result's given the primary key length");
610
643
  }
611
644
  else {
612
- const pk = this.config.restModel.PRIMARY_SHORT[0];
645
+ var pk = this.config.restModel.PRIMARY_SHORT[0];
613
646
  // TODO - should overrides be handled differently? Why override: (react/php), driver missmatches, aux data..
614
647
  // @ts-ignore - this is technically a correct error, but we allow it anyway...
615
- request[pk] = response.data?.created;
648
+ request[pk] = (_a = response.data) === null || _a === void 0 ? void 0 : _a.created;
616
649
  }
617
- this.config.reactBootstrap?.updateRestfulObjectArrays({
618
- callback,
650
+ (_b = this.config.reactBootstrap) === null || _b === void 0 ? void 0 : _b.updateRestfulObjectArrays({
651
+ callback: callback,
619
652
  dataOrCallback: undefined !== request.dataInsertMultipleRows
620
- ? request.dataInsertMultipleRows.map((request, index) => {
621
- return removeInvalidKeys({
622
- ...request,
623
- ...(index === 0 ? response?.data?.rest : {}),
624
- }, this.config.C6.TABLES);
653
+ ? request.dataInsertMultipleRows.map(function (request, index) {
654
+ var _a;
655
+ return removeInvalidKeys(__assign(__assign({}, request), (index === 0 ? (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.rest : {})), _this.config.C6.TABLES);
625
656
  })
626
657
  : [
627
- removeInvalidKeys({
628
- ...request,
629
- ...response?.data?.rest,
630
- }, this.config.C6.TABLES)
658
+ removeInvalidKeys(__assign(__assign({}, request), (_c = response === null || response === void 0 ? void 0 : response.data) === null || _c === void 0 ? void 0 : _c.rest), this.config.C6.TABLES)
631
659
  ],
632
660
  stateKey: this.config.restModel.TABLE_NAME,
633
661
  uniqueObjectId: this.config.restModel.PRIMARY_SHORT
634
662
  });
635
- }
636
- deleteState(_response, request, callback) {
637
- this.config.reactBootstrap?.deleteRestfulObjectArrays({
638
- callback,
663
+ };
664
+ HttpExecutor.prototype.deleteState = function (_response, request, callback) {
665
+ var _a;
666
+ (_a = this.config.reactBootstrap) === null || _a === void 0 ? void 0 : _a.deleteRestfulObjectArrays({
667
+ callback: callback,
639
668
  dataOrCallback: [
640
669
  request,
641
670
  ],
642
671
  stateKey: this.config.restModel.TABLE_NAME,
643
672
  uniqueObjectId: this.config.restModel.PRIMARY_SHORT
644
673
  });
645
- }
646
- async execute() {
647
- const { C6, axios, restURL, withCredentials, restModel, reactBootstrap, requestMethod, skipPrimaryCheck, clearCache, } = this.config;
648
- console.log('this.config', this.config);
649
- await this.runLifecycleHooks("beforeProcessing", {
650
- config: this.config,
651
- request: this.request,
652
- });
653
- const tableName = restModel.TABLE_NAME;
654
- const fullTableList = Array.isArray(tableName) ? tableName : [tableName];
655
- const operatingTableFullName = fullTableList[0];
656
- const operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
657
- const tables = fullTableList.join(',');
658
- switch (requestMethod) {
659
- case GET:
660
- case POST:
661
- case PUT:
662
- case DELETE:
663
- break;
664
- default:
665
- throw Error('Bad request method passed to getApi');
666
- }
667
- if (null !== clearCache || undefined !== clearCache) {
668
- userCustomClearCache[tables + requestMethod] = clearCache;
669
- }
670
- console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + tableName + ')', 'color: #0c0');
671
- console.log('request', this.request);
672
- console.groupEnd();
673
- // an undefined query would indicate queryCallback returned undefined,
674
- // thus the request shouldn't fire as is in custom cache
675
- if (undefined === this.request || null === this.request) {
676
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + tableName + ') undefined, returning null (will not fire)!', 'color: #c00');
677
- console.log('request', this.request);
678
- console.log('%c Returning (undefined|null) for a query would indicate a custom cache hit (outside API.tsx), thus the request should not fire.', 'color: #c00');
679
- console.trace();
680
- console.groupEnd();
681
- return null;
682
- }
683
- let query = this.request;
684
- if (C6.GET === requestMethod) {
685
- if (undefined === query[C6.PAGINATION]) {
686
- query[C6.PAGINATION] = {};
687
- }
688
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
689
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
690
- }
691
- // this is parameterless and could return itself with a new page number, or undefined if the end is reached
692
- const apiRequest = async () => {
693
- const { debug, cacheResults = (C6.GET === requestMethod), dataInsertMultipleRows, success, fetchDependencies = eFetchDependencies.NONE, error = "An unexpected API error occurred!" } = this.request;
694
- if (C6.GET === requestMethod
695
- && undefined !== query?.[C6.PAGINATION]?.[C6.PAGE]
696
- && 1 !== query[C6.PAGINATION][C6.PAGE]) {
697
- console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
698
- console.log('Request Data (note you may see the success and/or error prompt):', this.request);
699
- console.trace();
700
- console.groupEnd();
701
- }
702
- // The problem with creating cache keys with a stringified object is the order of keys matters and it's possible for the same query to be stringified differently.
703
- // Here we ensure the key order will be identical between two of the same requests. https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key
704
- // literally impossible for query to be undefined or null here but the editor is too busy licking windows to understand that
705
- let querySerialized = sortAndSerializeQueryObject(tables, query ?? {});
706
- let cacheResult = apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized);
707
- let cachingConfirmed = false;
708
- // determine if we need to paginate.
709
- if (requestMethod === C6.GET) {
710
- if (undefined === query?.[C6.PAGINATION]) {
711
- if (undefined === query || null === query) {
712
- query = {};
713
- }
714
- query[C6.PAGINATION] = {};
715
- }
716
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
717
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
718
- // this will evaluate true most the time
719
- if (true === cacheResults) {
720
- // just find the next, non-fetched, page and return a function to request it
721
- if (undefined !== cacheResult) { // we will return in this loop
722
- do {
723
- const cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
724
- if (false !== cacheCheck) {
725
- return (await cacheCheck).data;
726
- }
727
- // this line incrementing page is why we return recursively
728
- ++query[C6.PAGINATION][C6.PAGE];
729
- // this json stringify is to capture the new page number
730
- querySerialized = sortAndSerializeQueryObject(tables, query ?? {});
731
- cacheResult = apiRequestCache.find(cache => cache.requestArgumentsSerialized === querySerialized);
732
- } while (undefined !== cacheResult);
733
- if (debug && isLocal()) {
734
- toast.warning("DEVS: Request in cache. (" + apiRequestCache.findIndex(cache => cache.requestArgumentsSerialized === querySerialized) + "). Returning function to request page (" + query[C6.PAGINATION][C6.PAGE] + ")", toastOptionsDevs);
735
- }
736
- // @ts-ignore - this is an incorrect warning on TS, it's well typed
737
- return apiRequest;
738
- }
739
- cachingConfirmed = true;
740
- }
741
- else {
742
- if (debug && isLocal()) {
743
- toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
744
- }
745
- }
746
- if (debug && isLocal()) {
747
- toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
748
- }
749
- }
750
- else if (cacheResults) { // if we are not getting, we are updating, deleting, or inserting
751
- if (cacheResult) {
752
- const cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
753
- if (false !== cacheCheck) {
754
- return (await cacheCheck).data;
755
- }
756
- }
757
- cachingConfirmed = true;
758
- // push to cache so we do not repeat the request
759
- }
760
- let addBackPK;
761
- let apiResponse;
762
- let returnGetNextPageFunction = false;
763
- let restRequestUri = restURL + operatingTable + '/';
764
- const needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
765
- && false === skipPrimaryCheck;
766
- const TABLES = C6.TABLES;
767
- // todo - aggregate primary key check with condition check
768
- // check if PK exists in query, clone so pop does not affect the real data
769
- const primaryKey = structuredClone(TABLES[operatingTable]?.PRIMARY)?.pop()?.split('.')?.pop();
770
- if (needsConditionOrPrimaryCheck) {
771
- if (undefined === primaryKey) {
772
- if (null === query
773
- || undefined === query
774
- || undefined === query?.[C6.WHERE]
775
- || (true === Array.isArray(query[C6.WHERE])
776
- || query[C6.WHERE].length === 0)
777
- || (Object.keys(query?.[C6.WHERE]).length === 0)) {
778
- console.error(query);
779
- throw Error('Failed to parse primary key information. Query: (' + JSON.stringify(query) + ') Primary Key: (' + JSON.stringify(primaryKey) + ') TABLES[operatingTable]?.PRIMARY: (' + JSON.stringify(TABLES[operatingTable]?.PRIMARY) + ') for operatingTable (' + operatingTable + ').');
780
- }
781
- }
782
- else {
783
- if (undefined === query
784
- || null === query
785
- || false === primaryKey in query) {
786
- if (true === debug && isLocal()) {
787
- toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
788
- }
789
- throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
790
- }
791
- if (undefined === query?.[primaryKey]
792
- || null === query?.[primaryKey]) {
793
- toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
794
- throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
795
- }
796
- }
797
- }
798
- // A part of me exists that wants to remove this, but it's a good feature
799
- // this allows developers the ability to cache requests based on primary key
800
- // for tables like `photos` this can be a huge performance boost
801
- if (undefined !== query
802
- && null !== query
803
- && undefined !== primaryKey
804
- && primaryKey in query) {
805
- restRequestUri += query[primaryKey] + '/';
806
- const removedPkValue = query[primaryKey];
807
- addBackPK = () => {
808
- query ??= {};
809
- query[primaryKey] = removedPkValue;
810
- };
811
- delete query[primaryKey];
812
- console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue);
813
- }
814
- else {
815
- console.log('query', query);
816
- }
817
- try {
818
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
819
- console.log(this.request);
820
- console.log('%c If this is the first request for this datatype; thus the value being set is currently undefined, please remember to update the state to null.', 'color: #A020F0');
821
- console.log('%c Remember undefined indicated the request has not fired, null indicates the request is firing, an empty array would signal no data was returned for the sql stmt.', 'color: #A020F0');
822
- console.trace();
823
- console.groupEnd();
824
- this.runLifecycleHooks("beforeExecution", {
825
- config: this.config,
826
- request: this.request
827
- });
828
- const axiosActiveRequest = axios[requestMethod.toLowerCase()](restRequestUri, ...(() => {
829
- const convert = (data) => convertForRequestBody(data, fullTableList, C6, (message) => toast.error(message, toastOptions));
830
- const baseConfig = {
831
- withCredentials: withCredentials,
832
- };
833
- switch (requestMethod) {
834
- case GET:
835
- return [{
836
- ...baseConfig,
837
- params: query
838
- }];
839
- case POST:
840
- if (dataInsertMultipleRows !== undefined) {
841
- return [
842
- dataInsertMultipleRows.map(convert),
843
- baseConfig
844
- ];
845
- }
846
- return [convert(query), baseConfig];
847
- case PUT:
848
- return [convert(query), baseConfig];
849
- case DELETE:
850
- return [{
851
- ...baseConfig,
852
- data: convert(query)
853
- }];
854
- default:
855
- throw new Error(`The request method (${requestMethod}) was not recognized.`);
856
- }
857
- })());
858
- if (cachingConfirmed) {
859
- // push to cache so we do not repeat the request
860
- apiRequestCache.push({
861
- requestArgumentsSerialized: querySerialized,
862
- request: axiosActiveRequest
863
- });
864
- }
865
- // todo - wip verify this works
866
- // we had removed the value from the request to add to the URI.
867
- addBackPK?.(); // adding back so post-processing methods work
868
- // returning the promise with this then is important for tests. todo - we could make that optional.
869
- // https://rapidapi.com/guides/axios-async-await
870
- return axiosActiveRequest.then(async (response) => {
871
- // noinspection SuspiciousTypeOfGuard
872
- if (typeof response.data === 'string') {
873
- if (isTest()) {
874
- console.trace();
875
- throw new Error('The response data was a string this typically indicated html was sent. Make sure all cookies (' + JSON.stringify(response.config.headers) + ') needed are present! (' + response.data + ')');
876
- }
877
- return Promise.reject(response);
878
- }
879
- if (cachingConfirmed) {
880
- const cacheIndex = apiRequestCache.findIndex(cache => cache.requestArgumentsSerialized === querySerialized);
881
- // TODO - currently nonthing is setting this correctly
882
- apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
883
- // only cache get method requests
884
- apiRequestCache[cacheIndex].response = response;
885
- }
886
- this.runLifecycleHooks("afterExecution", {
887
- config: this.config,
888
- request: this.request,
889
- response
890
- });
891
- // todo - this feels dumb now, but i digress
892
- apiResponse = TestRestfulResponse(response, success, error);
893
- if (false === apiResponse) {
894
- if (debug && isLocal()) {
895
- toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
896
- }
897
- return response;
898
- }
899
- const callback = () => this.runLifecycleHooks("afterCommit", {
900
- config: this.config,
901
- request: this.request,
902
- response
903
- });
904
- if (undefined !== reactBootstrap && response) {
674
+ };
675
+ HttpExecutor.prototype.execute = function () {
676
+ return __awaiter(this, void 0, void 0, function () {
677
+ var _a, C6, axios, restURL, withCredentials, restModel, reactBootstrap, requestMethod, skipPrimaryCheck, clearCache, tableName, fullTableList, operatingTableFullName, operatingTable, tables, query, apiRequest;
678
+ var _this = this;
679
+ return __generator(this, function (_b) {
680
+ switch (_b.label) {
681
+ case 0:
682
+ _a = this.config, C6 = _a.C6, axios = _a.axios, restURL = _a.restURL, withCredentials = _a.withCredentials, restModel = _a.restModel, reactBootstrap = _a.reactBootstrap, requestMethod = _a.requestMethod, skipPrimaryCheck = _a.skipPrimaryCheck, clearCache = _a.clearCache;
683
+ console.log('this.config', this.config);
684
+ return [4 /*yield*/, this.runLifecycleHooks("beforeProcessing", {
685
+ config: this.config,
686
+ request: this.request,
687
+ })];
688
+ case 1:
689
+ _b.sent();
690
+ tableName = restModel.TABLE_NAME;
691
+ fullTableList = Array.isArray(tableName) ? tableName : [tableName];
692
+ operatingTableFullName = fullTableList[0];
693
+ operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
694
+ tables = fullTableList.join(',');
905
695
  switch (requestMethod) {
906
696
  case GET:
907
- response.data && reactBootstrap.updateRestfulObjectArrays({
908
- dataOrCallback: Array.isArray(response.data.rest) ? response.data.rest : [response.data.rest],
909
- stateKey: this.config.restModel.TABLE_NAME,
910
- uniqueObjectId: this.config.restModel.PRIMARY_SHORT,
911
- callback
912
- });
913
- break;
914
697
  case POST:
915
- this.postState(response, this.request, callback);
916
- break;
917
698
  case PUT:
918
- this.putState(response, this.request, callback);
919
- break;
920
699
  case DELETE:
921
- this.deleteState(response, this.request, callback);
922
700
  break;
701
+ default:
702
+ throw Error('Bad request method passed to getApi');
923
703
  }
924
- }
925
- else {
926
- callback();
927
- }
928
- if (C6.GET === requestMethod) {
929
- const responseData = response.data;
930
- returnGetNextPageFunction = 1 !== query?.[C6.PAGINATION]?.[C6.LIMIT] &&
931
- query?.[C6.PAGINATION]?.[C6.LIMIT] === responseData.rest.length;
932
- if (false === isTest() || this.config.verbose) {
933
- console.groupCollapsed('%c API: Response (' + requestMethod + ' ' + tableName + ') returned length (' + responseData.rest?.length + ') of possible (' + query?.[C6.PAGINATION]?.[C6.LIMIT] + ') limit!', 'color: #0c0');
934
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
935
- console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
936
- console.log('%c Response Data:', 'color: #0c0', responseData.rest);
937
- console.log('%c Will return get next page function:' + (returnGetNextPageFunction ? '' : ' (Will not return with explicit limit 1 set)'), 'color: #0c0', true === returnGetNextPageFunction);
704
+ if (null !== clearCache || undefined !== clearCache) {
705
+ userCustomClearCache[tables + requestMethod] = clearCache;
706
+ }
707
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + tableName + ')', 'color: #0c0');
708
+ console.log('request', this.request);
709
+ console.groupEnd();
710
+ // an undefined query would indicate queryCallback returned undefined,
711
+ // thus the request shouldn't fire as is in custom cache
712
+ if (undefined === this.request || null === this.request) {
713
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + tableName + ') undefined, returning null (will not fire)!', 'color: #c00');
714
+ console.log('request', this.request);
715
+ console.log('%c Returning (undefined|null) for a query would indicate a custom cache hit (outside API.tsx), thus the request should not fire.', 'color: #c00');
938
716
  console.trace();
939
717
  console.groupEnd();
718
+ return [2 /*return*/, null];
940
719
  }
941
- if (false === returnGetNextPageFunction) {
942
- responseData.next = apiRequest;
943
- }
944
- else {
945
- responseData.next = undefined;
946
- if (true === debug
947
- && isLocal()) {
948
- toast.success("DEVS: Response returned length (" + responseData.rest?.length + ") less than limit (" + query?.[C6.PAGINATION]?.[C6.LIMIT] + ").", toastOptionsDevs);
720
+ query = this.request;
721
+ if (C6.GET === requestMethod) {
722
+ if (undefined === query[C6.PAGINATION]) {
723
+ query[C6.PAGINATION] = {};
949
724
  }
725
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
726
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
950
727
  }
951
- if (fetchDependencies
952
- && 'number' === typeof fetchDependencies
953
- && responseData.rest.length > 0) {
954
- console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
955
- + (fetchDependencies & eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
956
- + (fetchDependencies & eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
957
- + (fetchDependencies & eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
958
- + (fetchDependencies & eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
959
- console.groupCollapsed('Collapsed JS Trace');
960
- console.trace(); // hidden in collapsed group
961
- console.groupEnd();
962
- // noinspection JSBitwiseOperatorUsage
963
- let dependencies = {};
964
- // Remember this is a binary bitwise operation, so we can check for multiple dependencies at once
965
- if (fetchDependencies & eFetchDependencies.C6ENTITY) {
966
- dependencies = operatingTable.endsWith("carbon_carbons")
967
- ? {
968
- // the context of the entity system is a bit different
969
- ...fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
970
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
971
- : {},
972
- ...fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
973
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
974
- : {}
975
- } : {
976
- // the context of the entity system is a bit different
977
- ...fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
978
- ? {
979
- ...Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce((accumulator, columnName) => {
980
- if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
981
- accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
728
+ apiRequest = function () { return __awaiter(_this, void 0, void 0, function () {
729
+ var _a, debug, _b, cacheResults, dataInsertMultipleRows, success, _c, fetchDependencies, _d, error, querySerialized, cacheResult, cachingConfirmed, cacheCheck, cacheCheck, addBackPK, apiResponse, returnGetNextPageFunction, restRequestUri, needsConditionOrPrimaryCheck, TABLES, primaryKey, removedPkValue_1, axiosActiveRequest;
730
+ var _e;
731
+ var _this = this;
732
+ var _f, _g, _h, _j, _k, _l;
733
+ return __generator(this, function (_m) {
734
+ switch (_m.label) {
735
+ case 0:
736
+ _a = this.request, debug = _a.debug, _b = _a.cacheResults, cacheResults = _b === void 0 ? (C6.GET === requestMethod) : _b, dataInsertMultipleRows = _a.dataInsertMultipleRows, success = _a.success, _c = _a.fetchDependencies, fetchDependencies = _c === void 0 ? eFetchDependencies.NONE : _c, _d = _a.error, error = _d === void 0 ? "An unexpected API error occurred!" : _d;
737
+ if (C6.GET === requestMethod
738
+ && undefined !== ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.PAGE])
739
+ && 1 !== query[C6.PAGINATION][C6.PAGE]) {
740
+ console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
741
+ console.log('Request Data (note you may see the success and/or error prompt):', this.request);
742
+ console.trace();
743
+ console.groupEnd();
744
+ }
745
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
746
+ cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
747
+ cachingConfirmed = false;
748
+ if (!(requestMethod === C6.GET)) return [3 /*break*/, 9];
749
+ if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
750
+ if (undefined === query || null === query) {
751
+ query = {};
752
+ }
753
+ query[C6.PAGINATION] = {};
754
+ }
755
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
756
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
757
+ if (!(true === cacheResults)) return [3 /*break*/, 7];
758
+ if (!(undefined !== cacheResult)) return [3 /*break*/, 6];
759
+ _m.label = 1;
760
+ case 1:
761
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
762
+ if (!(false !== cacheCheck)) return [3 /*break*/, 3];
763
+ return [4 /*yield*/, cacheCheck];
764
+ case 2: return [2 /*return*/, (_m.sent()).data];
765
+ case 3:
766
+ // this line incrementing page is why we return recursively
767
+ ++query[C6.PAGINATION][C6.PAGE];
768
+ // this json stringify is to capture the new page number
769
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
770
+ cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
771
+ _m.label = 4;
772
+ case 4:
773
+ if (undefined !== cacheResult) return [3 /*break*/, 1];
774
+ _m.label = 5;
775
+ case 5:
776
+ if (debug && isLocal()) {
777
+ toast.warning("DEVS: Request in cache. (" + apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; }) + "). Returning function to request page (" + query[C6.PAGINATION][C6.PAGE] + ")", toastOptionsDevs);
778
+ }
779
+ // @ts-ignore - this is an incorrect warning on TS, it's well typed
780
+ return [2 /*return*/, apiRequest];
781
+ case 6:
782
+ cachingConfirmed = true;
783
+ return [3 /*break*/, 8];
784
+ case 7:
785
+ if (debug && isLocal()) {
786
+ toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
787
+ }
788
+ _m.label = 8;
789
+ case 8:
790
+ if (debug && isLocal()) {
791
+ toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
792
+ }
793
+ return [3 /*break*/, 12];
794
+ case 9:
795
+ if (!cacheResults) return [3 /*break*/, 12];
796
+ if (!cacheResult) return [3 /*break*/, 11];
797
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, this.request);
798
+ if (!(false !== cacheCheck)) return [3 /*break*/, 11];
799
+ return [4 /*yield*/, cacheCheck];
800
+ case 10: return [2 /*return*/, (_m.sent()).data];
801
+ case 11:
802
+ cachingConfirmed = true;
803
+ _m.label = 12;
804
+ case 12:
805
+ returnGetNextPageFunction = false;
806
+ restRequestUri = restURL + operatingTable + '/';
807
+ needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
808
+ && false === skipPrimaryCheck;
809
+ TABLES = C6.TABLES;
810
+ primaryKey = (_k = (_j = (_h = structuredClone((_g = TABLES[operatingTable]) === null || _g === void 0 ? void 0 : _g.PRIMARY)) === null || _h === void 0 ? void 0 : _h.pop()) === null || _j === void 0 ? void 0 : _j.split('.')) === null || _k === void 0 ? void 0 : _k.pop();
811
+ if (needsConditionOrPrimaryCheck) {
812
+ if (undefined === primaryKey) {
813
+ if (null === query
814
+ || undefined === query
815
+ || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
816
+ || (true === Array.isArray(query[C6.WHERE])
817
+ || query[C6.WHERE].length === 0)
818
+ || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
819
+ console.error(query);
820
+ throw Error('Failed to parse primary key information. Query: (' + JSON.stringify(query) + ') Primary Key: (' + JSON.stringify(primaryKey) + ') TABLES[operatingTable]?.PRIMARY: (' + JSON.stringify((_l = TABLES[operatingTable]) === null || _l === void 0 ? void 0 : _l.PRIMARY) + ') for operatingTable (' + operatingTable + ').');
821
+ }
822
+ }
823
+ else {
824
+ if (undefined === query
825
+ || null === query
826
+ || false === primaryKey in query) {
827
+ if (true === debug && isLocal()) {
828
+ toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
829
+ }
830
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
831
+ }
832
+ if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
833
+ || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
834
+ toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
835
+ throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
982
836
  }
983
- return accumulator;
984
- }, {}),
985
- ...C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
837
+ }
838
+ }
839
+ // A part of me exists that wants to remove this, but it's a good feature
840
+ // this allows developers the ability to cache requests based on primary key
841
+ // for tables like `photos` this can be a huge performance boost
842
+ if (undefined !== query
843
+ && null !== query
844
+ && undefined !== primaryKey
845
+ && primaryKey in query) {
846
+ restRequestUri += query[primaryKey] + '/';
847
+ removedPkValue_1 = query[primaryKey];
848
+ addBackPK = function () {
849
+ query !== null && query !== void 0 ? query : (query = {});
850
+ query[primaryKey] = removedPkValue_1;
851
+ };
852
+ delete query[primaryKey];
853
+ console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue_1);
986
854
  }
987
- : {},
988
- ...fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
989
- ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce((accumulator, primaryKey) => {
990
- if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
991
- accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
855
+ else {
856
+ console.log('query', query);
857
+ }
858
+ try {
859
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
860
+ console.log(this.request);
861
+ console.log('%c If this is the first request for this datatype; thus the value being set is currently undefined, please remember to update the state to null.', 'color: #A020F0');
862
+ console.log('%c Remember undefined indicated the request has not fired, null indicates the request is firing, an empty array would signal no data was returned for the sql stmt.', 'color: #A020F0');
863
+ console.trace();
864
+ console.groupEnd();
865
+ this.runLifecycleHooks("beforeExecution", {
866
+ config: this.config,
867
+ request: this.request
868
+ });
869
+ axiosActiveRequest = (_e = axios)[requestMethod.toLowerCase()].apply(_e, __spreadArray([restRequestUri], (function () {
870
+ var convert = function (data) {
871
+ return convertForRequestBody(data, fullTableList, C6, function (message) { return toast.error(message, toastOptions); });
872
+ };
873
+ var baseConfig = {
874
+ withCredentials: withCredentials,
875
+ };
876
+ switch (requestMethod) {
877
+ case GET:
878
+ return [__assign(__assign({}, baseConfig), { params: query })];
879
+ case POST:
880
+ if (dataInsertMultipleRows !== undefined) {
881
+ return [
882
+ dataInsertMultipleRows.map(convert),
883
+ baseConfig
884
+ ];
885
+ }
886
+ return [convert(query), baseConfig];
887
+ case PUT:
888
+ return [convert(query), baseConfig];
889
+ case DELETE:
890
+ return [__assign(__assign({}, baseConfig), { data: convert(query) })];
891
+ default:
892
+ throw new Error("The request method (".concat(requestMethod, ") was not recognized."));
893
+ }
894
+ })(), false));
895
+ if (cachingConfirmed) {
896
+ // push to cache so we do not repeat the request
897
+ apiRequestCache.push({
898
+ requestArgumentsSerialized: querySerialized,
899
+ request: axiosActiveRequest
900
+ });
992
901
  }
993
- return accumulator;
994
- }, {})
995
- : {}
996
- };
997
- }
998
- else {
999
- // this is the natural mysql context
1000
- dependencies = {
1001
- ...fetchDependencies & eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
1002
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1003
- : {},
1004
- ...fetchDependencies & eFetchDependencies.REFERENCES // REFERENCES === PARENTS
1005
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
1006
- : {}
1007
- };
1008
- }
1009
- let fetchReferences = {};
1010
- let apiRequestPromises = [];
1011
- console.log('%c Dependencies', 'color: #005555', dependencies);
1012
- Object.keys(dependencies)
1013
- .forEach(column => dependencies[column]
1014
- .forEach((constraint) => {
1015
- const columnValues = responseData.rest[column] ?? responseData.rest.map((row) => {
1016
- if (operatingTable.endsWith("carbons")
1017
- && 'entity_tag' in row
1018
- && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
1019
- return false; // map
1020
- }
1021
- if (!(column in row)) {
1022
- return false;
1023
- }
1024
- // todo - row[column] is a FK value, we should optionally remove values that are already in state
1025
- // this could be any column in the table constraint.TABLE, not just the primary key
1026
- return row[column];
1027
- }).filter(n => n) ?? [];
1028
- if (columnValues.length === 0) {
1029
- return; // forEach
1030
- }
1031
- fetchReferences[constraint.TABLE] ??= {};
1032
- fetchReferences[constraint.TABLE][constraint.COLUMN] ??= [];
1033
- fetchReferences[constraint.TABLE][constraint.COLUMN].push(columnValues);
1034
- }));
1035
- console.log('fetchReferences', fetchReferences);
1036
- for (const tableToFetch in fetchReferences) {
1037
- if (fetchDependencies & eFetchDependencies.C6ENTITY
1038
- && 'string' === typeof tableName
1039
- && tableName.endsWith("carbon_carbons")) {
1040
- // todo - rethink the table ref entity system - when tables are renamed? no hooks exist in mysql
1041
- // since were already filtering on column, we can assume the first row constraint is the same as the rest
1042
- const referencesTables = responseData.rest.reduce((accumulator, row) => {
1043
- if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
1044
- accumulator.push(row['entity_tag']);
902
+ // todo - wip verify this works
903
+ // we had removed the value from the request to add to the URI.
904
+ addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
905
+ // returning the promise with this then is important for tests. todo - we could make that optional.
906
+ // https://rapidapi.com/guides/axios-async-await
907
+ return [2 /*return*/, axiosActiveRequest.then(function (response) { return __awaiter(_this, void 0, void 0, function () {
908
+ var cacheIndex, callback, responseData_1, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
909
+ var _this = this;
910
+ var _d, _e, _f, _g, _h, _j;
911
+ return __generator(this, function (_k) {
912
+ switch (_k.label) {
913
+ case 0:
914
+ // noinspection SuspiciousTypeOfGuard
915
+ if (typeof response.data === 'string') {
916
+ if (isTest()) {
917
+ console.trace();
918
+ throw new Error('The response data was a string this typically indicated html was sent. Make sure all cookies (' + JSON.stringify(response.config.headers) + ') needed are present! (' + response.data + ')');
919
+ }
920
+ return [2 /*return*/, Promise.reject(response)];
921
+ }
922
+ if (cachingConfirmed) {
923
+ cacheIndex = apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
924
+ // TODO - currently nonthing is setting this correctly
925
+ apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
926
+ // only cache get method requests
927
+ apiRequestCache[cacheIndex].response = response;
928
+ }
929
+ this.runLifecycleHooks("afterExecution", {
930
+ config: this.config,
931
+ request: this.request,
932
+ response: response
933
+ });
934
+ // todo - this feels dumb now, but i digress
935
+ apiResponse = TestRestfulResponse(response, success, error);
936
+ if (false === apiResponse) {
937
+ if (debug && isLocal()) {
938
+ toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
939
+ }
940
+ return [2 /*return*/, response];
941
+ }
942
+ callback = function () { return _this.runLifecycleHooks("afterCommit", {
943
+ config: _this.config,
944
+ request: _this.request,
945
+ response: response
946
+ }); };
947
+ if (undefined !== reactBootstrap && response) {
948
+ switch (requestMethod) {
949
+ case GET:
950
+ response.data && reactBootstrap.updateRestfulObjectArrays({
951
+ dataOrCallback: Array.isArray(response.data.rest) ? response.data.rest : [response.data.rest],
952
+ stateKey: this.config.restModel.TABLE_NAME,
953
+ uniqueObjectId: this.config.restModel.PRIMARY_SHORT,
954
+ callback: callback
955
+ });
956
+ break;
957
+ case POST:
958
+ this.postState(response, this.request, callback);
959
+ break;
960
+ case PUT:
961
+ this.putState(response, this.request, callback);
962
+ break;
963
+ case DELETE:
964
+ this.deleteState(response, this.request, callback);
965
+ break;
966
+ }
967
+ }
968
+ else {
969
+ callback();
970
+ }
971
+ if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
972
+ responseData_1 = response.data;
973
+ returnGetNextPageFunction = 1 !== ((_d = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _d === void 0 ? void 0 : _d[C6.LIMIT]) &&
974
+ ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) === responseData_1.rest.length;
975
+ if (false === isTest() || this.config.verbose) {
976
+ console.groupCollapsed('%c API: Response (' + requestMethod + ' ' + tableName + ') returned length (' + ((_f = responseData_1.rest) === null || _f === void 0 ? void 0 : _f.length) + ') of possible (' + ((_g = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _g === void 0 ? void 0 : _g[C6.LIMIT]) + ') limit!', 'color: #0c0');
977
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
978
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
979
+ console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
980
+ console.log('%c Will return get next page function:' + (returnGetNextPageFunction ? '' : ' (Will not return with explicit limit 1 set)'), 'color: #0c0', true === returnGetNextPageFunction);
981
+ console.trace();
982
+ console.groupEnd();
983
+ }
984
+ if (false === returnGetNextPageFunction) {
985
+ responseData_1.next = apiRequest;
986
+ }
987
+ else {
988
+ responseData_1.next = undefined;
989
+ if (true === debug
990
+ && isLocal()) {
991
+ toast.success("DEVS: Response returned length (" + ((_h = responseData_1.rest) === null || _h === void 0 ? void 0 : _h.length) + ") less than limit (" + ((_j = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _j === void 0 ? void 0 : _j[C6.LIMIT]) + ").", toastOptionsDevs);
992
+ }
993
+ }
994
+ if (!(fetchDependencies
995
+ && 'number' === typeof fetchDependencies
996
+ && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
997
+ console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
998
+ + (fetchDependencies & eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
999
+ + (fetchDependencies & eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
1000
+ + (fetchDependencies & eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
1001
+ + (fetchDependencies & eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
1002
+ console.groupCollapsed('Collapsed JS Trace');
1003
+ console.trace(); // hidden in collapsed group
1004
+ console.groupEnd();
1005
+ dependencies_1 = {};
1006
+ // Remember this is a binary bitwise operation, so we can check for multiple dependencies at once
1007
+ if (fetchDependencies & eFetchDependencies.C6ENTITY) {
1008
+ dependencies_1 = operatingTable.endsWith("carbon_carbons")
1009
+ ? __assign(__assign({}, fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1010
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1011
+ : {}), fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
1012
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1013
+ : {}) : __assign(__assign({}, fetchDependencies & eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1014
+ ? __assign(__assign({}, Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce(function (accumulator, columnName) {
1015
+ if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
1016
+ accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
1017
+ }
1018
+ return accumulator;
1019
+ }, {})), C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
1020
+ ) : {}), fetchDependencies & eFetchDependencies.PARENTS // REFERENCES === PARENTS
1021
+ ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce(function (accumulator, primaryKey) {
1022
+ if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
1023
+ accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
1024
+ }
1025
+ return accumulator;
1026
+ }, {})
1027
+ : {});
1028
+ }
1029
+ else {
1030
+ // this is the natural mysql context
1031
+ dependencies_1 = __assign(__assign({}, fetchDependencies & eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
1032
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1033
+ : {}), fetchDependencies & eFetchDependencies.REFERENCES // REFERENCES === PARENTS
1034
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1035
+ : {});
1036
+ }
1037
+ fetchReferences_1 = {};
1038
+ apiRequestPromises = [];
1039
+ console.log('%c Dependencies', 'color: #005555', dependencies_1);
1040
+ Object.keys(dependencies_1)
1041
+ .forEach(function (column) { return dependencies_1[column]
1042
+ .forEach(function (constraint) {
1043
+ var _a, _b, _c, _d;
1044
+ var _e, _f, _g;
1045
+ var columnValues = (_b = (_a = responseData_1.rest[column]) !== null && _a !== void 0 ? _a : responseData_1.rest.map(function (row) {
1046
+ if (operatingTable.endsWith("carbons")
1047
+ && 'entity_tag' in row
1048
+ && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
1049
+ return false; // map
1050
+ }
1051
+ if (!(column in row)) {
1052
+ return false;
1053
+ }
1054
+ // todo - row[column] is a FK value, we should optionally remove values that are already in state
1055
+ // this could be any column in the table constraint.TABLE, not just the primary key
1056
+ return row[column];
1057
+ }).filter(function (n) { return n; })) !== null && _b !== void 0 ? _b : [];
1058
+ if (columnValues.length === 0) {
1059
+ return; // forEach
1060
+ }
1061
+ (_c = fetchReferences_1[_e = constraint.TABLE]) !== null && _c !== void 0 ? _c : (fetchReferences_1[_e] = {});
1062
+ (_d = (_f = fetchReferences_1[constraint.TABLE])[_g = constraint.COLUMN]) !== null && _d !== void 0 ? _d : (_f[_g] = []);
1063
+ fetchReferences_1[constraint.TABLE][constraint.COLUMN].push(columnValues);
1064
+ }); });
1065
+ console.log('fetchReferences', fetchReferences_1);
1066
+ _loop_1 = function (tableToFetch) {
1067
+ var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
1068
+ var _l;
1069
+ return __generator(this, function (_m) {
1070
+ switch (_m.label) {
1071
+ case 0:
1072
+ if (fetchDependencies & eFetchDependencies.C6ENTITY
1073
+ && 'string' === typeof tableName
1074
+ && tableName.endsWith("carbon_carbons")) {
1075
+ referencesTables = responseData_1.rest.reduce(function (accumulator, row) {
1076
+ if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
1077
+ accumulator.push(row['entity_tag']);
1078
+ }
1079
+ return accumulator;
1080
+ }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
1081
+ shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
1082
+ if (!shouldContinue) {
1083
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
1084
+ return [2 /*return*/, "continue"];
1085
+ }
1086
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
1087
+ }
1088
+ return [4 /*yield*/, C6.IMPORT(tableToFetch)];
1089
+ case 1:
1090
+ fetchTable = _m.sent();
1091
+ RestApi = fetchTable.default;
1092
+ console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1093
+ nextFetchDependencies = eFetchDependencies.NONE;
1094
+ if (fetchDependencies & eFetchDependencies.RECURSIVE) {
1095
+ if (fetchDependencies & eFetchDependencies.ALL) {
1096
+ throw Error('Recursive fetch dependencies with both PARENT and CHILD reference will result in an infin1ite loop. As there is not real ending condition, this is not supported.');
1097
+ }
1098
+ nextFetchDependencies = fetchDependencies;
1099
+ }
1100
+ else if (fetchDependencies & eFetchDependencies.C6ENTITY) {
1101
+ if (tableToFetch === "carbon_carbons") {
1102
+ nextFetchDependencies = fetchDependencies;
1103
+ }
1104
+ else {
1105
+ nextFetchDependencies = fetchDependencies ^ eFetchDependencies.C6ENTITY;
1106
+ }
1107
+ }
1108
+ console.log('fetchReferences', fetchReferences_1[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
1109
+ // todo - filter out ids that exist in state?!? note - remember that this does not necessarily mean the pk, but only known is its an FK to somewhere
1110
+ // it not certain that they are using carbons' entities either
1111
+ // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1112
+ // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1113
+ apiRequestPromises.push(RestApi.Get((_l = {},
1114
+ _l[C6.WHERE] = {
1115
+ 0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
1116
+ fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
1117
+ if (0 === fetchReferences_1[tableToFetch][column].length) {
1118
+ console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData_1);
1119
+ return false;
1120
+ }
1121
+ sum[column] = fetchReferences_1[tableToFetch][column].length === 1
1122
+ ? fetchReferences_1[tableToFetch][column][0]
1123
+ : [
1124
+ C6.IN, fetchReferences_1[tableToFetch][column]
1125
+ ];
1126
+ return sum;
1127
+ }, {})
1128
+ },
1129
+ _l.fetchDependencies = nextFetchDependencies,
1130
+ _l)));
1131
+ return [2 /*return*/];
1132
+ }
1133
+ });
1134
+ };
1135
+ _a = fetchReferences_1;
1136
+ _b = [];
1137
+ for (_c in _a)
1138
+ _b.push(_c);
1139
+ _i = 0;
1140
+ _k.label = 1;
1141
+ case 1:
1142
+ if (!(_i < _b.length)) return [3 /*break*/, 4];
1143
+ _c = _b[_i];
1144
+ if (!(_c in _a)) return [3 /*break*/, 3];
1145
+ tableToFetch = _c;
1146
+ return [5 /*yield**/, _loop_1(tableToFetch)];
1147
+ case 2:
1148
+ _k.sent();
1149
+ _k.label = 3;
1150
+ case 3:
1151
+ _i++;
1152
+ return [3 /*break*/, 1];
1153
+ case 4:
1154
+ console.groupEnd();
1155
+ return [4 /*yield*/, Promise.all(apiRequestPromises)];
1156
+ case 5:
1157
+ _k.sent();
1158
+ apiRequestPromises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
1159
+ var _a, _b;
1160
+ return __generator(this, function (_c) {
1161
+ switch (_c.label) {
1162
+ case 0:
1163
+ if (!Array.isArray(this.request.fetchDependencies)) {
1164
+ // to reassign value we must ref the root
1165
+ this.request.fetchDependencies = [];
1166
+ }
1167
+ _b = (_a = this.request.fetchDependencies).push;
1168
+ return [4 /*yield*/, promise];
1169
+ case 1:
1170
+ _b.apply(_a, [_c.sent()]);
1171
+ return [2 /*return*/];
1172
+ }
1173
+ });
1174
+ }); });
1175
+ _k.label = 6;
1176
+ case 6:
1177
+ if (debug && isLocal()) {
1178
+ toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1179
+ }
1180
+ // this is the literal axios return
1181
+ return [2 /*return*/, response];
1182
+ }
1183
+ });
1184
+ }); }).then(function (response) { return response.data; })]; // this escapes from axios context
1045
1185
  }
1046
- return accumulator;
1047
- }, []).map((entityTag) => entityTag.split('\\').pop().toLowerCase());
1048
- const shouldContinue = referencesTables.find((referencesTable) => tableToFetch.endsWith(referencesTable));
1049
- if (!shouldContinue) {
1050
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
1051
- continue;
1052
- }
1053
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
1054
- }
1055
- const fetchTable = await C6.IMPORT(tableToFetch);
1056
- const RestApi = fetchTable.default;
1057
- console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1058
- let nextFetchDependencies = eFetchDependencies.NONE;
1059
- if (fetchDependencies & eFetchDependencies.RECURSIVE) {
1060
- if (fetchDependencies & eFetchDependencies.ALL) {
1061
- throw Error('Recursive fetch dependencies with both PARENT and CHILD reference will result in an infin1ite loop. As there is not real ending condition, this is not supported.');
1062
- }
1063
- nextFetchDependencies = fetchDependencies;
1064
- }
1065
- else if (fetchDependencies & eFetchDependencies.C6ENTITY) {
1066
- if (tableToFetch === "carbon_carbons") {
1067
- nextFetchDependencies = fetchDependencies;
1068
- }
1069
- else {
1070
- nextFetchDependencies = fetchDependencies ^ eFetchDependencies.C6ENTITY;
1071
- }
1072
- }
1073
- console.log('fetchReferences', fetchReferences[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
1074
- // todo - filter out ids that exist in state?!? note - remember that this does not necessarily mean the pk, but only known is its an FK to somewhere
1075
- // it not certain that they are using carbons' entities either
1076
- // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1077
- // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1078
- apiRequestPromises.push(RestApi.Get({
1079
- [C6.WHERE]: {
1080
- 0: Object.keys(fetchReferences[tableToFetch]).reduce((sum, column) => {
1081
- fetchReferences[tableToFetch][column] = fetchReferences[tableToFetch][column].flat(Infinity);
1082
- if (0 === fetchReferences[tableToFetch][column].length) {
1083
- console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData);
1084
- return false;
1186
+ catch (throwableError) {
1187
+ if (isTest()) {
1188
+ throw new Error(JSON.stringify(throwableError));
1085
1189
  }
1086
- sum[column] = fetchReferences[tableToFetch][column].length === 1
1087
- ? fetchReferences[tableToFetch][column][0]
1088
- : [
1089
- C6.IN, fetchReferences[tableToFetch][column]
1090
- ];
1091
- return sum;
1092
- }, {})
1093
- },
1094
- fetchDependencies: nextFetchDependencies
1095
- }));
1096
- }
1097
- console.groupEnd();
1098
- await Promise.all(apiRequestPromises);
1099
- apiRequestPromises.map(async (promise) => {
1100
- if (!Array.isArray(this.request.fetchDependencies)) {
1101
- // to reassign value we must ref the root
1102
- this.request.fetchDependencies = [];
1190
+ console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1191
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1192
+ console.warn(throwableError);
1193
+ console.trace();
1194
+ console.groupEnd();
1195
+ TestRestfulResponse(throwableError, success, error);
1196
+ return [2 /*return*/, null];
1197
+ }
1198
+ return [2 /*return*/];
1103
1199
  }
1104
- this.request.fetchDependencies.push(await promise);
1105
1200
  });
1106
- }
1107
- }
1108
- if (debug && isLocal()) {
1109
- toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1110
- }
1111
- // this is the literal axios return
1112
- return response;
1113
- }).then(response => response.data); // this escapes from axios context
1114
- }
1115
- catch (throwableError) {
1116
- if (isTest()) {
1117
- throw new Error(JSON.stringify(throwableError));
1201
+ }); };
1202
+ return [4 /*yield*/, apiRequest()];
1203
+ case 2: return [2 /*return*/, _b.sent()];
1118
1204
  }
1119
- console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1120
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1121
- console.warn(throwableError);
1122
- console.trace();
1123
- console.groupEnd();
1124
- TestRestfulResponse(throwableError, success, error);
1125
- return null;
1126
- }
1127
- };
1128
- return await apiRequest();
1129
- }
1130
- }
1205
+ });
1206
+ });
1207
+ };
1208
+ return HttpExecutor;
1209
+ }(Executor));
1131
1210
 
1132
1211
  var HttpExecutor$1 = /*#__PURE__*/Object.freeze({
1133
1212
  __proto__: null,
@@ -1144,188 +1223,221 @@ function convertHexIfBinary(_col, val, columnDef) {
1144
1223
  return val;
1145
1224
  }
1146
1225
 
1147
- class AggregateBuilder extends Executor {
1148
- buildAggregateField(field) {
1226
+ var AggregateBuilder = /** @class */ (function (_super) {
1227
+ __extends(AggregateBuilder, _super);
1228
+ function AggregateBuilder() {
1229
+ return _super !== null && _super.apply(this, arguments) || this;
1230
+ }
1231
+ AggregateBuilder.prototype.buildAggregateField = function (field) {
1232
+ var _this = this;
1149
1233
  if (typeof field === 'string') {
1150
1234
  return field;
1151
1235
  }
1152
1236
  if (!Array.isArray(field) || field.length === 0) {
1153
1237
  throw new Error('Invalid SELECT field entry');
1154
1238
  }
1155
- let [fn, ...args] = field;
1156
- let alias;
1239
+ var fn = field[0], args = field.slice(1);
1240
+ var alias;
1157
1241
  if (args.length >= 2 && String(args[args.length - 2]).toUpperCase() === 'AS') {
1158
1242
  alias = String(args.pop());
1159
1243
  args.pop();
1160
1244
  }
1161
- const F = String(fn).toUpperCase();
1162
- const argList = args.map(arg => Array.isArray(arg) ? this.buildAggregateField(arg) : arg).join(', ');
1163
- let expr = `${F}(${argList})`;
1245
+ var F = String(fn).toUpperCase();
1246
+ var argList = args.map(function (arg) {
1247
+ return Array.isArray(arg) ? _this.buildAggregateField(arg) : arg;
1248
+ }).join(', ');
1249
+ var expr = "".concat(F, "(").concat(argList, ")");
1164
1250
  if (alias) {
1165
- expr += ` AS ${alias}`;
1251
+ expr += " AS ".concat(alias);
1166
1252
  }
1167
- this.config.verbose && console.log(`[SELECT] ${expr}`);
1253
+ this.config.verbose && console.log("[SELECT] ".concat(expr));
1168
1254
  return expr;
1169
- }
1170
- }
1255
+ };
1256
+ return AggregateBuilder;
1257
+ }(Executor));
1171
1258
 
1172
- class ConditionBuilder extends AggregateBuilder {
1173
- aliasMap = {};
1174
- initAlias(baseTable, joins) {
1175
- this.aliasMap = { [baseTable]: baseTable };
1259
+ var ConditionBuilder = /** @class */ (function (_super) {
1260
+ __extends(ConditionBuilder, _super);
1261
+ function ConditionBuilder() {
1262
+ var _this = _super !== null && _super.apply(this, arguments) || this;
1263
+ _this.aliasMap = {};
1264
+ _this.OPERATORS = new Set([
1265
+ C6C.EQUAL, C6C.NOT_EQUAL, C6C.LESS_THAN, C6C.LESS_THAN_OR_EQUAL_TO,
1266
+ C6C.GREATER_THAN, C6C.GREATER_THAN_OR_EQUAL_TO,
1267
+ C6C.LIKE, C6C.NOT_LIKE,
1268
+ C6C.IN, C6C.NOT_IN, 'NOT IN',
1269
+ C6C.IS, C6C.IS_NOT,
1270
+ C6C.BETWEEN, 'NOT BETWEEN',
1271
+ C6C.MATCH_AGAINST,
1272
+ C6C.ST_DISTANCE_SPHERE
1273
+ ]);
1274
+ return _this;
1275
+ }
1276
+ ConditionBuilder.prototype.initAlias = function (baseTable, joins) {
1277
+ var _a;
1278
+ this.aliasMap = (_a = {}, _a[baseTable] = baseTable, _a);
1176
1279
  if (!joins)
1177
1280
  return;
1178
- for (const joinType in joins) {
1179
- for (const raw in joins[joinType]) {
1180
- const [table, alias] = raw.split(' ');
1281
+ for (var joinType in joins) {
1282
+ for (var raw in joins[joinType]) {
1283
+ var _b = raw.split(' '), table = _b[0], alias = _b[1];
1181
1284
  this.aliasMap[alias || table] = table;
1182
1285
  }
1183
1286
  }
1184
- }
1185
- isColumnRef(ref) {
1287
+ };
1288
+ ConditionBuilder.prototype.isColumnRef = function (ref) {
1289
+ var _a, _b;
1186
1290
  if (typeof ref !== 'string' || !ref.includes('.'))
1187
1291
  return false;
1188
- const [prefix, column] = ref.split('.', 2);
1189
- const tableName = this.aliasMap[prefix] || prefix;
1190
- const table = this.config.C6?.TABLES?.[tableName];
1292
+ var _c = ref.split('.', 2), prefix = _c[0], column = _c[1];
1293
+ var tableName = this.aliasMap[prefix] || prefix;
1294
+ var table = (_b = (_a = this.config.C6) === null || _a === void 0 ? void 0 : _a.TABLES) === null || _b === void 0 ? void 0 : _b[tableName];
1191
1295
  if (!table)
1192
1296
  return false;
1193
- const fullKey = `${tableName}.${column}`;
1297
+ var fullKey = "".concat(tableName, ".").concat(column);
1194
1298
  if (table.COLUMNS && (fullKey in table.COLUMNS))
1195
1299
  return true;
1196
- if (table.COLUMNS && Object.values(table.COLUMNS).includes(ref))
1300
+ if (table.COLUMNS && Object.values(table.COLUMNS).includes(column))
1197
1301
  return true;
1198
- this.config.verbose && console.log(`[COLUMN REF] ${ref} is not a valid column reference`);
1199
1302
  return false;
1200
- }
1201
- execute() {
1303
+ };
1304
+ ConditionBuilder.prototype.execute = function () {
1202
1305
  throw new Error("Method not implemented.");
1203
- }
1204
- OPERATORS = new Set([
1205
- C6C.EQUAL, C6C.NOT_EQUAL, C6C.LESS_THAN, C6C.LESS_THAN_OR_EQUAL_TO,
1206
- C6C.GREATER_THAN, C6C.GREATER_THAN_OR_EQUAL_TO,
1207
- C6C.LIKE, C6C.NOT_LIKE,
1208
- C6C.IN, C6C.NOT_IN, 'NOT IN',
1209
- C6C.IS, C6C.IS_NOT,
1210
- C6C.BETWEEN, 'NOT BETWEEN',
1211
- C6C.MATCH_AGAINST,
1212
- C6C.ST_DISTANCE_SPHERE
1213
- ]);
1214
- validateOperator(op) {
1306
+ };
1307
+ ConditionBuilder.prototype.isTableReference = function (val) {
1308
+ var _a, _b;
1309
+ if (typeof val !== 'string' || !val.includes('.'))
1310
+ return false;
1311
+ var _c = val.split('.'), prefix = _c[0], column = _c[1];
1312
+ var tableName = (_a = this.aliasMap[prefix]) !== null && _a !== void 0 ? _a : prefix;
1313
+ return (typeof ((_b = this.config.C6) === null || _b === void 0 ? void 0 : _b.TABLES[tableName]) === 'object' &&
1314
+ val in this.config.C6.TABLES[tableName].COLUMNS &&
1315
+ this.config.C6.TABLES[tableName].COLUMNS[val] === column);
1316
+ };
1317
+ ConditionBuilder.prototype.validateOperator = function (op) {
1215
1318
  if (!this.OPERATORS.has(op)) {
1216
- throw new Error(`Invalid or unsupported SQL operator detected: '${op}'`);
1319
+ throw new Error("Invalid or unsupported SQL operator detected: '".concat(op, "'"));
1217
1320
  }
1218
- }
1219
- addParam(params, column, value) {
1220
- const columnDef = this.config.C6[column.split('.')[0]]?.TYPE_VALIDATION?.[column];
1221
- const val = convertHexIfBinary(column, value, columnDef);
1321
+ };
1322
+ ConditionBuilder.prototype.addParam = function (params, column, value) {
1323
+ var _a, _b;
1324
+ var columnDef = (_b = (_a = this.config.C6[column.split('.')[0]]) === null || _a === void 0 ? void 0 : _a.TYPE_VALIDATION) === null || _b === void 0 ? void 0 : _b[column];
1325
+ var val = convertHexIfBinary(column, value, columnDef);
1222
1326
  if (this.useNamedParams) {
1223
- const key = `param${Object.keys(params).length}`;
1327
+ var key = "param".concat(Object.keys(params).length);
1224
1328
  params[key] = val;
1225
- return `:${key}`;
1329
+ return ":".concat(key);
1226
1330
  }
1227
1331
  else {
1228
1332
  params.push(val);
1229
1333
  return '?';
1230
1334
  }
1231
- }
1232
- buildBooleanJoinedConditions(set, andMode = true, params = []) {
1233
- const booleanOperator = andMode ? 'AND' : 'OR';
1234
- const addCondition = (column, op, value) => {
1335
+ };
1336
+ ConditionBuilder.prototype.buildBooleanJoinedConditions = function (set, andMode, params) {
1337
+ var _this = this;
1338
+ if (andMode === void 0) { andMode = true; }
1339
+ if (params === void 0) { params = []; }
1340
+ var booleanOperator = andMode ? 'AND' : 'OR';
1341
+ var addCondition = function (column, op, value) {
1235
1342
  // Support function-based expressions like [C6C.ST_DISTANCE_SPHERE, col1, col2]
1236
1343
  if (typeof column === 'string' &&
1237
- this.OPERATORS.has(column) &&
1344
+ _this.OPERATORS.has(column) &&
1238
1345
  Array.isArray(op)) {
1239
1346
  if (column === C6C.ST_DISTANCE_SPHERE) {
1240
- const [col1, col2] = op;
1241
- const threshold = Array.isArray(value) ? value[0] : value;
1242
- return `ST_Distance_Sphere(${col1}, ${col2}) < ${this.addParam(params, '', threshold)}`;
1347
+ var col1 = op[0], col2 = op[1];
1348
+ var threshold = Array.isArray(value) ? value[0] : value;
1349
+ return "ST_Distance_Sphere(".concat(col1, ", ").concat(col2, ") < ").concat(_this.addParam(params, '', threshold));
1243
1350
  }
1244
1351
  }
1245
- const leftIsCol = this.isColumnRef(column);
1246
- const rightIsCol = typeof value === 'string' && this.isColumnRef(value);
1352
+ var leftIsCol = _this.isColumnRef(column);
1353
+ var leftIsRef = _this.isTableReference(column);
1354
+ var rightIsCol = typeof value === 'string' && _this.isColumnRef(value);
1247
1355
  if (!leftIsCol && !rightIsCol) {
1248
- throw new Error(`Potential SQL injection detected: '${column} ${op} ${value}'`);
1356
+ throw new Error("Potential SQL injection detected: '".concat(column, " ").concat(op, " ").concat(value, "'"));
1249
1357
  }
1250
- this.validateOperator(op);
1358
+ _this.validateOperator(op);
1251
1359
  if (op === C6C.MATCH_AGAINST && Array.isArray(value)) {
1252
- const [search, mode] = value;
1253
- const paramName = this.useNamedParams ? `param${Object.keys(params).length}` : null;
1254
- if (this.useNamedParams) {
1360
+ var search = value[0], mode = value[1];
1361
+ var paramName = _this.useNamedParams ? "param".concat(Object.keys(params).length) : null;
1362
+ if (_this.useNamedParams) {
1255
1363
  params[paramName] = search;
1256
1364
  }
1257
1365
  else {
1258
1366
  params.push(search);
1259
1367
  }
1260
- let againstClause;
1368
+ var againstClause = void 0;
1261
1369
  switch ((mode || '').toUpperCase()) {
1262
1370
  case 'BOOLEAN':
1263
- againstClause = this.useNamedParams ? `AGAINST(:${paramName} IN BOOLEAN MODE)` : `AGAINST(? IN BOOLEAN MODE)`;
1371
+ againstClause = _this.useNamedParams ? "AGAINST(:".concat(paramName, " IN BOOLEAN MODE)") : "AGAINST(? IN BOOLEAN MODE)";
1264
1372
  break;
1265
1373
  case 'WITH QUERY EXPANSION':
1266
- againstClause = this.useNamedParams ? `AGAINST(:${paramName} WITH QUERY EXPANSION)` : `AGAINST(? WITH QUERY EXPANSION)`;
1374
+ againstClause = _this.useNamedParams ? "AGAINST(:".concat(paramName, " WITH QUERY EXPANSION)") : "AGAINST(? WITH QUERY EXPANSION)";
1267
1375
  break;
1268
1376
  default: // NATURAL or undefined
1269
- againstClause = this.useNamedParams ? `AGAINST(:${paramName})` : `AGAINST(?)`;
1377
+ againstClause = _this.useNamedParams ? "AGAINST(:".concat(paramName, ")") : "AGAINST(?)";
1270
1378
  break;
1271
1379
  }
1272
1380
  if (!leftIsCol) {
1273
- throw new Error(`MATCH_AGAINST requires a table reference as the left operand. Column '${column}' is not a valid table reference.`);
1381
+ throw new Error("MATCH_AGAINST requires a table reference as the left operand. Column '".concat(column, "' is not a valid table reference."));
1274
1382
  }
1275
- const matchClause = `(MATCH(${column}) ${againstClause})`;
1276
- this.config.verbose && console.log(`[MATCH_AGAINST] ${matchClause}`);
1383
+ var matchClause = "(MATCH(".concat(column, ") ").concat(againstClause, ")");
1384
+ _this.config.verbose && console.log("[MATCH_AGAINST] ".concat(matchClause));
1277
1385
  return matchClause;
1278
1386
  }
1279
1387
  if ((op === C6C.IN || op === C6C.NOT_IN) && Array.isArray(value)) {
1280
- const placeholders = value.map(v => this.isColumnRef(v) ? v : this.addParam(params, column, v)).join(', ');
1281
- const normalized = op.replace('_', ' ');
1282
- if (!leftIsCol) {
1283
- throw new Error(`IN operator requires a table reference as the left operand. Column '${column}' is not a valid table reference.`);
1388
+ var placeholders = value.map(function (v) {
1389
+ return _this.isColumnRef(v) ? v : _this.addParam(params, column, v);
1390
+ }).join(', ');
1391
+ var normalized = op.replace('_', ' ');
1392
+ if (!leftIsRef) {
1393
+ throw new Error("IN operator requires a table reference as the left operand. Column '".concat(column, "' is not a valid table reference."));
1284
1394
  }
1285
- return `( ${column} ${normalized} (${placeholders}) )`;
1395
+ return "( ".concat(column, " ").concat(normalized, " (").concat(placeholders, ") )");
1286
1396
  }
1287
1397
  if (op === C6C.BETWEEN || op === 'NOT BETWEEN') {
1288
1398
  if (!Array.isArray(value) || value.length !== 2) {
1289
- throw new Error(`BETWEEN operator requires an array of two values. Received: ${JSON.stringify(value)}`);
1399
+ throw new Error("BETWEEN operator requires an array of two values");
1290
1400
  }
1291
- const [start, end] = value;
1292
- if (!leftIsCol) {
1293
- throw new Error(`BETWEEN operator requires a table reference as the left operand. Column '${column}' is not a valid table reference.`);
1401
+ var start = value[0], end = value[1];
1402
+ if (!leftIsRef) {
1403
+ throw new Error("BETWEEN operator requires a table reference as the left operand. Column '".concat(column, "' is not a valid table reference."));
1294
1404
  }
1295
- return `(${column}) ${op.replace('_', ' ')} ${this.addParam(params, column, start)} AND ${this.addParam(params, column, end)}`;
1405
+ return "(".concat(column, ") ").concat(op.replace('_', ' '), " ").concat(_this.addParam(params, column, start), " AND ").concat(_this.addParam(params, column, end));
1296
1406
  }
1297
- if (leftIsCol && rightIsCol) {
1298
- return `(${column}) ${op} ${value}`;
1407
+ var rightIsRef = _this.isTableReference(value);
1408
+ if (leftIsRef && rightIsRef) {
1409
+ return "(".concat(column, ") ").concat(op, " ").concat(value);
1299
1410
  }
1300
- if (leftIsCol && !rightIsCol) {
1301
- return `(${column}) ${op} ${this.addParam(params, column, value)}`;
1411
+ if (leftIsRef && !rightIsRef) {
1412
+ return "(".concat(column, ") ").concat(op, " ").concat(_this.addParam(params, column, value));
1302
1413
  }
1303
- if (rightIsCol) {
1304
- return `(${this.addParam(params, column, column)}) ${op} ${value}`;
1414
+ if (rightIsRef) {
1415
+ return "(".concat(_this.addParam(params, column, column), ") ").concat(op, " ").concat(value);
1305
1416
  }
1306
- throw new Error(`Neither operand appears to be a table reference`);
1417
+ throw new Error("Neither operand appears to be a table reference");
1307
1418
  };
1308
- const parts = [];
1309
- const buildFromObject = (obj, mode) => {
1310
- const subParts = [];
1311
- for (const [k, v] of Object.entries(obj)) {
1419
+ var parts = [];
1420
+ var buildFromObject = function (obj, mode) {
1421
+ var subParts = [];
1422
+ for (var _i = 0, _a = Object.entries(obj); _i < _a.length; _i++) {
1423
+ var _b = _a[_i], k = _b[0], v = _b[1];
1312
1424
  // numeric keys represent nested OR groups
1313
1425
  if (!isNaN(Number(k))) {
1314
- const sub = this.buildBooleanJoinedConditions(v, false, params);
1426
+ var sub = _this.buildBooleanJoinedConditions(v, false, params);
1315
1427
  if (sub)
1316
1428
  subParts.push(sub);
1317
1429
  continue;
1318
1430
  }
1319
1431
  if (typeof v === 'object' && v !== null && Object.keys(v).length === 1) {
1320
- const [op, val] = Object.entries(v)[0];
1432
+ var _c = Object.entries(v)[0], op = _c[0], val = _c[1];
1321
1433
  subParts.push(addCondition(k, op, val));
1322
1434
  }
1323
1435
  else if (Array.isArray(v) && v.length >= 2 && typeof v[0] === 'string') {
1324
- const [op, val] = v;
1436
+ var _d = v, op = _d[0], val = _d[1];
1325
1437
  subParts.push(addCondition(k, op, val));
1326
1438
  }
1327
1439
  else if (typeof v === 'object' && v !== null) {
1328
- const sub = this.buildBooleanJoinedConditions(v, mode, params);
1440
+ var sub = _this.buildBooleanJoinedConditions(v, mode, params);
1329
1441
  if (sub)
1330
1442
  subParts.push(sub);
1331
1443
  }
@@ -1333,105 +1445,126 @@ class ConditionBuilder extends AggregateBuilder {
1333
1445
  subParts.push(addCondition(k, '=', v));
1334
1446
  }
1335
1447
  }
1336
- return subParts.join(` ${mode ? 'AND' : 'OR'} `);
1448
+ return subParts.join(" ".concat(mode ? 'AND' : 'OR', " "));
1337
1449
  };
1338
1450
  if (Array.isArray(set)) {
1339
- for (const item of set) {
1340
- const sub = this.buildBooleanJoinedConditions(item, false, params);
1451
+ for (var _i = 0, set_1 = set; _i < set_1.length; _i++) {
1452
+ var item = set_1[_i];
1453
+ var sub = this.buildBooleanJoinedConditions(item, false, params);
1341
1454
  if (sub)
1342
1455
  parts.push(sub);
1343
1456
  }
1344
1457
  }
1345
1458
  else if (typeof set === 'object' && set !== null) {
1346
- const sub = buildFromObject(set, andMode);
1459
+ var sub = buildFromObject(set, andMode);
1347
1460
  if (sub)
1348
1461
  parts.push(sub);
1349
1462
  }
1350
- const clause = parts.join(` ${booleanOperator} `);
1351
- return clause ? `(${clause})` : '';
1352
- }
1353
- buildWhereClause(whereArg, params) {
1354
- const clause = this.buildBooleanJoinedConditions(whereArg, true, params);
1463
+ var clause = parts.join(" ".concat(booleanOperator, " "));
1464
+ return clause ? "(".concat(clause, ")") : '';
1465
+ };
1466
+ ConditionBuilder.prototype.buildWhereClause = function (whereArg, params) {
1467
+ var clause = this.buildBooleanJoinedConditions(whereArg, true, params);
1355
1468
  if (!clause)
1356
1469
  return '';
1357
- const trimmed = clause.replace(/^\((.*)\)$/, '$1');
1358
- this.config.verbose && console.log(`[WHERE] ${trimmed}`);
1359
- return ` WHERE ${trimmed}`;
1360
- }
1361
- }
1470
+ var trimmed = clause.replace(/^\((.*)\)$/, '$1');
1471
+ this.config.verbose && console.log("[WHERE] ".concat(trimmed));
1472
+ return " WHERE ".concat(trimmed);
1473
+ };
1474
+ return ConditionBuilder;
1475
+ }(AggregateBuilder));
1362
1476
 
1363
- class JoinBuilder extends ConditionBuilder {
1364
- buildJoinClauses(joinArgs, params) {
1365
- let sql = '';
1366
- for (const joinType in joinArgs) {
1367
- const joinKind = joinType.replace('_', ' ').toUpperCase();
1368
- for (const raw in joinArgs[joinType]) {
1369
- const [table, alias] = raw.split(' ');
1477
+ var JoinBuilder = /** @class */ (function (_super) {
1478
+ __extends(JoinBuilder, _super);
1479
+ function JoinBuilder() {
1480
+ return _super !== null && _super.apply(this, arguments) || this;
1481
+ }
1482
+ JoinBuilder.prototype.buildJoinClauses = function (joinArgs, params) {
1483
+ var sql = '';
1484
+ for (var joinType in joinArgs) {
1485
+ var joinKind = joinType.replace('_', ' ').toUpperCase();
1486
+ for (var raw in joinArgs[joinType]) {
1487
+ var _a = raw.split(' '), table = _a[0], alias = _a[1];
1370
1488
  this.aliasMap[alias || table] = table;
1371
- const onClause = this.buildBooleanJoinedConditions(joinArgs[joinType][raw], true, params);
1372
- const joinSql = alias ? `\`${table}\` AS \`${alias}\`` : `\`${table}\``;
1373
- sql += ` ${joinKind} JOIN ${joinSql} ON ${onClause}`;
1489
+ var onClause = this.buildBooleanJoinedConditions(joinArgs[joinType][raw], true, params);
1490
+ var joinSql = alias ? "`".concat(table, "` AS `").concat(alias, "`") : "`".concat(table, "`");
1491
+ sql += " ".concat(joinKind, " JOIN ").concat(joinSql, " ON ").concat(onClause);
1374
1492
  }
1375
1493
  }
1376
- this.config.verbose && console.log(`[JOIN] ${sql.trim()}`);
1494
+ this.config.verbose && console.log("[JOIN] ".concat(sql.trim()));
1377
1495
  return sql;
1378
- }
1379
- }
1496
+ };
1497
+ return JoinBuilder;
1498
+ }(ConditionBuilder));
1380
1499
 
1381
- class DeleteQueryBuilder extends JoinBuilder {
1382
- build(table) {
1383
- const params = this.useNamedParams ? {} : [];
1500
+ var DeleteQueryBuilder = /** @class */ (function (_super) {
1501
+ __extends(DeleteQueryBuilder, _super);
1502
+ function DeleteQueryBuilder() {
1503
+ return _super !== null && _super.apply(this, arguments) || this;
1504
+ }
1505
+ DeleteQueryBuilder.prototype.build = function (table) {
1506
+ this.aliasMap = {};
1507
+ var params = this.useNamedParams ? {} : [];
1384
1508
  this.initAlias(table, this.request.JOIN);
1385
- let sql = `DELETE \`${table}\` FROM \`${table}\``;
1509
+ var sql = "DELETE `".concat(table, "` FROM `").concat(table, "`");
1386
1510
  if (this.request.JOIN) {
1387
1511
  sql += this.buildJoinClauses(this.request.JOIN, params);
1388
1512
  }
1389
1513
  if (this.request.WHERE) {
1390
1514
  sql += this.buildWhereClause(this.request.WHERE, params);
1391
1515
  }
1392
- return { sql, params };
1393
- }
1394
- }
1516
+ return { sql: sql, params: params };
1517
+ };
1518
+ return DeleteQueryBuilder;
1519
+ }(JoinBuilder));
1395
1520
 
1396
- class PostQueryBuilder extends ConditionBuilder {
1397
- trimTablePrefix(table, column) {
1521
+ var PostQueryBuilder = /** @class */ (function (_super) {
1522
+ __extends(PostQueryBuilder, _super);
1523
+ function PostQueryBuilder() {
1524
+ return _super !== null && _super.apply(this, arguments) || this;
1525
+ }
1526
+ PostQueryBuilder.prototype.trimTablePrefix = function (table, column) {
1398
1527
  if (!column.includes('.'))
1399
1528
  return column;
1400
- const [prefix, col] = column.split('.', 2);
1529
+ var _a = column.split('.', 2), prefix = _a[0], col = _a[1];
1401
1530
  if (prefix !== table) {
1402
- throw new Error(`Invalid prefixed column: '${column}'. Expected prefix '${table}.'`);
1531
+ throw new Error("Invalid prefixed column: '".concat(column, "'. Expected prefix '").concat(table, ".'"));
1403
1532
  }
1404
1533
  return col;
1405
- }
1406
- build(table) {
1407
- const verb = C6C.REPLACE in this.request ? C6C.REPLACE : C6C.INSERT;
1408
- const body = verb in this.request ? this.request[verb] : this.request;
1409
- const keys = Object.keys(body);
1410
- const params = [];
1411
- const placeholders = [];
1412
- for (const key of keys) {
1413
- const value = body[key];
1414
- const placeholder = this.addParam(params, key, value);
1534
+ };
1535
+ PostQueryBuilder.prototype.build = function (table) {
1536
+ var _this = this;
1537
+ this.aliasMap = {};
1538
+ var verb = C6C.REPLACE in this.request ? C6C.REPLACE : C6C.INSERT;
1539
+ var body = verb in this.request ? this.request[verb] : this.request;
1540
+ var keys = Object.keys(body);
1541
+ var params = [];
1542
+ var placeholders = [];
1543
+ for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
1544
+ var key = keys_1[_i];
1545
+ var value = body[key];
1546
+ var placeholder = this.addParam(params, key, value);
1415
1547
  placeholders.push(placeholder);
1416
1548
  }
1417
- let sql = `${verb} INTO \`${table}\` (
1418
- ${keys.map(k => `\`${this.trimTablePrefix(table, k)}\``).join(', ')}
1419
- ) VALUES (
1420
- ${placeholders.join(', ')}
1421
- )`;
1549
+ var sql = "".concat(verb, " INTO `").concat(table, "` (\n ").concat(keys.map(function (k) { return "`".concat(_this.trimTablePrefix(table, k), "`"); }).join(', '), "\n ) VALUES (\n ").concat(placeholders.join(', '), "\n )");
1422
1550
  if (C6C.UPDATE in this.request) {
1423
- const updateData = this.request[C6C.UPDATE];
1551
+ var updateData = this.request[C6C.UPDATE];
1424
1552
  if (!Array.isArray(updateData)) {
1425
- throw new Error(`Update data must be an array of keys to update, got: ${JSON.stringify(updateData)}`);
1553
+ throw new Error("Update data must be an array of keys to update, got: ".concat(JSON.stringify(updateData)));
1426
1554
  }
1427
- const updateClause = updateData.map(k => `\`${k}\` = VALUES(\`${k}\`)`).join(', ');
1428
- sql += ` ON DUPLICATE KEY UPDATE ${updateClause}`;
1555
+ var updateClause = updateData.map(function (k) { return "`".concat(k, "` = VALUES(`").concat(k, "`)"); }).join(', ');
1556
+ sql += " ON DUPLICATE KEY UPDATE ".concat(updateClause);
1429
1557
  }
1430
- return { sql, params };
1431
- }
1432
- }
1558
+ return { sql: sql, params: params };
1559
+ };
1560
+ return PostQueryBuilder;
1561
+ }(ConditionBuilder));
1433
1562
 
1434
- class PaginationBuilder extends JoinBuilder {
1563
+ var PaginationBuilder = /** @class */ (function (_super) {
1564
+ __extends(PaginationBuilder, _super);
1565
+ function PaginationBuilder() {
1566
+ return _super !== null && _super.apply(this, arguments) || this;
1567
+ }
1435
1568
  /**
1436
1569
  * MySQL ORDER/LIMIT/OFFSET generator.
1437
1570
  *
@@ -1445,49 +1578,61 @@ class PaginationBuilder extends JoinBuilder {
1445
1578
  * }
1446
1579
  * ```
1447
1580
  */
1448
- buildPaginationClause(pagination) {
1449
- let sql = "";
1581
+ PaginationBuilder.prototype.buildPaginationClause = function (pagination) {
1582
+ var _this = this;
1583
+ var _a;
1584
+ var sql = "";
1450
1585
  /* -------- ORDER BY -------- */
1451
- if (pagination?.[C6Constants.ORDER]) {
1452
- const orderParts = [];
1453
- for (const [key, val] of Object.entries(pagination[C6Constants.ORDER])) {
1586
+ if (pagination === null || pagination === void 0 ? void 0 : pagination[C6Constants.ORDER]) {
1587
+ var orderParts = [];
1588
+ for (var _i = 0, _b = Object.entries(pagination[C6Constants.ORDER]); _i < _b.length; _i++) {
1589
+ var _c = _b[_i], key = _c[0], val = _c[1];
1454
1590
  // FUNCTION CALL: val is an array of args
1455
1591
  if (Array.isArray(val)) {
1456
- const args = val
1457
- .map((arg) => Array.isArray(arg) ? this.buildAggregateField(arg) : String(arg))
1592
+ var args = val
1593
+ .map(function (arg) { return Array.isArray(arg) ? _this.buildAggregateField(arg) : String(arg); })
1458
1594
  .join(", ");
1459
- orderParts.push(`${key}(${args})`);
1595
+ orderParts.push("".concat(key, "(").concat(args, ")"));
1460
1596
  }
1461
1597
  // SIMPLE COLUMN + DIR (ASC/DESC)
1462
1598
  else {
1463
- orderParts.push(`${key} ${String(val).toUpperCase()}`);
1599
+ orderParts.push("".concat(key, " ").concat(String(val).toUpperCase()));
1464
1600
  }
1465
1601
  }
1466
1602
  if (orderParts.length)
1467
- sql += ` ORDER BY ${orderParts.join(", ")}`;
1603
+ sql += " ORDER BY ".concat(orderParts.join(", "));
1468
1604
  }
1469
1605
  /* -------- LIMIT / OFFSET -------- */
1470
- if (pagination?.[C6Constants.LIMIT] != null) {
1471
- const lim = parseInt(pagination[C6Constants.LIMIT], 10);
1472
- const page = parseInt(pagination[C6Constants.PAGE] ?? 1, 10);
1473
- const offset = (page - 1) * lim;
1474
- sql += ` LIMIT ${offset}, ${lim}`;
1606
+ if ((pagination === null || pagination === void 0 ? void 0 : pagination[C6Constants.LIMIT]) != null) {
1607
+ var lim = parseInt(pagination[C6Constants.LIMIT], 10);
1608
+ var page = parseInt((_a = pagination[C6Constants.PAGE]) !== null && _a !== void 0 ? _a : 1, 10);
1609
+ var offset = (page - 1) * lim;
1610
+ sql += " LIMIT ".concat(offset, ", ").concat(lim);
1475
1611
  }
1476
- this.config.verbose && console.log(`[PAGINATION] ${sql.trim()}`);
1612
+ this.config.verbose && console.log("[PAGINATION] ".concat(sql.trim()));
1477
1613
  return sql;
1478
- }
1479
- }
1614
+ };
1615
+ return PaginationBuilder;
1616
+ }(JoinBuilder));
1480
1617
 
1481
- class SelectQueryBuilder extends PaginationBuilder {
1482
- build(table, isSubSelect = false) {
1483
- const args = this.request;
1618
+ var SelectQueryBuilder = /** @class */ (function (_super) {
1619
+ __extends(SelectQueryBuilder, _super);
1620
+ function SelectQueryBuilder() {
1621
+ return _super !== null && _super.apply(this, arguments) || this;
1622
+ }
1623
+ SelectQueryBuilder.prototype.build = function (table, isSubSelect) {
1624
+ var _this = this;
1625
+ var _a;
1626
+ if (isSubSelect === void 0) { isSubSelect = false; }
1627
+ this.aliasMap = {};
1628
+ var args = this.request;
1484
1629
  this.initAlias(table, args.JOIN);
1485
- const params = this.useNamedParams ? {} : [];
1486
- const selectList = args.SELECT ?? ['*'];
1487
- const selectFields = selectList
1488
- .map((f) => this.buildAggregateField(f))
1630
+ var params = this.useNamedParams ? {} : [];
1631
+ var selectList = (_a = args.SELECT) !== null && _a !== void 0 ? _a : ['*'];
1632
+ var selectFields = selectList
1633
+ .map(function (f) { return _this.buildAggregateField(f); })
1489
1634
  .join(', ');
1490
- let sql = `SELECT ${selectFields} FROM \`${table}\``;
1635
+ var sql = "SELECT ".concat(selectFields, " FROM `").concat(table, "`");
1491
1636
  if (args.JOIN) {
1492
1637
  sql += this.buildJoinClauses(args.JOIN, params);
1493
1638
  }
@@ -1495,165 +1640,229 @@ class SelectQueryBuilder extends PaginationBuilder {
1495
1640
  sql += this.buildWhereClause(args.WHERE, params);
1496
1641
  }
1497
1642
  if (args.GROUP_BY) {
1498
- const groupBy = Array.isArray(args.GROUP_BY)
1643
+ var groupBy = Array.isArray(args.GROUP_BY)
1499
1644
  ? args.GROUP_BY.join(', ')
1500
1645
  : args.GROUP_BY;
1501
- sql += ` GROUP BY ${groupBy}`;
1646
+ sql += " GROUP BY ".concat(groupBy);
1502
1647
  }
1503
1648
  if (args.HAVING) {
1504
- sql += ` HAVING ${this.buildBooleanJoinedConditions(args.HAVING, true, params)}`;
1649
+ sql += " HAVING ".concat(this.buildBooleanJoinedConditions(args.HAVING, true, params));
1505
1650
  }
1506
1651
  if (args.PAGINATION) {
1507
1652
  sql += this.buildPaginationClause(args.PAGINATION);
1508
1653
  }
1509
1654
  else if (!isSubSelect) {
1510
- sql += ` LIMIT 100`;
1655
+ sql += " LIMIT 100";
1511
1656
  }
1512
- console.log(`[SELECT] ${sql.trim()}`);
1513
- return { sql, params };
1514
- }
1515
- }
1657
+ console.log("[SELECT] ".concat(sql.trim()));
1658
+ return { sql: sql, params: params };
1659
+ };
1660
+ return SelectQueryBuilder;
1661
+ }(PaginationBuilder));
1516
1662
 
1517
- class UpdateQueryBuilder extends PaginationBuilder {
1518
- build(table) {
1519
- const args = this.request;
1520
- const params = this.useNamedParams ? {} : [];
1663
+ var UpdateQueryBuilder = /** @class */ (function (_super) {
1664
+ __extends(UpdateQueryBuilder, _super);
1665
+ function UpdateQueryBuilder() {
1666
+ return _super !== null && _super.apply(this, arguments) || this;
1667
+ }
1668
+ UpdateQueryBuilder.prototype.build = function (table) {
1669
+ var _this = this;
1670
+ this.aliasMap = {};
1671
+ var args = this.request;
1672
+ var params = this.useNamedParams ? {} : [];
1521
1673
  this.initAlias(table, args.JOIN);
1522
- let sql = `UPDATE \`${table}\``;
1674
+ var sql = "UPDATE `".concat(table, "`");
1523
1675
  if (args.JOIN) {
1524
1676
  sql += this.buildJoinClauses(args.JOIN, params);
1525
1677
  }
1526
1678
  if (!(C6C.UPDATE in this.request)) {
1527
1679
  throw new Error("No update data provided in the request.");
1528
1680
  }
1529
- const setClauses = Object.entries(this.request[C6C.UPDATE]).map(([col, val]) => this.addParam(params, col, val));
1530
- sql += ` SET ${setClauses.join(', ')}`;
1681
+ var setClauses = Object.entries(this.request[C6C.UPDATE]).map(function (_a) {
1682
+ var col = _a[0], val = _a[1];
1683
+ return _this.addParam(params, col, val);
1684
+ });
1685
+ sql += " SET ".concat(setClauses.join(', '));
1531
1686
  if (args.WHERE) {
1532
1687
  sql += this.buildWhereClause(args.WHERE, params);
1533
1688
  }
1534
1689
  if (args.PAGINATION) {
1535
1690
  sql += this.buildPaginationClause(args.PAGINATION);
1536
1691
  }
1537
- return { sql, params };
1538
- }
1539
- }
1692
+ return { sql: sql, params: params };
1693
+ };
1694
+ return UpdateQueryBuilder;
1695
+ }(PaginationBuilder));
1540
1696
 
1541
- class SqlExecutor extends Executor {
1542
- async execute() {
1543
- const { TABLE_NAME } = this.config.restModel;
1544
- const method = this.config.requestMethod;
1545
- this.config.verbose && console.log(`[SQL EXECUTOR] ▶️ Executing ${method} on table "${TABLE_NAME}"`);
1546
- this.config.verbose && console.log(`[SQL EXECUTOR] 🧩 Request:`, JSON.stringify(this.request, undefined, 2));
1547
- switch (method) {
1548
- case 'GET': {
1549
- const rest = await this.runQuery();
1550
- return rest;
1551
- }
1552
- case 'POST': {
1553
- const result = await this.runQuery();
1554
- return result;
1555
- }
1556
- case 'PUT': {
1557
- const result = await this.runQuery();
1558
- return result;
1559
- }
1560
- case 'DELETE': {
1561
- const result = await this.runQuery();
1562
- return result;
1563
- }
1564
- default:
1565
- throw new Error(`Unsupported request method: ${method}`);
1566
- }
1567
- }
1568
- async withConnection(cb) {
1569
- console.log(`[SQL EXECUTOR] 📡 Getting DB connection`);
1570
- const conn = await this.config.mysqlPool.getConnection();
1571
- try {
1572
- this.config.verbose && console.log(`[SQL EXECUTOR] ✅ Connection acquired`);
1573
- return await cb(conn);
1574
- }
1575
- finally {
1576
- this.config.verbose && console.log(`[SQL EXECUTOR] 🔌 Releasing DB connection`);
1577
- conn.release();
1578
- }
1697
+ var SqlExecutor = /** @class */ (function (_super) {
1698
+ __extends(SqlExecutor, _super);
1699
+ function SqlExecutor() {
1700
+ var _this = _super !== null && _super.apply(this, arguments) || this;
1701
+ _this.serialize = function (row) { return Object.fromEntries(Object.entries(row).map(function (_a) {
1702
+ var k = _a[0], v = _a[1];
1703
+ return [k, Buffer$1.isBuffer(v) ? v.toString('hex').toUpperCase() : v];
1704
+ })); };
1705
+ return _this;
1579
1706
  }
1580
- serialize = (row) => Object.fromEntries(Object.entries(row).map(([k, v]) => [k, Buffer$1.isBuffer(v) ? v.toString('hex').toUpperCase() : v]));
1581
- formatSQLWithParams(sql, params) {
1707
+ SqlExecutor.prototype.execute = function () {
1708
+ return __awaiter(this, void 0, void 0, function () {
1709
+ var TABLE_NAME, method, _a, rest, result, result, result;
1710
+ return __generator(this, function (_b) {
1711
+ switch (_b.label) {
1712
+ case 0:
1713
+ TABLE_NAME = this.config.restModel.TABLE_NAME;
1714
+ method = this.config.requestMethod;
1715
+ this.config.verbose && console.log("[SQL EXECUTOR] \u25B6\uFE0F Executing ".concat(method, " on table \"").concat(TABLE_NAME, "\""));
1716
+ this.config.verbose && console.log("[SQL EXECUTOR] \uD83E\uDDE9 Request body:", this.request.body);
1717
+ this.config.verbose && console.log("[SQL EXECUTOR] \uD83E\uDDE9 Request query:", this.request.query);
1718
+ _a = method;
1719
+ switch (_a) {
1720
+ case 'GET': return [3 /*break*/, 1];
1721
+ case 'POST': return [3 /*break*/, 3];
1722
+ case 'PUT': return [3 /*break*/, 5];
1723
+ case 'DELETE': return [3 /*break*/, 7];
1724
+ }
1725
+ return [3 /*break*/, 9];
1726
+ case 1: return [4 /*yield*/, this.runQuery()];
1727
+ case 2:
1728
+ rest = _b.sent();
1729
+ return [2 /*return*/, rest];
1730
+ case 3: return [4 /*yield*/, this.runQuery()];
1731
+ case 4:
1732
+ result = _b.sent();
1733
+ return [2 /*return*/, result];
1734
+ case 5: return [4 /*yield*/, this.runQuery()];
1735
+ case 6:
1736
+ result = _b.sent();
1737
+ return [2 /*return*/, result];
1738
+ case 7: return [4 /*yield*/, this.runQuery()];
1739
+ case 8:
1740
+ result = _b.sent();
1741
+ return [2 /*return*/, result];
1742
+ case 9: throw new Error("Unsupported request method: ".concat(method));
1743
+ }
1744
+ });
1745
+ });
1746
+ };
1747
+ SqlExecutor.prototype.withConnection = function (cb) {
1748
+ return __awaiter(this, void 0, void 0, function () {
1749
+ var conn;
1750
+ return __generator(this, function (_a) {
1751
+ switch (_a.label) {
1752
+ case 0:
1753
+ console.log("[SQL EXECUTOR] \uD83D\uDCE1 Getting DB connection");
1754
+ return [4 /*yield*/, this.config.mysqlPool.getConnection()];
1755
+ case 1:
1756
+ conn = _a.sent();
1757
+ _a.label = 2;
1758
+ case 2:
1759
+ _a.trys.push([2, , 4, 5]);
1760
+ this.config.verbose && console.log("[SQL EXECUTOR] \u2705 Connection acquired");
1761
+ return [4 /*yield*/, cb(conn)];
1762
+ case 3: return [2 /*return*/, _a.sent()];
1763
+ case 4:
1764
+ this.config.verbose && console.log("[SQL EXECUTOR] \uD83D\uDD0C Releasing DB connection");
1765
+ conn.release();
1766
+ return [7 /*endfinally*/];
1767
+ case 5: return [2 /*return*/];
1768
+ }
1769
+ });
1770
+ });
1771
+ };
1772
+ SqlExecutor.prototype.formatSQLWithParams = function (sql, params) {
1773
+ var _this = this;
1582
1774
  if (Array.isArray(params)) {
1583
- let index = 0;
1584
- return sql.replace(/\?/g, () => {
1585
- if (index >= params.length)
1775
+ var index_1 = 0;
1776
+ return sql.replace(/\?/g, function () {
1777
+ if (index_1 >= params.length)
1586
1778
  return '?';
1587
- const val = params[index++];
1588
- return this.formatValue(val);
1779
+ var val = params[index_1++];
1780
+ return _this.formatValue(val);
1589
1781
  });
1590
1782
  }
1591
1783
  else {
1592
- return sql.replace(/:([a-zA-Z0-9_]+)/g, (_, key) => {
1593
- const val = params[key];
1594
- return this.formatValue(val);
1784
+ return sql.replace(/:([a-zA-Z0-9_]+)/g, function (_, key) {
1785
+ var val = params[key];
1786
+ return _this.formatValue(val);
1595
1787
  });
1596
1788
  }
1597
- }
1598
- formatValue(val) {
1789
+ };
1790
+ SqlExecutor.prototype.formatValue = function (val) {
1599
1791
  if (val === null || val === undefined)
1600
1792
  return 'NULL';
1601
1793
  if (Buffer$1.isBuffer(val))
1602
- return `UNHEX('${val.toString('hex')}')`;
1794
+ return "UNHEX('".concat(val.toString('hex'), "')");
1603
1795
  if (typeof val === 'string')
1604
- return `'${val.replace(/'/g, "''")}'`;
1796
+ return "'".concat(val.replace(/'/g, "''"), "'");
1605
1797
  if (typeof val === 'number')
1606
1798
  return val.toString();
1607
1799
  if (val instanceof Date)
1608
- return `'${val.toISOString().slice(0, 19).replace('T', ' ')}'`;
1609
- return `'${JSON.stringify(val)}'`;
1610
- }
1611
- async runQuery() {
1612
- const { TABLE_NAME } = this.config.restModel;
1613
- const method = this.config.requestMethod;
1614
- let builder;
1615
- switch (method) {
1616
- case 'GET':
1617
- builder = new SelectQueryBuilder(this.config, this.request);
1618
- break;
1619
- case 'PUT':
1620
- builder = new UpdateQueryBuilder(this.config, this.request);
1621
- break;
1622
- case 'DELETE':
1623
- builder = new DeleteQueryBuilder(this.config, this.request);
1624
- break;
1625
- case 'POST':
1626
- builder = new PostQueryBuilder(this.config, this.request);
1627
- break;
1628
- default:
1629
- throw new Error(`Unsupported query method: ${method}`);
1630
- }
1631
- const QueryResult = builder.build(TABLE_NAME);
1632
- this.config.verbose && console.log(`[SQL EXECUTOR] 🧠 Generated ${method.toUpperCase()} SQL:`, QueryResult);
1633
- const formatted = this.formatSQLWithParams(QueryResult.sql, QueryResult.params);
1634
- this.config.verbose && console.log(`[SQL EXECUTOR] 🧠 Formatted ${method.toUpperCase()} SQL:`, formatted);
1635
- const toUnnamed = namedPlaceholders();
1636
- const [sql, values] = toUnnamed(QueryResult.sql, QueryResult.params);
1637
- return await this.withConnection(async (conn) => {
1638
- const [result] = await conn.query(sql, values);
1639
- if (method === 'GET') {
1640
- this.config.verbose && console.log(`[SQL EXECUTOR] 📦 Rows fetched:`, result);
1641
- return {
1642
- rest: result.map(this.serialize),
1643
- sql: { sql, values }
1644
- };
1645
- }
1646
- else {
1647
- this.config.verbose && console.log(`[SQL EXECUTOR] ✏️ Rows affected:`, result.affectedRows);
1648
- return {
1649
- affected: result.affectedRows,
1650
- rest: [],
1651
- sql: { sql, values }
1652
- };
1653
- }
1800
+ return "'".concat(val.toISOString().slice(0, 19).replace('T', ' '), "'");
1801
+ return "'".concat(JSON.stringify(val), "'");
1802
+ };
1803
+ SqlExecutor.prototype.runQuery = function () {
1804
+ return __awaiter(this, void 0, void 0, function () {
1805
+ var TABLE_NAME, method, builder, QueryResult, formatted, toUnnamed, _a, sql, values;
1806
+ var _this = this;
1807
+ return __generator(this, function (_b) {
1808
+ switch (_b.label) {
1809
+ case 0:
1810
+ TABLE_NAME = this.config.restModel.TABLE_NAME;
1811
+ method = this.config.requestMethod;
1812
+ switch (method) {
1813
+ case 'GET':
1814
+ builder = new SelectQueryBuilder(this.config, this.request);
1815
+ break;
1816
+ case 'PUT':
1817
+ builder = new UpdateQueryBuilder(this.config, this.request);
1818
+ break;
1819
+ case 'DELETE':
1820
+ builder = new DeleteQueryBuilder(this.config, this.request);
1821
+ break;
1822
+ case 'POST':
1823
+ builder = new PostQueryBuilder(this.config, this.request);
1824
+ break;
1825
+ default:
1826
+ throw new Error("Unsupported query method: ".concat(method));
1827
+ }
1828
+ QueryResult = builder.build(TABLE_NAME);
1829
+ this.config.verbose && console.log("[SQL EXECUTOR] \uD83E\uDDE0 Generated ".concat(method.toUpperCase(), " SQL:"), QueryResult);
1830
+ formatted = this.formatSQLWithParams(QueryResult.sql, QueryResult.params);
1831
+ this.config.verbose && console.log("[SQL EXECUTOR] \uD83E\uDDE0 Formatted ".concat(method.toUpperCase(), " SQL:"), formatted);
1832
+ toUnnamed = namedPlaceholders();
1833
+ _a = toUnnamed(QueryResult.sql, QueryResult.params), sql = _a[0], values = _a[1];
1834
+ return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1835
+ var result;
1836
+ return __generator(this, function (_a) {
1837
+ switch (_a.label) {
1838
+ case 0: return [4 /*yield*/, conn.query(sql, values)];
1839
+ case 1:
1840
+ result = (_a.sent())[0];
1841
+ if (method === 'GET') {
1842
+ this.config.verbose && console.log("[SQL EXECUTOR] \uD83D\uDCE6 Rows fetched:", result);
1843
+ return [2 /*return*/, {
1844
+ rest: result.map(this.serialize),
1845
+ sql: { sql: sql, values: values }
1846
+ }];
1847
+ }
1848
+ else {
1849
+ this.config.verbose && console.log("[SQL EXECUTOR] \u270F\uFE0F Rows affected:", result.affectedRows);
1850
+ return [2 /*return*/, {
1851
+ affected: result.affectedRows,
1852
+ rest: [],
1853
+ sql: { sql: sql, values: values }
1854
+ }];
1855
+ }
1856
+ }
1857
+ });
1858
+ }); })];
1859
+ case 1: return [2 /*return*/, _b.sent()];
1860
+ }
1861
+ });
1654
1862
  });
1655
- }
1656
- }
1863
+ };
1864
+ return SqlExecutor;
1865
+ }(Executor));
1657
1866
 
1658
1867
  var SqlExecutor$1 = /*#__PURE__*/Object.freeze({
1659
1868
  __proto__: null,
@@ -1662,80 +1871,101 @@ var SqlExecutor$1 = /*#__PURE__*/Object.freeze({
1662
1871
 
1663
1872
  // TODO - WE MUST make this a generic - optional, but helpful
1664
1873
  // note sure how it would help anyone actually...
1665
- function ExpressHandler({ C6, mysqlPool }) {
1666
- return async (req, res, next) => {
1667
- try {
1668
- const method = req.method.toUpperCase();
1669
- const table = req.params.table;
1670
- const primary = req.params.primary;
1671
- const payload = method === 'GET' ? req.query : req.body;
1672
- if (!(table in C6.TABLES)) {
1673
- res.status(400).json({ error: `Invalid table: ${table}` });
1674
- return;
1675
- }
1676
- const primaryKeys = C6.TABLES[table].PRIMARY;
1677
- if (primary && primaryKeys.length !== 1) {
1678
- if (primaryKeys.length > 1) {
1679
- res.status(400).json({ error: `Table ${table} has multiple primary keys. Cannot implicitly determine key.` });
1680
- return;
1681
- }
1682
- res.status(400).json({
1683
- error: `Table ${table} has no primary keys. Please specify one.`
1684
- });
1685
- return;
1686
- }
1687
- const primaryKeyName = primaryKeys[0];
1688
- // 👇 Call restRequest for the resolved method
1689
- // TODO - add primary conditionally based on method signature
1690
- switch (method) {
1691
- case 'GET':
1692
- if (primary) {
1693
- payload[C6C.WHERE][primaryKeyName] = primary;
1874
+ function ExpressHandler(_a) {
1875
+ var _this = this;
1876
+ var C6 = _a.C6, mysqlPool = _a.mysqlPool;
1877
+ return function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
1878
+ var method, table, primary, payload, primaryKeys, primaryKeyName, response, err_1;
1879
+ return __generator(this, function (_a) {
1880
+ switch (_a.label) {
1881
+ case 0:
1882
+ _a.trys.push([0, 2, , 3]);
1883
+ method = req.method.toUpperCase();
1884
+ table = req.params.table;
1885
+ primary = req.params.primary;
1886
+ payload = method === 'GET' ? req.query : req.body;
1887
+ if (!(table in C6.TABLES)) {
1888
+ res.status(400).json({ error: "Invalid table: ".concat(table) });
1889
+ return [2 /*return*/];
1694
1890
  }
1695
- break;
1696
- case 'PUT':
1697
- case 'DELETE':
1698
- if (primary) {
1699
- payload[C6C.WHERE][primaryKeyName] = primary;
1891
+ primaryKeys = C6.TABLES[table].PRIMARY;
1892
+ if (primary && primaryKeys.length !== 1) {
1893
+ if (primaryKeys.length > 1) {
1894
+ res.status(400).json({ error: "Table ".concat(table, " has multiple primary keys. Cannot implicitly determine key.") });
1895
+ return [2 /*return*/];
1896
+ }
1897
+ res.status(400).json({
1898
+ error: "Table ".concat(table, " has no primary keys. Please specify one.")
1899
+ });
1900
+ return [2 /*return*/];
1700
1901
  }
1701
- else {
1702
- res.status(400).json({ error: `Invalid request: ${method} requires a primary key.` });
1902
+ primaryKeyName = primaryKeys[0];
1903
+ // 👇 Call restRequest for the resolved method
1904
+ // TODO - add primary conditionally based on method signature
1905
+ switch (method) {
1906
+ case 'GET':
1907
+ if (primary) {
1908
+ payload[C6C.WHERE][primaryKeyName] = primary;
1909
+ }
1910
+ break;
1911
+ case 'PUT':
1912
+ case 'DELETE':
1913
+ if (primary) {
1914
+ payload[C6C.WHERE][primaryKeyName] = primary;
1915
+ }
1916
+ else {
1917
+ res.status(400).json({ error: "Invalid request: ".concat(method, " requires a primary key.") });
1918
+ }
1919
+ break;
1920
+ case 'POST':
1921
+ break;
1922
+ default:
1923
+ res.status(405).json({ error: "Method ".concat(method, " not allowed") });
1924
+ return [2 /*return*/];
1703
1925
  }
1704
- break;
1705
- case 'POST':
1706
- break;
1707
- default:
1708
- res.status(405).json({ error: `Method ${method} not allowed` });
1709
- return;
1926
+ return [4 /*yield*/, restRequest({
1927
+ C6: C6,
1928
+ mysqlPool: mysqlPool,
1929
+ requestMethod: method,
1930
+ restModel: C6.TABLES[table]
1931
+ })(payload)];
1932
+ case 1:
1933
+ response = _a.sent();
1934
+ res.status(200).json(__assign({ success: true }, response));
1935
+ return [3 /*break*/, 3];
1936
+ case 2:
1937
+ err_1 = _a.sent();
1938
+ res.status(500).json({ success: false, error: err_1 });
1939
+ next(err_1);
1940
+ return [3 /*break*/, 3];
1941
+ case 3: return [2 /*return*/];
1710
1942
  }
1711
- const response = await restRequest({
1712
- C6,
1713
- mysqlPool,
1714
- requestMethod: method,
1715
- restModel: C6.TABLES[table]
1716
- })(payload);
1717
- res.status(200).json({ success: true, ...response });
1718
- }
1719
- catch (err) {
1720
- res.status(500).json({ success: false, error: err });
1721
- next(err);
1722
- }
1723
- };
1943
+ });
1944
+ }); };
1724
1945
  }
1725
1946
 
1726
1947
  // Alias a table name with a given alias
1727
- const A = (tableName, alias) => `${tableName} ${alias}`;
1948
+ var A = function (tableName, alias) {
1949
+ return "".concat(tableName, " ").concat(alias);
1950
+ };
1728
1951
  // Qualify a column constant (e.g. 'property_units.parcel_id') to an alias
1729
- const F = (qualifiedCol, alias) => `${alias}.${qualifiedCol.split('.').pop()}`;
1952
+ var F = function (qualifiedCol, alias) {
1953
+ return "".concat(alias, ".").concat(qualifiedCol.split('.').pop());
1954
+ };
1730
1955
  // Equal join condition using full-qualified column constants
1731
- const fieldEq = (leftCol, rightCol, leftAlias, rightAlias) => ({
1732
- [F(leftCol, leftAlias)]: F(rightCol, rightAlias)
1733
- });
1956
+ var fieldEq = function (leftCol, rightCol, leftAlias, rightAlias) {
1957
+ var _a;
1958
+ return (_a = {},
1959
+ _a[F(leftCol, leftAlias)] = F(rightCol, rightAlias),
1960
+ _a);
1961
+ };
1734
1962
  // ST_Distance_Sphere for aliased fields
1735
- const distSphere = (fromCol, toCol, fromAlias, toAlias) => [C6C.ST_DISTANCE_SPHERE, F(fromCol, fromAlias), F(toCol, toAlias)];
1963
+ var distSphere = function (fromCol, toCol, fromAlias, toAlias) {
1964
+ return [C6C.ST_DISTANCE_SPHERE, F(fromCol, fromAlias), F(toCol, toAlias)];
1965
+ };
1736
1966
 
1737
1967
  function determineRuntimeJsType(mysqlType) {
1738
- const base = mysqlType.toLowerCase().split('(')[0];
1968
+ var base = mysqlType.toLowerCase().split('(')[0];
1739
1969
  if ([
1740
1970
  'binary', 'varbinary', 'blob', 'tinyblob', 'mediumblob', 'longblob'
1741
1971
  ].includes(base))
@@ -1756,15 +1986,23 @@ function determineRuntimeJsType(mysqlType) {
1756
1986
  return 'string';
1757
1987
  }
1758
1988
  function getPrimaryKeyTypes(table) {
1759
- const result = {};
1760
- for (const key of table.PRIMARY_SHORT) {
1761
- const fullKey = Object.entries(table.COLUMNS).find(([_, short]) => short === key)?.[0];
1989
+ var _a;
1990
+ var result = {};
1991
+ var _loop_1 = function (key) {
1992
+ var fullKey = (_a = Object.entries(table.COLUMNS).find(function (_a) {
1993
+ _a[0]; var short = _a[1];
1994
+ return short === key;
1995
+ })) === null || _a === void 0 ? void 0 : _a[0];
1762
1996
  if (typeof fullKey === 'string') {
1763
- const validation = table.TYPE_VALIDATION[fullKey];
1997
+ var validation = table.TYPE_VALIDATION[fullKey];
1764
1998
  if (!validation)
1765
- continue;
1999
+ return "continue";
1766
2000
  result[key] = determineRuntimeJsType(validation.MYSQL_TYPE);
1767
2001
  }
2002
+ };
2003
+ for (var _i = 0, _b = table.PRIMARY_SHORT; _i < _b.length; _i++) {
2004
+ var key = _b[_i];
2005
+ _loop_1(key);
1768
2006
  }
1769
2007
  return result;
1770
2008
  }
@@ -1773,30 +2011,42 @@ function getPrimaryKeyTypes(table) {
1773
2011
  * Conditionally group a log if verbose.
1774
2012
  */
1775
2013
  function group(title, data) {
1776
- console.groupCollapsed(`%c${title}`, "color: #007acc");
2014
+ console.groupCollapsed("%c".concat(title), "color: #007acc");
1777
2015
  if (data !== undefined)
1778
2016
  console.log(data);
1779
2017
  console.groupEnd();
1780
2018
  }
1781
- function info(message, ...optional) {
1782
- console.info(`%cINFO: ${message}`, "color: #0a0", ...optional);
2019
+ function info(message) {
2020
+ var optional = [];
2021
+ for (var _i = 1; _i < arguments.length; _i++) {
2022
+ optional[_i - 1] = arguments[_i];
2023
+ }
2024
+ console.info.apply(console, __spreadArray(["%cINFO: ".concat(message), "color: #0a0"], optional, false));
1783
2025
  }
1784
- function warn(message, ...optional) {
1785
- console.warn(`%cWARN: ${message}`, "color: #e90", ...optional);
2026
+ function warn(message) {
2027
+ var optional = [];
2028
+ for (var _i = 1; _i < arguments.length; _i++) {
2029
+ optional[_i - 1] = arguments[_i];
2030
+ }
2031
+ console.warn.apply(console, __spreadArray(["%cWARN: ".concat(message), "color: #e90"], optional, false));
1786
2032
  }
1787
- function error(message, ...optional) {
1788
- console.error(`%cERROR: ${message}`, "color: #c00", ...optional);
2033
+ function error(message) {
2034
+ var optional = [];
2035
+ for (var _i = 1; _i < arguments.length; _i++) {
2036
+ optional[_i - 1] = arguments[_i];
2037
+ }
2038
+ console.error.apply(console, __spreadArray(["%cERROR: ".concat(message), "color: #c00"], optional, false));
1789
2039
  }
1790
2040
 
1791
2041
  function checkAllRequestsComplete() {
1792
- const stillRunning = apiRequestCache.filter((cache) => undefined === cache.response);
2042
+ var stillRunning = apiRequestCache.filter(function (cache) { return undefined === cache.response; });
1793
2043
  if (stillRunning.length !== 0) {
1794
2044
  if (document === null || document === undefined) {
1795
2045
  throw new Error('document is undefined while waiting for API requests to complete (' + JSON.stringify(apiRequestCache) + ')');
1796
2046
  }
1797
2047
  // when requests return emtpy sets in full renders, it may not be possible to track their progress.
1798
2048
  console.warn('stillRunning...', stillRunning);
1799
- return stillRunning.map((cache) => cache.requestArgumentsSerialized);
2049
+ return stillRunning.map(function (cache) { return cache.requestArgumentsSerialized; });
1800
2050
  }
1801
2051
  return true;
1802
2052
  }
@@ -1809,7 +2059,7 @@ function onError(message) {
1809
2059
  }
1810
2060
 
1811
2061
  function isVerbose () {
1812
- const envVerbose = getEnvVar('VERBOSE') || getEnvVar('REACT_APP_VERBOSE') || getEnvVar('VITE_VERBOSE') || '';
2062
+ var envVerbose = getEnvVar('VERBOSE') || getEnvVar('REACT_APP_VERBOSE') || getEnvVar('VITE_VERBOSE') || '';
1813
2063
  return ['true', '1', 'yes', 'on'].includes(envVerbose.toLowerCase());
1814
2064
  }
1815
2065