@carbonorm/carbonnode 2.0.33 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/api/carbonSqlExecutor.d.ts +17 -0
  2. package/dist/api/interfaces/ormInterfaces.d.ts +22 -1
  3. package/dist/api/rest/Blog_Categories.d.ts +37 -0
  4. package/dist/api/rest/Blog_Categories.test.d.ts +11 -0
  5. package/dist/api/rest/Blog_Images.d.ts +37 -0
  6. package/dist/api/rest/Blog_Images.test.d.ts +15 -0
  7. package/dist/api/rest/Blog_Post_Categories.d.ts +37 -0
  8. package/dist/api/rest/Blog_Post_Categories.test.d.ts +13 -0
  9. package/dist/api/rest/Blog_Post_Tags.d.ts +37 -0
  10. package/dist/api/rest/Blog_Post_Tags.test.d.ts +13 -0
  11. package/dist/api/rest/Blog_Posts.d.ts +37 -0
  12. package/dist/api/rest/Blog_Posts.test.d.ts +21 -0
  13. package/dist/api/rest/Blog_Tags.d.ts +37 -0
  14. package/dist/api/rest/Blog_Tags.test.d.ts +11 -0
  15. package/dist/api/rest/C6.d.ts +1000 -0
  16. package/dist/api/rest/Cache.d.ts +37 -0
  17. package/dist/api/rest/Cache.test.d.ts +12 -0
  18. package/dist/api/rest/Cities.d.ts +37 -0
  19. package/dist/api/rest/Cities.test.d.ts +17 -0
  20. package/dist/api/rest/Counties.d.ts +37 -0
  21. package/dist/api/rest/Counties.test.d.ts +18 -0
  22. package/dist/api/rest/Countries.d.ts +37 -0
  23. package/dist/api/rest/Countries.test.d.ts +24 -0
  24. package/dist/api/rest/Geometries.d.ts +37 -0
  25. package/dist/api/rest/Geometries.test.d.ts +16 -0
  26. package/dist/api/rest/Images.d.ts +37 -0
  27. package/dist/api/rest/Images.test.d.ts +16 -0
  28. package/dist/api/rest/Land_Section_Info.d.ts +37 -0
  29. package/dist/api/rest/Land_Section_Info.test.d.ts +15 -0
  30. package/dist/api/rest/Neighborhoods.d.ts +37 -0
  31. package/dist/api/rest/Neighborhoods.test.d.ts +12 -0
  32. package/dist/api/rest/Parcel_Building_Details.d.ts +37 -0
  33. package/dist/api/rest/Parcel_Building_Details.test.d.ts +40 -0
  34. package/dist/api/rest/Parcel_Neighborhoods.d.ts +37 -0
  35. package/dist/api/rest/Parcel_Neighborhoods.test.d.ts +15 -0
  36. package/dist/api/rest/Parcel_Owners.d.ts +37 -0
  37. package/dist/api/rest/Parcel_Owners.test.d.ts +23 -0
  38. package/dist/api/rest/Parcel_Sales.d.ts +37 -0
  39. package/dist/api/rest/Parcel_Sales.test.d.ts +19 -0
  40. package/dist/api/rest/Parcel_Tax_History.d.ts +37 -0
  41. package/dist/api/rest/Parcel_Tax_History.test.d.ts +24 -0
  42. package/dist/api/rest/Parcels.d.ts +37 -0
  43. package/dist/api/rest/Parcels.test.d.ts +42 -0
  44. package/dist/api/rest/Payment_Charge_Logs.d.ts +37 -0
  45. package/dist/api/rest/Payment_Charge_Logs.test.d.ts +17 -0
  46. package/dist/api/rest/Payment_Subscriptions.d.ts +37 -0
  47. package/dist/api/rest/Payment_Subscriptions.test.d.ts +20 -0
  48. package/dist/api/rest/Property_Units.d.ts +37 -0
  49. package/dist/api/rest/Property_Units.test.d.ts +55 -0
  50. package/dist/api/rest/Sources.d.ts +37 -0
  51. package/dist/api/rest/Sources.test.d.ts +17 -0
  52. package/dist/api/rest/States.d.ts +37 -0
  53. package/dist/api/rest/States.test.d.ts +20 -0
  54. package/dist/api/rest/Tax_Districts.d.ts +37 -0
  55. package/dist/api/rest/Tax_Districts.test.d.ts +12 -0
  56. package/dist/api/rest/Users.d.ts +37 -0
  57. package/dist/api/rest/Users.test.d.ts +14 -0
  58. package/dist/api/rest/Valuation_Reports.d.ts +37 -0
  59. package/dist/api/rest/Valuation_Reports.test.d.ts +36 -0
  60. package/dist/api/rest/Zip_Codes.d.ts +37 -0
  61. package/dist/api/rest/Zip_Codes.test.d.ts +15 -0
  62. package/dist/api/restRequest.d.ts +44 -21
  63. package/dist/index.cjs.js +903 -558
  64. package/dist/index.cjs.js.map +1 -1
  65. package/dist/index.d.ts +4 -0
  66. package/dist/index.esm.js +899 -557
  67. package/dist/index.esm.js.map +1 -1
  68. package/dist/variables/getEnvVar.d.ts +1 -0
  69. package/dist/variables/isNode.d.ts +2 -0
  70. package/dist/variables/isTest.d.ts +1 -1
  71. package/dist/variables/toastOptions.d.ts +2 -2
  72. package/package.json +23 -12
  73. package/scripts/assets/handlebars/C6.ts.handlebars +5 -1
  74. package/scripts/generateRestBindings.cjs +89 -23
  75. package/scripts/generateRestBindings.ts +100 -27
  76. package/src/api/carbonSqlExecutor.ts +279 -0
  77. package/src/api/interfaces/ormInterfaces.ts +9 -1
  78. package/src/api/restRequest.ts +164 -19
  79. package/src/index.ts +4 -0
  80. package/src/variables/getEnvVar.ts +15 -0
  81. package/src/variables/isLocal.ts +3 -6
  82. package/src/variables/isNode.ts +3 -0
  83. package/src/variables/isTest.ts +4 -16
  84. package/src/variables/isVerbose.ts +2 -6
package/dist/index.cjs.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  var axios = require('axios');
4
4
  var Qs = require('qs');
5
+ var tslib = require('tslib');
5
6
  var reactToastify = require('react-toastify');
6
7
 
7
8
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -234,86 +235,365 @@ var axiosInstance = (axios.create({
234
235
  */
235
236
  }));
236
237
 
237
- /******************************************************************************
238
- Copyright (c) Microsoft Corporation.
239
-
240
- Permission to use, copy, modify, and/or distribute this software for any
241
- purpose with or without fee is hereby granted.
242
-
243
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
244
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
245
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
246
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
247
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
248
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
249
- PERFORMANCE OF THIS SOFTWARE.
250
- ***************************************************************************** */
251
- /* global Reflect, Promise, SuppressedError, Symbol */
252
-
253
-
254
- var __assign = function() {
255
- __assign = Object.assign || function __assign(t) {
256
- for (var s, i = 1, n = arguments.length; i < n; i++) {
257
- s = arguments[i];
258
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
259
- }
260
- return t;
261
- };
262
- return __assign.apply(this, arguments);
263
- };
264
-
265
- function __awaiter(thisArg, _arguments, P, generator) {
266
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
267
- return new (P || (P = Promise))(function (resolve, reject) {
268
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
269
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
270
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
271
- step((generator = generator.apply(thisArg, _arguments || [])).next());
272
- });
273
- }
274
-
275
- function __generator(thisArg, body) {
276
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
277
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
278
- function verb(n) { return function (v) { return step([n, v]); }; }
279
- function step(op) {
280
- if (f) throw new TypeError("Generator is already executing.");
281
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
282
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
283
- if (y = 0, t) op = [op[0] & 2, t.value];
284
- switch (op[0]) {
285
- case 0: case 1: t = op; break;
286
- case 4: _.label++; return { value: op[1], done: false };
287
- case 5: _.label++; y = op[1]; op = [0]; continue;
288
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
289
- default:
290
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
291
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
292
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
293
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
294
- if (t[2]) _.ops.pop();
295
- _.trys.pop(); continue;
296
- }
297
- op = body.call(thisArg, _);
298
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
299
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
300
- }
301
- }
302
-
303
- function __spreadArray(to, from, pack) {
304
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
305
- if (ar || !(i in from)) {
306
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
307
- ar[i] = from[i];
308
- }
309
- }
310
- return to.concat(ar || Array.prototype.slice.call(from));
311
- }
312
-
313
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
314
- var e = new Error(message);
315
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
316
- };
238
+ // import { validatePayloadAgainstSchema } from './validator'; // C6 schema validator
239
+ var CarbonSqlExecutor = /** @class */ (function () {
240
+ function CarbonSqlExecutor(pool, C6) {
241
+ this.pool = pool;
242
+ this.C6 = C6;
243
+ }
244
+ CarbonSqlExecutor.prototype.withConnection = function (cb) {
245
+ return tslib.__awaiter(this, void 0, void 0, function () {
246
+ var conn;
247
+ return tslib.__generator(this, function (_a) {
248
+ switch (_a.label) {
249
+ case 0: return [4 /*yield*/, this.pool.getConnection()];
250
+ case 1:
251
+ conn = _a.sent();
252
+ _a.label = 2;
253
+ case 2:
254
+ _a.trys.push([2, , 4, 5]);
255
+ return [4 /*yield*/, cb(conn)];
256
+ case 3: return [2 /*return*/, _a.sent()];
257
+ case 4:
258
+ conn.release();
259
+ return [7 /*endfinally*/];
260
+ case 5: return [2 /*return*/];
261
+ }
262
+ });
263
+ });
264
+ };
265
+ CarbonSqlExecutor.prototype.handle = function (req, res, next) {
266
+ return tslib.__awaiter(this, void 0, void 0, function () {
267
+ var method, table, primary, payload, result, _a, err_1;
268
+ return tslib.__generator(this, function (_b) {
269
+ switch (_b.label) {
270
+ case 0:
271
+ _b.trys.push([0, 11, , 12]);
272
+ method = req.method.toUpperCase();
273
+ table = req.params.table;
274
+ primary = req.params.primary;
275
+ payload = method === 'GET' ? req.query : req.body;
276
+ if (!(table in this.C6.TABLES)) {
277
+ res.status(400).json({ error: "Invalid table: ".concat(table) });
278
+ return [2 /*return*/];
279
+ }
280
+ result = void 0;
281
+ _a = method;
282
+ switch (_a) {
283
+ case 'GET': return [3 /*break*/, 1];
284
+ case 'OPTIONS': return [3 /*break*/, 1];
285
+ case 'POST': return [3 /*break*/, 3];
286
+ case 'PUT': return [3 /*break*/, 5];
287
+ case 'DELETE': return [3 /*break*/, 7];
288
+ }
289
+ return [3 /*break*/, 9];
290
+ case 1: return [4 /*yield*/, this.select(table, primary, payload)];
291
+ case 2:
292
+ result = _b.sent();
293
+ return [3 /*break*/, 10];
294
+ case 3: return [4 /*yield*/, this.insert(table, payload)];
295
+ case 4:
296
+ result = _b.sent();
297
+ return [3 /*break*/, 10];
298
+ case 5: return [4 /*yield*/, this.update(table, primary, payload)];
299
+ case 6:
300
+ result = _b.sent();
301
+ return [3 /*break*/, 10];
302
+ case 7: return [4 /*yield*/, this.delete(table, primary, payload)];
303
+ case 8:
304
+ result = _b.sent();
305
+ return [3 /*break*/, 10];
306
+ case 9: throw new Error("Unsupported method: ".concat(method));
307
+ case 10:
308
+ res.status(200).json({ success: true, result: result });
309
+ return [3 /*break*/, 12];
310
+ case 11:
311
+ err_1 = _b.sent();
312
+ next(err_1);
313
+ return [3 /*break*/, 12];
314
+ case 12: return [2 /*return*/];
315
+ }
316
+ });
317
+ });
318
+ };
319
+ CarbonSqlExecutor.prototype.buildBooleanJoinedConditions = function (set, andMode) {
320
+ if (andMode === void 0) { andMode = true; }
321
+ var booleanOperator = andMode ? 'AND' : 'OR';
322
+ var sql = '';
323
+ var OPERATORS = ['=', '!=', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'IS', 'IS NOT'];
324
+ var isAggregateArray = function (value) { return Array.isArray(value) && typeof value[0] === 'string' && OPERATORS.includes(value[0]); };
325
+ var isNumericKeyed = function (obj) { return Array.isArray(obj) && Object.keys(obj).every(function (k) { return /^\d+$/.test(k); }); };
326
+ // todo - we should be doing something with value no????
327
+ var addCondition = function (column, op, _value) {
328
+ var paramName = column.replace(/\W+/g, '_');
329
+ return "(".concat(column, " ").concat(op, " :").concat(paramName, ")");
330
+ };
331
+ if (isNumericKeyed(set)) {
332
+ switch (set.length) {
333
+ case 2:
334
+ sql += addCondition(set[0], '=', set[1]);
335
+ break;
336
+ case 3:
337
+ if (!OPERATORS.includes(set[1])) {
338
+ throw new Error("Invalid operator: ".concat(set[1]));
339
+ }
340
+ sql += addCondition(set[0], set[1], set[2]);
341
+ break;
342
+ default:
343
+ throw new Error("Invalid array condition: ".concat(JSON.stringify(set)));
344
+ }
345
+ }
346
+ else {
347
+ var parts = [];
348
+ for (var _i = 0, _a = Object.entries(set); _i < _a.length; _i++) {
349
+ var _b = _a[_i], key = _b[0], value = _b[1];
350
+ if (/^\d+$/.test(key)) {
351
+ parts.push(this.buildBooleanJoinedConditions(value, !andMode));
352
+ continue;
353
+ }
354
+ if (!Array.isArray(value) || isAggregateArray(value)) {
355
+ parts.push(addCondition(key, '='));
356
+ continue;
357
+ }
358
+ if (value.length === 2 && OPERATORS.includes(value[0])) {
359
+ parts.push(addCondition(key, value[0], value[1]));
360
+ }
361
+ else if (value.length === 1 && isAggregateArray(value[0])) {
362
+ parts.push(addCondition(key, '=', value[0]));
363
+ }
364
+ else {
365
+ throw new Error("Invalid condition for ".concat(key, ": ").concat(JSON.stringify(value)));
366
+ }
367
+ }
368
+ sql = parts.join(" ".concat(booleanOperator, " "));
369
+ }
370
+ return "(".concat(sql, ")");
371
+ };
372
+ CarbonSqlExecutor.prototype.buildAggregateField = function (field) {
373
+ if (typeof field === 'string')
374
+ return field;
375
+ if (!Array.isArray(field))
376
+ throw new Error('Invalid SELECT entry: must be string or array');
377
+ var agg = field[0], args = field.slice(1);
378
+ switch (agg) {
379
+ case 'COUNT':
380
+ return "COUNT(".concat(args[0] || '*', ")");
381
+ case 'SUM':
382
+ case 'AVG':
383
+ case 'MIN':
384
+ case 'MAX':
385
+ return "".concat(agg, "(").concat(args[0], ")").concat(args[1] ? " AS ".concat(args[1]) : '');
386
+ case 'DISTINCT':
387
+ return "DISTINCT(".concat(args[0], ")").concat(args[1] ? " AS ".concat(args[1]) : '');
388
+ case 'GROUP_CONCAT': {
389
+ var col = args[0], alias = args[1], sortCol = args[2], sortType = args[3];
390
+ var order = sortCol ? " ORDER BY ".concat(sortCol, " ").concat(sortType || 'ASC') : '';
391
+ return "GROUP_CONCAT(DISTINCT ".concat(col).concat(order, " SEPARATOR ',')").concat(alias ? " AS ".concat(alias) : '');
392
+ }
393
+ case 'AS': {
394
+ var col = args[0], alias = args[1];
395
+ return "".concat(col, " AS ").concat(alias);
396
+ }
397
+ case 'CONVERT_TZ': {
398
+ var ts = args[0], fromTz = args[1], toTz = args[2];
399
+ return "CONVERT_TZ(".concat(ts, ", ").concat(fromTz, ", ").concat(toTz, ")");
400
+ }
401
+ case 'NOW':
402
+ return 'NOW()';
403
+ default:
404
+ throw new Error("Unsupported aggregate: ".concat(agg));
405
+ }
406
+ };
407
+ CarbonSqlExecutor.prototype.buildSelectQuery = function (table, primary, args, isSubSelect) {
408
+ var _this = this;
409
+ var _a, _b, _c, _d;
410
+ if (isSubSelect === void 0) { isSubSelect = false; }
411
+ var selectList = (_a = args === null || args === void 0 ? void 0 : args[this.C6.SELECT]) !== null && _a !== void 0 ? _a : ['*'];
412
+ var selectFields = Array.isArray(selectList)
413
+ ? selectList.map(function (f) { return _this.buildAggregateField(f); }).join(', ')
414
+ : '*';
415
+ var sql = "SELECT ".concat(selectFields, " FROM `").concat(table, "`");
416
+ if (args === null || args === void 0 ? void 0 : args[this.C6.JOIN]) {
417
+ var joins = args[this.C6.JOIN];
418
+ for (var joinType in joins) {
419
+ var joinKeyword = joinType.replace('_', ' ').toUpperCase();
420
+ for (var joinTable in joins[joinType]) {
421
+ var onClause = this.buildBooleanJoinedConditions(joins[joinType][joinTable]);
422
+ sql += " ".concat(joinKeyword, " JOIN `").concat(joinTable, "` ON ").concat(onClause);
423
+ }
424
+ }
425
+ }
426
+ if (args === null || args === void 0 ? void 0 : args[this.C6.WHERE]) {
427
+ sql += " WHERE ".concat(this.buildBooleanJoinedConditions(args[this.C6.WHERE]));
428
+ }
429
+ if (args === null || args === void 0 ? void 0 : args[this.C6.GROUP_BY]) {
430
+ var groupByFields = Array.isArray(args[this.C6.GROUP_BY]) ? args[this.C6.GROUP_BY].join(', ') : args[this.C6.GROUP_BY];
431
+ sql += " GROUP BY ".concat(groupByFields);
432
+ }
433
+ if (args === null || args === void 0 ? void 0 : args[this.C6.HAVING]) {
434
+ sql += " HAVING ".concat(this.buildBooleanJoinedConditions(args[this.C6.HAVING]));
435
+ }
436
+ if (args === null || args === void 0 ? void 0 : args[this.C6.PAGINATION]) {
437
+ var p = args[this.C6.PAGINATION];
438
+ var limitClause = '';
439
+ if (p[this.C6.ORDER]) {
440
+ var orderArray = Object.entries(p[this.C6.ORDER]).map(function (_a) {
441
+ var col = _a[0], dir = _a[1];
442
+ if (!['ASC', 'DESC'].includes(String(dir).toUpperCase())) {
443
+ throw new Error("Invalid order direction: ".concat(dir));
444
+ }
445
+ return "".concat(col, " ").concat(String(dir).toUpperCase());
446
+ });
447
+ sql += " ORDER BY ".concat(orderArray.join(', '));
448
+ }
449
+ else if (primary) {
450
+ sql += " ORDER BY ".concat(primary, " DESC");
451
+ }
452
+ else {
453
+ // todo this is wrong
454
+ var primaryKey = (_c = (_b = this.C6.TABLES['users'].PRIMARY_SHORT) === null || _b === void 0 ? void 0 : _b[0]) !== null && _c !== void 0 ? _c : 'user_id';
455
+ sql += " ORDER BY ".concat(primaryKey, " DESC");
456
+ }
457
+ if (p[this.C6.LIMIT] != null) {
458
+ var limit = parseInt(p[this.C6.LIMIT], 10);
459
+ if (isNaN(limit) || limit < 0) {
460
+ throw new Error("Invalid LIMIT: ".concat(p[this.C6.LIMIT]));
461
+ }
462
+ var page = parseInt((_d = p[this.C6.PAGE]) !== null && _d !== void 0 ? _d : 1, 10);
463
+ if (isNaN(page) || page < 1) {
464
+ throw new Error("PAGE must be >= 1 (got ".concat(p[this.C6.PAGE], ")"));
465
+ }
466
+ var offset = (page - 1) * limit;
467
+ limitClause += " LIMIT ".concat(offset, ", ").concat(limit);
468
+ }
469
+ sql += limitClause;
470
+ }
471
+ else if (!isSubSelect && primary) {
472
+ sql += " ORDER BY ".concat(primary, " ASC LIMIT 1");
473
+ }
474
+ else if (!isSubSelect && !primary) {
475
+ sql += " ORDER BY id ASC LIMIT 100"; // fallback default limit
476
+ }
477
+ return sql;
478
+ };
479
+ CarbonSqlExecutor.prototype.select = function (table, primary, args) {
480
+ return tslib.__awaiter(this, void 0, void 0, function () {
481
+ var sql;
482
+ var _this = this;
483
+ return tslib.__generator(this, function (_a) {
484
+ switch (_a.label) {
485
+ case 0:
486
+ sql = this.buildSelectQuery(table, primary, args);
487
+ return [4 /*yield*/, this.withConnection(function (conn) { return tslib.__awaiter(_this, void 0, void 0, function () {
488
+ var rows;
489
+ return tslib.__generator(this, function (_a) {
490
+ switch (_a.label) {
491
+ case 0:
492
+ console.log(sql);
493
+ return [4 /*yield*/, conn.query(sql)];
494
+ case 1:
495
+ rows = (_a.sent())[0];
496
+ return [2 /*return*/, rows];
497
+ }
498
+ });
499
+ }); })];
500
+ case 1: return [2 /*return*/, _a.sent()];
501
+ }
502
+ });
503
+ });
504
+ };
505
+ CarbonSqlExecutor.prototype.insert = function (table, data) {
506
+ return tslib.__awaiter(this, void 0, void 0, function () {
507
+ var keys, values, placeholders, sql;
508
+ var _this = this;
509
+ return tslib.__generator(this, function (_a) {
510
+ switch (_a.label) {
511
+ case 0:
512
+ keys = Object.keys(data);
513
+ values = keys.map(function (k) { return data[k]; });
514
+ placeholders = keys.map(function () { return '?'; }).join(', ');
515
+ sql = "INSERT INTO `".concat(table, "` (").concat(keys.join(', '), ") VALUES (").concat(placeholders, ")");
516
+ return [4 /*yield*/, this.withConnection(function (conn) { return tslib.__awaiter(_this, void 0, void 0, function () {
517
+ var result;
518
+ return tslib.__generator(this, function (_a) {
519
+ switch (_a.label) {
520
+ case 0: return [4 /*yield*/, conn.execute(sql, values)];
521
+ case 1:
522
+ result = (_a.sent())[0];
523
+ return [2 /*return*/, result];
524
+ }
525
+ });
526
+ }); })];
527
+ case 1: return [2 /*return*/, _a.sent()];
528
+ }
529
+ });
530
+ });
531
+ };
532
+ CarbonSqlExecutor.prototype.update = function (table, primary, data) {
533
+ return tslib.__awaiter(this, void 0, void 0, function () {
534
+ var keys, values, updates, sql;
535
+ var _this = this;
536
+ return tslib.__generator(this, function (_a) {
537
+ switch (_a.label) {
538
+ case 0:
539
+ if (!primary) {
540
+ throw new Error('Primary key is required for update');
541
+ }
542
+ keys = Object.keys(data);
543
+ values = keys.map(function (k) { return data[k]; });
544
+ updates = keys.map(function (k) { return "`".concat(k, "` = ?"); }).join(', ');
545
+ sql = "UPDATE `".concat(table, "` SET ").concat(updates, " WHERE `").concat(primary, "` = ?");
546
+ values.push(data[primary]);
547
+ return [4 /*yield*/, this.withConnection(function (conn) { return tslib.__awaiter(_this, void 0, void 0, function () {
548
+ var result;
549
+ return tslib.__generator(this, function (_a) {
550
+ switch (_a.label) {
551
+ case 0: return [4 /*yield*/, conn.execute(sql, values)];
552
+ case 1:
553
+ result = (_a.sent())[0];
554
+ return [2 /*return*/, result];
555
+ }
556
+ });
557
+ }); })];
558
+ case 1: return [2 /*return*/, _a.sent()];
559
+ }
560
+ });
561
+ });
562
+ };
563
+ CarbonSqlExecutor.prototype.delete = function (table, primary, args) {
564
+ return tslib.__awaiter(this, void 0, void 0, function () {
565
+ var sql;
566
+ var _this = this;
567
+ return tslib.__generator(this, function (_a) {
568
+ switch (_a.label) {
569
+ case 0:
570
+ if (!primary || !(args === null || args === void 0 ? void 0 : args[primary])) {
571
+ throw new Error('Primary key and value required for delete');
572
+ }
573
+ sql = "DELETE FROM `".concat(table, "` WHERE `").concat(primary, "` = ?");
574
+ return [4 /*yield*/, this.withConnection(function (conn) { return tslib.__awaiter(_this, void 0, void 0, function () {
575
+ var result;
576
+ return tslib.__generator(this, function (_a) {
577
+ switch (_a.label) {
578
+ case 0: return [4 /*yield*/, conn.execute(sql, [args[primary]])];
579
+ case 1:
580
+ result = (_a.sent())[0];
581
+ return [2 /*return*/, result];
582
+ }
583
+ });
584
+ }); })];
585
+ case 1: return [2 /*return*/, _a.sent()];
586
+ }
587
+ });
588
+ });
589
+ };
590
+ return CarbonSqlExecutor;
591
+ }());
592
+
593
+ var carbonSqlExecutor = /*#__PURE__*/Object.freeze({
594
+ __proto__: null,
595
+ CarbonSqlExecutor: CarbonSqlExecutor
596
+ });
317
597
 
318
598
  function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler) {
319
599
  if (regexErrorHandler === void 0) { regexErrorHandler = alert; }
@@ -349,7 +629,7 @@ function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler)
349
629
  .sort()
350
630
  .reduce(function (acc, key) {
351
631
  var _a;
352
- return (__assign(__assign({}, acc), (_a = {}, _a[key] = restfulObject[value][key], _a)));
632
+ return (tslib.__assign(tslib.__assign({}, acc), (_a = {}, _a[key] = restfulObject[value][key], _a)));
353
633
  }, {});
354
634
  }
355
635
  return;
@@ -382,35 +662,35 @@ function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler)
382
662
  .sort()
383
663
  .reduce(function (acc, key) {
384
664
  var _a;
385
- return (__assign(__assign({}, acc), (_a = {}, _a[key] = payload[key], _a)));
665
+ return (tslib.__assign(tslib.__assign({}, acc), (_a = {}, _a[key] = payload[key], _a)));
386
666
  }, {});
387
667
  }
388
668
 
389
- var _a$2, _b$2, _c$2, _d$2;
390
- var nodeEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV
391
- ? process.env.NODE_ENV
392
- : // @ts-ignore
393
- ((_b$2 = (_a$2 = ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href)) })) === null || _a$2 === void 0 ? void 0 : _a$2.env) === null || _b$2 === void 0 ? void 0 : _b$2.MODE) || ((_d$2 = (_c$2 = ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href)) })) === null || _c$2 === void 0 ? void 0 : _c$2.env) === null || _d$2 === void 0 ? void 0 : _d$2.NODE_ENV);
394
- var isDevelopment = nodeEnv === 'development';
669
+ var _a;
670
+ var isNode = typeof process !== 'undefined' && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
395
671
 
396
- var _a$1, _b$1, _c$1, _d$1;
397
- var isTest = typeof process !== 'undefined' &&
398
- typeof process.env !== 'undefined' &&
399
- (process.env.JEST_WORKER_ID !== undefined ||
400
- process.env.NODE_ENV === 'test' ||
401
- process.env.REACT_APP_TEST === 'true') ||
402
- // Vite-only branch
403
- typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href)) }) !== 'undefined' &&
404
- (
672
+ function getEnvVar(key, fallback) {
673
+ if (fallback === void 0) { fallback = ''; }
674
+ // Vite-style injection
675
+ // @ts-ignore
676
+ if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href)) }) !== 'undefined' && undefined && key in undefined) {
405
677
  // @ts-ignore
406
- ((_b$1 = (_a$1 = ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href)) })) === null || _a$1 === void 0 ? void 0 : _a$1.env) === null || _b$1 === void 0 ? void 0 : _b$1.MODE) === 'test' ||
407
- // @ts-ignore
408
- ((_d$1 = (_c$1 = ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href)) })) === null || _c$1 === void 0 ? void 0 : _c$1.env) === null || _d$1 === void 0 ? void 0 : _d$1.VITE_TEST) === 'true');
678
+ return undefined[key];
679
+ }
680
+ // Node or SSR
681
+ if (typeof process !== 'undefined' && process.env && key in process.env) {
682
+ return process.env[key];
683
+ }
684
+ return fallback;
685
+ }
409
686
 
410
- var _a, _b, _c, _d, _e, _f, _g;
411
- var envVerbose =
412
- // @ts-ignore
413
- (_g = (_e = (_c = (_b = (_a = ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs.js', document.baseURI).href)) })) === null || _a === void 0 ? void 0 : _a.env) === null || _b === void 0 ? void 0 : _b.VITE_VERBOSE) !== null && _c !== void 0 ? _c : (_d = process === null || process === void 0 ? void 0 : process.env) === null || _d === void 0 ? void 0 : _d.REACT_APP_VERBOSE) !== null && _e !== void 0 ? _e : (_f = process === null || process === void 0 ? void 0 : process.env) === null || _f === void 0 ? void 0 : _f.VERBOSE) !== null && _g !== void 0 ? _g : '';
687
+ var isDevelopment = getEnvVar('NODE_ENV', '') === 'development';
688
+
689
+ var isTest = getEnvVar('JEST_WORKER_ID') || getEnvVar('NODE_ENV') === 'test'
690
+ || getEnvVar('REACT_APP_TEST') === 'true' || getEnvVar('VITE_TEST') === 'true'
691
+ || getEnvVar('MODE') === 'test' || getEnvVar('VITE_TEST_MODE') === 'true';
692
+
693
+ var envVerbose = getEnvVar('VERBOSE') || getEnvVar('REACT_APP_VERBOSE') || getEnvVar('VITE_VERBOSE') || '';
414
694
  var isVerbose = ['true', '1', 'yes', 'on'].includes(envVerbose.toLowerCase());
415
695
 
416
696
  var toastOptions = {
@@ -559,7 +839,8 @@ function extendedTypeHints() {
559
839
  return function (argv) { return restRequest(argv); };
560
840
  }
561
841
  function restRequest(_a) {
562
- var C6 = _a.C6, _b = _a.axios, axios = _b === void 0 ? axiosInstance : _b, _c = _a.restURL, restURL = _c === void 0 ? '/rest/' : _c, _d = _a.withCredentials, withCredentials = _d === void 0 ? true : _d, tableName = _a.tableName, _e = _a.requestMethod, requestMethod = _e === void 0 ? GET : _e, _f = _a.queryCallback, queryCallback = _f === void 0 ? {} : _f, responseCallback = _a.responseCallback, _g = _a.skipPrimaryCheck, skipPrimaryCheck = _g === void 0 ? false : _g, _h = _a.clearCache, clearCache = _h === void 0 ? undefined : _h;
842
+ var _this = this;
843
+ var C6 = _a.C6, _b = _a.axios, axios = _b === void 0 ? axiosInstance : _b, _c = _a.restURL, restURL = _c === void 0 ? '/rest/' : _c, mysqlPool = _a.mysqlPool, _d = _a.withCredentials, withCredentials = _d === void 0 ? true : _d, tableName = _a.tableName, _e = _a.requestMethod, requestMethod = _e === void 0 ? GET : _e, _f = _a.queryCallback, queryCallback = _f === void 0 ? {} : _f, responseCallback = _a.responseCallback, _g = _a.skipPrimaryCheck, skipPrimaryCheck = _g === void 0 ? false : _g, _h = _a.clearCache, clearCache = _h === void 0 ? undefined : _h;
563
844
  var fullTableList = Array.isArray(tableName) ? tableName : [tableName];
564
845
  var operatingTableFullName = fullTableList[0];
565
846
  var operatingTable = removePrefixIfExists(operatingTableFullName, C6.PREFIX);
@@ -576,483 +857,544 @@ function restRequest(_a) {
576
857
  if (null !== clearCache || undefined !== clearCache) {
577
858
  userCustomClearCache[tables + requestMethod] = clearCache;
578
859
  }
579
- return function (request) {
580
- if (request === void 0) { request = {}; }
581
- console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + operatingTable + ')', 'color: #0c0');
582
- console.log('request', request);
583
- console.groupEnd();
584
- // an undefined query would indicate queryCallback returned undefined,
585
- // thus the request shouldn't fire as is in custom cache
586
- var query;
587
- if ('function' === typeof queryCallback) {
588
- query = queryCallback(request); // obj or obj[]
589
- }
590
- else {
591
- query = queryCallback;
592
- }
593
- if (undefined === query || null === query) {
594
- if (request.debug && isDevelopment) {
595
- reactToastify.toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs);
596
- }
597
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') undefined, returning null (will not fire ajax)!', 'color: #c00');
598
- 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');
599
- console.trace();
600
- console.groupEnd();
601
- return null;
602
- }
603
- if (C6.GET === requestMethod) {
604
- if (undefined === query[C6.PAGINATION]) {
605
- query[C6.PAGINATION] = {};
606
- }
607
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
608
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
860
+ return function () {
861
+ var args_1 = [];
862
+ for (var _i = 0; _i < arguments.length; _i++) {
863
+ args_1[_i] = arguments[_i];
609
864
  }
610
- // this could return itself with a new page number, or undefined if the end is reached
611
- function apiRequest() {
612
- var _this = this;
613
- var _a, _b, _c, _d, _e, _f, _g;
614
- (_a = request.cacheResults) !== null && _a !== void 0 ? _a : (request.cacheResults = C6.GET === requestMethod);
615
- if (C6.GET === requestMethod
616
- && undefined !== ((_b = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _b === void 0 ? void 0 : _b[C6.PAGE])
617
- && 1 !== query[C6.PAGINATION][C6.PAGE]) {
618
- console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
619
- console.log('Request Data (note you may see the success and/or error prompt):', request);
620
- console.trace();
621
- console.groupEnd();
622
- }
623
- // 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.
624
- // 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
625
- // literally impossible for query to be undefined or null here but the editor is too busy licking windows to understand that
626
- var querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
627
- var cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
628
- var cachingConfirmed = false;
629
- // determine if we need to paginate.
630
- if (requestMethod === C6.GET) {
631
- if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
632
- if (undefined === query || null === query) {
633
- query = {};
634
- }
635
- query[C6.PAGINATION] = {};
636
- }
637
- query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
638
- query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
639
- // this will evaluate true most the time
640
- if (true === request.cacheResults) {
641
- // just find the next, non-fetched, page and return a function to request it
642
- if (undefined !== cacheResult) {
643
- do {
644
- var cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
645
- if (false !== cacheCheck) {
646
- return cacheCheck;
647
- }
648
- // this line incrementing page is why we return recursively
649
- ++query[C6.PAGINATION][C6.PAGE];
650
- // this json stringify is to capture the new page number
651
- querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
652
- cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
653
- } while (undefined !== cacheResult);
654
- if (request.debug && isDevelopment) {
655
- reactToastify.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);
656
- }
657
- // @ts-ignore - this is an incorrect warning on TS, it's well typed
658
- return apiRequest;
659
- }
660
- cachingConfirmed = true;
661
- }
662
- else {
663
- if (request.debug && isDevelopment) {
664
- reactToastify.toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
665
- }
666
- }
667
- if (request.debug && isDevelopment) {
668
- reactToastify.toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
669
- }
670
- }
671
- else if (request.cacheResults) { // if we are not getting, we are updating, deleting, or inserting
672
- if (cacheResult) {
673
- var cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
674
- if (false !== cacheCheck) {
675
- return cacheCheck;
676
- }
677
- }
678
- cachingConfirmed = true;
679
- // push to cache so we do not repeat the request
680
- }
681
- var addBackPK;
682
- var apiResponse;
683
- var returnGetNextPageFunction = false;
684
- var restRequestUri = restURL + operatingTable + '/';
685
- var needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
686
- && false === skipPrimaryCheck;
687
- var TABLES = C6.TABLES;
688
- // todo - aggregate primary key check with condition check
689
- // check if PK exists in query, clone so pop does not affect the real data
690
- var primaryKey = (_f = (_e = (_d = structuredClone((_c = TABLES[operatingTable]) === null || _c === void 0 ? void 0 : _c.PRIMARY)) === null || _d === void 0 ? void 0 : _d.pop()) === null || _e === void 0 ? void 0 : _e.split('.')) === null || _f === void 0 ? void 0 : _f.pop();
691
- if (needsConditionOrPrimaryCheck) {
692
- if (undefined === primaryKey) {
693
- if (null === query
694
- || undefined === query
695
- || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
696
- || (true === Array.isArray(query[C6.WHERE])
697
- || query[C6.WHERE].length === 0)
698
- || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
699
- console.error(query);
700
- throw Error('Failed to parse primary key information. Query: (' + JSON.stringify(query) + ') Primary Key: (' + JSON.stringify(primaryKey) + ') TABLES[operatingTable]?.PRIMARY: (' + JSON.stringify((_g = TABLES[operatingTable]) === null || _g === void 0 ? void 0 : _g.PRIMARY) + ') for operatingTable (' + operatingTable + ').');
701
- }
702
- }
703
- else {
704
- if (undefined === query
705
- || null === query
706
- || false === primaryKey in query) {
707
- if (true === request.debug && isDevelopment) {
708
- reactToastify.toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
709
- }
710
- throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
711
- }
712
- if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
713
- || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
714
- reactToastify.toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
715
- throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
716
- }
717
- }
718
- }
719
- // A part of me exists that wants to remove this, but it's a good feature
720
- // this allows developers the ability to cache requests based on primary key
721
- // for tables like `photos` this can be a huge performance boost
722
- if (undefined !== query
723
- && null !== query
724
- && undefined !== primaryKey
725
- && primaryKey in query) {
726
- restRequestUri += query[primaryKey] + '/';
727
- var removedPkValue_1 = query[primaryKey];
728
- addBackPK = function () {
729
- query !== null && query !== void 0 ? query : (query = {});
730
- query[primaryKey] = removedPkValue_1;
731
- };
732
- delete query[primaryKey];
733
- console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue_1);
734
- }
735
- else {
736
- console.log('query', query);
737
- }
738
- try {
739
- console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
740
- console.log(request);
741
- 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');
742
- 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');
743
- console.trace();
744
- console.groupEnd();
745
- var axiosActiveRequest = axios[requestMethod.toLowerCase()].apply(axios, __spreadArray([restRequestUri], ((function () {
746
- // @link - https://axios-http.com/docs/instance
747
- // How configuration vs data is passed is variable, use documentation above for reference
748
- if (requestMethod === GET) {
749
- return [{
750
- withCredentials: withCredentials,
751
- params: query
752
- }];
753
- }
754
- else if (requestMethod === POST) {
755
- if (undefined !== (request === null || request === void 0 ? void 0 : request.dataInsertMultipleRows)) {
756
- return [
757
- request.dataInsertMultipleRows.map(function (data) {
758
- return convertForRequestBody(data, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); });
759
- }),
760
- {
761
- withCredentials: withCredentials,
762
- }
763
- ];
764
- }
765
- return [
766
- convertForRequestBody(query, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); }),
767
- {
768
- withCredentials: withCredentials,
769
- }
770
- ];
771
- }
772
- else if (requestMethod === PUT) {
773
- return [
774
- convertForRequestBody(query, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); }),
775
- {
776
- withCredentials: withCredentials,
777
- }
778
- ];
779
- }
780
- else if (requestMethod === DELETE) {
781
- return [{
782
- withCredentials: withCredentials,
783
- data: convertForRequestBody(query, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); })
784
- }];
785
- }
786
- else {
787
- throw new Error('The request method (' + requestMethod + ') was not recognized.');
788
- }
789
- })()), false));
790
- if (cachingConfirmed) {
791
- // push to cache so we do not repeat the request
792
- apiRequestCache.push({
793
- requestArgumentsSerialized: querySerialized,
794
- request: axiosActiveRequest
795
- });
796
- }
797
- // todo - wip verify this works
798
- // we had removed the value from the request to add to the URI.
799
- addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
800
- // returning the promise with this then is important for tests. todo - we could make that optional.
801
- // https://rapidapi.com/guides/axios-async-await
802
- return axiosActiveRequest.then(function (response) { return __awaiter(_this, void 0, void 0, function () {
803
- var cacheIndex, responseData_1, fetchDependencies, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
865
+ return tslib.__awaiter(_this, tslib.__spreadArray([], args_1, true), void 0, function (request) {
866
+ // this could return itself with a new page number, or undefined if the end is reached
867
+ function apiRequest() {
868
+ return tslib.__awaiter(this, void 0, void 0, function () {
869
+ var querySerialized, cacheResult, cachingConfirmed, cacheCheck, cacheCheck, addBackPK, apiResponse, returnGetNextPageFunction, restRequestUri, needsConditionOrPrimaryCheck, TABLES, primaryKey, CarbonSqlExecutor, engine, removedPkValue_1, axiosActiveRequest;
804
870
  var _this = this;
805
- var _d, _e, _f, _g, _h, _j, _k, _l, _m;
806
- return __generator(this, function (_o) {
807
- switch (_o.label) {
871
+ var _a, _b, _c, _d, _e, _f, _g;
872
+ return tslib.__generator(this, function (_h) {
873
+ switch (_h.label) {
808
874
  case 0:
809
- if (typeof response.data === 'string') {
810
- if (isTest) {
811
- console.trace();
812
- 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 + ')');
813
- }
814
- return [2 /*return*/, Promise.reject(response)];
815
- }
816
- if (cachingConfirmed) {
817
- cacheIndex = apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
818
- apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
819
- // only cache get method requests
820
- apiRequestCache[cacheIndex].response = response;
875
+ (_a = request.cacheResults) !== null && _a !== void 0 ? _a : (request.cacheResults = C6.GET === requestMethod);
876
+ if (C6.GET === requestMethod
877
+ && undefined !== ((_b = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _b === void 0 ? void 0 : _b[C6.PAGE])
878
+ && 1 !== query[C6.PAGINATION][C6.PAGE]) {
879
+ console.groupCollapsed('Request on table (' + tableName + ') is firing for page (' + query[C6.PAGINATION][C6.PAGE] + '), please wait!');
880
+ console.log('Request Data (note you may see the success and/or error prompt):', request);
881
+ console.trace();
882
+ console.groupEnd();
821
883
  }
822
- apiResponse = TestRestfulResponse(response, request === null || request === void 0 ? void 0 : request.success, (_d = request === null || request === void 0 ? void 0 : request.error) !== null && _d !== void 0 ? _d : "An unexpected API error occurred!");
823
- if (false === apiResponse) {
884
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
885
+ cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
886
+ cachingConfirmed = false;
887
+ // determine if we need to paginate.
888
+ if (requestMethod === C6.GET) {
889
+ if (undefined === (query === null || query === void 0 ? void 0 : query[C6.PAGINATION])) {
890
+ if (undefined === query || null === query) {
891
+ query = {};
892
+ }
893
+ query[C6.PAGINATION] = {};
894
+ }
895
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
896
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
897
+ // this will evaluate true most the time
898
+ if (true === request.cacheResults) {
899
+ // just find the next, non-fetched, page and return a function to request it
900
+ if (undefined !== cacheResult) {
901
+ do {
902
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
903
+ if (false !== cacheCheck) {
904
+ return [2 /*return*/, cacheCheck];
905
+ }
906
+ // this line incrementing page is why we return recursively
907
+ ++query[C6.PAGINATION][C6.PAGE];
908
+ // this json stringify is to capture the new page number
909
+ querySerialized = sortAndSerializeQueryObject(tables, query !== null && query !== void 0 ? query : {});
910
+ cacheResult = apiRequestCache.find(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
911
+ } while (undefined !== cacheResult);
912
+ if (request.debug && isDevelopment) {
913
+ reactToastify.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);
914
+ }
915
+ // @ts-ignore - this is an incorrect warning on TS, it's well typed
916
+ return [2 /*return*/, apiRequest];
917
+ }
918
+ cachingConfirmed = true;
919
+ }
920
+ else {
921
+ if (request.debug && isDevelopment) {
922
+ reactToastify.toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
923
+ }
924
+ }
824
925
  if (request.debug && isDevelopment) {
825
- reactToastify.toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
926
+ reactToastify.toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
826
927
  }
827
- return [2 /*return*/, response];
828
928
  }
829
- // stateful operations are done in the response callback - its leverages rest generated functions
830
- if (responseCallback) {
831
- responseCallback(response, request, apiResponse);
929
+ else if (request.cacheResults) { // if we are not getting, we are updating, deleting, or inserting
930
+ if (cacheResult) {
931
+ cacheCheck = checkCache(cacheResult, requestMethod, tableName, request);
932
+ if (false !== cacheCheck) {
933
+ return [2 /*return*/, cacheCheck];
934
+ }
935
+ }
936
+ cachingConfirmed = true;
937
+ // push to cache so we do not repeat the request
832
938
  }
833
- if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
834
- responseData_1 = response.data;
835
- returnGetNextPageFunction = 1 !== ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) &&
836
- ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.LIMIT]) === responseData_1.rest.length;
837
- if (false === isTest || true === isVerbose) {
838
- console.groupCollapsed('%c API: Response (' + requestMethod + ' ' + tableName + ') returned length (' + ((_g = responseData_1.rest) === null || _g === void 0 ? void 0 : _g.length) + ') of possible (' + ((_h = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _h === void 0 ? void 0 : _h[C6.LIMIT]) + ') limit!', 'color: #0c0');
839
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
840
- console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request);
841
- console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
842
- console.log('%c Will return get next page function:' + (1 !== ((_j = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _j === void 0 ? void 0 : _j[C6.LIMIT]) ? '' : ' (Will not return with explicit limit 1 set)'), 'color: #0c0', true === returnGetNextPageFunction);
843
- console.trace();
844
- console.groupEnd();
939
+ returnGetNextPageFunction = false;
940
+ restRequestUri = restURL + operatingTable + '/';
941
+ needsConditionOrPrimaryCheck = (PUT === requestMethod || DELETE === requestMethod)
942
+ && false === skipPrimaryCheck;
943
+ TABLES = C6.TABLES;
944
+ primaryKey = (_f = (_e = (_d = structuredClone((_c = TABLES[operatingTable]) === null || _c === void 0 ? void 0 : _c.PRIMARY)) === null || _d === void 0 ? void 0 : _d.pop()) === null || _e === void 0 ? void 0 : _e.split('.')) === null || _f === void 0 ? void 0 : _f.pop();
945
+ if (needsConditionOrPrimaryCheck) {
946
+ if (undefined === primaryKey) {
947
+ if (null === query
948
+ || undefined === query
949
+ || undefined === (query === null || query === void 0 ? void 0 : query[C6.WHERE])
950
+ || (true === Array.isArray(query[C6.WHERE])
951
+ || query[C6.WHERE].length === 0)
952
+ || (Object.keys(query === null || query === void 0 ? void 0 : query[C6.WHERE]).length === 0)) {
953
+ console.error(query);
954
+ throw Error('Failed to parse primary key information. Query: (' + JSON.stringify(query) + ') Primary Key: (' + JSON.stringify(primaryKey) + ') TABLES[operatingTable]?.PRIMARY: (' + JSON.stringify((_g = TABLES[operatingTable]) === null || _g === void 0 ? void 0 : _g.PRIMARY) + ') for operatingTable (' + operatingTable + ').');
955
+ }
956
+ }
957
+ else {
958
+ if (undefined === query
959
+ || null === query
960
+ || false === primaryKey in query) {
961
+ if (true === request.debug && isDevelopment) {
962
+ reactToastify.toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
963
+ }
964
+ throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
965
+ }
966
+ if (undefined === (query === null || query === void 0 ? void 0 : query[primaryKey])
967
+ || null === (query === null || query === void 0 ? void 0 : query[primaryKey])) {
968
+ reactToastify.toast.error('The primary key (' + primaryKey + ') provided is undefined or null explicitly!!');
969
+ throw Error('The primary key (' + primaryKey + ') provided in the request was exactly equal to undefined.');
970
+ }
971
+ }
845
972
  }
846
- if (false === returnGetNextPageFunction
847
- && true === request.debug
848
- && isDevelopment) {
849
- reactToastify.toast.success("DEVS: Response returned length (" + ((_k = responseData_1.rest) === null || _k === void 0 ? void 0 : _k.length) + ") less than limit (" + ((_l = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _l === void 0 ? void 0 : _l[C6.LIMIT]) + ").", toastOptionsDevs);
973
+ if (!(isNode && mysqlPool)) return [3 /*break*/, 2];
974
+ return [4 /*yield*/, Promise.resolve().then(function () { return carbonSqlExecutor; })];
975
+ case 1:
976
+ CarbonSqlExecutor = (_h.sent()).CarbonSqlExecutor;
977
+ engine = new CarbonSqlExecutor(mysqlPool, C6);
978
+ switch (requestMethod) {
979
+ case GET:
980
+ return [2 /*return*/, engine
981
+ .select(tableName, undefined, request)
982
+ .then(function (rows) {
983
+ // mirror the front‐end shape
984
+ var serverResponse = {
985
+ rest: rows,
986
+ session: undefined,
987
+ sql: true,
988
+ };
989
+ return serverResponse;
990
+ })];
991
+ case POST:
992
+ return [2 /*return*/, engine
993
+ .insert(tableName, request)
994
+ .then(function (created) { return ({
995
+ rest: created,
996
+ }); })];
997
+ case PUT:
998
+ return [2 /*return*/, engine
999
+ .update(tableName, undefined, request)
1000
+ .then(function (updatedResult) {
1001
+ var _a;
1002
+ return ({
1003
+ rest: updatedResult,
1004
+ rowCount: (_a = updatedResult.affectedRows) !== null && _a !== void 0 ? _a : 0,
1005
+ });
1006
+ })];
1007
+ case DELETE:
1008
+ return [2 /*return*/, engine
1009
+ .delete(tableName, undefined, request)
1010
+ .then(function (deletedResult) {
1011
+ var _a;
1012
+ return ({
1013
+ rest: deletedResult,
1014
+ rowCount: (_a = deletedResult.affectedRows) !== null && _a !== void 0 ? _a : 0,
1015
+ deleted: true,
1016
+ });
1017
+ })];
1018
+ default:
1019
+ throw new Error("Unsupported method: ".concat(requestMethod));
850
1020
  }
851
- (_m = request.fetchDependencies) !== null && _m !== void 0 ? _m : (request.fetchDependencies = exports.eFetchDependencies.NONE);
852
- if (!(request.fetchDependencies
853
- && 'number' === typeof request.fetchDependencies
854
- && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
855
- fetchDependencies = request.fetchDependencies;
856
- console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
857
- + (fetchDependencies & exports.eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
858
- + (fetchDependencies & exports.eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
859
- + (fetchDependencies & exports.eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
860
- + (fetchDependencies & exports.eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
861
- console.groupCollapsed('Collapsed JS Trace');
862
- console.trace(); // hidden in collapsed group
863
- console.groupEnd();
864
- dependencies_1 = {};
865
- if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
866
- dependencies_1 = operatingTable.endsWith("carbon_carbons")
867
- ? __assign(__assign({}, fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
868
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
869
- : {}), fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
870
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
871
- : {}) : __assign(__assign({}, fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
872
- ? __assign(__assign({}, Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce(function (accumulator, columnName) {
873
- if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
874
- accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
875
- }
876
- return accumulator;
877
- }, {})), C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
878
- ) : {}), fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
879
- ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce(function (accumulator, primaryKey) {
880
- if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
881
- accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
882
- }
883
- return accumulator;
884
- }, {})
885
- : {});
1021
+ case 2:
1022
+ // A part of me exists that wants to remove this, but it's a good feature
1023
+ // this allows developers the ability to cache requests based on primary key
1024
+ // for tables like `photos` this can be a huge performance boost
1025
+ if (undefined !== query
1026
+ && null !== query
1027
+ && undefined !== primaryKey
1028
+ && primaryKey in query) {
1029
+ restRequestUri += query[primaryKey] + '/';
1030
+ removedPkValue_1 = query[primaryKey];
1031
+ addBackPK = function () {
1032
+ query !== null && query !== void 0 ? query : (query = {});
1033
+ query[primaryKey] = removedPkValue_1;
1034
+ };
1035
+ delete query[primaryKey];
1036
+ console.log('query', query, 'primaryKey', primaryKey, 'removedPkValue', removedPkValue_1);
886
1037
  }
887
1038
  else {
888
- // this is the natural mysql context
889
- dependencies_1 = __assign(__assign({}, fetchDependencies & exports.eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
890
- ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
891
- : {}), fetchDependencies & exports.eFetchDependencies.REFERENCES // REFERENCES === PARENTS
892
- ? C6.TABLES[operatingTable].TABLE_REFERENCES
893
- : {});
1039
+ console.log('query', query);
894
1040
  }
895
- fetchReferences_1 = {};
896
- apiRequestPromises = [];
897
- console.log('%c Dependencies', 'color: #005555', dependencies_1);
898
- Object.keys(dependencies_1)
899
- .forEach(function (column) { return dependencies_1[column]
900
- .forEach(function (constraint) {
901
- var _a, _b, _c, _d;
902
- var _e, _f, _g;
903
- var columnValues = (_b = (_a = responseData_1.rest[column]) !== null && _a !== void 0 ? _a : responseData_1.rest.map(function (row) {
904
- if (operatingTable.endsWith("carbons")
905
- && 'entity_tag' in row
906
- && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
907
- return false; // map
908
- }
909
- if (!(column in row)) {
910
- return false;
1041
+ try {
1042
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') is about to fire, will return with promise!', 'color: #A020F0');
1043
+ console.log(request);
1044
+ 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');
1045
+ 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');
1046
+ console.trace();
1047
+ console.groupEnd();
1048
+ axiosActiveRequest = axios[requestMethod.toLowerCase()].apply(axios, tslib.__spreadArray([restRequestUri], ((function () {
1049
+ // @link - https://axios-http.com/docs/instance
1050
+ // How configuration vs data is passed is variable, use documentation above for reference
1051
+ if (requestMethod === GET) {
1052
+ return [{
1053
+ withCredentials: withCredentials,
1054
+ params: query
1055
+ }];
911
1056
  }
912
- // todo - row[column] is a FK value, we should optionally remove values that are already in state
913
- // this could be any column in the table constraint.TABLE, not just the primary key
914
- return row[column];
915
- }).filter(function (n) { return n; })) !== null && _b !== void 0 ? _b : [];
916
- if (columnValues.length === 0) {
917
- return; // forEach
918
- }
919
- (_c = fetchReferences_1[_e = constraint.TABLE]) !== null && _c !== void 0 ? _c : (fetchReferences_1[_e] = {});
920
- (_d = (_f = fetchReferences_1[constraint.TABLE])[_g = constraint.COLUMN]) !== null && _d !== void 0 ? _d : (_f[_g] = []);
921
- fetchReferences_1[constraint.TABLE][constraint.COLUMN].push(columnValues);
922
- }); });
923
- console.log('fetchReferences', fetchReferences_1);
924
- _loop_1 = function (tableToFetch) {
925
- var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
926
- var _p;
927
- return __generator(this, function (_q) {
928
- switch (_q.label) {
929
- case 0:
930
- if (fetchDependencies & exports.eFetchDependencies.C6ENTITY
931
- && 'string' === typeof tableName
932
- && tableName.endsWith("carbon_carbons")) {
933
- referencesTables = responseData_1.rest.reduce(function (accumulator, row) {
934
- if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
935
- accumulator.push(row['entity_tag']);
936
- }
937
- return accumulator;
938
- }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
939
- shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
940
- if (!shouldContinue) {
941
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
942
- return [2 /*return*/, "continue"];
943
- }
944
- console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
945
- }
946
- return [4 /*yield*/, C6.IMPORT(tableToFetch)];
947
- case 1:
948
- fetchTable = _q.sent();
949
- RestApi = fetchTable.default;
950
- console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
951
- nextFetchDependencies = exports.eFetchDependencies.NONE;
952
- if (fetchDependencies & exports.eFetchDependencies.RECURSIVE) {
953
- if (fetchDependencies & exports.eFetchDependencies.ALL) {
954
- 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.');
955
- }
956
- nextFetchDependencies = fetchDependencies;
957
- }
958
- else if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
959
- if (tableToFetch === "carbon_carbons") {
960
- nextFetchDependencies = fetchDependencies;
961
- }
962
- else {
963
- nextFetchDependencies = fetchDependencies ^ exports.eFetchDependencies.C6ENTITY;
1057
+ else if (requestMethod === POST) {
1058
+ if (undefined !== (request === null || request === void 0 ? void 0 : request.dataInsertMultipleRows)) {
1059
+ return [
1060
+ request.dataInsertMultipleRows.map(function (data) {
1061
+ return convertForRequestBody(data, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); });
1062
+ }),
1063
+ {
1064
+ withCredentials: withCredentials,
964
1065
  }
1066
+ ];
1067
+ }
1068
+ return [
1069
+ convertForRequestBody(query, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); }),
1070
+ {
1071
+ withCredentials: withCredentials,
965
1072
  }
966
- console.log('fetchReferences', fetchReferences_1[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
967
- // 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
968
- // it not certain that they are using carbons' entities either
969
- // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
970
- // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
971
- apiRequestPromises.push(RestApi.Get((_p = {},
972
- _p[C6.WHERE] = {
973
- 0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
974
- fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
975
- if (0 === fetchReferences_1[tableToFetch][column].length) {
976
- console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData_1);
977
- return false;
978
- }
979
- sum[column] = fetchReferences_1[tableToFetch][column].length === 1
980
- ? fetchReferences_1[tableToFetch][column][0]
981
- : [
982
- C6.IN, fetchReferences_1[tableToFetch][column]
983
- ];
984
- return sum;
985
- }, {})
986
- },
987
- _p.fetchDependencies = nextFetchDependencies,
988
- _p)));
989
- return [2 /*return*/];
1073
+ ];
990
1074
  }
991
- });
992
- };
993
- _a = fetchReferences_1;
994
- _b = [];
995
- for (_c in _a)
996
- _b.push(_c);
997
- _i = 0;
998
- _o.label = 1;
999
- case 1:
1000
- if (!(_i < _b.length)) return [3 /*break*/, 4];
1001
- _c = _b[_i];
1002
- if (!(_c in _a)) return [3 /*break*/, 3];
1003
- tableToFetch = _c;
1004
- return [5 /*yield**/, _loop_1(tableToFetch)];
1005
- case 2:
1006
- _o.sent();
1007
- _o.label = 3;
1008
- case 3:
1009
- _i++;
1010
- return [3 /*break*/, 1];
1011
- case 4:
1012
- console.groupEnd();
1013
- return [4 /*yield*/, Promise.all(apiRequestPromises)];
1014
- case 5:
1015
- _o.sent();
1016
- apiRequestPromises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
1017
- var _a, _b;
1018
- return __generator(this, function (_c) {
1019
- switch (_c.label) {
1020
- case 0:
1021
- if (!Array.isArray(request.fetchDependencies)) {
1022
- request.fetchDependencies = [];
1075
+ else if (requestMethod === PUT) {
1076
+ return [
1077
+ convertForRequestBody(query, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); }),
1078
+ {
1079
+ withCredentials: withCredentials,
1023
1080
  }
1024
- _b = (_a = request.fetchDependencies).push;
1025
- return [4 /*yield*/, promise];
1026
- case 1:
1027
- _b.apply(_a, [_c.sent()]);
1028
- return [2 /*return*/];
1081
+ ];
1029
1082
  }
1030
- });
1031
- }); });
1032
- _o.label = 6;
1033
- case 6:
1034
- if (request.debug && isDevelopment) {
1035
- reactToastify.toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1083
+ else if (requestMethod === DELETE) {
1084
+ return [{
1085
+ withCredentials: withCredentials,
1086
+ data: convertForRequestBody(query, fullTableList, C6, function (message) { return reactToastify.toast.error(message, toastOptions); })
1087
+ }];
1088
+ }
1089
+ else {
1090
+ throw new Error('The request method (' + requestMethod + ') was not recognized.');
1091
+ }
1092
+ })()), false));
1093
+ if (cachingConfirmed) {
1094
+ // push to cache so we do not repeat the request
1095
+ apiRequestCache.push({
1096
+ requestArgumentsSerialized: querySerialized,
1097
+ request: axiosActiveRequest
1098
+ });
1099
+ }
1100
+ // todo - wip verify this works
1101
+ // we had removed the value from the request to add to the URI.
1102
+ addBackPK === null || addBackPK === void 0 ? void 0 : addBackPK(); // adding back so post-processing methods work
1103
+ // returning the promise with this then is important for tests. todo - we could make that optional.
1104
+ // https://rapidapi.com/guides/axios-async-await
1105
+ return [2 /*return*/, axiosActiveRequest.then(function (response) { return tslib.__awaiter(_this, void 0, void 0, function () {
1106
+ var cacheIndex, responseData_1, fetchDependencies, dependencies_1, fetchReferences_1, apiRequestPromises, _loop_1, _a, _b, _c, _i, tableToFetch;
1107
+ var _this = this;
1108
+ var _d, _e, _f, _g, _h, _j, _k, _l, _m;
1109
+ return tslib.__generator(this, function (_o) {
1110
+ switch (_o.label) {
1111
+ case 0:
1112
+ if (typeof response.data === 'string') {
1113
+ if (isTest) {
1114
+ console.trace();
1115
+ 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 + ')');
1116
+ }
1117
+ return [2 /*return*/, Promise.reject(response)];
1118
+ }
1119
+ if (cachingConfirmed) {
1120
+ cacheIndex = apiRequestCache.findIndex(function (cache) { return cache.requestArgumentsSerialized === querySerialized; });
1121
+ apiRequestCache[cacheIndex].final = false === returnGetNextPageFunction;
1122
+ // only cache get method requests
1123
+ apiRequestCache[cacheIndex].response = response;
1124
+ }
1125
+ apiResponse = TestRestfulResponse(response, request === null || request === void 0 ? void 0 : request.success, (_d = request === null || request === void 0 ? void 0 : request.error) !== null && _d !== void 0 ? _d : "An unexpected API error occurred!");
1126
+ if (false === apiResponse) {
1127
+ if (request.debug && isDevelopment) {
1128
+ reactToastify.toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
1129
+ }
1130
+ return [2 /*return*/, response];
1131
+ }
1132
+ // stateful operations are done in the response callback - its leverages rest generated functions
1133
+ if (responseCallback) {
1134
+ responseCallback(response, request, apiResponse);
1135
+ }
1136
+ if (!(C6.GET === requestMethod)) return [3 /*break*/, 6];
1137
+ responseData_1 = response.data;
1138
+ returnGetNextPageFunction = 1 !== ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) &&
1139
+ ((_f = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _f === void 0 ? void 0 : _f[C6.LIMIT]) === responseData_1.rest.length;
1140
+ if (false === isTest || true === isVerbose) {
1141
+ console.groupCollapsed('%c API: Response (' + requestMethod + ' ' + tableName + ') returned length (' + ((_g = responseData_1.rest) === null || _g === void 0 ? void 0 : _g.length) + ') of possible (' + ((_h = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _h === void 0 ? void 0 : _h[C6.LIMIT]) + ') limit!', 'color: #0c0');
1142
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
1143
+ console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', request);
1144
+ console.log('%c Response Data:', 'color: #0c0', responseData_1.rest);
1145
+ console.log('%c Will return get next page function:' + (1 !== ((_j = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _j === void 0 ? void 0 : _j[C6.LIMIT]) ? '' : ' (Will not return with explicit limit 1 set)'), 'color: #0c0', true === returnGetNextPageFunction);
1146
+ console.trace();
1147
+ console.groupEnd();
1148
+ }
1149
+ if (false === returnGetNextPageFunction
1150
+ && true === request.debug
1151
+ && isDevelopment) {
1152
+ reactToastify.toast.success("DEVS: Response returned length (" + ((_k = responseData_1.rest) === null || _k === void 0 ? void 0 : _k.length) + ") less than limit (" + ((_l = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _l === void 0 ? void 0 : _l[C6.LIMIT]) + ").", toastOptionsDevs);
1153
+ }
1154
+ (_m = request.fetchDependencies) !== null && _m !== void 0 ? _m : (request.fetchDependencies = exports.eFetchDependencies.NONE);
1155
+ if (!(request.fetchDependencies
1156
+ && 'number' === typeof request.fetchDependencies
1157
+ && responseData_1.rest.length > 0)) return [3 /*break*/, 6];
1158
+ fetchDependencies = request.fetchDependencies;
1159
+ console.groupCollapsed('%c API: Fetch Dependencies segment (' + requestMethod + ' ' + tableName + ')'
1160
+ + (fetchDependencies & exports.eFetchDependencies.CHILDREN ? ' | (CHILDREN|REFERENCED) ' : '')
1161
+ + (fetchDependencies & exports.eFetchDependencies.PARENTS ? ' | (PARENTS|REFERENCED_BY)' : '')
1162
+ + (fetchDependencies & exports.eFetchDependencies.C6ENTITY ? ' | (C6ENTITY)' : '')
1163
+ + (fetchDependencies & exports.eFetchDependencies.RECURSIVE ? ' | (RECURSIVE)' : ''), 'color: #33ccff');
1164
+ console.groupCollapsed('Collapsed JS Trace');
1165
+ console.trace(); // hidden in collapsed group
1166
+ console.groupEnd();
1167
+ dependencies_1 = {};
1168
+ if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
1169
+ dependencies_1 = operatingTable.endsWith("carbon_carbons")
1170
+ ? tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1171
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1172
+ : {}), fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
1173
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1174
+ : {}) : tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.CHILDREN // REFERENCED === CHILDREN
1175
+ ? tslib.__assign(tslib.__assign({}, Object.keys(C6.TABLES[operatingTable].TABLE_REFERENCES).reduce(function (accumulator, columnName) {
1176
+ if (!C6.TABLES[operatingTable].PRIMARY_SHORT.includes(columnName)) {
1177
+ accumulator[columnName] = C6.TABLES[operatingTable].TABLE_REFERENCES[columnName];
1178
+ }
1179
+ return accumulator;
1180
+ }, {})), C6.TABLES[operatingTable].TABLE_REFERENCED_BY // it is unlikely that a C6 table will have any TABLE_REFERENCED_BY
1181
+ ) : {}), fetchDependencies & exports.eFetchDependencies.PARENTS // REFERENCES === PARENTS
1182
+ ? C6.TABLES[operatingTable].PRIMARY_SHORT.reduce(function (accumulator, primaryKey) {
1183
+ if (primaryKey in C6.TABLES[operatingTable].TABLE_REFERENCES) {
1184
+ accumulator[primaryKey] = C6.TABLES[operatingTable].TABLE_REFERENCES[primaryKey];
1185
+ }
1186
+ return accumulator;
1187
+ }, {})
1188
+ : {});
1189
+ }
1190
+ else {
1191
+ // this is the natural mysql context
1192
+ dependencies_1 = tslib.__assign(tslib.__assign({}, fetchDependencies & exports.eFetchDependencies.REFERENCED // REFERENCED === CHILDREN
1193
+ ? C6.TABLES[operatingTable].TABLE_REFERENCED_BY
1194
+ : {}), fetchDependencies & exports.eFetchDependencies.REFERENCES // REFERENCES === PARENTS
1195
+ ? C6.TABLES[operatingTable].TABLE_REFERENCES
1196
+ : {});
1197
+ }
1198
+ fetchReferences_1 = {};
1199
+ apiRequestPromises = [];
1200
+ console.log('%c Dependencies', 'color: #005555', dependencies_1);
1201
+ Object.keys(dependencies_1)
1202
+ .forEach(function (column) { return dependencies_1[column]
1203
+ .forEach(function (constraint) {
1204
+ var _a, _b, _c, _d;
1205
+ var _e, _f, _g;
1206
+ var columnValues = (_b = (_a = responseData_1.rest[column]) !== null && _a !== void 0 ? _a : responseData_1.rest.map(function (row) {
1207
+ if (operatingTable.endsWith("carbons")
1208
+ && 'entity_tag' in row
1209
+ && !constraint.TABLE.endsWith(row['entity_tag'].split('\\').pop().toLowerCase())) {
1210
+ return false; // map
1211
+ }
1212
+ if (!(column in row)) {
1213
+ return false;
1214
+ }
1215
+ // todo - row[column] is a FK value, we should optionally remove values that are already in state
1216
+ // this could be any column in the table constraint.TABLE, not just the primary key
1217
+ return row[column];
1218
+ }).filter(function (n) { return n; })) !== null && _b !== void 0 ? _b : [];
1219
+ if (columnValues.length === 0) {
1220
+ return; // forEach
1221
+ }
1222
+ (_c = fetchReferences_1[_e = constraint.TABLE]) !== null && _c !== void 0 ? _c : (fetchReferences_1[_e] = {});
1223
+ (_d = (_f = fetchReferences_1[constraint.TABLE])[_g = constraint.COLUMN]) !== null && _d !== void 0 ? _d : (_f[_g] = []);
1224
+ fetchReferences_1[constraint.TABLE][constraint.COLUMN].push(columnValues);
1225
+ }); });
1226
+ console.log('fetchReferences', fetchReferences_1);
1227
+ _loop_1 = function (tableToFetch) {
1228
+ var referencesTables, shouldContinue, fetchTable, RestApi, nextFetchDependencies;
1229
+ var _p;
1230
+ return tslib.__generator(this, function (_q) {
1231
+ switch (_q.label) {
1232
+ case 0:
1233
+ if (fetchDependencies & exports.eFetchDependencies.C6ENTITY
1234
+ && 'string' === typeof tableName
1235
+ && tableName.endsWith("carbon_carbons")) {
1236
+ referencesTables = responseData_1.rest.reduce(function (accumulator, row) {
1237
+ if ('entity_tag' in row && !accumulator.includes(row['entity_tag'])) {
1238
+ accumulator.push(row['entity_tag']);
1239
+ }
1240
+ return accumulator;
1241
+ }, []).map(function (entityTag) { return entityTag.split('\\').pop().toLowerCase(); });
1242
+ shouldContinue = referencesTables.find(function (referencesTable) { return tableToFetch.endsWith(referencesTable); });
1243
+ if (!shouldContinue) {
1244
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') did not end with any value in referencesTables', 'color: #c00', referencesTables);
1245
+ return [2 /*return*/, "continue"];
1246
+ }
1247
+ console.log('%c C6ENTITY: The constraintTableName (' + tableToFetch + ') will be fetched.', 'color: #0c0');
1248
+ }
1249
+ return [4 /*yield*/, C6.IMPORT(tableToFetch)];
1250
+ case 1:
1251
+ fetchTable = _q.sent();
1252
+ RestApi = fetchTable.default;
1253
+ console.log('%c Fetch Dependencies will select (' + tableToFetch + ') using GET request', 'color: #33ccff');
1254
+ nextFetchDependencies = exports.eFetchDependencies.NONE;
1255
+ if (fetchDependencies & exports.eFetchDependencies.RECURSIVE) {
1256
+ if (fetchDependencies & exports.eFetchDependencies.ALL) {
1257
+ 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.');
1258
+ }
1259
+ nextFetchDependencies = fetchDependencies;
1260
+ }
1261
+ else if (fetchDependencies & exports.eFetchDependencies.C6ENTITY) {
1262
+ if (tableToFetch === "carbon_carbons") {
1263
+ nextFetchDependencies = fetchDependencies;
1264
+ }
1265
+ else {
1266
+ nextFetchDependencies = fetchDependencies ^ exports.eFetchDependencies.C6ENTITY;
1267
+ }
1268
+ }
1269
+ console.log('fetchReferences', fetchReferences_1[tableToFetch], "Current fetchDependencies for (" + operatingTable + "):", fetchDependencies, "New fetchDependencies for (" + tableToFetch + "): ", nextFetchDependencies);
1270
+ // 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
1271
+ // it not certain that they are using carbons' entities either
1272
+ // this is a dynamic call to the rest api, any generated table may resolve with (RestApi)
1273
+ // todo - using value to avoid joins.... but. maybe this should be a parameterizable option -- think race conditions; its safer to join
1274
+ apiRequestPromises.push(RestApi.Get((_p = {},
1275
+ _p[C6.WHERE] = {
1276
+ 0: Object.keys(fetchReferences_1[tableToFetch]).reduce(function (sum, column) {
1277
+ fetchReferences_1[tableToFetch][column] = fetchReferences_1[tableToFetch][column].flat(Infinity);
1278
+ if (0 === fetchReferences_1[tableToFetch][column].length) {
1279
+ console.warn('The column (' + column + ') was not found in the response data. We will not fetch.', responseData_1);
1280
+ return false;
1281
+ }
1282
+ sum[column] = fetchReferences_1[tableToFetch][column].length === 1
1283
+ ? fetchReferences_1[tableToFetch][column][0]
1284
+ : [
1285
+ C6.IN, fetchReferences_1[tableToFetch][column]
1286
+ ];
1287
+ return sum;
1288
+ }, {})
1289
+ },
1290
+ _p.fetchDependencies = nextFetchDependencies,
1291
+ _p)));
1292
+ return [2 /*return*/];
1293
+ }
1294
+ });
1295
+ };
1296
+ _a = fetchReferences_1;
1297
+ _b = [];
1298
+ for (_c in _a)
1299
+ _b.push(_c);
1300
+ _i = 0;
1301
+ _o.label = 1;
1302
+ case 1:
1303
+ if (!(_i < _b.length)) return [3 /*break*/, 4];
1304
+ _c = _b[_i];
1305
+ if (!(_c in _a)) return [3 /*break*/, 3];
1306
+ tableToFetch = _c;
1307
+ return [5 /*yield**/, _loop_1(tableToFetch)];
1308
+ case 2:
1309
+ _o.sent();
1310
+ _o.label = 3;
1311
+ case 3:
1312
+ _i++;
1313
+ return [3 /*break*/, 1];
1314
+ case 4:
1315
+ console.groupEnd();
1316
+ return [4 /*yield*/, Promise.all(apiRequestPromises)];
1317
+ case 5:
1318
+ _o.sent();
1319
+ apiRequestPromises.map(function (promise) { return tslib.__awaiter(_this, void 0, void 0, function () {
1320
+ var _a, _b;
1321
+ return tslib.__generator(this, function (_c) {
1322
+ switch (_c.label) {
1323
+ case 0:
1324
+ if (!Array.isArray(request.fetchDependencies)) {
1325
+ request.fetchDependencies = [];
1326
+ }
1327
+ _b = (_a = request.fetchDependencies).push;
1328
+ return [4 /*yield*/, promise];
1329
+ case 1:
1330
+ _b.apply(_a, [_c.sent()]);
1331
+ return [2 /*return*/];
1332
+ }
1333
+ });
1334
+ }); });
1335
+ _o.label = 6;
1336
+ case 6:
1337
+ if (request.debug && isDevelopment) {
1338
+ reactToastify.toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1339
+ }
1340
+ return [2 /*return*/, response];
1341
+ }
1342
+ });
1343
+ }); })];
1344
+ }
1345
+ catch (error) {
1346
+ if (isTest) {
1347
+ throw new Error(JSON.stringify(error));
1348
+ }
1349
+ console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1350
+ console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1351
+ console.warn(error);
1352
+ console.trace();
1353
+ console.groupEnd();
1354
+ TestRestfulResponse(error, request === null || request === void 0 ? void 0 : request.success, (request === null || request === void 0 ? void 0 : request.error) || "An restful API error occurred!");
1355
+ return [2 /*return*/, null];
1036
1356
  }
1037
- return [2 /*return*/, response];
1357
+ return [2 /*return*/];
1038
1358
  }
1039
1359
  });
1040
- }); });
1360
+ });
1041
1361
  }
1042
- catch (error) {
1043
- if (isTest) {
1044
- throw new Error(JSON.stringify(error));
1362
+ var query;
1363
+ if (request === void 0) { request = {}; }
1364
+ return tslib.__generator(this, function (_a) {
1365
+ switch (_a.label) {
1366
+ case 0:
1367
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request for (' + operatingTable + ')', 'color: #0c0');
1368
+ console.log('request', request);
1369
+ console.groupEnd();
1370
+ if ('function' === typeof queryCallback) {
1371
+ query = queryCallback(request); // obj or obj[]
1372
+ }
1373
+ else {
1374
+ query = queryCallback;
1375
+ }
1376
+ if (undefined === query || null === query) {
1377
+ if (request.debug && isDevelopment) {
1378
+ reactToastify.toast.warning("DEV: queryCallback returned undefined, signaling in Custom Cache. (returning null)", toastOptionsDevs);
1379
+ }
1380
+ console.groupCollapsed('%c API: (' + requestMethod + ') Request Query for (' + operatingTable + ') undefined, returning null (will not fire ajax)!', 'color: #c00');
1381
+ 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');
1382
+ console.trace();
1383
+ console.groupEnd();
1384
+ return [2 /*return*/, null];
1385
+ }
1386
+ if (C6.GET === requestMethod) {
1387
+ if (undefined === query[C6.PAGINATION]) {
1388
+ query[C6.PAGINATION] = {};
1389
+ }
1390
+ query[C6.PAGINATION][C6.PAGE] = query[C6.PAGINATION][C6.PAGE] || 1;
1391
+ query[C6.PAGINATION][C6.LIMIT] = query[C6.PAGINATION][C6.LIMIT] || 100;
1392
+ }
1393
+ return [4 /*yield*/, apiRequest()];
1394
+ case 1: return [2 /*return*/, _a.sent()];
1045
1395
  }
1046
- console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
1047
- console.log('%c ' + requestMethod + ' ' + tableName, 'color: #A020F0');
1048
- console.warn(error);
1049
- console.trace();
1050
- console.groupEnd();
1051
- TestRestfulResponse(error, request === null || request === void 0 ? void 0 : request.success, (request === null || request === void 0 ? void 0 : request.error) || "An restful API error occurred!");
1052
- return null;
1053
- }
1054
- }
1055
- return apiRequest();
1396
+ });
1397
+ });
1056
1398
  };
1057
1399
  }
1058
1400
 
@@ -1071,6 +1413,7 @@ function timeout(shouldContinueAfterTimeout, cb, timeoutMs) {
1071
1413
  }
1072
1414
 
1073
1415
  exports.C6Constants = C6Constants;
1416
+ exports.CarbonSqlExecutor = CarbonSqlExecutor;
1074
1417
  exports.DELETE = DELETE;
1075
1418
  exports.GET = GET;
1076
1419
  exports.POST = POST;
@@ -1081,7 +1424,9 @@ exports.checkAllRequestsComplete = checkAllRequestsComplete;
1081
1424
  exports.clearCache = clearCache;
1082
1425
  exports.convertForRequestBody = convertForRequestBody;
1083
1426
  exports.extendedTypeHints = extendedTypeHints;
1427
+ exports.getEnvVar = getEnvVar;
1084
1428
  exports.isLocal = isDevelopment;
1429
+ exports.isNode = isNode;
1085
1430
  exports.isPromise = isPromise;
1086
1431
  exports.isTest = isTest;
1087
1432
  exports.isVerbose = isVerbose;