@carbonorm/carbonnode 3.0.10 → 3.0.12

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.
package/dist/index.esm.js CHANGED
@@ -308,8 +308,13 @@ function convertForRequestBody (restfulObject, tableName, C6, regexErrorHandler)
308
308
  }, {});
309
309
  }
310
310
 
311
- var _a;
312
- var isNode = typeof process !== 'undefined' && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
311
+ var isNode = function () {
312
+ var _a;
313
+ console.log('Checking if running in Node.js environment...');
314
+ var isNodeEnv = typeof process !== 'undefined' && !!((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);
315
+ console.log("Is Node.js environment: ".concat(isNodeEnv));
316
+ return isNodeEnv;
317
+ };
313
318
 
314
319
  /**
315
320
  * Facade: routes API calls to SQL or HTTP executors based on runtime context.
@@ -322,7 +327,7 @@ function restRequest(configX) {
322
327
  switch (_a.label) {
323
328
  case 0:
324
329
  config = typeof configX === "function" ? configX() : configX;
325
- if (!(isNode && config.mysqlPool)) return [3 /*break*/, 2];
330
+ if (!(isNode() && config.mysqlPool)) return [3 /*break*/, 2];
326
331
  return [4 /*yield*/, Promise.resolve().then(function () { return SqlExecutor$1; })];
327
332
  case 1:
328
333
  SqlExecutor = (_a.sent()).SqlExecutor;
@@ -360,165 +365,6 @@ function timeout(shouldContinueAfterTimeout, cb, timeoutMs) {
360
365
  };
361
366
  }
362
367
 
363
- function buildBooleanJoinedConditions(set, andMode) {
364
- if (andMode === void 0) { andMode = true; }
365
- var booleanOperator = andMode ? 'AND' : 'OR';
366
- var sql = '';
367
- var OPERATORS = ['=', '!=', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'IS', 'IS NOT'];
368
- var isAggregateArray = function (value) { return Array.isArray(value) && typeof value[0] === 'string' && OPERATORS.includes(value[0]); };
369
- var isNumericKeyed = function (obj) { return Array.isArray(obj) && Object.keys(obj).every(function (k) { return /^\d+$/.test(k); }); };
370
- // todo - we should be doing something with value no????
371
- var addCondition = function (column, op, _value) {
372
- var paramName = column.replace(/\W+/g, '_');
373
- return "(".concat(column, " ").concat(op, " :").concat(paramName, ")");
374
- };
375
- if (isNumericKeyed(set)) {
376
- switch (set.length) {
377
- case 2:
378
- sql += addCondition(set[0], '=', set[1]);
379
- break;
380
- case 3:
381
- if (!OPERATORS.includes(set[1])) {
382
- throw new Error("Invalid operator: ".concat(set[1]));
383
- }
384
- sql += addCondition(set[0], set[1], set[2]);
385
- break;
386
- default:
387
- throw new Error("Invalid array condition: ".concat(JSON.stringify(set)));
388
- }
389
- }
390
- else {
391
- var parts = [];
392
- for (var _i = 0, _a = Object.entries(set); _i < _a.length; _i++) {
393
- var _b = _a[_i], key = _b[0], value = _b[1];
394
- if (/^\d+$/.test(key)) {
395
- parts.push(buildBooleanJoinedConditions(value, !andMode));
396
- continue;
397
- }
398
- if (!Array.isArray(value) || isAggregateArray(value)) {
399
- parts.push(addCondition(key, '='));
400
- continue;
401
- }
402
- if (value.length === 2 && OPERATORS.includes(value[0])) {
403
- parts.push(addCondition(key, value[0], value[1]));
404
- }
405
- else if (value.length === 1 && isAggregateArray(value[0])) {
406
- parts.push(addCondition(key, '=', value[0]));
407
- }
408
- else {
409
- throw new Error("Invalid condition for ".concat(key, ": ").concat(JSON.stringify(value)));
410
- }
411
- }
412
- sql = parts.join(" ".concat(booleanOperator, " "));
413
- }
414
- return "(".concat(sql, ")");
415
- }
416
- function buildAggregateField(field) {
417
- if (typeof field === 'string')
418
- return field;
419
- if (!Array.isArray(field))
420
- throw new Error('Invalid SELECT entry: must be string or array');
421
- var agg = field[0], args = field.slice(1);
422
- switch (agg) {
423
- case 'COUNT':
424
- return "COUNT(".concat(args[0] || '*', ")");
425
- case 'SUM':
426
- case 'AVG':
427
- case 'MIN':
428
- case 'MAX':
429
- return "".concat(agg, "(").concat(args[0], ")").concat(args[1] ? " AS ".concat(args[1]) : '');
430
- case 'DISTINCT':
431
- return "DISTINCT(".concat(args[0], ")").concat(args[1] ? " AS ".concat(args[1]) : '');
432
- case 'GROUP_CONCAT': {
433
- var col = args[0], alias = args[1], sortCol = args[2], sortType = args[3];
434
- var order = sortCol ? " ORDER BY ".concat(sortCol, " ").concat(sortType || 'ASC') : '';
435
- return "GROUP_CONCAT(DISTINCT ".concat(col).concat(order, " SEPARATOR ',')").concat(alias ? " AS ".concat(alias) : '');
436
- }
437
- case 'AS': {
438
- var col = args[0], alias = args[1];
439
- return "".concat(col, " AS ").concat(alias);
440
- }
441
- case 'CONVERT_TZ': {
442
- var ts = args[0], fromTz = args[1], toTz = args[2];
443
- return "CONVERT_TZ(".concat(ts, ", ").concat(fromTz, ", ").concat(toTz, ")");
444
- }
445
- case 'NOW':
446
- return 'NOW()';
447
- default:
448
- throw new Error("Unsupported aggregate: ".concat(agg));
449
- }
450
- }
451
- function buildSelectQuery(table, primary, args, isSubSelect) {
452
- var _a, _b;
453
- if (isSubSelect === void 0) { isSubSelect = false; }
454
- var selectList = (_a = args === null || args === void 0 ? void 0 : args[C6Constants.SELECT]) !== null && _a !== void 0 ? _a : ['*'];
455
- var selectFields = Array.isArray(selectList)
456
- ? selectList.map(function (f) { return buildAggregateField(f); }).join(', ')
457
- : '*';
458
- var sql = "SELECT ".concat(selectFields, " FROM `").concat(table, "`");
459
- if (args === null || args === void 0 ? void 0 : args[C6Constants.JOIN]) {
460
- var joins = args[C6Constants.JOIN];
461
- for (var joinType in joins) {
462
- var joinKeyword = joinType.replace('_', ' ').toUpperCase();
463
- for (var joinTable in joins[joinType]) {
464
- var onClause = buildBooleanJoinedConditions(joins[joinType][joinTable]);
465
- sql += " ".concat(joinKeyword, " JOIN `").concat(joinTable, "` ON ").concat(onClause);
466
- }
467
- }
468
- }
469
- if (args === null || args === void 0 ? void 0 : args[C6Constants.WHERE]) {
470
- sql += " WHERE ".concat(buildBooleanJoinedConditions(args[C6Constants.WHERE]));
471
- }
472
- if (args === null || args === void 0 ? void 0 : args[C6Constants.GROUP_BY]) {
473
- var groupByFields = Array.isArray(args[C6Constants.GROUP_BY]) ? args[C6Constants.GROUP_BY].join(', ') : args[C6Constants.GROUP_BY];
474
- sql += " GROUP BY ".concat(groupByFields);
475
- }
476
- if (args === null || args === void 0 ? void 0 : args[C6Constants.HAVING]) {
477
- sql += " HAVING ".concat(buildBooleanJoinedConditions(args[C6Constants.HAVING]));
478
- }
479
- if (args === null || args === void 0 ? void 0 : args[C6Constants.PAGINATION]) {
480
- var p = args[C6Constants.PAGINATION];
481
- var limitClause = '';
482
- if (p[C6Constants.ORDER]) {
483
- var orderArray = Object.entries(p[C6Constants.ORDER]).map(function (_a) {
484
- var col = _a[0], dir = _a[1];
485
- if (!['ASC', 'DESC'].includes(String(dir).toUpperCase())) {
486
- throw new Error("Invalid order direction: ".concat(dir));
487
- }
488
- return "".concat(col, " ").concat(String(dir).toUpperCase());
489
- });
490
- sql += " ORDER BY ".concat(orderArray.join(', '));
491
- }
492
- else if (primary) {
493
- sql += " ORDER BY ".concat(primary, " DESC");
494
- } /*else {
495
- // todo - this is wrong
496
- const primaryKey = C6Constants.TABLES['users'].PRIMARY_SHORT?.[0] ?? 'user_id';
497
- sql += ` ORDER BY ${primaryKey} DESC`;
498
- }*/
499
- if (p[C6Constants.LIMIT] != null) {
500
- var limit = parseInt(p[C6Constants.LIMIT], 10);
501
- if (isNaN(limit) || limit < 0) {
502
- throw new Error("Invalid LIMIT: ".concat(p[C6Constants.LIMIT]));
503
- }
504
- var page = parseInt((_b = p[C6Constants.PAGE]) !== null && _b !== void 0 ? _b : 1, 10);
505
- if (isNaN(page) || page < 1) {
506
- throw new Error("PAGE must be >= 1 (got ".concat(p[C6Constants.PAGE], ")"));
507
- }
508
- var offset = (page - 1) * limit;
509
- limitClause += " LIMIT ".concat(offset, ", ").concat(limit);
510
- }
511
- sql += limitClause;
512
- }
513
- else if (!isSubSelect && primary) {
514
- sql += " ORDER BY ".concat(primary, " ASC LIMIT 1");
515
- }
516
- else if (!isSubSelect && !primary) {
517
- sql += " ORDER BY id ASC LIMIT 100"; // fallback default limit
518
- }
519
- return sql;
520
- }
521
-
522
368
  function getEnvVar(key, fallback) {
523
369
  if (fallback === void 0) { fallback = ''; }
524
370
  // Vite-style injection
@@ -534,8 +380,10 @@ function getEnvVar(key, fallback) {
534
380
  return fallback;
535
381
  }
536
382
 
537
- var envVerbose = getEnvVar('VERBOSE') || getEnvVar('REACT_APP_VERBOSE') || getEnvVar('VITE_VERBOSE') || '';
538
- var isVerbose = ['true', '1', 'yes', 'on'].includes(envVerbose.toLowerCase());
383
+ function isVerbose () {
384
+ var envVerbose = getEnvVar('VERBOSE') || getEnvVar('REACT_APP_VERBOSE') || getEnvVar('VITE_VERBOSE') || '';
385
+ return ['true', '1', 'yes', 'on'].includes(envVerbose.toLowerCase());
386
+ }
539
387
 
540
388
  var Executor = /** @class */ (function () {
541
389
  function Executor(config, request) {
@@ -558,7 +406,7 @@ var Executor = /** @class */ (function () {
558
406
  if (!(_i < _a.length)) return [3 /*break*/, 6];
559
407
  _b = _a[_i], key = _b[0], fn = _b[1];
560
408
  if (!(typeof fn === "function")) return [3 /*break*/, 5];
561
- if (isVerbose || args.request.debug) {
409
+ if (isVerbose() || args.request.debug) {
562
410
  console.groupCollapsed("[LIFECYCLE] ".concat(this.config.requestMethod, ".").concat(String(phase), ":").concat(key));
563
411
  console.log("config:", args.config);
564
412
  console.log("request:", args.request);
@@ -589,11 +437,220 @@ var Executor = /** @class */ (function () {
589
437
  return Executor;
590
438
  }());
591
439
 
592
- var isDevelopment = getEnvVar('NODE_ENV', '') === 'development';
440
+ var SqlBuilder = /** @class */ (function (_super) {
441
+ __extends(SqlBuilder, _super);
442
+ function SqlBuilder() {
443
+ return _super !== null && _super.apply(this, arguments) || this;
444
+ }
445
+ /** Generate nested WHERE/JOIN conditions with parameter binding */
446
+ SqlBuilder.prototype.buildBooleanJoinedConditions = function (set, andMode, params) {
447
+ if (andMode === void 0) { andMode = true; }
448
+ if (params === void 0) { params = []; }
449
+ var booleanOperator = andMode ? 'AND' : 'OR';
450
+ var OPERATORS = ['=', '!=', '<', '<=', '>', '>=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'IS', 'IS NOT'];
451
+ var isAggregateArray = function (value) {
452
+ return Array.isArray(value) && typeof value[0] === 'string' && OPERATORS.includes(value[0]);
453
+ };
454
+ var isNumericKeyed = function (obj) {
455
+ return Array.isArray(obj) && Object.keys(obj).every(function (k) { return /^\d+$/.test(k); });
456
+ };
457
+ var addCondition = function (column, op, value) {
458
+ var clause;
459
+ /*if (Buffer.isBuffer(value)) { // TODO - I want this as a parameterized option, for now default to faster
460
+ params.push(value.toString('hex')); // Or use UNHEX(?) in SQL
461
+ clause = `(${column} = UNHEX(?))`;
462
+ } else {*/
463
+ params.push(value);
464
+ clause = "( ".concat(column, " ").concat(op, " ? )");
465
+ //}
466
+ isVerbose() && console.log("[WHERE] \u2795 ".concat(clause, " ->"), value);
467
+ return clause;
468
+ };
469
+ var sql;
470
+ if (isNumericKeyed(set)) {
471
+ isVerbose() && console.log("[WHERE] Numeric keyed condition:", set);
472
+ switch (set.length) {
473
+ case 2:
474
+ sql = addCondition(set[0], '=', set[1]);
475
+ break;
476
+ case 3:
477
+ if (!OPERATORS.includes(set[1]))
478
+ throw new Error("Invalid operator: ".concat(set[1]));
479
+ sql = addCondition(set[0], set[1], set[2]);
480
+ break;
481
+ default:
482
+ throw new Error("Invalid array condition: ".concat(JSON.stringify(set)));
483
+ }
484
+ }
485
+ else {
486
+ var parts = [];
487
+ for (var _i = 0, _a = Object.entries(set); _i < _a.length; _i++) {
488
+ var _b = _a[_i], key = _b[0], value = _b[1];
489
+ if (/^\d+$/.test(key)) {
490
+ parts.push(this.buildBooleanJoinedConditions(value, !andMode, params));
491
+ }
492
+ else if (!Array.isArray(value) || isAggregateArray(value)) {
493
+ parts.push(addCondition(key, '=', value));
494
+ }
495
+ else if (value.length === 2 && OPERATORS.includes(value[0])) {
496
+ parts.push(addCondition(key, value[0], value[1]));
497
+ }
498
+ else {
499
+ throw new Error("Invalid condition for ".concat(key, ": ").concat(JSON.stringify(value)));
500
+ }
501
+ }
502
+ sql = parts.join(" ".concat(booleanOperator, " "));
503
+ }
504
+ isVerbose() && console.log("[WHERE] Final: (".concat(sql, ")"));
505
+ return "(".concat(sql, ")");
506
+ };
507
+ /** Translate array or function calls into SQL expressions */
508
+ SqlBuilder.prototype.buildAggregateField = function (field) {
509
+ if (typeof field === 'string')
510
+ return field;
511
+ if (!Array.isArray(field))
512
+ throw new Error('Invalid SELECT entry');
513
+ var fn = field[0], args = field.slice(1);
514
+ var alias;
515
+ if (args.length >= 2 && args[args.length - 2] === 'AS') {
516
+ alias = String(args.pop());
517
+ args.pop();
518
+ }
519
+ var F = String(fn).toUpperCase();
520
+ var p = args.join(', ');
521
+ isVerbose() && console.log("[SELECT] ".concat(F, "(").concat(p, ")").concat(alias ? " AS ".concat(alias) : ''));
522
+ switch (F) {
523
+ case 'DATE_ADD':
524
+ return "DATE_ADD(".concat(args[0], ", ").concat(args[1], ")").concat(alias ? " AS ".concat(alias) : '');
525
+ case 'DATE_SUB':
526
+ return "DATE_SUB(".concat(args[0], ", ").concat(args[1], ")").concat(alias ? " AS ".concat(alias) : '');
527
+ case 'YEAR':
528
+ return "YEAR(".concat(args[0], ")").concat(alias ? " AS ".concat(alias) : '');
529
+ case 'MONTH':
530
+ return "MONTH(".concat(args[0], ")").concat(alias ? " AS ".concat(alias) : '');
531
+ case 'DAY':
532
+ return "DAY(".concat(args[0], ")").concat(alias ? " AS ".concat(alias) : '');
533
+ case 'ROUND':
534
+ case 'CEIL':
535
+ case 'FLOOR':
536
+ case 'ABS':
537
+ case 'SQRT':
538
+ return "".concat(F, "(").concat(p, ")").concat(alias ? " AS ".concat(alias) : '');
539
+ case 'ST_DISTANCE':
540
+ return "ST_Distance(".concat(p, ")").concat(alias ? " AS ".concat(alias) : '');
541
+ default:
542
+ if (/^[A-Z_]+$/.test(F))
543
+ return "".concat(F, "(").concat(p, ")").concat(alias ? " AS ".concat(alias) : '');
544
+ throw new Error("Unsupported function: ".concat(F));
545
+ }
546
+ };
547
+ /** Compose a parameterized SELECT query with optional JOIN/WHERE/GROUP/HAVING/PAGINATION */
548
+ SqlBuilder.prototype.buildSelectQuery = function (table, primary, args, isSubSelect) {
549
+ var _this = this;
550
+ var _a, _b, _c, _d;
551
+ if (isSubSelect === void 0) { isSubSelect = false; }
552
+ var model = this.config.C6.TABLES[table];
553
+ var params = [];
554
+ // SELECT
555
+ var selectList = (_a = args === null || args === void 0 ? void 0 : args[C6Constants.SELECT]) !== null && _a !== void 0 ? _a : ['*'];
556
+ var selectFields = Array.isArray(selectList)
557
+ ? selectList.map(function (f) { return _this.buildAggregateField(f); }).join(', ')
558
+ : '*';
559
+ var sql = "SELECT ".concat(selectFields, " FROM ").concat(table);
560
+ isVerbose() && console.log("[SELECT]", selectFields);
561
+ // JOIN
562
+ if (args === null || args === void 0 ? void 0 : args[C6Constants.JOIN]) {
563
+ for (var jt in args[C6Constants.JOIN]) {
564
+ var jk = jt.replace('_', ' ').toUpperCase();
565
+ for (var jn in args[C6Constants.JOIN][jt]) {
566
+ var on = this.buildBooleanJoinedConditions(args[C6Constants.JOIN][jt][jn], true, params);
567
+ sql += " ".concat(jk, " JOIN `").concat(jn, "` ON ").concat(on);
568
+ isVerbose() && console.log("[JOIN]", jk, jn, on);
569
+ }
570
+ }
571
+ }
572
+ // WHERE
573
+ if (args === null || args === void 0 ? void 0 : args[C6Constants.WHERE]) {
574
+ var wc = this.buildBooleanJoinedConditions(args[C6Constants.WHERE], true, params);
575
+ // Trim leading and trailing parentheses if they fully wrap the condition
576
+ while (wc.startsWith('(') && wc.endsWith(')')) {
577
+ wc = wc.slice(1, -1).trim();
578
+ }
579
+ sql += " WHERE ".concat(wc);
580
+ }
581
+ // GROUP BY
582
+ if (args === null || args === void 0 ? void 0 : args[C6Constants.GROUP_BY]) {
583
+ var gb = Array.isArray(args[C6Constants.GROUP_BY])
584
+ ? args[C6Constants.GROUP_BY].join(', ')
585
+ : args[C6Constants.GROUP_BY];
586
+ sql += " GROUP BY ".concat(gb);
587
+ isVerbose() && console.log("[GROUP BY]", gb);
588
+ }
589
+ // HAVING
590
+ if (args === null || args === void 0 ? void 0 : args[C6Constants.HAVING]) {
591
+ var hc = this.buildBooleanJoinedConditions(args[C6Constants.HAVING], true, params);
592
+ sql += " HAVING ".concat(hc);
593
+ }
594
+ // PAGINATION
595
+ if (args === null || args === void 0 ? void 0 : args[C6Constants.PAGINATION]) {
596
+ var p = args[C6Constants.PAGINATION];
597
+ if (p[C6Constants.ORDER]) {
598
+ var ord = Object.entries(p[C6Constants.ORDER]).map(function (_a) {
599
+ var c = _a[0], d = _a[1];
600
+ return "".concat(c, " ").concat(String(d).toUpperCase());
601
+ });
602
+ sql += " ORDER BY ".concat(ord.join(', '));
603
+ isVerbose() && console.log("[ORDER BY]", ord);
604
+ }
605
+ if (p[C6Constants.LIMIT] != null) {
606
+ var lim = parseInt(p[C6Constants.LIMIT], 10);
607
+ var pg = parseInt((_b = p[C6Constants.PAGE]) !== null && _b !== void 0 ? _b : 1, 10);
608
+ var off = (pg - 1) * lim;
609
+ sql += " LIMIT ".concat(off, ", ").concat(lim);
610
+ isVerbose() && console.log("[LIMIT]", off, lim);
611
+ }
612
+ }
613
+ // Fallback ORDER/LIMIT
614
+ else if (!isSubSelect) {
615
+ var ok = void 0;
616
+ if (primary)
617
+ ok = primary;
618
+ else if ((_c = model === null || model === void 0 ? void 0 : model.PRIMARY_SHORT) === null || _c === void 0 ? void 0 : _c[0])
619
+ ok = model.PRIMARY_SHORT[0];
620
+ else
621
+ for (var _i = 0, _e = ['created_at', 'updated_at']; _i < _e.length; _i++) {
622
+ var ts = _e[_i];
623
+ if ((_d = model === null || model === void 0 ? void 0 : model.COLUMNS) === null || _d === void 0 ? void 0 : _d["".concat(table, ".").concat(ts)]) {
624
+ ok = ts;
625
+ break;
626
+ }
627
+ }
628
+ if (ok) {
629
+ var dir = primary ? 'ASC' : 'DESC';
630
+ var lim = primary ? 1 : 100;
631
+ sql += " ORDER BY ".concat(ok, " ").concat(dir, " LIMIT ").concat(lim);
632
+ isVerbose() && console.log("[ORDER]", ok, dir, lim);
633
+ }
634
+ else {
635
+ sql += " LIMIT 100";
636
+ isVerbose() && console.warn("[ORDER] fallback LIMIT 100");
637
+ }
638
+ }
639
+ isVerbose() && console.log("[SQL]", sql, params);
640
+ return { sql: sql, params: params };
641
+ };
642
+ return SqlBuilder;
643
+ }(Executor));
644
+
645
+ function isLocal () {
646
+ return getEnvVar('NODE_ENV', '') === 'development';
647
+ }
593
648
 
594
- var isTest = getEnvVar('JEST_WORKER_ID') || getEnvVar('NODE_ENV') === 'test'
595
- || getEnvVar('REACT_APP_TEST') === 'true' || getEnvVar('VITE_TEST') === 'true'
596
- || getEnvVar('MODE') === 'test' || getEnvVar('VITE_TEST_MODE') === 'true';
649
+ function isTest () {
650
+ return getEnvVar('JEST_WORKER_ID') || getEnvVar('NODE_ENV') === 'test'
651
+ || getEnvVar('REACT_APP_TEST') === 'true' || getEnvVar('VITE_TEST') === 'true'
652
+ || getEnvVar('MODE') === 'test' || getEnvVar('VITE_TEST_MODE') === 'true';
653
+ }
597
654
 
598
655
  var eFetchDependencies;
599
656
  (function (eFetchDependencies) {
@@ -673,7 +730,7 @@ function removeInvalidKeys(request, c6Tables) {
673
730
  intersection[key] = request[key];
674
731
  }
675
732
  });
676
- isTest || console.log('intersection', intersection);
733
+ isTest() || console.log('intersection', intersection);
677
734
  return intersection;
678
735
  }
679
736
 
@@ -698,7 +755,7 @@ function checkCache(cacheResult, requestMethod, tableName, request) {
698
755
  return cacheResult.request;
699
756
  }
700
757
  if (true === (cacheResult === null || cacheResult === void 0 ? void 0 : cacheResult.final)) {
701
- if (false === isTest || true === isVerbose) {
758
+ if (false === isTest() || true === isVerbose()) {
702
759
  console.groupCollapsed('%c API: Rest api cache (' + requestMethod + ' ' + tableName + ') has reached the final result. Returning undefined!', 'color: #cc0');
703
760
  console.log('%c ' + requestMethod + ' ' + tableName, 'color: #cc0');
704
761
  console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #cc0', request);
@@ -871,7 +928,7 @@ var HttpExecutor = /** @class */ (function (_super) {
871
928
  if (undefined !== cacheResult) return [3 /*break*/, 1];
872
929
  _p.label = 5;
873
930
  case 5:
874
- if (debug && isDevelopment) {
931
+ if (debug && isLocal()) {
875
932
  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);
876
933
  }
877
934
  // @ts-ignore - this is an incorrect warning on TS, it's well typed
@@ -880,12 +937,12 @@ var HttpExecutor = /** @class */ (function (_super) {
880
937
  cachingConfirmed = true;
881
938
  return [3 /*break*/, 8];
882
939
  case 7:
883
- if (debug && isDevelopment) {
940
+ if (debug && isLocal()) {
884
941
  toast.info("DEVS: Ignore cache was set to true.", toastOptionsDevs);
885
942
  }
886
943
  _p.label = 8;
887
944
  case 8:
888
- if (debug && isDevelopment) {
945
+ if (debug && isLocal()) {
889
946
  toast.success("DEVS: Request not in cache." + (requestMethod === C6.GET ? "Page (" + query[C6.PAGINATION][C6.PAGE] + ")." : '') + " Logging cache 2 console.", toastOptionsDevs);
890
947
  }
891
948
  return [3 /*break*/, 12];
@@ -922,7 +979,7 @@ var HttpExecutor = /** @class */ (function (_super) {
922
979
  if (undefined === query
923
980
  || null === query
924
981
  || false === primaryKey in query) {
925
- if (true === debug && isDevelopment) {
982
+ if (true === debug && isLocal()) {
926
983
  toast.error('DEVS: The primary key (' + primaryKey + ') was not provided!!');
927
984
  }
928
985
  throw Error('You must provide the primary key (' + primaryKey + ') for table (' + operatingTable + '). Request (' + JSON.stringify(this.request, undefined, 4) + ') Query (' + JSON.stringify(query) + ')');
@@ -1011,7 +1068,7 @@ var HttpExecutor = /** @class */ (function (_super) {
1011
1068
  case 0:
1012
1069
  // noinspection SuspiciousTypeOfGuard
1013
1070
  if (typeof response.data === 'string') {
1014
- if (isTest) {
1071
+ if (isTest()) {
1015
1072
  console.trace();
1016
1073
  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 + ')');
1017
1074
  }
@@ -1031,7 +1088,7 @@ var HttpExecutor = /** @class */ (function (_super) {
1031
1088
  // todo - this feels dumb now, but i digress
1032
1089
  apiResponse = TestRestfulResponse(response, success, error);
1033
1090
  if (false === apiResponse) {
1034
- if (debug && isDevelopment) {
1091
+ if (debug && isLocal()) {
1035
1092
  toast.warning("DEVS: TestRestfulResponse returned false for (" + operatingTable + ").", toastOptionsDevs);
1036
1093
  }
1037
1094
  return [2 /*return*/, response];
@@ -1069,7 +1126,7 @@ var HttpExecutor = /** @class */ (function (_super) {
1069
1126
  responseData_1 = response.data;
1070
1127
  returnGetNextPageFunction = 1 !== ((_d = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _d === void 0 ? void 0 : _d[C6.LIMIT]) &&
1071
1128
  ((_e = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _e === void 0 ? void 0 : _e[C6.LIMIT]) === responseData_1.rest.length;
1072
- if (false === isTest || true === isVerbose) {
1129
+ if (false === isTest() || true === isVerbose()) {
1073
1130
  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');
1074
1131
  console.log('%c ' + requestMethod + ' ' + tableName, 'color: #0c0');
1075
1132
  console.log('%c Request Data (note you may see the success and/or error prompt):', 'color: #0c0', this.request);
@@ -1080,7 +1137,7 @@ var HttpExecutor = /** @class */ (function (_super) {
1080
1137
  }
1081
1138
  if (false === returnGetNextPageFunction
1082
1139
  && true === debug
1083
- && isDevelopment) {
1140
+ && isLocal()) {
1084
1141
  toast.success("DEVS: Response returned length (" + ((_j = responseData_1.rest) === null || _j === void 0 ? void 0 : _j.length) + ") less than limit (" + ((_k = query === null || query === void 0 ? void 0 : query[C6.PAGINATION]) === null || _k === void 0 ? void 0 : _k[C6.LIMIT]) + ").", toastOptionsDevs);
1085
1142
  }
1086
1143
  if (!(fetchDependencies
@@ -1265,7 +1322,7 @@ var HttpExecutor = /** @class */ (function (_super) {
1265
1322
  }); });
1266
1323
  _l.label = 6;
1267
1324
  case 6:
1268
- if (debug && isDevelopment) {
1325
+ if (debug && isLocal()) {
1269
1326
  toast.success("DEVS: (" + requestMethod + ") request complete.", toastOptionsDevs);
1270
1327
  }
1271
1328
  return [2 /*return*/, response];
@@ -1274,7 +1331,7 @@ var HttpExecutor = /** @class */ (function (_super) {
1274
1331
  }); }).then(function (response) { return response.data; })];
1275
1332
  }
1276
1333
  catch (throwableError) {
1277
- if (isTest) {
1334
+ if (isTest()) {
1278
1335
  throw new Error(JSON.stringify(throwableError));
1279
1336
  }
1280
1337
  console.groupCollapsed('%c API: An error occurred in the try catch block. returning null!', 'color: #ff0000');
@@ -1310,13 +1367,16 @@ var SqlExecutor = /** @class */ (function (_super) {
1310
1367
  }
1311
1368
  SqlExecutor.prototype.execute = function () {
1312
1369
  return __awaiter(this, void 0, void 0, function () {
1313
- var _a, TABLE_NAME, PRIMARY, _b, rest, result, created, result, updated, result, deleted;
1314
- return __generator(this, function (_c) {
1315
- switch (_c.label) {
1370
+ var TABLE_NAME, method, _a, rest, result, created, result, updated, result, deleted;
1371
+ return __generator(this, function (_b) {
1372
+ switch (_b.label) {
1316
1373
  case 0:
1317
- _a = this.config.restModel, TABLE_NAME = _a.TABLE_NAME, PRIMARY = _a.PRIMARY;
1318
- _b = this.config.requestMethod;
1319
- switch (_b) {
1374
+ TABLE_NAME = this.config.restModel.TABLE_NAME;
1375
+ method = this.config.requestMethod;
1376
+ console.log("[SQL EXECUTOR] \u25B6\uFE0F Executing ".concat(method, " on table \"").concat(TABLE_NAME, "\""));
1377
+ console.log("[SQL EXECUTOR] \uD83E\uDDFE Request payload:", this.request);
1378
+ _a = method;
1379
+ switch (_a) {
1320
1380
  case 'GET': return [3 /*break*/, 1];
1321
1381
  case 'POST': return [3 /*break*/, 3];
1322
1382
  case 'PUT': return [3 /*break*/, 5];
@@ -1325,24 +1385,36 @@ var SqlExecutor = /** @class */ (function (_super) {
1325
1385
  return [3 /*break*/, 9];
1326
1386
  case 1: return [4 /*yield*/, this.select(TABLE_NAME, undefined, this.request)];
1327
1387
  case 2:
1328
- rest = _c.sent();
1388
+ rest = _b.sent();
1389
+ console.log("[SQL EXECUTOR] \u2705 GET result:", rest);
1329
1390
  return [2 /*return*/, { rest: rest }];
1330
1391
  case 3: return [4 /*yield*/, this.insert(TABLE_NAME, this.request)];
1331
1392
  case 4:
1332
- result = _c.sent();
1393
+ result = _b.sent();
1394
+ console.log("[SQL EXECUTOR] \u2705 POST result:", result);
1333
1395
  created = { rest: result, created: true };
1334
1396
  return [2 /*return*/, created];
1335
- case 5: return [4 /*yield*/, this.update(TABLE_NAME, PRIMARY, this.request)];
1397
+ case 5: return [4 /*yield*/, this.update(TABLE_NAME, [], this.request)];
1336
1398
  case 6:
1337
- result = _c.sent();
1338
- updated = { rest: result, updated: true, rowCount: result.affectedRows };
1399
+ result = _b.sent();
1400
+ console.log("[SQL EXECUTOR] \u2705 PUT result:", result);
1401
+ updated = {
1402
+ rest: result,
1403
+ updated: true,
1404
+ rowCount: result.affectedRows
1405
+ };
1339
1406
  return [2 /*return*/, updated];
1340
- case 7: return [4 /*yield*/, this.delete(TABLE_NAME, PRIMARY, this.request)];
1407
+ case 7: return [4 /*yield*/, this.delete(TABLE_NAME, [], this.request)];
1341
1408
  case 8:
1342
- result = _c.sent();
1343
- deleted = { rest: result, deleted: true, rowCount: result.affectedRows };
1409
+ result = _b.sent();
1410
+ console.log("[SQL EXECUTOR] \u2705 DELETE result:", result);
1411
+ deleted = {
1412
+ rest: result,
1413
+ deleted: true,
1414
+ rowCount: result.affectedRows
1415
+ };
1344
1416
  return [2 /*return*/, deleted];
1345
- case 9: throw new Error("Unsupported request method: ".concat(this.config.requestMethod));
1417
+ case 9: throw new Error("Unsupported request method: ".concat(method));
1346
1418
  }
1347
1419
  });
1348
1420
  });
@@ -1352,15 +1424,19 @@ var SqlExecutor = /** @class */ (function (_super) {
1352
1424
  var conn;
1353
1425
  return __generator(this, function (_a) {
1354
1426
  switch (_a.label) {
1355
- case 0: return [4 /*yield*/, this.config.mysqlPool.getConnection()];
1427
+ case 0:
1428
+ console.log("[SQL EXECUTOR] \uD83D\uDCE1 Getting DB connection");
1429
+ return [4 /*yield*/, this.config.mysqlPool.getConnection()];
1356
1430
  case 1:
1357
1431
  conn = _a.sent();
1358
1432
  _a.label = 2;
1359
1433
  case 2:
1360
1434
  _a.trys.push([2, , 4, 5]);
1435
+ console.log("[SQL EXECUTOR] \u2705 Connection acquired");
1361
1436
  return [4 /*yield*/, cb(conn)];
1362
1437
  case 3: return [2 /*return*/, _a.sent()];
1363
1438
  case 4:
1439
+ console.log("[SQL EXECUTOR] \uD83D\uDD0C Releasing DB connection");
1364
1440
  conn.release();
1365
1441
  return [7 /*endfinally*/];
1366
1442
  case 5: return [2 /*return*/];
@@ -1370,21 +1446,23 @@ var SqlExecutor = /** @class */ (function (_super) {
1370
1446
  };
1371
1447
  SqlExecutor.prototype.select = function (table, primary, args) {
1372
1448
  return __awaiter(this, void 0, void 0, function () {
1373
- var sql;
1449
+ var sql, formatted;
1374
1450
  var _this = this;
1375
1451
  return __generator(this, function (_a) {
1376
1452
  switch (_a.label) {
1377
1453
  case 0:
1378
- sql = buildSelectQuery(table, primary, args);
1454
+ sql = this.buildSelectQuery(table, primary, args);
1455
+ console.log("[SQL EXECUTOR] \uD83E\uDDE0 Generated SELECT SQL:", sql);
1456
+ formatted = this.formatSQLWithParams(sql.sql, sql.params);
1457
+ console.log("[SQL EXECUTOR] \uD83E\uDDE0 Formatted SELECT SQL:", formatted);
1379
1458
  return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1380
1459
  var rows;
1381
1460
  return __generator(this, function (_a) {
1382
1461
  switch (_a.label) {
1383
- case 0:
1384
- console.log(sql);
1385
- return [4 /*yield*/, conn.query(sql)];
1462
+ case 0: return [4 /*yield*/, conn.query(sql.sql, sql.params)];
1386
1463
  case 1:
1387
1464
  rows = (_a.sent())[0];
1465
+ console.log("[SQL EXECUTOR] \uD83D\uDCE6 Rows fetched:", rows);
1388
1466
  return [2 /*return*/, rows];
1389
1467
  }
1390
1468
  });
@@ -1405,6 +1483,8 @@ var SqlExecutor = /** @class */ (function (_super) {
1405
1483
  values = keys.map(function (k) { return data[k]; });
1406
1484
  placeholders = keys.map(function () { return '?'; }).join(', ');
1407
1485
  sql = "INSERT INTO `".concat(table, "` (").concat(keys.join(', '), ") VALUES (").concat(placeholders, ")");
1486
+ console.log("[SQL EXECUTOR] \uD83E\uDDE0 Generated INSERT SQL:", sql);
1487
+ console.log("[SQL EXECUTOR] \uD83D\uDD22 Values:", values);
1408
1488
  return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1409
1489
  var result;
1410
1490
  return __generator(this, function (_a) {
@@ -1435,6 +1515,8 @@ var SqlExecutor = /** @class */ (function (_super) {
1435
1515
  updates = keys.map(function (k) { return "`".concat(k, "` = ?"); }).join(', ');
1436
1516
  sql = "UPDATE `".concat(table, "` SET ").concat(updates, " WHERE `").concat(primary[0], "` = ?");
1437
1517
  values.push(data[primary[0]]);
1518
+ console.log("[SQL EXECUTOR] \uD83E\uDDE0 Generated UPDATE SQL:", sql);
1519
+ console.log("[SQL EXECUTOR] \uD83D\uDD22 Values:", values);
1438
1520
  return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1439
1521
  var result;
1440
1522
  return __generator(this, function (_a) {
@@ -1462,6 +1544,8 @@ var SqlExecutor = /** @class */ (function (_super) {
1462
1544
  if (!key || !(args === null || args === void 0 ? void 0 : args[key]))
1463
1545
  throw new Error('Primary key and value required for delete');
1464
1546
  sql = "DELETE FROM `".concat(table, "` WHERE `").concat(key, "` = ?");
1547
+ console.log("[SQL EXECUTOR] \uD83E\uDDE0 Generated DELETE SQL:", sql);
1548
+ console.log("[SQL EXECUTOR] \uD83D\uDD22 Value:", args[key]);
1465
1549
  return [4 /*yield*/, this.withConnection(function (conn) { return __awaiter(_this, void 0, void 0, function () {
1466
1550
  var result;
1467
1551
  return __generator(this, function (_a) {
@@ -1478,8 +1562,27 @@ var SqlExecutor = /** @class */ (function (_super) {
1478
1562
  });
1479
1563
  });
1480
1564
  };
1565
+ SqlExecutor.prototype.formatSQLWithParams = function (sql, params) {
1566
+ var index = 0;
1567
+ return sql.replace(/\?/g, function () {
1568
+ if (index >= params.length)
1569
+ return '?'; // fallback if params are missing
1570
+ var val = params[index++];
1571
+ if (val === null || val === undefined)
1572
+ return 'NULL';
1573
+ if (Buffer.isBuffer(val))
1574
+ return "UNHEX('".concat(val.toString('hex'), "')");
1575
+ if (typeof val === 'string')
1576
+ return "'".concat(val.replace(/'/g, "''"), "'");
1577
+ if (typeof val === 'number')
1578
+ return val.toString();
1579
+ if (val instanceof Date)
1580
+ return "'".concat(val.toISOString().slice(0, 19).replace('T', ' '), "'");
1581
+ return "'".concat(JSON.stringify(val), "'");
1582
+ });
1583
+ };
1481
1584
  return SqlExecutor;
1482
- }(Executor));
1585
+ }(SqlBuilder));
1483
1586
 
1484
1587
  var SqlExecutor$1 = /*#__PURE__*/Object.freeze({
1485
1588
  __proto__: null,
@@ -1590,7 +1693,7 @@ function getPrimaryKeyTypes(table) {
1590
1693
  * Conditionally group a log if verbose.
1591
1694
  */
1592
1695
  function group(title, data) {
1593
- if (!isVerbose)
1696
+ if (!isVerbose())
1594
1697
  return;
1595
1698
  console.groupCollapsed("%c".concat(title), "color: #007acc");
1596
1699
  if (data !== undefined)
@@ -1602,7 +1705,7 @@ function info(message) {
1602
1705
  for (var _i = 1; _i < arguments.length; _i++) {
1603
1706
  optional[_i - 1] = arguments[_i];
1604
1707
  }
1605
- if (!isVerbose)
1708
+ if (!isVerbose())
1606
1709
  return;
1607
1710
  console.info.apply(console, __spreadArray(["%cINFO: ".concat(message), "color: #0a0"], optional, false));
1608
1711
  }
@@ -1635,11 +1738,11 @@ function checkAllRequestsComplete() {
1635
1738
  }
1636
1739
 
1637
1740
  function onSuccess(message) {
1638
- toast.success(message, isDevelopment ? toastOptionsDevs : toastOptions);
1741
+ toast.success(message, isLocal() ? toastOptionsDevs : toastOptions);
1639
1742
  }
1640
1743
  function onError(message) {
1641
- toast.error(message, isDevelopment ? toastOptionsDevs : toastOptions);
1744
+ toast.error(message, isLocal() ? toastOptionsDevs : toastOptions);
1642
1745
  }
1643
1746
 
1644
- export { C6Constants, DELETE, Executor, ExpressHandler, GET, HttpExecutor, POST, PUT, SqlExecutor, TestRestfulResponse, apiRequestCache, axiosInstance, buildAggregateField, buildBooleanJoinedConditions, buildSelectQuery, checkAllRequestsComplete, checkCache, clearCache, convertForRequestBody, determineRuntimeJsType, eFetchDependencies, error, getEnvVar, getPrimaryKeyTypes, group, info, isDevelopment as isLocal, isNode, isTest, isVerbose, onError, onSuccess, removeInvalidKeys, removePrefixIfExists, restOrm, restRequest, sortAndSerializeQueryObject, timeout, toastOptions, toastOptionsDevs, userCustomClearCache, warn };
1747
+ export { C6Constants, DELETE, Executor, ExpressHandler, GET, HttpExecutor, POST, PUT, SqlBuilder, SqlExecutor, TestRestfulResponse, apiRequestCache, axiosInstance, checkAllRequestsComplete, checkCache, clearCache, convertForRequestBody, determineRuntimeJsType, eFetchDependencies, error, getEnvVar, getPrimaryKeyTypes, group, info, isLocal, isNode, isTest, isVerbose, onError, onSuccess, removeInvalidKeys, removePrefixIfExists, restOrm, restRequest, sortAndSerializeQueryObject, timeout, toastOptions, toastOptionsDevs, userCustomClearCache, warn };
1645
1748
  //# sourceMappingURL=index.esm.js.map