@base44-preview/cli 0.0.33-pr.278.e2f6489 → 0.0.33-pr.279.c3fe9fe

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/cli/index.js CHANGED
@@ -14757,8 +14757,8 @@ var require_lodash2 = __commonJS((exports, module) => {
14757
14757
  return object2[key];
14758
14758
  });
14759
14759
  }
14760
- function cacheHas(cache2, key) {
14761
- return cache2.has(key);
14760
+ function cacheHas(cache3, key) {
14761
+ return cache3.has(key);
14762
14762
  }
14763
14763
  function charsStartIndex(strSymbols, chrSymbols) {
14764
14764
  var index = -1, length = strSymbols.length;
@@ -15525,8 +15525,8 @@ var require_lodash2 = __commonJS((exports, module) => {
15525
15525
  if (!(seen ? cacheHas(seen, computed) : includes2(result2, computed, comparator))) {
15526
15526
  othIndex = othLength;
15527
15527
  while (--othIndex) {
15528
- var cache2 = caches[othIndex];
15529
- if (!(cache2 ? cacheHas(cache2, computed) : includes2(arrays[othIndex], computed, comparator))) {
15528
+ var cache3 = caches[othIndex];
15529
+ if (!(cache3 ? cacheHas(cache3, computed) : includes2(arrays[othIndex], computed, comparator))) {
15530
15530
  continue outer;
15531
15531
  }
15532
15532
  }
@@ -17098,12 +17098,12 @@ var require_lodash2 = __commonJS((exports, module) => {
17098
17098
  }
17099
17099
  function memoizeCapped(func) {
17100
17100
  var result2 = memoize(func, function(key) {
17101
- if (cache2.size === MAX_MEMOIZE_SIZE) {
17102
- cache2.clear();
17101
+ if (cache3.size === MAX_MEMOIZE_SIZE) {
17102
+ cache3.clear();
17103
17103
  }
17104
17104
  return key;
17105
17105
  });
17106
- var cache2 = result2.cache;
17106
+ var cache3 = result2.cache;
17107
17107
  return result2;
17108
17108
  }
17109
17109
  function mergeData(data, source) {
@@ -18055,12 +18055,12 @@ var require_lodash2 = __commonJS((exports, module) => {
18055
18055
  throw new TypeError2(FUNC_ERROR_TEXT);
18056
18056
  }
18057
18057
  var memoized = function() {
18058
- var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache2 = memoized.cache;
18059
- if (cache2.has(key)) {
18060
- return cache2.get(key);
18058
+ var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache3 = memoized.cache;
18059
+ if (cache3.has(key)) {
18060
+ return cache3.get(key);
18061
18061
  }
18062
18062
  var result2 = func.apply(this, args);
18063
- memoized.cache = cache2.set(key, result2) || cache2;
18063
+ memoized.cache = cache3.set(key, result2) || cache3;
18064
18064
  return result2;
18065
18065
  };
18066
18066
  memoized.cache = new (memoize.Cache || MapCache);
@@ -109913,7 +109913,7 @@ function determineSpecificType(value) {
109913
109913
  return `type ${typeof value} (${inspected})`;
109914
109914
  }
109915
109915
  function read2(jsonPath, { base, specifier }) {
109916
- const existing = cache2.get(jsonPath);
109916
+ const existing = cache3.get(jsonPath);
109917
109917
  if (existing) {
109918
109918
  return existing;
109919
109919
  }
@@ -109962,7 +109962,7 @@ function read2(jsonPath, { base, specifier }) {
109962
109962
  result.type = parsed.type;
109963
109963
  }
109964
109964
  }
109965
- cache2.set(jsonPath, result);
109965
+ cache3.set(jsonPath, result);
109966
109966
  return result;
109967
109967
  }
109968
109968
  function getPackageScopeConfig(resolved) {
@@ -112135,7 +112135,7 @@ async function printAstToDoc(ast, options8) {
112135
112135
  ({
112136
112136
  ast
112137
112137
  } = await prepareToPrint(ast, options8));
112138
- const cache3 = /* @__PURE__ */ new Map;
112138
+ const cache32 = /* @__PURE__ */ new Map;
112139
112139
  const path152 = new ast_path_default(ast);
112140
112140
  const ensurePrintingNode = create_print_pre_check_function_default(options8);
112141
112141
  const embeds = /* @__PURE__ */ new Map;
@@ -112167,12 +112167,12 @@ async function printAstToDoc(ast, options8) {
112167
112167
  return "";
112168
112168
  }
112169
112169
  const shouldCache = is_object_default(value) && args === undefined;
112170
- if (shouldCache && cache3.has(value)) {
112171
- return cache3.get(value);
112170
+ if (shouldCache && cache32.has(value)) {
112171
+ return cache32.get(value);
112172
112172
  }
112173
112173
  const doc3 = callPluginPrintFunction(path152, options8, mainPrint, args, embeds);
112174
112174
  if (shouldCache) {
112175
- cache3.set(value, doc3);
112175
+ cache32.set(value, doc3);
112176
112176
  }
112177
112177
  return doc3;
112178
112178
  }
@@ -113547,7 +113547,7 @@ var require2, __filename2, __dirname4, __create2, __defProp3, __getOwnPropDesc,
113547
113547
  return { line: Number(line3), column: Number(column2) };
113548
113548
  }
113549
113549
  return indexToPosition(string4, Number(index), { oneBased: true });
113550
- }, addCodePointToUnexpectedToken = (message) => message.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/, (_10, _quote, token2) => `"${token2}"(${getCodePoint(token2)})`), TomlError, DATE_TIME_RE, TomlDate, INT_REGEX, FLOAT_REGEX, LEADING_ZERO, ESCAPE_REGEX, ESC_MAP, KEY_PART_RE, read_file_default, loadConfigFromPackageJson, parseYaml, loaders, loaders_default, CONFIG_FILE_NAMES, config_searcher_default, own, classRegExp, kTypes, codes, messages, nodeInternalPrefix = "__node_internal_", userStackTraceLimit, captureLargerStackTrace, hasOwnProperty, ERR_INVALID_PACKAGE_CONFIG, cache2, ERR_UNKNOWN_FILE_EXTENSION, hasOwnProperty2, extensionFormatMap, protocolHandlers, ERR_INVALID_ARG_VALUE, DEFAULT_CONDITIONS, DEFAULT_CONDITIONS_SET, RegExpPrototypeSymbolReplace, ERR_NETWORK_IMPORT_DISALLOWED, ERR_INVALID_MODULE_SPECIFIER, ERR_INVALID_PACKAGE_CONFIG2, ERR_INVALID_PACKAGE_TARGET, ERR_MODULE_NOT_FOUND, ERR_PACKAGE_IMPORT_NOT_DEFINED, ERR_PACKAGE_PATH_NOT_EXPORTED, ERR_UNSUPPORTED_DIR_IMPORT, ERR_UNSUPPORTED_RESOLVE_REQUEST, own2, invalidSegmentRegEx, deprecatedInvalidSegmentRegEx, invalidPackageNameRegEx, patternRegEx, encodedSeparatorRegEx, emittedPackageWarnings, doubleSlashRegEx, import_from_file_default, require_from_file_default, requireErrorCodesShouldBeIgnored, load_external_config_default, load_config_default, loadCache, searchCache, OPTIONAL_OBJECT2 = 1, createMethodShim2 = (methodName, getImplementation) => (flags, object2, ...arguments_) => {
113550
+ }, addCodePointToUnexpectedToken = (message) => message.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/, (_10, _quote, token2) => `"${token2}"(${getCodePoint(token2)})`), TomlError, DATE_TIME_RE, TomlDate, INT_REGEX, FLOAT_REGEX, LEADING_ZERO, ESCAPE_REGEX, ESC_MAP, KEY_PART_RE, read_file_default, loadConfigFromPackageJson, parseYaml, loaders, loaders_default, CONFIG_FILE_NAMES, config_searcher_default, own, classRegExp, kTypes, codes, messages, nodeInternalPrefix = "__node_internal_", userStackTraceLimit, captureLargerStackTrace, hasOwnProperty, ERR_INVALID_PACKAGE_CONFIG, cache3, ERR_UNKNOWN_FILE_EXTENSION, hasOwnProperty2, extensionFormatMap, protocolHandlers, ERR_INVALID_ARG_VALUE, DEFAULT_CONDITIONS, DEFAULT_CONDITIONS_SET, RegExpPrototypeSymbolReplace, ERR_NETWORK_IMPORT_DISALLOWED, ERR_INVALID_MODULE_SPECIFIER, ERR_INVALID_PACKAGE_CONFIG2, ERR_INVALID_PACKAGE_TARGET, ERR_MODULE_NOT_FOUND, ERR_PACKAGE_IMPORT_NOT_DEFINED, ERR_PACKAGE_PATH_NOT_EXPORTED, ERR_UNSUPPORTED_DIR_IMPORT, ERR_UNSUPPORTED_RESOLVE_REQUEST, own2, invalidSegmentRegEx, deprecatedInvalidSegmentRegEx, invalidPackageNameRegEx, patternRegEx, encodedSeparatorRegEx, emittedPackageWarnings, doubleSlashRegEx, import_from_file_default, require_from_file_default, requireErrorCodesShouldBeIgnored, load_external_config_default, load_config_default, loadCache, searchCache, OPTIONAL_OBJECT2 = 1, createMethodShim2 = (methodName, getImplementation) => (flags, object2, ...arguments_) => {
113551
113551
  if (flags | OPTIONAL_OBJECT2 && (object2 === undefined || object2 === null)) {
113552
113552
  return;
113553
113553
  }
@@ -123690,7 +123690,7 @@ ${codeblock}`, options8);
123690
123690
  });
123691
123691
  hasOwnProperty = {}.hasOwnProperty;
123692
123692
  ({ ERR_INVALID_PACKAGE_CONFIG } = codes);
123693
- cache2 = /* @__PURE__ */ new Map;
123693
+ cache3 = /* @__PURE__ */ new Map;
123694
123694
  ({ ERR_UNKNOWN_FILE_EXTENSION } = codes);
123695
123695
  hasOwnProperty2 = {}.hasOwnProperty;
123696
123696
  extensionFormatMap = {
@@ -136448,22 +136448,22 @@ var require_dereference = __commonJS((exports) => {
136448
136448
  const isExternalRef = ref_js_1.default.isExternal$Ref($ref);
136449
136449
  const shouldResolveOnCwd = isExternalRef && options8?.dereference?.externalReferenceResolution === "root";
136450
136450
  const $refPath = url3.resolve(shouldResolveOnCwd ? url3.cwd() : path18, $ref.$ref);
136451
- const cache3 = dereferencedCache.get($refPath);
136452
- if (cache3 && !cache3.circular) {
136451
+ const cache4 = dereferencedCache.get($refPath);
136452
+ if (cache4 && !cache4.circular) {
136453
136453
  const refKeys = Object.keys($ref);
136454
136454
  if (refKeys.length > 1) {
136455
136455
  const extraKeys = {};
136456
136456
  for (const key2 of refKeys) {
136457
- if (key2 !== "$ref" && !(key2 in cache3.value)) {
136457
+ if (key2 !== "$ref" && !(key2 in cache4.value)) {
136458
136458
  extraKeys[key2] = $ref[key2];
136459
136459
  }
136460
136460
  }
136461
136461
  return {
136462
- circular: cache3.circular,
136463
- value: Object.assign({}, cache3.value, extraKeys)
136462
+ circular: cache4.circular,
136463
+ value: Object.assign({}, cache4.value, extraKeys)
136464
136464
  };
136465
136465
  }
136466
- return cache3;
136466
+ return cache4;
136467
136467
  }
136468
136468
  const pointer = $refs._resolve($refPath, path18, options8);
136469
136469
  if (pointer === null) {
@@ -158092,7 +158092,7 @@ var require_application = __commonJS((exports, module) => {
158092
158092
  return this;
158093
158093
  };
158094
158094
  app.render = function render(name2, options8, callback) {
158095
- var cache3 = this.cache;
158095
+ var cache4 = this.cache;
158096
158096
  var done = callback;
158097
158097
  var engines = this.engines;
158098
158098
  var opts = options8;
@@ -158106,7 +158106,7 @@ var require_application = __commonJS((exports, module) => {
158106
158106
  renderOptions.cache = this.enabled("view cache");
158107
158107
  }
158108
158108
  if (renderOptions.cache) {
158109
- view = cache3[name2];
158109
+ view = cache4[name2];
158110
158110
  }
158111
158111
  if (!view) {
158112
158112
  var View2 = this.get("view");
@@ -158122,7 +158122,7 @@ var require_application = __commonJS((exports, module) => {
158122
158122
  return done(err);
158123
158123
  }
158124
158124
  if (renderOptions.cache) {
158125
- cache3[name2] = view;
158125
+ cache4[name2] = view;
158126
158126
  }
158127
158127
  }
158128
158128
  tryRender(view, renderOptions, done);
@@ -162727,6 +162727,2467 @@ var require_dist2 = __commonJS((exports) => {
162727
162727
  __exportStar(require_legacy(), exports);
162728
162728
  });
162729
162729
 
162730
+ // node_modules/@seald-io/nedb/lib/utils.js
162731
+ var require_utils11 = __commonJS((exports, module) => {
162732
+ var uniq = (array3, iteratee) => {
162733
+ if (iteratee)
162734
+ return [...new Map(array3.map((x10) => [iteratee(x10), x10])).values()];
162735
+ else
162736
+ return [...new Set(array3)];
162737
+ };
162738
+ var isObject5 = (arg) => typeof arg === "object" && arg !== null;
162739
+ var isDate = (d5) => isObject5(d5) && Object.prototype.toString.call(d5) === "[object Date]";
162740
+ var isRegExp = (re9) => isObject5(re9) && Object.prototype.toString.call(re9) === "[object RegExp]";
162741
+ var pick2 = (object2, keys) => {
162742
+ return keys.reduce((obj, key2) => {
162743
+ if (object2 && Object.prototype.hasOwnProperty.call(object2, key2)) {
162744
+ obj[key2] = object2[key2];
162745
+ }
162746
+ return obj;
162747
+ }, {});
162748
+ };
162749
+ var filterIndexNames = (indexNames) => ([k9, v10]) => !!(typeof v10 === "string" || typeof v10 === "number" || typeof v10 === "boolean" || isDate(v10) || v10 === null) && indexNames.includes(k9);
162750
+ exports.uniq = uniq;
162751
+ exports.isDate = isDate;
162752
+ exports.isRegExp = isRegExp;
162753
+ exports.pick = pick2;
162754
+ exports.filterIndexNames = filterIndexNames;
162755
+ });
162756
+
162757
+ // node_modules/@seald-io/nedb/lib/model.js
162758
+ var require_model = __commonJS((exports, module) => {
162759
+ var { uniq, isDate, isRegExp } = require_utils11();
162760
+ var checkKey = (k9, v10) => {
162761
+ if (typeof k9 === "number")
162762
+ k9 = k9.toString();
162763
+ if (k9[0] === "$" && !(k9 === "$$date" && typeof v10 === "number") && !(k9 === "$$deleted" && v10 === true) && !(k9 === "$$indexCreated") && !(k9 === "$$indexRemoved"))
162764
+ throw new Error("Field names cannot begin with the $ character");
162765
+ if (k9.indexOf(".") !== -1)
162766
+ throw new Error("Field names cannot contain a .");
162767
+ };
162768
+ var checkObject = (obj) => {
162769
+ if (Array.isArray(obj)) {
162770
+ obj.forEach((o5) => {
162771
+ checkObject(o5);
162772
+ });
162773
+ }
162774
+ if (typeof obj === "object" && obj !== null) {
162775
+ for (const k9 in obj) {
162776
+ if (Object.prototype.hasOwnProperty.call(obj, k9)) {
162777
+ checkKey(k9, obj[k9]);
162778
+ checkObject(obj[k9]);
162779
+ }
162780
+ }
162781
+ }
162782
+ };
162783
+ var serialize2 = (obj) => {
162784
+ return JSON.stringify(obj, function(k9, v10) {
162785
+ checkKey(k9, v10);
162786
+ if (v10 === undefined)
162787
+ return;
162788
+ if (v10 === null)
162789
+ return null;
162790
+ if (typeof this[k9].getTime === "function")
162791
+ return { $$date: this[k9].getTime() };
162792
+ return v10;
162793
+ });
162794
+ };
162795
+ var deserialize = (rawData) => JSON.parse(rawData, function(k9, v10) {
162796
+ if (k9 === "$$date")
162797
+ return new Date(v10);
162798
+ if (typeof v10 === "string" || typeof v10 === "number" || typeof v10 === "boolean" || v10 === null)
162799
+ return v10;
162800
+ if (v10 && v10.$$date)
162801
+ return v10.$$date;
162802
+ return v10;
162803
+ });
162804
+ function deepCopy(obj, strictKeys) {
162805
+ if (typeof obj === "boolean" || typeof obj === "number" || typeof obj === "string" || obj === null || isDate(obj))
162806
+ return obj;
162807
+ if (Array.isArray(obj))
162808
+ return obj.map((o5) => deepCopy(o5, strictKeys));
162809
+ if (typeof obj === "object") {
162810
+ const res = {};
162811
+ for (const k9 in obj) {
162812
+ if (Object.prototype.hasOwnProperty.call(obj, k9) && (!strictKeys || k9[0] !== "$" && k9.indexOf(".") === -1)) {
162813
+ res[k9] = deepCopy(obj[k9], strictKeys);
162814
+ }
162815
+ }
162816
+ return res;
162817
+ }
162818
+ return;
162819
+ }
162820
+ var isPrimitiveType = (obj) => typeof obj === "boolean" || typeof obj === "number" || typeof obj === "string" || obj === null || isDate(obj) || Array.isArray(obj);
162821
+ var compareNSB = (a5, b7) => {
162822
+ if (a5 < b7)
162823
+ return -1;
162824
+ if (a5 > b7)
162825
+ return 1;
162826
+ return 0;
162827
+ };
162828
+ var compareArrays = (a5, b7) => {
162829
+ const minLength = Math.min(a5.length, b7.length);
162830
+ for (let i5 = 0;i5 < minLength; i5 += 1) {
162831
+ const comp = compareThings(a5[i5], b7[i5]);
162832
+ if (comp !== 0)
162833
+ return comp;
162834
+ }
162835
+ return compareNSB(a5.length, b7.length);
162836
+ };
162837
+ var compareThings = (a5, b7, _compareStrings) => {
162838
+ const compareStrings = _compareStrings || compareNSB;
162839
+ if (a5 === undefined)
162840
+ return b7 === undefined ? 0 : -1;
162841
+ if (b7 === undefined)
162842
+ return 1;
162843
+ if (a5 === null)
162844
+ return b7 === null ? 0 : -1;
162845
+ if (b7 === null)
162846
+ return 1;
162847
+ if (typeof a5 === "number")
162848
+ return typeof b7 === "number" ? compareNSB(a5, b7) : -1;
162849
+ if (typeof b7 === "number")
162850
+ return typeof a5 === "number" ? compareNSB(a5, b7) : 1;
162851
+ if (typeof a5 === "string")
162852
+ return typeof b7 === "string" ? compareStrings(a5, b7) : -1;
162853
+ if (typeof b7 === "string")
162854
+ return typeof a5 === "string" ? compareStrings(a5, b7) : 1;
162855
+ if (typeof a5 === "boolean")
162856
+ return typeof b7 === "boolean" ? compareNSB(a5, b7) : -1;
162857
+ if (typeof b7 === "boolean")
162858
+ return typeof a5 === "boolean" ? compareNSB(a5, b7) : 1;
162859
+ if (isDate(a5))
162860
+ return isDate(b7) ? compareNSB(a5.getTime(), b7.getTime()) : -1;
162861
+ if (isDate(b7))
162862
+ return isDate(a5) ? compareNSB(a5.getTime(), b7.getTime()) : 1;
162863
+ if (Array.isArray(a5))
162864
+ return Array.isArray(b7) ? compareArrays(a5, b7) : -1;
162865
+ if (Array.isArray(b7))
162866
+ return Array.isArray(a5) ? compareArrays(a5, b7) : 1;
162867
+ const aKeys = Object.keys(a5).sort();
162868
+ const bKeys = Object.keys(b7).sort();
162869
+ for (let i5 = 0;i5 < Math.min(aKeys.length, bKeys.length); i5 += 1) {
162870
+ const comp = compareThings(a5[aKeys[i5]], b7[bKeys[i5]]);
162871
+ if (comp !== 0)
162872
+ return comp;
162873
+ }
162874
+ return compareNSB(aKeys.length, bKeys.length);
162875
+ };
162876
+ var createModifierFunction = (lastStepModifierFunction, unset = false) => {
162877
+ const func = (obj, field, value) => {
162878
+ const fieldParts = typeof field === "string" ? field.split(".") : field;
162879
+ if (fieldParts.length === 1)
162880
+ lastStepModifierFunction(obj, field, value);
162881
+ else {
162882
+ if (obj[fieldParts[0]] === undefined) {
162883
+ if (unset)
162884
+ return;
162885
+ obj[fieldParts[0]] = {};
162886
+ }
162887
+ func(obj[fieldParts[0]], fieldParts.slice(1), value);
162888
+ }
162889
+ };
162890
+ return func;
162891
+ };
162892
+ var $addToSetPartial = (obj, field, value) => {
162893
+ if (!Object.prototype.hasOwnProperty.call(obj, field)) {
162894
+ obj[field] = [];
162895
+ }
162896
+ if (!Array.isArray(obj[field]))
162897
+ throw new Error("Can't $addToSet an element on non-array values");
162898
+ if (value !== null && typeof value === "object" && value.$each) {
162899
+ if (Object.keys(value).length > 1)
162900
+ throw new Error("Can't use another field in conjunction with $each");
162901
+ if (!Array.isArray(value.$each))
162902
+ throw new Error("$each requires an array value");
162903
+ value.$each.forEach((v10) => {
162904
+ $addToSetPartial(obj, field, v10);
162905
+ });
162906
+ } else {
162907
+ let addToSet = true;
162908
+ obj[field].forEach((v10) => {
162909
+ if (compareThings(v10, value) === 0)
162910
+ addToSet = false;
162911
+ });
162912
+ if (addToSet)
162913
+ obj[field].push(value);
162914
+ }
162915
+ };
162916
+ var modifierFunctions = {
162917
+ $set: createModifierFunction((obj, field, value) => {
162918
+ obj[field] = value;
162919
+ }),
162920
+ $unset: createModifierFunction((obj, field, value) => {
162921
+ delete obj[field];
162922
+ }, true),
162923
+ $min: createModifierFunction((obj, field, value) => {
162924
+ if (typeof obj[field] === "undefined")
162925
+ obj[field] = value;
162926
+ else if (value < obj[field])
162927
+ obj[field] = value;
162928
+ }),
162929
+ $max: createModifierFunction((obj, field, value) => {
162930
+ if (typeof obj[field] === "undefined")
162931
+ obj[field] = value;
162932
+ else if (value > obj[field])
162933
+ obj[field] = value;
162934
+ }),
162935
+ $inc: createModifierFunction((obj, field, value) => {
162936
+ if (typeof value !== "number")
162937
+ throw new Error(`${value} must be a number`);
162938
+ if (typeof obj[field] !== "number") {
162939
+ if (!Object.prototype.hasOwnProperty.call(obj, field))
162940
+ obj[field] = value;
162941
+ else
162942
+ throw new Error("Don't use the $inc modifier on non-number fields");
162943
+ } else
162944
+ obj[field] += value;
162945
+ }),
162946
+ $pull: createModifierFunction((obj, field, value) => {
162947
+ if (!Array.isArray(obj[field]))
162948
+ throw new Error("Can't $pull an element from non-array values");
162949
+ const arr = obj[field];
162950
+ for (let i5 = arr.length - 1;i5 >= 0; i5 -= 1) {
162951
+ if (match(arr[i5], value))
162952
+ arr.splice(i5, 1);
162953
+ }
162954
+ }),
162955
+ $pop: createModifierFunction((obj, field, value) => {
162956
+ if (!Array.isArray(obj[field]))
162957
+ throw new Error("Can't $pop an element from non-array values");
162958
+ if (typeof value !== "number")
162959
+ throw new Error(`${value} isn't an integer, can't use it with $pop`);
162960
+ if (value === 0)
162961
+ return;
162962
+ if (value > 0)
162963
+ obj[field] = obj[field].slice(0, obj[field].length - 1);
162964
+ else
162965
+ obj[field] = obj[field].slice(1);
162966
+ }),
162967
+ $addToSet: createModifierFunction($addToSetPartial),
162968
+ $push: createModifierFunction((obj, field, value) => {
162969
+ if (!Object.prototype.hasOwnProperty.call(obj, field))
162970
+ obj[field] = [];
162971
+ if (!Array.isArray(obj[field]))
162972
+ throw new Error("Can't $push an element on non-array values");
162973
+ if (value !== null && typeof value === "object" && value.$slice && value.$each === undefined)
162974
+ value.$each = [];
162975
+ if (value !== null && typeof value === "object" && value.$each) {
162976
+ if (Object.keys(value).length >= 3 || Object.keys(value).length === 2 && value.$slice === undefined)
162977
+ throw new Error("Can only use $slice in cunjunction with $each when $push to array");
162978
+ if (!Array.isArray(value.$each))
162979
+ throw new Error("$each requires an array value");
162980
+ value.$each.forEach((v10) => {
162981
+ obj[field].push(v10);
162982
+ });
162983
+ if (value.$slice === undefined || typeof value.$slice !== "number")
162984
+ return;
162985
+ if (value.$slice === 0)
162986
+ obj[field] = [];
162987
+ else {
162988
+ let start;
162989
+ let end;
162990
+ const n5 = obj[field].length;
162991
+ if (value.$slice < 0) {
162992
+ start = Math.max(0, n5 + value.$slice);
162993
+ end = n5;
162994
+ } else if (value.$slice > 0) {
162995
+ start = 0;
162996
+ end = Math.min(n5, value.$slice);
162997
+ }
162998
+ obj[field] = obj[field].slice(start, end);
162999
+ }
163000
+ } else {
163001
+ obj[field].push(value);
163002
+ }
163003
+ })
163004
+ };
163005
+ var modify = (obj, updateQuery) => {
163006
+ const keys = Object.keys(updateQuery);
163007
+ const firstChars = keys.map((item) => item[0]);
163008
+ const dollarFirstChars = firstChars.filter((c8) => c8 === "$");
163009
+ let newDoc;
163010
+ let modifiers;
163011
+ if (keys.indexOf("_id") !== -1 && updateQuery._id !== obj._id)
163012
+ throw new Error("You cannot change a document's _id");
163013
+ if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length)
163014
+ throw new Error("You cannot mix modifiers and normal fields");
163015
+ if (dollarFirstChars.length === 0) {
163016
+ newDoc = deepCopy(updateQuery);
163017
+ newDoc._id = obj._id;
163018
+ } else {
163019
+ modifiers = uniq(keys);
163020
+ newDoc = deepCopy(obj);
163021
+ modifiers.forEach((m7) => {
163022
+ if (!modifierFunctions[m7])
163023
+ throw new Error(`Unknown modifier ${m7}`);
163024
+ if (typeof updateQuery[m7] !== "object")
163025
+ throw new Error(`Modifier ${m7}'s argument must be an object`);
163026
+ const keys2 = Object.keys(updateQuery[m7]);
163027
+ keys2.forEach((k9) => {
163028
+ modifierFunctions[m7](newDoc, k9, updateQuery[m7][k9]);
163029
+ });
163030
+ });
163031
+ }
163032
+ checkObject(newDoc);
163033
+ if (obj._id !== newDoc._id)
163034
+ throw new Error("You can't change a document's _id");
163035
+ return newDoc;
163036
+ };
163037
+ var getDotValue = (obj, field) => {
163038
+ const fieldParts = typeof field === "string" ? field.split(".") : field;
163039
+ if (!obj)
163040
+ return;
163041
+ if (fieldParts.length === 0)
163042
+ return obj;
163043
+ if (fieldParts.length === 1)
163044
+ return obj[fieldParts[0]];
163045
+ if (Array.isArray(obj[fieldParts[0]])) {
163046
+ const i5 = parseInt(fieldParts[1], 10);
163047
+ if (typeof i5 === "number" && !isNaN(i5))
163048
+ return getDotValue(obj[fieldParts[0]][i5], fieldParts.slice(2));
163049
+ return obj[fieldParts[0]].map((el5) => getDotValue(el5, fieldParts.slice(1)));
163050
+ } else
163051
+ return getDotValue(obj[fieldParts[0]], fieldParts.slice(1));
163052
+ };
163053
+ var getDotValues = (obj, fields) => {
163054
+ if (!Array.isArray(fields))
163055
+ throw new Error("fields must be an Array");
163056
+ if (fields.length > 1) {
163057
+ const key2 = {};
163058
+ for (const field of fields) {
163059
+ key2[field] = getDotValue(obj, field);
163060
+ }
163061
+ return key2;
163062
+ } else
163063
+ return getDotValue(obj, fields[0]);
163064
+ };
163065
+ var areThingsEqual = (a5, b7) => {
163066
+ if (a5 === null || typeof a5 === "string" || typeof a5 === "boolean" || typeof a5 === "number" || b7 === null || typeof b7 === "string" || typeof b7 === "boolean" || typeof b7 === "number")
163067
+ return a5 === b7;
163068
+ if (isDate(a5) || isDate(b7))
163069
+ return isDate(a5) && isDate(b7) && a5.getTime() === b7.getTime();
163070
+ if (!(Array.isArray(a5) && Array.isArray(b7)) && (Array.isArray(a5) || Array.isArray(b7)) || a5 === undefined || b7 === undefined)
163071
+ return false;
163072
+ let aKeys;
163073
+ let bKeys;
163074
+ try {
163075
+ aKeys = Object.keys(a5);
163076
+ bKeys = Object.keys(b7);
163077
+ } catch (e8) {
163078
+ return false;
163079
+ }
163080
+ if (aKeys.length !== bKeys.length)
163081
+ return false;
163082
+ for (const el5 of aKeys) {
163083
+ if (bKeys.indexOf(el5) === -1)
163084
+ return false;
163085
+ if (!areThingsEqual(a5[el5], b7[el5]))
163086
+ return false;
163087
+ }
163088
+ return true;
163089
+ };
163090
+ var areComparable = (a5, b7) => {
163091
+ if (typeof a5 !== "string" && typeof a5 !== "number" && !isDate(a5) && typeof b7 !== "string" && typeof b7 !== "number" && !isDate(b7))
163092
+ return false;
163093
+ if (typeof a5 !== typeof b7)
163094
+ return false;
163095
+ return true;
163096
+ };
163097
+ var comparisonFunctions = {
163098
+ $lt: (a5, b7) => areComparable(a5, b7) && a5 < b7,
163099
+ $lte: (a5, b7) => areComparable(a5, b7) && a5 <= b7,
163100
+ $gt: (a5, b7) => areComparable(a5, b7) && a5 > b7,
163101
+ $gte: (a5, b7) => areComparable(a5, b7) && a5 >= b7,
163102
+ $ne: (a5, b7) => a5 === undefined || !areThingsEqual(a5, b7),
163103
+ $in: (a5, b7) => {
163104
+ if (!Array.isArray(b7))
163105
+ throw new Error("$in operator called with a non-array");
163106
+ for (const el5 of b7) {
163107
+ if (areThingsEqual(a5, el5))
163108
+ return true;
163109
+ }
163110
+ return false;
163111
+ },
163112
+ $nin: (a5, b7) => {
163113
+ if (!Array.isArray(b7))
163114
+ throw new Error("$nin operator called with a non-array");
163115
+ return !comparisonFunctions.$in(a5, b7);
163116
+ },
163117
+ $regex: (a5, b7) => {
163118
+ if (!isRegExp(b7))
163119
+ throw new Error("$regex operator called with non regular expression");
163120
+ if (typeof a5 !== "string")
163121
+ return false;
163122
+ else
163123
+ return b7.test(a5);
163124
+ },
163125
+ $exists: (a5, b7) => {
163126
+ if (b7 || b7 === "")
163127
+ b7 = true;
163128
+ else
163129
+ b7 = false;
163130
+ if (a5 === undefined)
163131
+ return !b7;
163132
+ else
163133
+ return b7;
163134
+ },
163135
+ $size: (a5, b7) => {
163136
+ if (!Array.isArray(a5))
163137
+ return false;
163138
+ if (b7 % 1 !== 0)
163139
+ throw new Error("$size operator called without an integer");
163140
+ return a5.length === b7;
163141
+ },
163142
+ $elemMatch: (a5, b7) => {
163143
+ if (!Array.isArray(a5))
163144
+ return false;
163145
+ return a5.some((el5) => match(el5, b7));
163146
+ }
163147
+ };
163148
+ var arrayComparisonFunctions = { $size: true, $elemMatch: true };
163149
+ var logicalOperators = {
163150
+ $or: (obj, query) => {
163151
+ if (!Array.isArray(query))
163152
+ throw new Error("$or operator used without an array");
163153
+ for (let i5 = 0;i5 < query.length; i5 += 1) {
163154
+ if (match(obj, query[i5]))
163155
+ return true;
163156
+ }
163157
+ return false;
163158
+ },
163159
+ $and: (obj, query) => {
163160
+ if (!Array.isArray(query))
163161
+ throw new Error("$and operator used without an array");
163162
+ for (let i5 = 0;i5 < query.length; i5 += 1) {
163163
+ if (!match(obj, query[i5]))
163164
+ return false;
163165
+ }
163166
+ return true;
163167
+ },
163168
+ $not: (obj, query) => !match(obj, query),
163169
+ $where: (obj, fn9) => {
163170
+ if (typeof fn9 !== "function")
163171
+ throw new Error("$where operator used without a function");
163172
+ const result = fn9.call(obj);
163173
+ if (typeof result !== "boolean")
163174
+ throw new Error("$where function must return boolean");
163175
+ return result;
163176
+ }
163177
+ };
163178
+ var match = (obj, query) => {
163179
+ if (isPrimitiveType(obj) || isPrimitiveType(query))
163180
+ return matchQueryPart({ needAKey: obj }, "needAKey", query);
163181
+ for (const queryKey in query) {
163182
+ if (Object.prototype.hasOwnProperty.call(query, queryKey)) {
163183
+ const queryValue = query[queryKey];
163184
+ if (queryKey[0] === "$") {
163185
+ if (!logicalOperators[queryKey])
163186
+ throw new Error(`Unknown logical operator ${queryKey}`);
163187
+ if (!logicalOperators[queryKey](obj, queryValue))
163188
+ return false;
163189
+ } else if (!matchQueryPart(obj, queryKey, queryValue))
163190
+ return false;
163191
+ }
163192
+ }
163193
+ return true;
163194
+ };
163195
+ function matchQueryPart(obj, queryKey, queryValue, treatObjAsValue) {
163196
+ const objValue = getDotValue(obj, queryKey);
163197
+ if (Array.isArray(objValue) && !treatObjAsValue) {
163198
+ if (Array.isArray(queryValue))
163199
+ return matchQueryPart(obj, queryKey, queryValue, true);
163200
+ if (queryValue !== null && typeof queryValue === "object" && !isRegExp(queryValue)) {
163201
+ for (const key2 in queryValue) {
163202
+ if (Object.prototype.hasOwnProperty.call(queryValue, key2) && arrayComparisonFunctions[key2]) {
163203
+ return matchQueryPart(obj, queryKey, queryValue, true);
163204
+ }
163205
+ }
163206
+ }
163207
+ for (const el5 of objValue) {
163208
+ if (matchQueryPart({ k: el5 }, "k", queryValue))
163209
+ return true;
163210
+ }
163211
+ return false;
163212
+ }
163213
+ if (queryValue !== null && typeof queryValue === "object" && !isRegExp(queryValue) && !Array.isArray(queryValue)) {
163214
+ const keys = Object.keys(queryValue);
163215
+ const firstChars = keys.map((item) => item[0]);
163216
+ const dollarFirstChars = firstChars.filter((c8) => c8 === "$");
163217
+ if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length)
163218
+ throw new Error("You cannot mix operators and normal fields");
163219
+ if (dollarFirstChars.length > 0) {
163220
+ for (const key2 of keys) {
163221
+ if (!comparisonFunctions[key2])
163222
+ throw new Error(`Unknown comparison function ${key2}`);
163223
+ if (!comparisonFunctions[key2](objValue, queryValue[key2]))
163224
+ return false;
163225
+ }
163226
+ return true;
163227
+ }
163228
+ }
163229
+ if (isRegExp(queryValue))
163230
+ return comparisonFunctions.$regex(objValue, queryValue);
163231
+ return areThingsEqual(objValue, queryValue);
163232
+ }
163233
+ exports.serialize = serialize2;
163234
+ exports.deserialize = deserialize;
163235
+ exports.deepCopy = deepCopy;
163236
+ exports.checkObject = checkObject;
163237
+ exports.isPrimitiveType = isPrimitiveType;
163238
+ exports.modify = modify;
163239
+ exports.getDotValue = getDotValue;
163240
+ exports.getDotValues = getDotValues;
163241
+ exports.match = match;
163242
+ exports.areThingsEqual = areThingsEqual;
163243
+ exports.compareThings = compareThings;
163244
+ });
163245
+
163246
+ // node_modules/@seald-io/nedb/lib/cursor.js
163247
+ var require_cursor = __commonJS((exports, module) => {
163248
+ var model = require_model();
163249
+ var { callbackify: callbackify5 } = __require("util");
163250
+
163251
+ class Cursor {
163252
+ constructor(db2, query, mapFn) {
163253
+ this.db = db2;
163254
+ this.query = query || {};
163255
+ if (mapFn)
163256
+ this.mapFn = mapFn;
163257
+ this._limit = undefined;
163258
+ this._skip = undefined;
163259
+ this._sort = undefined;
163260
+ this._projection = undefined;
163261
+ }
163262
+ limit(limit) {
163263
+ this._limit = limit;
163264
+ return this;
163265
+ }
163266
+ skip(skip2) {
163267
+ this._skip = skip2;
163268
+ return this;
163269
+ }
163270
+ sort(sortQuery) {
163271
+ this._sort = sortQuery;
163272
+ return this;
163273
+ }
163274
+ projection(projection) {
163275
+ this._projection = projection;
163276
+ return this;
163277
+ }
163278
+ _project(candidates) {
163279
+ const res = [];
163280
+ let action;
163281
+ if (this._projection === undefined || Object.keys(this._projection).length === 0) {
163282
+ return candidates;
163283
+ }
163284
+ const keepId = this._projection._id !== 0;
163285
+ const { _id, ...rest } = this._projection;
163286
+ this._projection = rest;
163287
+ const keys = Object.keys(this._projection);
163288
+ keys.forEach((k9) => {
163289
+ if (action !== undefined && this._projection[k9] !== action)
163290
+ throw new Error("Can't both keep and omit fields except for _id");
163291
+ action = this._projection[k9];
163292
+ });
163293
+ candidates.forEach((candidate) => {
163294
+ let toPush;
163295
+ if (action === 1) {
163296
+ toPush = { $set: {} };
163297
+ keys.forEach((k9) => {
163298
+ toPush.$set[k9] = model.getDotValue(candidate, k9);
163299
+ if (toPush.$set[k9] === undefined)
163300
+ delete toPush.$set[k9];
163301
+ });
163302
+ toPush = model.modify({}, toPush);
163303
+ } else {
163304
+ toPush = { $unset: {} };
163305
+ keys.forEach((k9) => {
163306
+ toPush.$unset[k9] = true;
163307
+ });
163308
+ toPush = model.modify(candidate, toPush);
163309
+ }
163310
+ if (keepId)
163311
+ toPush._id = candidate._id;
163312
+ else
163313
+ delete toPush._id;
163314
+ res.push(toPush);
163315
+ });
163316
+ return res;
163317
+ }
163318
+ async _execAsync() {
163319
+ let res = [];
163320
+ let added = 0;
163321
+ let skipped = 0;
163322
+ const candidates = await this.db._getCandidatesAsync(this.query);
163323
+ for (const candidate of candidates) {
163324
+ if (model.match(candidate, this.query)) {
163325
+ if (!this._sort) {
163326
+ if (this._skip && this._skip > skipped)
163327
+ skipped += 1;
163328
+ else {
163329
+ res.push(candidate);
163330
+ added += 1;
163331
+ if (this._limit && this._limit <= added)
163332
+ break;
163333
+ }
163334
+ } else
163335
+ res.push(candidate);
163336
+ }
163337
+ }
163338
+ if (this._sort) {
163339
+ const criteria = Object.entries(this._sort).map(([key2, direction]) => ({ key: key2, direction }));
163340
+ res.sort((a5, b7) => {
163341
+ for (const criterion of criteria) {
163342
+ const compare = criterion.direction * model.compareThings(model.getDotValue(a5, criterion.key), model.getDotValue(b7, criterion.key), this.db.compareStrings);
163343
+ if (compare !== 0)
163344
+ return compare;
163345
+ }
163346
+ return 0;
163347
+ });
163348
+ const limit = this._limit || res.length;
163349
+ const skip2 = this._skip || 0;
163350
+ res = res.slice(skip2, skip2 + limit);
163351
+ }
163352
+ res = this._project(res);
163353
+ if (this.mapFn)
163354
+ return this.mapFn(res);
163355
+ return res;
163356
+ }
163357
+ exec(_callback) {
163358
+ callbackify5(() => this.execAsync())(_callback);
163359
+ }
163360
+ execAsync() {
163361
+ return this.db.executor.pushAsync(() => this._execAsync());
163362
+ }
163363
+ then(onFulfilled, onRejected) {
163364
+ return this.execAsync().then(onFulfilled, onRejected);
163365
+ }
163366
+ catch(onRejected) {
163367
+ return this.execAsync().catch(onRejected);
163368
+ }
163369
+ finally(onFinally) {
163370
+ return this.execAsync().finally(onFinally);
163371
+ }
163372
+ }
163373
+ module.exports = Cursor;
163374
+ });
163375
+
163376
+ // node_modules/@seald-io/nedb/lib/customUtils.js
163377
+ var require_customUtils = __commonJS((exports, module) => {
163378
+ var crypto = __require("crypto");
163379
+ var uid = (len) => crypto.randomBytes(Math.ceil(Math.max(8, len * 2))).toString("base64").replace(/[+/]/g, "").slice(0, len);
163380
+ exports.uid = uid;
163381
+ });
163382
+
163383
+ // node_modules/@seald-io/nedb/lib/waterfall.js
163384
+ var require_waterfall = __commonJS((exports, module) => {
163385
+ class Waterfall {
163386
+ constructor() {
163387
+ this.guardian = Promise.resolve();
163388
+ }
163389
+ waterfall(func) {
163390
+ return (...args) => {
163391
+ this.guardian = this.guardian.then(() => {
163392
+ return func(...args).then((result) => ({ error: false, result }), (result) => ({ error: true, result }));
163393
+ });
163394
+ return this.guardian.then(({ error: error48, result }) => {
163395
+ if (error48)
163396
+ return Promise.reject(result);
163397
+ else
163398
+ return Promise.resolve(result);
163399
+ });
163400
+ };
163401
+ }
163402
+ chain(promise2) {
163403
+ return this.waterfall(() => promise2)();
163404
+ }
163405
+ }
163406
+ module.exports = Waterfall;
163407
+ });
163408
+
163409
+ // node_modules/@seald-io/nedb/lib/executor.js
163410
+ var require_executor = __commonJS((exports, module) => {
163411
+ var Waterfall = require_waterfall();
163412
+
163413
+ class Executor {
163414
+ constructor() {
163415
+ this.ready = false;
163416
+ this.queue = new Waterfall;
163417
+ this.buffer = null;
163418
+ this._triggerBuffer = null;
163419
+ this.resetBuffer();
163420
+ }
163421
+ pushAsync(task, forceQueuing = false) {
163422
+ if (this.ready || forceQueuing)
163423
+ return this.queue.waterfall(task)();
163424
+ else
163425
+ return this.buffer.waterfall(task)();
163426
+ }
163427
+ processBuffer() {
163428
+ this.ready = true;
163429
+ this._triggerBuffer();
163430
+ this.queue.waterfall(() => this.buffer.guardian);
163431
+ }
163432
+ resetBuffer() {
163433
+ this.buffer = new Waterfall;
163434
+ this.buffer.chain(new Promise((resolve5) => {
163435
+ this._triggerBuffer = resolve5;
163436
+ }));
163437
+ if (this.ready)
163438
+ this._triggerBuffer();
163439
+ }
163440
+ }
163441
+ module.exports = Executor;
163442
+ });
163443
+
163444
+ // node_modules/@seald-io/binary-search-tree/lib/customUtils.js
163445
+ var require_customUtils2 = __commonJS((exports, module) => {
163446
+ var getRandomArray = (n5) => {
163447
+ if (n5 === 0)
163448
+ return [];
163449
+ if (n5 === 1)
163450
+ return [0];
163451
+ const res = getRandomArray(n5 - 1);
163452
+ const next = Math.floor(Math.random() * n5);
163453
+ res.splice(next, 0, n5 - 1);
163454
+ return res;
163455
+ };
163456
+ exports.getRandomArray = getRandomArray;
163457
+ var defaultCompareKeysFunction = (a5, b7) => {
163458
+ if (a5 < b7)
163459
+ return -1;
163460
+ if (a5 > b7)
163461
+ return 1;
163462
+ if (a5 === b7)
163463
+ return 0;
163464
+ const err = new Error("Couldn't compare elements");
163465
+ err.a = a5;
163466
+ err.b = b7;
163467
+ throw err;
163468
+ };
163469
+ exports.defaultCompareKeysFunction = defaultCompareKeysFunction;
163470
+ var defaultCheckValueEquality = (a5, b7) => a5 === b7;
163471
+ exports.defaultCheckValueEquality = defaultCheckValueEquality;
163472
+ });
163473
+
163474
+ // node_modules/@seald-io/binary-search-tree/lib/bst.js
163475
+ var require_bst = __commonJS((exports, module) => {
163476
+ var customUtils = require_customUtils2();
163477
+
163478
+ class BinarySearchTree {
163479
+ constructor(options8) {
163480
+ options8 = options8 || {};
163481
+ this.left = null;
163482
+ this.right = null;
163483
+ this.parent = options8.parent !== undefined ? options8.parent : null;
163484
+ if (Object.prototype.hasOwnProperty.call(options8, "key")) {
163485
+ this.key = options8.key;
163486
+ }
163487
+ this.data = Object.prototype.hasOwnProperty.call(options8, "value") ? [options8.value] : [];
163488
+ this.unique = options8.unique || false;
163489
+ this.compareKeys = options8.compareKeys || customUtils.defaultCompareKeysFunction;
163490
+ this.checkValueEquality = options8.checkValueEquality || customUtils.defaultCheckValueEquality;
163491
+ }
163492
+ getMaxKeyDescendant() {
163493
+ if (this.right)
163494
+ return this.right.getMaxKeyDescendant();
163495
+ else
163496
+ return this;
163497
+ }
163498
+ getMaxKey() {
163499
+ return this.getMaxKeyDescendant().key;
163500
+ }
163501
+ getMinKeyDescendant() {
163502
+ if (this.left)
163503
+ return this.left.getMinKeyDescendant();
163504
+ else
163505
+ return this;
163506
+ }
163507
+ getMinKey() {
163508
+ return this.getMinKeyDescendant().key;
163509
+ }
163510
+ checkAllNodesFullfillCondition(test) {
163511
+ if (!Object.prototype.hasOwnProperty.call(this, "key"))
163512
+ return;
163513
+ test(this.key, this.data);
163514
+ if (this.left)
163515
+ this.left.checkAllNodesFullfillCondition(test);
163516
+ if (this.right)
163517
+ this.right.checkAllNodesFullfillCondition(test);
163518
+ }
163519
+ checkNodeOrdering() {
163520
+ if (!Object.prototype.hasOwnProperty.call(this, "key"))
163521
+ return;
163522
+ if (this.left) {
163523
+ this.left.checkAllNodesFullfillCondition((k9) => {
163524
+ if (this.compareKeys(k9, this.key) >= 0)
163525
+ throw new Error(`Tree with root ${this.key} is not a binary search tree`);
163526
+ });
163527
+ this.left.checkNodeOrdering();
163528
+ }
163529
+ if (this.right) {
163530
+ this.right.checkAllNodesFullfillCondition((k9) => {
163531
+ if (this.compareKeys(k9, this.key) <= 0)
163532
+ throw new Error(`Tree with root ${this.key} is not a binary search tree`);
163533
+ });
163534
+ this.right.checkNodeOrdering();
163535
+ }
163536
+ }
163537
+ checkInternalPointers() {
163538
+ if (this.left) {
163539
+ if (this.left.parent !== this)
163540
+ throw new Error(`Parent pointer broken for key ${this.key}`);
163541
+ this.left.checkInternalPointers();
163542
+ }
163543
+ if (this.right) {
163544
+ if (this.right.parent !== this)
163545
+ throw new Error(`Parent pointer broken for key ${this.key}`);
163546
+ this.right.checkInternalPointers();
163547
+ }
163548
+ }
163549
+ checkIsBST() {
163550
+ this.checkNodeOrdering();
163551
+ this.checkInternalPointers();
163552
+ if (this.parent)
163553
+ throw new Error("The root shouldn't have a parent");
163554
+ }
163555
+ getNumberOfKeys() {
163556
+ let res;
163557
+ if (!Object.prototype.hasOwnProperty.call(this, "key"))
163558
+ return 0;
163559
+ res = 1;
163560
+ if (this.left)
163561
+ res += this.left.getNumberOfKeys();
163562
+ if (this.right)
163563
+ res += this.right.getNumberOfKeys();
163564
+ return res;
163565
+ }
163566
+ createSimilar(options8) {
163567
+ options8 = options8 || {};
163568
+ options8.unique = this.unique;
163569
+ options8.compareKeys = this.compareKeys;
163570
+ options8.checkValueEquality = this.checkValueEquality;
163571
+ return new this.constructor(options8);
163572
+ }
163573
+ createLeftChild(options8) {
163574
+ const leftChild = this.createSimilar(options8);
163575
+ leftChild.parent = this;
163576
+ this.left = leftChild;
163577
+ return leftChild;
163578
+ }
163579
+ createRightChild(options8) {
163580
+ const rightChild = this.createSimilar(options8);
163581
+ rightChild.parent = this;
163582
+ this.right = rightChild;
163583
+ return rightChild;
163584
+ }
163585
+ insert(key2, value) {
163586
+ if (!Object.prototype.hasOwnProperty.call(this, "key")) {
163587
+ this.key = key2;
163588
+ this.data.push(value);
163589
+ return;
163590
+ }
163591
+ if (this.compareKeys(this.key, key2) === 0) {
163592
+ if (this.unique) {
163593
+ const err = new Error(`Can't insert key ${JSON.stringify(key2)}, it violates the unique constraint`);
163594
+ err.key = key2;
163595
+ err.errorType = "uniqueViolated";
163596
+ throw err;
163597
+ } else
163598
+ this.data.push(value);
163599
+ return;
163600
+ }
163601
+ if (this.compareKeys(key2, this.key) < 0) {
163602
+ if (this.left)
163603
+ this.left.insert(key2, value);
163604
+ else
163605
+ this.createLeftChild({ key: key2, value });
163606
+ } else {
163607
+ if (this.right)
163608
+ this.right.insert(key2, value);
163609
+ else
163610
+ this.createRightChild({ key: key2, value });
163611
+ }
163612
+ }
163613
+ search(key2) {
163614
+ if (!Object.prototype.hasOwnProperty.call(this, "key"))
163615
+ return [];
163616
+ if (this.compareKeys(this.key, key2) === 0)
163617
+ return this.data;
163618
+ if (this.compareKeys(key2, this.key) < 0) {
163619
+ if (this.left)
163620
+ return this.left.search(key2);
163621
+ else
163622
+ return [];
163623
+ } else {
163624
+ if (this.right)
163625
+ return this.right.search(key2);
163626
+ else
163627
+ return [];
163628
+ }
163629
+ }
163630
+ getLowerBoundMatcher(query) {
163631
+ if (!Object.prototype.hasOwnProperty.call(query, "$gt") && !Object.prototype.hasOwnProperty.call(query, "$gte"))
163632
+ return () => true;
163633
+ if (Object.prototype.hasOwnProperty.call(query, "$gt") && Object.prototype.hasOwnProperty.call(query, "$gte")) {
163634
+ if (this.compareKeys(query.$gte, query.$gt) === 0)
163635
+ return (key2) => this.compareKeys(key2, query.$gt) > 0;
163636
+ if (this.compareKeys(query.$gte, query.$gt) > 0)
163637
+ return (key2) => this.compareKeys(key2, query.$gte) >= 0;
163638
+ else
163639
+ return (key2) => this.compareKeys(key2, query.$gt) > 0;
163640
+ }
163641
+ if (Object.prototype.hasOwnProperty.call(query, "$gt"))
163642
+ return (key2) => this.compareKeys(key2, query.$gt) > 0;
163643
+ else
163644
+ return (key2) => this.compareKeys(key2, query.$gte) >= 0;
163645
+ }
163646
+ getUpperBoundMatcher(query) {
163647
+ if (!Object.prototype.hasOwnProperty.call(query, "$lt") && !Object.prototype.hasOwnProperty.call(query, "$lte"))
163648
+ return () => true;
163649
+ if (Object.prototype.hasOwnProperty.call(query, "$lt") && Object.prototype.hasOwnProperty.call(query, "$lte")) {
163650
+ if (this.compareKeys(query.$lte, query.$lt) === 0)
163651
+ return (key2) => this.compareKeys(key2, query.$lt) < 0;
163652
+ if (this.compareKeys(query.$lte, query.$lt) < 0)
163653
+ return (key2) => this.compareKeys(key2, query.$lte) <= 0;
163654
+ else
163655
+ return (key2) => this.compareKeys(key2, query.$lt) < 0;
163656
+ }
163657
+ if (Object.prototype.hasOwnProperty.call(query, "$lt"))
163658
+ return (key2) => this.compareKeys(key2, query.$lt) < 0;
163659
+ else
163660
+ return (key2) => this.compareKeys(key2, query.$lte) <= 0;
163661
+ }
163662
+ betweenBounds(query, lbm, ubm) {
163663
+ const res = [];
163664
+ if (!Object.prototype.hasOwnProperty.call(this, "key"))
163665
+ return [];
163666
+ lbm = lbm || this.getLowerBoundMatcher(query);
163667
+ ubm = ubm || this.getUpperBoundMatcher(query);
163668
+ if (lbm(this.key) && this.left)
163669
+ append(res, this.left.betweenBounds(query, lbm, ubm));
163670
+ if (lbm(this.key) && ubm(this.key))
163671
+ append(res, this.data);
163672
+ if (ubm(this.key) && this.right)
163673
+ append(res, this.right.betweenBounds(query, lbm, ubm));
163674
+ return res;
163675
+ }
163676
+ deleteIfLeaf() {
163677
+ if (this.left || this.right)
163678
+ return false;
163679
+ if (!this.parent) {
163680
+ delete this.key;
163681
+ this.data = [];
163682
+ return true;
163683
+ }
163684
+ if (this.parent.left === this)
163685
+ this.parent.left = null;
163686
+ else
163687
+ this.parent.right = null;
163688
+ return true;
163689
+ }
163690
+ deleteIfOnlyOneChild() {
163691
+ let child;
163692
+ if (this.left && !this.right)
163693
+ child = this.left;
163694
+ if (!this.left && this.right)
163695
+ child = this.right;
163696
+ if (!child)
163697
+ return false;
163698
+ if (!this.parent) {
163699
+ this.key = child.key;
163700
+ this.data = child.data;
163701
+ this.left = null;
163702
+ if (child.left) {
163703
+ this.left = child.left;
163704
+ child.left.parent = this;
163705
+ }
163706
+ this.right = null;
163707
+ if (child.right) {
163708
+ this.right = child.right;
163709
+ child.right.parent = this;
163710
+ }
163711
+ return true;
163712
+ }
163713
+ if (this.parent.left === this) {
163714
+ this.parent.left = child;
163715
+ child.parent = this.parent;
163716
+ } else {
163717
+ this.parent.right = child;
163718
+ child.parent = this.parent;
163719
+ }
163720
+ return true;
163721
+ }
163722
+ delete(key2, value) {
163723
+ const newData = [];
163724
+ let replaceWith;
163725
+ if (!Object.prototype.hasOwnProperty.call(this, "key"))
163726
+ return;
163727
+ if (this.compareKeys(key2, this.key) < 0) {
163728
+ if (this.left)
163729
+ this.left.delete(key2, value);
163730
+ return;
163731
+ }
163732
+ if (this.compareKeys(key2, this.key) > 0) {
163733
+ if (this.right)
163734
+ this.right.delete(key2, value);
163735
+ return;
163736
+ }
163737
+ if (!this.compareKeys(key2, this.key) === 0)
163738
+ return;
163739
+ if (this.data.length > 1 && value !== undefined) {
163740
+ this.data.forEach((d5) => {
163741
+ if (!this.checkValueEquality(d5, value))
163742
+ newData.push(d5);
163743
+ });
163744
+ this.data = newData;
163745
+ return;
163746
+ }
163747
+ if (this.deleteIfLeaf())
163748
+ return;
163749
+ if (this.deleteIfOnlyOneChild())
163750
+ return;
163751
+ if (Math.random() >= 0.5) {
163752
+ replaceWith = this.left.getMaxKeyDescendant();
163753
+ this.key = replaceWith.key;
163754
+ this.data = replaceWith.data;
163755
+ if (this === replaceWith.parent) {
163756
+ this.left = replaceWith.left;
163757
+ if (replaceWith.left)
163758
+ replaceWith.left.parent = replaceWith.parent;
163759
+ } else {
163760
+ replaceWith.parent.right = replaceWith.left;
163761
+ if (replaceWith.left)
163762
+ replaceWith.left.parent = replaceWith.parent;
163763
+ }
163764
+ } else {
163765
+ replaceWith = this.right.getMinKeyDescendant();
163766
+ this.key = replaceWith.key;
163767
+ this.data = replaceWith.data;
163768
+ if (this === replaceWith.parent) {
163769
+ this.right = replaceWith.right;
163770
+ if (replaceWith.right)
163771
+ replaceWith.right.parent = replaceWith.parent;
163772
+ } else {
163773
+ replaceWith.parent.left = replaceWith.right;
163774
+ if (replaceWith.right)
163775
+ replaceWith.right.parent = replaceWith.parent;
163776
+ }
163777
+ }
163778
+ }
163779
+ executeOnEveryNode(fn9) {
163780
+ if (this.left)
163781
+ this.left.executeOnEveryNode(fn9);
163782
+ fn9(this);
163783
+ if (this.right)
163784
+ this.right.executeOnEveryNode(fn9);
163785
+ }
163786
+ prettyPrint(printData, spacing) {
163787
+ spacing = spacing || "";
163788
+ console.log(`${spacing}* ${this.key}`);
163789
+ if (printData)
163790
+ console.log(`${spacing}* ${this.data}`);
163791
+ if (!this.left && !this.right)
163792
+ return;
163793
+ if (this.left)
163794
+ this.left.prettyPrint(printData, `${spacing} `);
163795
+ else
163796
+ console.log(`${spacing} *`);
163797
+ if (this.right)
163798
+ this.right.prettyPrint(printData, `${spacing} `);
163799
+ else
163800
+ console.log(`${spacing} *`);
163801
+ }
163802
+ }
163803
+ function append(array3, toAppend) {
163804
+ for (let i5 = 0;i5 < toAppend.length; i5 += 1) {
163805
+ array3.push(toAppend[i5]);
163806
+ }
163807
+ }
163808
+ module.exports = BinarySearchTree;
163809
+ });
163810
+
163811
+ // node_modules/@seald-io/binary-search-tree/lib/avltree.js
163812
+ var require_avltree = __commonJS((exports, module) => {
163813
+ var BinarySearchTree = require_bst();
163814
+ var customUtils = require_customUtils2();
163815
+
163816
+ class AVLTree {
163817
+ constructor(options8) {
163818
+ this.tree = new _AVLTree(options8);
163819
+ }
163820
+ checkIsAVLT() {
163821
+ this.tree.checkIsAVLT();
163822
+ }
163823
+ insert(key2, value) {
163824
+ const newTree = this.tree.insert(key2, value);
163825
+ if (newTree) {
163826
+ this.tree = newTree;
163827
+ }
163828
+ }
163829
+ delete(key2, value) {
163830
+ const newTree = this.tree.delete(key2, value);
163831
+ if (newTree) {
163832
+ this.tree = newTree;
163833
+ }
163834
+ }
163835
+ }
163836
+
163837
+ class _AVLTree extends BinarySearchTree {
163838
+ constructor(options8) {
163839
+ super();
163840
+ options8 = options8 || {};
163841
+ this.left = null;
163842
+ this.right = null;
163843
+ this.parent = options8.parent !== undefined ? options8.parent : null;
163844
+ if (Object.prototype.hasOwnProperty.call(options8, "key"))
163845
+ this.key = options8.key;
163846
+ this.data = Object.prototype.hasOwnProperty.call(options8, "value") ? [options8.value] : [];
163847
+ this.unique = options8.unique || false;
163848
+ this.compareKeys = options8.compareKeys || customUtils.defaultCompareKeysFunction;
163849
+ this.checkValueEquality = options8.checkValueEquality || customUtils.defaultCheckValueEquality;
163850
+ }
163851
+ checkHeightCorrect() {
163852
+ if (!Object.prototype.hasOwnProperty.call(this, "key")) {
163853
+ return;
163854
+ }
163855
+ if (this.left && this.left.height === undefined) {
163856
+ throw new Error("Undefined height for node " + this.left.key);
163857
+ }
163858
+ if (this.right && this.right.height === undefined) {
163859
+ throw new Error("Undefined height for node " + this.right.key);
163860
+ }
163861
+ if (this.height === undefined) {
163862
+ throw new Error("Undefined height for node " + this.key);
163863
+ }
163864
+ const leftH = this.left ? this.left.height : 0;
163865
+ const rightH = this.right ? this.right.height : 0;
163866
+ if (this.height !== 1 + Math.max(leftH, rightH)) {
163867
+ throw new Error("Height constraint failed for node " + this.key);
163868
+ }
163869
+ if (this.left) {
163870
+ this.left.checkHeightCorrect();
163871
+ }
163872
+ if (this.right) {
163873
+ this.right.checkHeightCorrect();
163874
+ }
163875
+ }
163876
+ balanceFactor() {
163877
+ const leftH = this.left ? this.left.height : 0;
163878
+ const rightH = this.right ? this.right.height : 0;
163879
+ return leftH - rightH;
163880
+ }
163881
+ checkBalanceFactors() {
163882
+ if (Math.abs(this.balanceFactor()) > 1) {
163883
+ throw new Error("Tree is unbalanced at node " + this.key);
163884
+ }
163885
+ if (this.left) {
163886
+ this.left.checkBalanceFactors();
163887
+ }
163888
+ if (this.right) {
163889
+ this.right.checkBalanceFactors();
163890
+ }
163891
+ }
163892
+ checkIsAVLT() {
163893
+ super.checkIsBST();
163894
+ this.checkHeightCorrect();
163895
+ this.checkBalanceFactors();
163896
+ }
163897
+ rightRotation() {
163898
+ const q13 = this;
163899
+ const p4 = this.left;
163900
+ if (!p4)
163901
+ return q13;
163902
+ const b7 = p4.right;
163903
+ if (q13.parent) {
163904
+ p4.parent = q13.parent;
163905
+ if (q13.parent.left === q13)
163906
+ q13.parent.left = p4;
163907
+ else
163908
+ q13.parent.right = p4;
163909
+ } else {
163910
+ p4.parent = null;
163911
+ }
163912
+ p4.right = q13;
163913
+ q13.parent = p4;
163914
+ q13.left = b7;
163915
+ if (b7) {
163916
+ b7.parent = q13;
163917
+ }
163918
+ const ah2 = p4.left ? p4.left.height : 0;
163919
+ const bh = b7 ? b7.height : 0;
163920
+ const ch2 = q13.right ? q13.right.height : 0;
163921
+ q13.height = Math.max(bh, ch2) + 1;
163922
+ p4.height = Math.max(ah2, q13.height) + 1;
163923
+ return p4;
163924
+ }
163925
+ leftRotation() {
163926
+ const p4 = this;
163927
+ const q13 = this.right;
163928
+ if (!q13) {
163929
+ return this;
163930
+ }
163931
+ const b7 = q13.left;
163932
+ if (p4.parent) {
163933
+ q13.parent = p4.parent;
163934
+ if (p4.parent.left === p4)
163935
+ p4.parent.left = q13;
163936
+ else
163937
+ p4.parent.right = q13;
163938
+ } else {
163939
+ q13.parent = null;
163940
+ }
163941
+ q13.left = p4;
163942
+ p4.parent = q13;
163943
+ p4.right = b7;
163944
+ if (b7) {
163945
+ b7.parent = p4;
163946
+ }
163947
+ const ah2 = p4.left ? p4.left.height : 0;
163948
+ const bh = b7 ? b7.height : 0;
163949
+ const ch2 = q13.right ? q13.right.height : 0;
163950
+ p4.height = Math.max(ah2, bh) + 1;
163951
+ q13.height = Math.max(ch2, p4.height) + 1;
163952
+ return q13;
163953
+ }
163954
+ rightTooSmall() {
163955
+ if (this.balanceFactor() <= 1)
163956
+ return this;
163957
+ if (this.left.balanceFactor() < 0)
163958
+ this.left.leftRotation();
163959
+ return this.rightRotation();
163960
+ }
163961
+ leftTooSmall() {
163962
+ if (this.balanceFactor() >= -1) {
163963
+ return this;
163964
+ }
163965
+ if (this.right.balanceFactor() > 0)
163966
+ this.right.rightRotation();
163967
+ return this.leftRotation();
163968
+ }
163969
+ rebalanceAlongPath(path18) {
163970
+ let newRoot = this;
163971
+ let rotated;
163972
+ let i5;
163973
+ if (!Object.prototype.hasOwnProperty.call(this, "key")) {
163974
+ delete this.height;
163975
+ return this;
163976
+ }
163977
+ for (i5 = path18.length - 1;i5 >= 0; i5 -= 1) {
163978
+ path18[i5].height = 1 + Math.max(path18[i5].left ? path18[i5].left.height : 0, path18[i5].right ? path18[i5].right.height : 0);
163979
+ if (path18[i5].balanceFactor() > 1) {
163980
+ rotated = path18[i5].rightTooSmall();
163981
+ if (i5 === 0)
163982
+ newRoot = rotated;
163983
+ }
163984
+ if (path18[i5].balanceFactor() < -1) {
163985
+ rotated = path18[i5].leftTooSmall();
163986
+ if (i5 === 0)
163987
+ newRoot = rotated;
163988
+ }
163989
+ }
163990
+ return newRoot;
163991
+ }
163992
+ insert(key2, value) {
163993
+ const insertPath = [];
163994
+ let currentNode = this;
163995
+ if (!Object.prototype.hasOwnProperty.call(this, "key")) {
163996
+ this.key = key2;
163997
+ this.data.push(value);
163998
+ this.height = 1;
163999
+ return this;
164000
+ }
164001
+ while (true) {
164002
+ if (currentNode.compareKeys(currentNode.key, key2) === 0) {
164003
+ if (currentNode.unique) {
164004
+ const err = new Error(`Can't insert key ${JSON.stringify(key2)}, it violates the unique constraint`);
164005
+ err.key = key2;
164006
+ err.errorType = "uniqueViolated";
164007
+ throw err;
164008
+ } else
164009
+ currentNode.data.push(value);
164010
+ return this;
164011
+ }
164012
+ insertPath.push(currentNode);
164013
+ if (currentNode.compareKeys(key2, currentNode.key) < 0) {
164014
+ if (!currentNode.left) {
164015
+ insertPath.push(currentNode.createLeftChild({ key: key2, value }));
164016
+ break;
164017
+ } else
164018
+ currentNode = currentNode.left;
164019
+ } else {
164020
+ if (!currentNode.right) {
164021
+ insertPath.push(currentNode.createRightChild({ key: key2, value }));
164022
+ break;
164023
+ } else
164024
+ currentNode = currentNode.right;
164025
+ }
164026
+ }
164027
+ return this.rebalanceAlongPath(insertPath);
164028
+ }
164029
+ delete(key2, value) {
164030
+ const newData = [];
164031
+ let replaceWith;
164032
+ let currentNode = this;
164033
+ const deletePath = [];
164034
+ if (!Object.prototype.hasOwnProperty.call(this, "key"))
164035
+ return this;
164036
+ while (true) {
164037
+ if (currentNode.compareKeys(key2, currentNode.key) === 0) {
164038
+ break;
164039
+ }
164040
+ deletePath.push(currentNode);
164041
+ if (currentNode.compareKeys(key2, currentNode.key) < 0) {
164042
+ if (currentNode.left) {
164043
+ currentNode = currentNode.left;
164044
+ } else
164045
+ return this;
164046
+ } else {
164047
+ if (currentNode.right) {
164048
+ currentNode = currentNode.right;
164049
+ } else
164050
+ return this;
164051
+ }
164052
+ }
164053
+ if (currentNode.data.length > 1 && value !== undefined) {
164054
+ currentNode.data.forEach(function(d5) {
164055
+ if (!currentNode.checkValueEquality(d5, value))
164056
+ newData.push(d5);
164057
+ });
164058
+ currentNode.data = newData;
164059
+ return this;
164060
+ }
164061
+ if (!currentNode.left && !currentNode.right) {
164062
+ if (currentNode === this) {
164063
+ delete currentNode.key;
164064
+ currentNode.data = [];
164065
+ delete currentNode.height;
164066
+ return this;
164067
+ } else {
164068
+ if (currentNode.parent.left === currentNode)
164069
+ currentNode.parent.left = null;
164070
+ else
164071
+ currentNode.parent.right = null;
164072
+ return this.rebalanceAlongPath(deletePath);
164073
+ }
164074
+ }
164075
+ if (!currentNode.left || !currentNode.right) {
164076
+ replaceWith = currentNode.left ? currentNode.left : currentNode.right;
164077
+ if (currentNode === this) {
164078
+ replaceWith.parent = null;
164079
+ return replaceWith;
164080
+ } else {
164081
+ if (currentNode.parent.left === currentNode) {
164082
+ currentNode.parent.left = replaceWith;
164083
+ replaceWith.parent = currentNode.parent;
164084
+ } else {
164085
+ currentNode.parent.right = replaceWith;
164086
+ replaceWith.parent = currentNode.parent;
164087
+ }
164088
+ return this.rebalanceAlongPath(deletePath);
164089
+ }
164090
+ }
164091
+ deletePath.push(currentNode);
164092
+ replaceWith = currentNode.left;
164093
+ if (!replaceWith.right) {
164094
+ currentNode.key = replaceWith.key;
164095
+ currentNode.data = replaceWith.data;
164096
+ currentNode.left = replaceWith.left;
164097
+ if (replaceWith.left) {
164098
+ replaceWith.left.parent = currentNode;
164099
+ }
164100
+ return this.rebalanceAlongPath(deletePath);
164101
+ }
164102
+ while (true) {
164103
+ if (replaceWith.right) {
164104
+ deletePath.push(replaceWith);
164105
+ replaceWith = replaceWith.right;
164106
+ } else
164107
+ break;
164108
+ }
164109
+ currentNode.key = replaceWith.key;
164110
+ currentNode.data = replaceWith.data;
164111
+ replaceWith.parent.right = replaceWith.left;
164112
+ if (replaceWith.left)
164113
+ replaceWith.left.parent = replaceWith.parent;
164114
+ return this.rebalanceAlongPath(deletePath);
164115
+ }
164116
+ }
164117
+ AVLTree._AVLTree = _AVLTree;
164118
+ ["getNumberOfKeys", "search", "betweenBounds", "prettyPrint", "executeOnEveryNode"].forEach(function(fn9) {
164119
+ AVLTree.prototype[fn9] = function() {
164120
+ return this.tree[fn9].apply(this.tree, arguments);
164121
+ };
164122
+ });
164123
+ module.exports = AVLTree;
164124
+ });
164125
+
164126
+ // node_modules/@seald-io/binary-search-tree/index.js
164127
+ var require_binary_search_tree = __commonJS((exports, module) => {
164128
+ exports.BinarySearchTree = require_bst();
164129
+ exports.AVLTree = require_avltree();
164130
+ });
164131
+
164132
+ // node_modules/@seald-io/nedb/lib/indexes.js
164133
+ var require_indexes = __commonJS((exports, module) => {
164134
+ var BinarySearchTree = require_binary_search_tree().AVLTree;
164135
+ var model = require_model();
164136
+ var { uniq, isDate } = require_utils11();
164137
+ var checkValueEquality = (a5, b7) => a5 === b7;
164138
+ var projectForUnique = (elt) => {
164139
+ if (elt === null)
164140
+ return "$null";
164141
+ if (typeof elt === "string")
164142
+ return "$string" + elt;
164143
+ if (typeof elt === "boolean")
164144
+ return "$boolean" + elt;
164145
+ if (typeof elt === "number")
164146
+ return "$number" + elt;
164147
+ if (isDate(elt))
164148
+ return "$date" + elt.getTime();
164149
+ return elt;
164150
+ };
164151
+
164152
+ class Index {
164153
+ constructor(options8) {
164154
+ this.fieldName = options8.fieldName;
164155
+ if (typeof this.fieldName !== "string")
164156
+ throw new Error("fieldName must be a string");
164157
+ this._fields = this.fieldName.split(",");
164158
+ this.unique = options8.unique || false;
164159
+ this.sparse = options8.sparse || false;
164160
+ this.treeOptions = { unique: this.unique, compareKeys: model.compareThings, checkValueEquality };
164161
+ this.tree = new BinarySearchTree(this.treeOptions);
164162
+ }
164163
+ reset(newData) {
164164
+ this.tree = new BinarySearchTree(this.treeOptions);
164165
+ if (newData)
164166
+ this.insert(newData);
164167
+ }
164168
+ insert(doc2) {
164169
+ let keys;
164170
+ let failingIndex;
164171
+ let error48;
164172
+ if (Array.isArray(doc2)) {
164173
+ this.insertMultipleDocs(doc2);
164174
+ return;
164175
+ }
164176
+ const key2 = model.getDotValues(doc2, this._fields);
164177
+ if ((key2 === undefined || typeof key2 === "object" && key2 !== null && Object.values(key2).every((el5) => el5 === undefined)) && this.sparse)
164178
+ return;
164179
+ if (!Array.isArray(key2))
164180
+ this.tree.insert(key2, doc2);
164181
+ else {
164182
+ keys = uniq(key2, projectForUnique);
164183
+ for (let i5 = 0;i5 < keys.length; i5 += 1) {
164184
+ try {
164185
+ this.tree.insert(keys[i5], doc2);
164186
+ } catch (e8) {
164187
+ error48 = e8;
164188
+ failingIndex = i5;
164189
+ break;
164190
+ }
164191
+ }
164192
+ if (error48) {
164193
+ for (let i5 = 0;i5 < failingIndex; i5 += 1) {
164194
+ this.tree.delete(keys[i5], doc2);
164195
+ }
164196
+ throw error48;
164197
+ }
164198
+ }
164199
+ }
164200
+ insertMultipleDocs(docs) {
164201
+ let error48;
164202
+ let failingIndex;
164203
+ for (let i5 = 0;i5 < docs.length; i5 += 1) {
164204
+ try {
164205
+ this.insert(docs[i5]);
164206
+ } catch (e8) {
164207
+ error48 = e8;
164208
+ failingIndex = i5;
164209
+ break;
164210
+ }
164211
+ }
164212
+ if (error48) {
164213
+ for (let i5 = 0;i5 < failingIndex; i5 += 1) {
164214
+ this.remove(docs[i5]);
164215
+ }
164216
+ throw error48;
164217
+ }
164218
+ }
164219
+ remove(doc2) {
164220
+ if (Array.isArray(doc2)) {
164221
+ doc2.forEach((d5) => {
164222
+ this.remove(d5);
164223
+ });
164224
+ return;
164225
+ }
164226
+ const key2 = model.getDotValues(doc2, this._fields);
164227
+ if (key2 === undefined && this.sparse)
164228
+ return;
164229
+ if (!Array.isArray(key2)) {
164230
+ this.tree.delete(key2, doc2);
164231
+ } else {
164232
+ uniq(key2, projectForUnique).forEach((_key) => {
164233
+ this.tree.delete(_key, doc2);
164234
+ });
164235
+ }
164236
+ }
164237
+ update(oldDoc, newDoc) {
164238
+ if (Array.isArray(oldDoc)) {
164239
+ this.updateMultipleDocs(oldDoc);
164240
+ return;
164241
+ }
164242
+ this.remove(oldDoc);
164243
+ try {
164244
+ this.insert(newDoc);
164245
+ } catch (e8) {
164246
+ this.insert(oldDoc);
164247
+ throw e8;
164248
+ }
164249
+ }
164250
+ updateMultipleDocs(pairs) {
164251
+ let failingIndex;
164252
+ let error48;
164253
+ for (let i5 = 0;i5 < pairs.length; i5 += 1) {
164254
+ this.remove(pairs[i5].oldDoc);
164255
+ }
164256
+ for (let i5 = 0;i5 < pairs.length; i5 += 1) {
164257
+ try {
164258
+ this.insert(pairs[i5].newDoc);
164259
+ } catch (e8) {
164260
+ error48 = e8;
164261
+ failingIndex = i5;
164262
+ break;
164263
+ }
164264
+ }
164265
+ if (error48) {
164266
+ for (let i5 = 0;i5 < failingIndex; i5 += 1) {
164267
+ this.remove(pairs[i5].newDoc);
164268
+ }
164269
+ for (let i5 = 0;i5 < pairs.length; i5 += 1) {
164270
+ this.insert(pairs[i5].oldDoc);
164271
+ }
164272
+ throw error48;
164273
+ }
164274
+ }
164275
+ revertUpdate(oldDoc, newDoc) {
164276
+ const revert = [];
164277
+ if (!Array.isArray(oldDoc))
164278
+ this.update(newDoc, oldDoc);
164279
+ else {
164280
+ oldDoc.forEach((pair) => {
164281
+ revert.push({ oldDoc: pair.newDoc, newDoc: pair.oldDoc });
164282
+ });
164283
+ this.update(revert);
164284
+ }
164285
+ }
164286
+ getMatching(value) {
164287
+ if (!Array.isArray(value))
164288
+ return this.tree.search(value);
164289
+ else {
164290
+ const _res = {};
164291
+ const res = [];
164292
+ value.forEach((v10) => {
164293
+ this.getMatching(v10).forEach((doc2) => {
164294
+ _res[doc2._id] = doc2;
164295
+ });
164296
+ });
164297
+ Object.keys(_res).forEach((_id) => {
164298
+ res.push(_res[_id]);
164299
+ });
164300
+ return res;
164301
+ }
164302
+ }
164303
+ getBetweenBounds(query) {
164304
+ return this.tree.betweenBounds(query);
164305
+ }
164306
+ getAll() {
164307
+ const res = [];
164308
+ this.tree.executeOnEveryNode((node) => {
164309
+ res.push(...node.data);
164310
+ });
164311
+ return res;
164312
+ }
164313
+ }
164314
+ module.exports = Index;
164315
+ });
164316
+
164317
+ // node_modules/@seald-io/nedb/lib/byline.js
164318
+ var require_byline = __commonJS((exports, module) => {
164319
+ var stream = __require("stream");
164320
+ var timers = __require("timers");
164321
+ var { Buffer: Buffer7 } = __require("buffer");
164322
+ var createLineStream = (readStream, options8) => {
164323
+ if (!readStream)
164324
+ throw new Error("expected readStream");
164325
+ if (!readStream.readable)
164326
+ throw new Error("readStream must be readable");
164327
+ const ls7 = new LineStream(options8);
164328
+ readStream.pipe(ls7);
164329
+ return ls7;
164330
+ };
164331
+
164332
+ class LineStream extends stream.Transform {
164333
+ constructor(options8) {
164334
+ super(options8);
164335
+ options8 = options8 || {};
164336
+ this._readableState.objectMode = true;
164337
+ this._lineBuffer = [];
164338
+ this._keepEmptyLines = options8.keepEmptyLines || false;
164339
+ this._lastChunkEndedWithCR = false;
164340
+ this.once("pipe", (src) => {
164341
+ if (!this.encoding && src instanceof stream.Readable)
164342
+ this.encoding = src._readableState.encoding;
164343
+ });
164344
+ }
164345
+ _transform(chunk, encoding, done) {
164346
+ encoding = encoding || "utf8";
164347
+ if (Buffer7.isBuffer(chunk)) {
164348
+ if (encoding === "buffer") {
164349
+ chunk = chunk.toString();
164350
+ encoding = "utf8";
164351
+ } else
164352
+ chunk = chunk.toString(encoding);
164353
+ }
164354
+ this._chunkEncoding = encoding;
164355
+ const lines = chunk.split(/\r\n|[\n\v\f\r\x85\u2028\u2029]/g);
164356
+ if (this._lastChunkEndedWithCR && chunk[0] === `
164357
+ `)
164358
+ lines.shift();
164359
+ if (this._lineBuffer.length > 0) {
164360
+ this._lineBuffer[this._lineBuffer.length - 1] += lines[0];
164361
+ lines.shift();
164362
+ }
164363
+ this._lastChunkEndedWithCR = chunk[chunk.length - 1] === "\r";
164364
+ this._lineBuffer = this._lineBuffer.concat(lines);
164365
+ this._pushBuffer(encoding, 1, done);
164366
+ }
164367
+ _pushBuffer(encoding, keep, done) {
164368
+ while (this._lineBuffer.length > keep) {
164369
+ const line3 = this._lineBuffer.shift();
164370
+ if (this._keepEmptyLines || line3.length > 0) {
164371
+ if (!this.push(this._reencode(line3, encoding))) {
164372
+ timers.setImmediate(() => {
164373
+ this._pushBuffer(encoding, keep, done);
164374
+ });
164375
+ return;
164376
+ }
164377
+ }
164378
+ }
164379
+ done();
164380
+ }
164381
+ _flush(done) {
164382
+ this._pushBuffer(this._chunkEncoding, 0, done);
164383
+ }
164384
+ _reencode(line3, chunkEncoding) {
164385
+ if (this.encoding && this.encoding !== chunkEncoding)
164386
+ return Buffer7.from(line3, chunkEncoding).toString(this.encoding);
164387
+ else if (this.encoding)
164388
+ return line3;
164389
+ else
164390
+ return Buffer7.from(line3, chunkEncoding);
164391
+ }
164392
+ }
164393
+ module.exports = createLineStream;
164394
+ });
164395
+
164396
+ // node_modules/@seald-io/nedb/lib/storage.js
164397
+ var require_storage = __commonJS((exports, module) => {
164398
+ var fs28 = __require("fs");
164399
+ var fsPromises2 = fs28.promises;
164400
+ var path18 = __require("path");
164401
+ var { Readable: Readable6 } = __require("stream");
164402
+ var DEFAULT_DIR_MODE = 493;
164403
+ var DEFAULT_FILE_MODE = 420;
164404
+ var existsAsync = (file2) => fsPromises2.access(file2, fs28.constants.F_OK).then(() => true, () => false);
164405
+ var renameAsync = fsPromises2.rename;
164406
+ var writeFileAsync = fsPromises2.writeFile;
164407
+ var writeFileStream = fs28.createWriteStream;
164408
+ var unlinkAsync = fsPromises2.unlink;
164409
+ var appendFileAsync = fsPromises2.appendFile;
164410
+ var readFileAsync = fsPromises2.readFile;
164411
+ var readFileStream = fs28.createReadStream;
164412
+ var mkdirAsync = fsPromises2.mkdir;
164413
+ var ensureFileDoesntExistAsync = async (file2) => {
164414
+ if (await existsAsync(file2))
164415
+ await unlinkAsync(file2);
164416
+ };
164417
+ var flushToStorageAsync = async (options8) => {
164418
+ let filename;
164419
+ let flags;
164420
+ let mode;
164421
+ if (typeof options8 === "string") {
164422
+ filename = options8;
164423
+ flags = "r+";
164424
+ mode = DEFAULT_FILE_MODE;
164425
+ } else {
164426
+ filename = options8.filename;
164427
+ flags = options8.isDir ? "r" : "r+";
164428
+ mode = options8.mode !== undefined ? options8.mode : DEFAULT_FILE_MODE;
164429
+ }
164430
+ let filehandle, errorOnFsync, errorOnClose;
164431
+ try {
164432
+ filehandle = await fsPromises2.open(filename, flags, mode);
164433
+ try {
164434
+ await filehandle.sync();
164435
+ } catch (errFS) {
164436
+ errorOnFsync = errFS;
164437
+ }
164438
+ } catch (error48) {
164439
+ if (error48.code !== "EISDIR" || !options8.isDir)
164440
+ throw error48;
164441
+ } finally {
164442
+ try {
164443
+ await filehandle.close();
164444
+ } catch (errC) {
164445
+ errorOnClose = errC;
164446
+ }
164447
+ }
164448
+ if ((errorOnFsync || errorOnClose) && !((errorOnFsync.code === "EPERM" || errorOnClose.code === "EISDIR") && options8.isDir)) {
164449
+ const e8 = new Error("Failed to flush to storage");
164450
+ e8.errorOnFsync = errorOnFsync;
164451
+ e8.errorOnClose = errorOnClose;
164452
+ throw e8;
164453
+ }
164454
+ };
164455
+ var writeFileLinesAsync = (filename, lines, mode = DEFAULT_FILE_MODE) => new Promise((resolve5, reject) => {
164456
+ try {
164457
+ const stream = writeFileStream(filename, { mode });
164458
+ const readable2 = Readable6.from(lines);
164459
+ readable2.on("data", (line3) => {
164460
+ try {
164461
+ stream.write(line3 + `
164462
+ `);
164463
+ } catch (err) {
164464
+ reject(err);
164465
+ }
164466
+ });
164467
+ readable2.on("end", () => {
164468
+ stream.close((err) => {
164469
+ if (err)
164470
+ reject(err);
164471
+ else
164472
+ resolve5();
164473
+ });
164474
+ });
164475
+ readable2.on("error", (err) => {
164476
+ reject(err);
164477
+ });
164478
+ stream.on("error", (err) => {
164479
+ reject(err);
164480
+ });
164481
+ } catch (err) {
164482
+ reject(err);
164483
+ }
164484
+ });
164485
+ var crashSafeWriteFileLinesAsync = async (filename, lines, modes = { fileMode: DEFAULT_FILE_MODE, dirMode: DEFAULT_DIR_MODE }) => {
164486
+ const tempFilename = filename + "~";
164487
+ await flushToStorageAsync({ filename: path18.dirname(filename), isDir: true, mode: modes.dirMode });
164488
+ const exists = await existsAsync(filename);
164489
+ if (exists)
164490
+ await flushToStorageAsync({ filename, mode: modes.fileMode });
164491
+ await writeFileLinesAsync(tempFilename, lines, modes.fileMode);
164492
+ await flushToStorageAsync({ filename: tempFilename, mode: modes.fileMode });
164493
+ await renameAsync(tempFilename, filename);
164494
+ await flushToStorageAsync({ filename: path18.dirname(filename), isDir: true, mode: modes.dirMode });
164495
+ };
164496
+ var ensureDatafileIntegrityAsync = async (filename, mode = DEFAULT_FILE_MODE) => {
164497
+ const tempFilename = filename + "~";
164498
+ const filenameExists = await existsAsync(filename);
164499
+ if (filenameExists)
164500
+ return;
164501
+ const oldFilenameExists = await existsAsync(tempFilename);
164502
+ if (!oldFilenameExists)
164503
+ await writeFileAsync(filename, "", { encoding: "utf8", mode });
164504
+ else
164505
+ await renameAsync(tempFilename, filename);
164506
+ };
164507
+ var ensureParentDirectoryExistsAsync = async (filename, mode) => {
164508
+ const dir = path18.dirname(filename);
164509
+ const parsedDir = path18.parse(path18.resolve(dir));
164510
+ if (process.platform !== "win32" || parsedDir.dir !== parsedDir.root || parsedDir.base !== "") {
164511
+ await mkdirAsync(dir, { recursive: true, mode });
164512
+ }
164513
+ };
164514
+ exports.existsAsync = existsAsync;
164515
+ exports.renameAsync = renameAsync;
164516
+ exports.writeFileAsync = writeFileAsync;
164517
+ exports.writeFileLinesAsync = writeFileLinesAsync;
164518
+ exports.crashSafeWriteFileLinesAsync = crashSafeWriteFileLinesAsync;
164519
+ exports.appendFileAsync = appendFileAsync;
164520
+ exports.readFileAsync = readFileAsync;
164521
+ exports.unlinkAsync = unlinkAsync;
164522
+ exports.mkdirAsync = mkdirAsync;
164523
+ exports.readFileStream = readFileStream;
164524
+ exports.flushToStorageAsync = flushToStorageAsync;
164525
+ exports.ensureDatafileIntegrityAsync = ensureDatafileIntegrityAsync;
164526
+ exports.ensureFileDoesntExistAsync = ensureFileDoesntExistAsync;
164527
+ exports.ensureParentDirectoryExistsAsync = ensureParentDirectoryExistsAsync;
164528
+ });
164529
+
164530
+ // node_modules/@seald-io/nedb/lib/persistence.js
164531
+ var require_persistence = __commonJS((exports, module) => {
164532
+ var { deprecate } = __require("util");
164533
+ var byline = require_byline();
164534
+ var Index = require_indexes();
164535
+ var model = require_model();
164536
+ var storage = require_storage();
164537
+ var Waterfall = require_waterfall();
164538
+ var DEFAULT_DIR_MODE = 493;
164539
+ var DEFAULT_FILE_MODE = 420;
164540
+
164541
+ class Persistence {
164542
+ constructor(options8) {
164543
+ this.db = options8.db;
164544
+ this.inMemoryOnly = this.db.inMemoryOnly;
164545
+ this.filename = this.db.filename;
164546
+ this.corruptAlertThreshold = options8.corruptAlertThreshold !== undefined ? options8.corruptAlertThreshold : 0.1;
164547
+ this.modes = options8.modes !== undefined ? options8.modes : {
164548
+ fileMode: DEFAULT_FILE_MODE,
164549
+ dirMode: DEFAULT_DIR_MODE
164550
+ };
164551
+ if (this.modes.fileMode === undefined)
164552
+ this.modes.fileMode = DEFAULT_FILE_MODE;
164553
+ if (this.modes.dirMode === undefined)
164554
+ this.modes.dirMode = DEFAULT_DIR_MODE;
164555
+ if (!this.inMemoryOnly && this.filename && this.filename.charAt(this.filename.length - 1) === "~")
164556
+ throw new Error("The datafile name can't end with a ~, which is reserved for crash safe backup files");
164557
+ if (options8.afterSerialization && !options8.beforeDeserialization)
164558
+ throw new Error("Serialization hook defined but deserialization hook undefined, cautiously refusing to start NeDB to prevent dataloss");
164559
+ if (!options8.afterSerialization && options8.beforeDeserialization)
164560
+ throw new Error("Serialization hook undefined but deserialization hook defined, cautiously refusing to start NeDB to prevent dataloss");
164561
+ this.afterSerialization = async (s5) => (options8.afterSerialization || ((x10) => x10))(s5);
164562
+ this.beforeDeserialization = async (s5) => (options8.beforeDeserialization || ((x10) => x10))(s5);
164563
+ }
164564
+ async persistCachedDatabaseAsync() {
164565
+ const lines = [];
164566
+ if (this.inMemoryOnly)
164567
+ return;
164568
+ for (const doc2 of this.db.getAllData()) {
164569
+ lines.push(await this.afterSerialization(model.serialize(doc2)));
164570
+ }
164571
+ for (const fieldName of Object.keys(this.db.indexes)) {
164572
+ if (fieldName !== "_id") {
164573
+ lines.push(await this.afterSerialization(model.serialize({
164574
+ $$indexCreated: {
164575
+ fieldName: this.db.indexes[fieldName].fieldName,
164576
+ unique: this.db.indexes[fieldName].unique,
164577
+ sparse: this.db.indexes[fieldName].sparse
164578
+ }
164579
+ })));
164580
+ }
164581
+ }
164582
+ await storage.crashSafeWriteFileLinesAsync(this.filename, lines, this.modes);
164583
+ this.db.emit("compaction.done");
164584
+ }
164585
+ compactDatafile(callback) {
164586
+ deprecate((_callback) => this.db.compactDatafile(_callback), "@seald-io/nedb: calling Datastore#persistence#compactDatafile is deprecated, please use Datastore#compactDatafile, it will be removed in the next major version.")(callback);
164587
+ }
164588
+ setAutocompactionInterval(interval) {
164589
+ deprecate((_interval) => this.db.setAutocompactionInterval(_interval), "@seald-io/nedb: calling Datastore#persistence#setAutocompactionInterval is deprecated, please use Datastore#setAutocompactionInterval, it will be removed in the next major version.")(interval);
164590
+ }
164591
+ stopAutocompaction() {
164592
+ deprecate(() => this.db.stopAutocompaction(), "@seald-io/nedb: calling Datastore#persistence#stopAutocompaction is deprecated, please use Datastore#stopAutocompaction, it will be removed in the next major version.")();
164593
+ }
164594
+ async persistNewStateAsync(newDocs) {
164595
+ let toPersist = "";
164596
+ if (this.inMemoryOnly)
164597
+ return;
164598
+ for (const doc2 of newDocs) {
164599
+ toPersist += await this.afterSerialization(model.serialize(doc2)) + `
164600
+ `;
164601
+ }
164602
+ if (toPersist.length === 0)
164603
+ return;
164604
+ await storage.appendFileAsync(this.filename, toPersist, { encoding: "utf8", mode: this.modes.fileMode });
164605
+ }
164606
+ async treatRawData(rawData) {
164607
+ const data = rawData.split(`
164608
+ `).filter((datum) => datum !== "").map(async (datum) => model.deserialize(await this.beforeDeserialization(datum)));
164609
+ const dataById = {};
164610
+ const indexes = {};
164611
+ const dataLength = data.length;
164612
+ let corruptItems = 0;
164613
+ for (const docToAwait of data) {
164614
+ try {
164615
+ const doc2 = await docToAwait;
164616
+ if (doc2._id) {
164617
+ if (doc2.$$deleted === true)
164618
+ delete dataById[doc2._id];
164619
+ else
164620
+ dataById[doc2._id] = doc2;
164621
+ } else if (doc2.$$indexCreated && doc2.$$indexCreated.fieldName != null)
164622
+ indexes[doc2.$$indexCreated.fieldName] = doc2.$$indexCreated;
164623
+ else if (typeof doc2.$$indexRemoved === "string")
164624
+ delete indexes[doc2.$$indexRemoved];
164625
+ } catch (e8) {
164626
+ corruptItems += 1;
164627
+ }
164628
+ }
164629
+ if (dataLength > 0) {
164630
+ const corruptionRate = corruptItems / dataLength;
164631
+ if (corruptionRate > this.corruptAlertThreshold) {
164632
+ const error48 = new Error(`${Math.floor(100 * corruptionRate)}% of the data file is corrupt, more than given corruptAlertThreshold (${Math.floor(100 * this.corruptAlertThreshold)}%). Cautiously refusing to start NeDB to prevent dataloss.`);
164633
+ error48.corruptionRate = corruptionRate;
164634
+ error48.corruptItems = corruptItems;
164635
+ error48.dataLength = dataLength;
164636
+ throw error48;
164637
+ }
164638
+ }
164639
+ const tdata = Object.values(dataById);
164640
+ return { data: tdata, indexes };
164641
+ }
164642
+ treatRawStreamAsync(rawStream) {
164643
+ return new Promise((resolve5, reject) => {
164644
+ const dataById = {};
164645
+ const indexes = {};
164646
+ let corruptItems = 0;
164647
+ const lineStream = byline(rawStream);
164648
+ let dataLength = 0;
164649
+ const waterfall = new Waterfall;
164650
+ lineStream.on("data", (line3) => {
164651
+ const deserializedPromise = this.beforeDeserialization(line3);
164652
+ return waterfall.waterfall(async () => {
164653
+ if (line3 === "")
164654
+ return;
164655
+ try {
164656
+ const doc2 = model.deserialize(await deserializedPromise);
164657
+ if (doc2._id) {
164658
+ if (doc2.$$deleted === true)
164659
+ delete dataById[doc2._id];
164660
+ else
164661
+ dataById[doc2._id] = doc2;
164662
+ } else if (doc2.$$indexCreated && doc2.$$indexCreated.fieldName != null)
164663
+ indexes[doc2.$$indexCreated.fieldName] = doc2.$$indexCreated;
164664
+ else if (typeof doc2.$$indexRemoved === "string")
164665
+ delete indexes[doc2.$$indexRemoved];
164666
+ } catch (e8) {
164667
+ corruptItems += 1;
164668
+ }
164669
+ dataLength++;
164670
+ })();
164671
+ });
164672
+ lineStream.on("end", async () => {
164673
+ await waterfall.guardian;
164674
+ if (dataLength > 0) {
164675
+ const corruptionRate = corruptItems / dataLength;
164676
+ if (corruptionRate > this.corruptAlertThreshold) {
164677
+ const error48 = new Error(`${Math.floor(100 * corruptionRate)}% of the data file is corrupt, more than given corruptAlertThreshold (${Math.floor(100 * this.corruptAlertThreshold)}%). Cautiously refusing to start NeDB to prevent dataloss.`);
164678
+ error48.corruptionRate = corruptionRate;
164679
+ error48.corruptItems = corruptItems;
164680
+ error48.dataLength = dataLength;
164681
+ reject(error48, null);
164682
+ return;
164683
+ }
164684
+ }
164685
+ const data = Object.values(dataById);
164686
+ resolve5({ data, indexes });
164687
+ });
164688
+ lineStream.on("error", function(err) {
164689
+ reject(err, null);
164690
+ });
164691
+ });
164692
+ }
164693
+ async loadDatabaseAsync() {
164694
+ this.db._resetIndexes();
164695
+ if (this.inMemoryOnly)
164696
+ return;
164697
+ await Persistence.ensureParentDirectoryExistsAsync(this.filename, this.modes.dirMode);
164698
+ await storage.ensureDatafileIntegrityAsync(this.filename, this.modes.fileMode);
164699
+ let treatedData;
164700
+ if (storage.readFileStream) {
164701
+ const fileStream = storage.readFileStream(this.filename, { encoding: "utf8", mode: this.modes.fileMode });
164702
+ treatedData = await this.treatRawStreamAsync(fileStream);
164703
+ } else {
164704
+ const rawData = await storage.readFileAsync(this.filename, { encoding: "utf8", mode: this.modes.fileMode });
164705
+ treatedData = await this.treatRawData(rawData);
164706
+ }
164707
+ Object.keys(treatedData.indexes).forEach((key2) => {
164708
+ this.db.indexes[key2] = new Index(treatedData.indexes[key2]);
164709
+ });
164710
+ try {
164711
+ this.db._resetIndexes(treatedData.data);
164712
+ } catch (e8) {
164713
+ this.db._resetIndexes();
164714
+ throw e8;
164715
+ }
164716
+ await this.db.persistence.persistCachedDatabaseAsync();
164717
+ this.db.executor.processBuffer();
164718
+ }
164719
+ async dropDatabaseAsync() {
164720
+ this.db.stopAutocompaction();
164721
+ this.db.executor.ready = false;
164722
+ this.db.executor.resetBuffer();
164723
+ await this.db.executor.queue.guardian;
164724
+ this.db.indexes = {};
164725
+ this.db.indexes._id = new Index({ fieldName: "_id", unique: true });
164726
+ this.db.ttlIndexes = {};
164727
+ if (!this.db.inMemoryOnly) {
164728
+ await this.db.executor.pushAsync(async () => {
164729
+ if (await storage.existsAsync(this.filename))
164730
+ await storage.unlinkAsync(this.filename);
164731
+ }, true);
164732
+ }
164733
+ }
164734
+ static async ensureParentDirectoryExistsAsync(dir, mode = DEFAULT_DIR_MODE) {
164735
+ return storage.ensureParentDirectoryExistsAsync(dir, mode);
164736
+ }
164737
+ }
164738
+ module.exports = Persistence;
164739
+ });
164740
+
164741
+ // node_modules/@seald-io/nedb/lib/datastore.js
164742
+ var require_datastore = __commonJS((exports, module) => {
164743
+ var { EventEmitter: EventEmitter3 } = __require("events");
164744
+ var { callbackify: callbackify5, deprecate } = __require("util");
164745
+ var Cursor = require_cursor();
164746
+ var customUtils = require_customUtils();
164747
+ var Executor = require_executor();
164748
+ var Index = require_indexes();
164749
+ var model = require_model();
164750
+ var Persistence = require_persistence();
164751
+ var { isDate, pick: pick2, filterIndexNames } = require_utils11();
164752
+
164753
+ class Datastore extends EventEmitter3 {
164754
+ constructor(options8) {
164755
+ super();
164756
+ let filename;
164757
+ if (typeof options8 === "string") {
164758
+ deprecate(() => {
164759
+ filename = options8;
164760
+ this.inMemoryOnly = false;
164761
+ }, "@seald-io/nedb: Giving a string to the Datastore constructor is deprecated and will be removed in the next major version. Please use an options object with an argument 'filename'.")();
164762
+ } else {
164763
+ options8 = options8 || {};
164764
+ filename = options8.filename;
164765
+ this.inMemoryOnly = options8.inMemoryOnly || false;
164766
+ this.autoload = options8.autoload || false;
164767
+ this.timestampData = options8.timestampData || false;
164768
+ }
164769
+ if (!filename || typeof filename !== "string" || filename.length === 0) {
164770
+ this.filename = null;
164771
+ this.inMemoryOnly = true;
164772
+ } else {
164773
+ this.filename = filename;
164774
+ }
164775
+ this.compareStrings = options8.compareStrings;
164776
+ this.persistence = new Persistence({
164777
+ db: this,
164778
+ afterSerialization: options8.afterSerialization,
164779
+ beforeDeserialization: options8.beforeDeserialization,
164780
+ corruptAlertThreshold: options8.corruptAlertThreshold,
164781
+ modes: options8.modes,
164782
+ testSerializationHooks: options8.testSerializationHooks
164783
+ });
164784
+ this.executor = new Executor;
164785
+ if (this.inMemoryOnly)
164786
+ this.executor.ready = true;
164787
+ this.indexes = {};
164788
+ this.indexes._id = new Index({ fieldName: "_id", unique: true });
164789
+ this.ttlIndexes = {};
164790
+ if (this.autoload) {
164791
+ this.autoloadPromise = this.loadDatabaseAsync();
164792
+ this.autoloadPromise.then(() => {
164793
+ if (options8.onload)
164794
+ options8.onload();
164795
+ }, (err) => {
164796
+ if (options8.onload)
164797
+ options8.onload(err);
164798
+ else
164799
+ throw err;
164800
+ });
164801
+ } else
164802
+ this.autoloadPromise = null;
164803
+ this._autocompactionIntervalId = null;
164804
+ }
164805
+ compactDatafileAsync() {
164806
+ return this.executor.pushAsync(() => this.persistence.persistCachedDatabaseAsync());
164807
+ }
164808
+ compactDatafile(callback) {
164809
+ const promise2 = this.compactDatafileAsync();
164810
+ if (typeof callback === "function")
164811
+ callbackify5(() => promise2)(callback);
164812
+ }
164813
+ setAutocompactionInterval(interval) {
164814
+ const minInterval = 5000;
164815
+ if (Number.isNaN(Number(interval)))
164816
+ throw new Error("Interval must be a non-NaN number");
164817
+ const realInterval = Math.max(Number(interval), minInterval);
164818
+ this.stopAutocompaction();
164819
+ this._autocompactionIntervalId = setInterval(() => {
164820
+ this.compactDatafile();
164821
+ }, realInterval);
164822
+ }
164823
+ stopAutocompaction() {
164824
+ if (this._autocompactionIntervalId) {
164825
+ clearInterval(this._autocompactionIntervalId);
164826
+ this._autocompactionIntervalId = null;
164827
+ }
164828
+ }
164829
+ loadDatabase(callback) {
164830
+ const promise2 = this.loadDatabaseAsync();
164831
+ if (typeof callback === "function")
164832
+ callbackify5(() => promise2)(callback);
164833
+ }
164834
+ dropDatabaseAsync() {
164835
+ return this.persistence.dropDatabaseAsync();
164836
+ }
164837
+ dropDatabase(callback) {
164838
+ const promise2 = this.dropDatabaseAsync();
164839
+ if (typeof callback === "function")
164840
+ callbackify5(() => promise2)(callback);
164841
+ }
164842
+ loadDatabaseAsync() {
164843
+ return this.executor.pushAsync(() => this.persistence.loadDatabaseAsync(), true);
164844
+ }
164845
+ getAllData() {
164846
+ return this.indexes._id.getAll();
164847
+ }
164848
+ _resetIndexes(newData) {
164849
+ for (const index of Object.values(this.indexes)) {
164850
+ index.reset(newData);
164851
+ }
164852
+ }
164853
+ ensureIndex(options8 = {}, callback) {
164854
+ const promise2 = this.ensureIndexAsync(options8);
164855
+ if (typeof callback === "function")
164856
+ callbackify5(() => promise2)(callback);
164857
+ }
164858
+ async ensureIndexAsync(options8 = {}) {
164859
+ if (!options8.fieldName) {
164860
+ const err = new Error("Cannot create an index without a fieldName");
164861
+ err.missingFieldName = true;
164862
+ throw err;
164863
+ }
164864
+ const _fields = [].concat(options8.fieldName).sort();
164865
+ if (_fields.some((field) => field.includes(","))) {
164866
+ throw new Error("Cannot use comma in index fieldName");
164867
+ }
164868
+ const _options = {
164869
+ ...options8,
164870
+ fieldName: _fields.join(",")
164871
+ };
164872
+ if (this.indexes[_options.fieldName])
164873
+ return;
164874
+ this.indexes[_options.fieldName] = new Index(_options);
164875
+ if (options8.expireAfterSeconds !== undefined)
164876
+ this.ttlIndexes[_options.fieldName] = _options.expireAfterSeconds;
164877
+ try {
164878
+ this.indexes[_options.fieldName].insert(this.getAllData());
164879
+ } catch (e8) {
164880
+ delete this.indexes[_options.fieldName];
164881
+ throw e8;
164882
+ }
164883
+ await this.executor.pushAsync(() => this.persistence.persistNewStateAsync([{ $$indexCreated: _options }]), true);
164884
+ }
164885
+ removeIndex(fieldName, callback = () => {}) {
164886
+ const promise2 = this.removeIndexAsync(fieldName);
164887
+ callbackify5(() => promise2)(callback);
164888
+ }
164889
+ async removeIndexAsync(fieldName) {
164890
+ delete this.indexes[fieldName];
164891
+ await this.executor.pushAsync(() => this.persistence.persistNewStateAsync([{ $$indexRemoved: fieldName }]), true);
164892
+ }
164893
+ _addToIndexes(doc2) {
164894
+ let failingIndex;
164895
+ let error48;
164896
+ const keys = Object.keys(this.indexes);
164897
+ for (let i5 = 0;i5 < keys.length; i5 += 1) {
164898
+ try {
164899
+ this.indexes[keys[i5]].insert(doc2);
164900
+ } catch (e8) {
164901
+ failingIndex = i5;
164902
+ error48 = e8;
164903
+ break;
164904
+ }
164905
+ }
164906
+ if (error48) {
164907
+ for (let i5 = 0;i5 < failingIndex; i5 += 1) {
164908
+ this.indexes[keys[i5]].remove(doc2);
164909
+ }
164910
+ throw error48;
164911
+ }
164912
+ }
164913
+ _removeFromIndexes(doc2) {
164914
+ for (const index of Object.values(this.indexes)) {
164915
+ index.remove(doc2);
164916
+ }
164917
+ }
164918
+ _updateIndexes(oldDoc, newDoc) {
164919
+ let failingIndex;
164920
+ let error48;
164921
+ const keys = Object.keys(this.indexes);
164922
+ for (let i5 = 0;i5 < keys.length; i5 += 1) {
164923
+ try {
164924
+ this.indexes[keys[i5]].update(oldDoc, newDoc);
164925
+ } catch (e8) {
164926
+ failingIndex = i5;
164927
+ error48 = e8;
164928
+ break;
164929
+ }
164930
+ }
164931
+ if (error48) {
164932
+ for (let i5 = 0;i5 < failingIndex; i5 += 1) {
164933
+ this.indexes[keys[i5]].revertUpdate(oldDoc, newDoc);
164934
+ }
164935
+ throw error48;
164936
+ }
164937
+ }
164938
+ _getRawCandidates(query) {
164939
+ const indexNames = Object.keys(this.indexes);
164940
+ let usableQuery;
164941
+ usableQuery = Object.entries(query).filter(filterIndexNames(indexNames)).pop();
164942
+ if (usableQuery)
164943
+ return this.indexes[usableQuery[0]].getMatching(usableQuery[1]);
164944
+ const compoundQueryKeys = indexNames.filter((indexName) => indexName.indexOf(",") !== -1).map((indexName) => indexName.split(",")).filter((subIndexNames) => Object.entries(query).filter(filterIndexNames(subIndexNames)).length === subIndexNames.length);
164945
+ if (compoundQueryKeys.length > 0)
164946
+ return this.indexes[compoundQueryKeys[0]].getMatching(pick2(query, compoundQueryKeys[0]));
164947
+ usableQuery = Object.entries(query).filter(([k9, v10]) => !!(query[k9] && Object.prototype.hasOwnProperty.call(query[k9], "$in")) && indexNames.includes(k9)).pop();
164948
+ if (usableQuery)
164949
+ return this.indexes[usableQuery[0]].getMatching(usableQuery[1].$in);
164950
+ usableQuery = Object.entries(query).filter(([k9, v10]) => !!(query[k9] && (Object.prototype.hasOwnProperty.call(query[k9], "$lt") || Object.prototype.hasOwnProperty.call(query[k9], "$lte") || Object.prototype.hasOwnProperty.call(query[k9], "$gt") || Object.prototype.hasOwnProperty.call(query[k9], "$gte"))) && indexNames.includes(k9)).pop();
164951
+ if (usableQuery)
164952
+ return this.indexes[usableQuery[0]].getBetweenBounds(usableQuery[1]);
164953
+ return this.getAllData();
164954
+ }
164955
+ async _getCandidatesAsync(query, dontExpireStaleDocs = false) {
164956
+ const validDocs = [];
164957
+ const docs = this._getRawCandidates(query);
164958
+ if (!dontExpireStaleDocs) {
164959
+ const expiredDocsIds = [];
164960
+ const ttlIndexesFieldNames = Object.keys(this.ttlIndexes);
164961
+ docs.forEach((doc2) => {
164962
+ if (ttlIndexesFieldNames.every((i5) => !(doc2[i5] !== undefined && isDate(doc2[i5]) && Date.now() > doc2[i5].getTime() + this.ttlIndexes[i5] * 1000)))
164963
+ validDocs.push(doc2);
164964
+ else
164965
+ expiredDocsIds.push(doc2._id);
164966
+ });
164967
+ for (const _id of expiredDocsIds) {
164968
+ await this._removeAsync({ _id }, {});
164969
+ }
164970
+ } else
164971
+ validDocs.push(...docs);
164972
+ return validDocs;
164973
+ }
164974
+ async _insertAsync(newDoc) {
164975
+ const preparedDoc = this._prepareDocumentForInsertion(newDoc);
164976
+ this._insertInCache(preparedDoc);
164977
+ await this.persistence.persistNewStateAsync(Array.isArray(preparedDoc) ? preparedDoc : [preparedDoc]);
164978
+ return model.deepCopy(preparedDoc);
164979
+ }
164980
+ _createNewId() {
164981
+ let attemptId = customUtils.uid(16);
164982
+ if (this.indexes._id.getMatching(attemptId).length > 0)
164983
+ attemptId = this._createNewId();
164984
+ return attemptId;
164985
+ }
164986
+ _prepareDocumentForInsertion(newDoc) {
164987
+ let preparedDoc;
164988
+ if (Array.isArray(newDoc)) {
164989
+ preparedDoc = [];
164990
+ newDoc.forEach((doc2) => {
164991
+ preparedDoc.push(this._prepareDocumentForInsertion(doc2));
164992
+ });
164993
+ } else {
164994
+ preparedDoc = model.deepCopy(newDoc);
164995
+ if (preparedDoc._id === undefined)
164996
+ preparedDoc._id = this._createNewId();
164997
+ const now = new Date;
164998
+ if (this.timestampData && preparedDoc.createdAt === undefined)
164999
+ preparedDoc.createdAt = now;
165000
+ if (this.timestampData && preparedDoc.updatedAt === undefined)
165001
+ preparedDoc.updatedAt = now;
165002
+ model.checkObject(preparedDoc);
165003
+ }
165004
+ return preparedDoc;
165005
+ }
165006
+ _insertInCache(preparedDoc) {
165007
+ if (Array.isArray(preparedDoc))
165008
+ this._insertMultipleDocsInCache(preparedDoc);
165009
+ else
165010
+ this._addToIndexes(preparedDoc);
165011
+ }
165012
+ _insertMultipleDocsInCache(preparedDocs) {
165013
+ let failingIndex;
165014
+ let error48;
165015
+ for (let i5 = 0;i5 < preparedDocs.length; i5 += 1) {
165016
+ try {
165017
+ this._addToIndexes(preparedDocs[i5]);
165018
+ } catch (e8) {
165019
+ error48 = e8;
165020
+ failingIndex = i5;
165021
+ break;
165022
+ }
165023
+ }
165024
+ if (error48) {
165025
+ for (let i5 = 0;i5 < failingIndex; i5 += 1) {
165026
+ this._removeFromIndexes(preparedDocs[i5]);
165027
+ }
165028
+ throw error48;
165029
+ }
165030
+ }
165031
+ insert(newDoc, callback) {
165032
+ const promise2 = this.insertAsync(newDoc);
165033
+ if (typeof callback === "function")
165034
+ callbackify5(() => promise2)(callback);
165035
+ }
165036
+ insertAsync(newDoc) {
165037
+ return this.executor.pushAsync(() => this._insertAsync(newDoc));
165038
+ }
165039
+ count(query, callback) {
165040
+ const cursor3 = this.countAsync(query);
165041
+ if (typeof callback === "function")
165042
+ callbackify5(cursor3.execAsync.bind(cursor3))(callback);
165043
+ else
165044
+ return cursor3;
165045
+ }
165046
+ countAsync(query) {
165047
+ return new Cursor(this, query, (docs) => docs.length);
165048
+ }
165049
+ find(query, projection, callback) {
165050
+ if (arguments.length === 1) {
165051
+ projection = {};
165052
+ } else if (arguments.length === 2) {
165053
+ if (typeof projection === "function") {
165054
+ callback = projection;
165055
+ projection = {};
165056
+ }
165057
+ }
165058
+ const cursor3 = this.findAsync(query, projection);
165059
+ if (typeof callback === "function")
165060
+ callbackify5(cursor3.execAsync.bind(cursor3))(callback);
165061
+ else
165062
+ return cursor3;
165063
+ }
165064
+ findAsync(query, projection = {}) {
165065
+ const cursor3 = new Cursor(this, query, (docs) => docs.map((doc2) => model.deepCopy(doc2)));
165066
+ cursor3.projection(projection);
165067
+ return cursor3;
165068
+ }
165069
+ findOne(query, projection, callback) {
165070
+ if (arguments.length === 1) {
165071
+ projection = {};
165072
+ } else if (arguments.length === 2) {
165073
+ if (typeof projection === "function") {
165074
+ callback = projection;
165075
+ projection = {};
165076
+ }
165077
+ }
165078
+ const cursor3 = this.findOneAsync(query, projection);
165079
+ if (typeof callback === "function")
165080
+ callbackify5(cursor3.execAsync.bind(cursor3))(callback);
165081
+ else
165082
+ return cursor3;
165083
+ }
165084
+ findOneAsync(query, projection = {}) {
165085
+ const cursor3 = new Cursor(this, query, (docs) => docs.length === 1 ? model.deepCopy(docs[0]) : null);
165086
+ cursor3.projection(projection).limit(1);
165087
+ return cursor3;
165088
+ }
165089
+ async _updateAsync(query, update3, options8) {
165090
+ const multi = options8.multi !== undefined ? options8.multi : false;
165091
+ const upsert = options8.upsert !== undefined ? options8.upsert : false;
165092
+ if (upsert) {
165093
+ const cursor3 = new Cursor(this, query);
165094
+ const docs = await cursor3.limit(1)._execAsync();
165095
+ if (docs.length !== 1) {
165096
+ let toBeInserted;
165097
+ try {
165098
+ model.checkObject(update3);
165099
+ toBeInserted = update3;
165100
+ } catch (e8) {
165101
+ toBeInserted = model.modify(model.deepCopy(query, true), update3);
165102
+ }
165103
+ const newDoc = await this._insertAsync(toBeInserted);
165104
+ return { numAffected: 1, affectedDocuments: newDoc, upsert: true };
165105
+ }
165106
+ }
165107
+ let numReplaced = 0;
165108
+ let modifiedDoc;
165109
+ const modifications = [];
165110
+ let createdAt;
165111
+ const candidates = await this._getCandidatesAsync(query);
165112
+ for (const candidate of candidates) {
165113
+ if (model.match(candidate, query) && (multi || numReplaced === 0)) {
165114
+ numReplaced += 1;
165115
+ if (this.timestampData) {
165116
+ createdAt = candidate.createdAt;
165117
+ }
165118
+ modifiedDoc = model.modify(candidate, update3);
165119
+ if (this.timestampData) {
165120
+ modifiedDoc.createdAt = createdAt;
165121
+ modifiedDoc.updatedAt = new Date;
165122
+ }
165123
+ modifications.push({ oldDoc: candidate, newDoc: modifiedDoc });
165124
+ }
165125
+ }
165126
+ this._updateIndexes(modifications);
165127
+ const updatedDocs = modifications.map((x10) => x10.newDoc);
165128
+ await this.persistence.persistNewStateAsync(updatedDocs);
165129
+ if (!options8.returnUpdatedDocs)
165130
+ return { numAffected: numReplaced, upsert: false, affectedDocuments: null };
165131
+ else {
165132
+ let updatedDocsDC = [];
165133
+ updatedDocs.forEach((doc2) => {
165134
+ updatedDocsDC.push(model.deepCopy(doc2));
165135
+ });
165136
+ if (!multi)
165137
+ updatedDocsDC = updatedDocsDC[0];
165138
+ return { numAffected: numReplaced, affectedDocuments: updatedDocsDC, upsert: false };
165139
+ }
165140
+ }
165141
+ update(query, update3, options8, callback) {
165142
+ if (typeof options8 === "function") {
165143
+ callback = options8;
165144
+ options8 = {};
165145
+ }
165146
+ const _callback = (err, res = {}) => {
165147
+ if (callback)
165148
+ callback(err, res.numAffected, res.affectedDocuments, res.upsert);
165149
+ };
165150
+ callbackify5((query2, update4, options9) => this.updateAsync(query2, update4, options9))(query, update3, options8, _callback);
165151
+ }
165152
+ updateAsync(query, update3, options8 = {}) {
165153
+ return this.executor.pushAsync(() => this._updateAsync(query, update3, options8));
165154
+ }
165155
+ async _removeAsync(query, options8 = {}) {
165156
+ const multi = options8.multi !== undefined ? options8.multi : false;
165157
+ const candidates = await this._getCandidatesAsync(query, true);
165158
+ const removedDocs = [];
165159
+ let numRemoved = 0;
165160
+ candidates.forEach((d5) => {
165161
+ if (model.match(d5, query) && (multi || numRemoved === 0)) {
165162
+ numRemoved += 1;
165163
+ removedDocs.push({ $$deleted: true, _id: d5._id });
165164
+ this._removeFromIndexes(d5);
165165
+ }
165166
+ });
165167
+ await this.persistence.persistNewStateAsync(removedDocs);
165168
+ return numRemoved;
165169
+ }
165170
+ remove(query, options8, cb2) {
165171
+ if (typeof options8 === "function") {
165172
+ cb2 = options8;
165173
+ options8 = {};
165174
+ }
165175
+ const callback = cb2 || (() => {});
165176
+ callbackify5((query2, options9) => this.removeAsync(query2, options9))(query, options8, callback);
165177
+ }
165178
+ removeAsync(query, options8 = {}) {
165179
+ return this.executor.pushAsync(() => this._removeAsync(query, options8));
165180
+ }
165181
+ }
165182
+ module.exports = Datastore;
165183
+ });
165184
+
165185
+ // node_modules/@seald-io/nedb/index.js
165186
+ var require_nedb = __commonJS((exports, module) => {
165187
+ var Datastore = require_datastore();
165188
+ module.exports = Datastore;
165189
+ });
165190
+
162730
165191
  // node_modules/@vercel/detect-agent/dist/index.js
162731
165192
  var require_dist3 = __commonJS((exports, module) => {
162732
165193
  var __defProp4 = Object.defineProperty;
@@ -178341,7 +180802,7 @@ var ProjectConfigSchema = exports_external.object({
178341
180802
  agentsDir: exports_external.string().optional().default("agents"),
178342
180803
  connectorsDir: exports_external.string().optional().default("connectors")
178343
180804
  });
178344
- var AppConfigFileSchema = exports_external.object({
180805
+ var AppConfigSchema = exports_external.object({
178345
180806
  id: exports_external.string().min(1, "id cannot be empty")
178346
180807
  });
178347
180808
  var CreateProjectResponseSchema = exports_external.looseObject({
@@ -178370,8 +180831,7 @@ var TestOverridesSchema = exports_external.object({
178370
180831
  // src/core/config.ts
178371
180832
  var __dirname2 = dirname(fileURLToPath(import.meta.url));
178372
180833
  function getBase44GlobalDir() {
178373
- const home = process.env.HOME || homedir();
178374
- return join(home, ".base44");
180834
+ return join(homedir(), ".base44");
178375
180835
  }
178376
180836
  function getAuthFilePath() {
178377
180837
  return join(getBase44GlobalDir(), "auth", "auth.json");
@@ -184400,9 +186860,9 @@ async function downloadProject(projectId, projectPath) {
184400
186860
  } catch (error48) {
184401
186861
  throw await ApiError.fromHttpError(error48, "downloading project");
184402
186862
  }
184403
- const buffer = Buffer.from(await response.arrayBuffer());
186863
+ const nodeStream = Readable.fromWeb(response.body);
184404
186864
  await makeDirectory(projectPath);
184405
- await pipeline(Readable.from(buffer), extract({ cwd: projectPath }));
186865
+ await pipeline(nodeStream, extract({ cwd: projectPath }));
184406
186866
  }
184407
186867
  // node_modules/globby/index.js
184408
186868
  import process4 from "node:process";
@@ -186160,20 +188620,21 @@ async function readProjectConfig(projectRoot) {
186160
188620
  }
186161
188621
 
186162
188622
  // src/core/project/app-config.ts
186163
- var _current = null;
186164
- async function withAppConfig(config6, fn) {
186165
- const prev = _current;
186166
- _current = config6;
186167
- try {
186168
- return await fn();
186169
- } finally {
186170
- _current = prev;
188623
+ var cache2 = null;
188624
+ function loadFromTestOverrides() {
188625
+ const appConfig = getTestOverrides()?.appConfig;
188626
+ if (appConfig?.id && appConfig.projectRoot) {
188627
+ cache2 = { id: appConfig.id, projectRoot: appConfig.projectRoot };
188628
+ return true;
186171
188629
  }
188630
+ return false;
186172
188631
  }
186173
- async function resolveAppConfig() {
186174
- const testOverride = getTestOverrides()?.appConfig;
186175
- if (testOverride?.id && testOverride.projectRoot) {
186176
- return { id: testOverride.id, projectRoot: testOverride.projectRoot };
188632
+ async function initAppConfig() {
188633
+ if (loadFromTestOverrides()) {
188634
+ return cache2;
188635
+ }
188636
+ if (cache2) {
188637
+ return cache2;
186177
188638
  }
186178
188639
  const projectRoot = await findProjectRoot();
186179
188640
  if (!projectRoot) {
@@ -186191,13 +188652,17 @@ async function resolveAppConfig() {
186191
188652
  ]
186192
188653
  });
186193
188654
  }
186194
- return { projectRoot: projectRoot.root, id: config6.id };
188655
+ cache2 = { projectRoot: projectRoot.root, id: config6.id };
188656
+ return cache2;
186195
188657
  }
186196
188658
  function getAppConfig() {
186197
- if (!_current) {
188659
+ if (!cache2) {
186198
188660
  throw new ConfigInvalidError("App config not initialized. Ensure the command uses requireAppConfig option.");
186199
188661
  }
186200
- return _current;
188662
+ return cache2;
188663
+ }
188664
+ function setAppConfig(config6) {
188665
+ cache2 = config6;
186201
188666
  }
186202
188667
  function generateAppConfigContent(id) {
186203
188668
  return `// Base44 App Configuration
@@ -186231,7 +188696,7 @@ async function readAppConfig(projectRoot) {
186231
188696
  return null;
186232
188697
  }
186233
188698
  const parsed = await readJsonFile(configPath);
186234
- const result = AppConfigFileSchema.safeParse(parsed);
188699
+ const result = AppConfigSchema.safeParse(parsed);
186235
188700
  if (!result.success) {
186236
188701
  throw new SchemaValidationError("Invalid app configuration", result.error, configPath);
186237
188702
  }
@@ -193890,8 +196355,8 @@ var package_default = {
193890
196355
  clean: "rm -rf dist && mkdir -p dist",
193891
196356
  lint: "biome check src tests",
193892
196357
  "lint:fix": "biome check --write src tests",
193893
- test: "bun test",
193894
- "test:watch": "bun test --watch",
196358
+ test: "vitest run",
196359
+ "test:watch": "vitest",
193895
196360
  knip: "knip",
193896
196361
  "knip:fix": "knip --fix"
193897
196362
  },
@@ -193909,6 +196374,7 @@ var package_default = {
193909
196374
  devDependencies: {
193910
196375
  "@biomejs/biome": "^2.0.0",
193911
196376
  "@clack/prompts": "^1.0.1",
196377
+ "@seald-io/nedb": "^4.1.2",
193912
196378
  "@types/bun": "^1.2.15",
193913
196379
  "@types/common-tags": "^1.8.4",
193914
196380
  "@types/cors": "^2.8.19",
@@ -193944,6 +196410,7 @@ var package_default = {
193944
196410
  tar: "^7.5.4",
193945
196411
  "tmp-promise": "^3.0.3",
193946
196412
  typescript: "^5.7.2",
196413
+ vitest: "^4.0.16",
193947
196414
  zod: "^4.3.5"
193948
196415
  },
193949
196416
  engines: {
@@ -194020,15 +196487,11 @@ async function runCommand(commandFn, options, context) {
194020
196487
  });
194021
196488
  } catch {}
194022
196489
  }
194023
- let outroMessage;
194024
196490
  if (options?.requireAppConfig !== false) {
194025
- const appConfig = await resolveAppConfig();
194026
- context.appConfig = appConfig;
196491
+ const appConfig = await initAppConfig();
194027
196492
  context.errorReporter.setContext({ appId: appConfig.id });
194028
- ({ outroMessage } = await withAppConfig(appConfig, commandFn));
194029
- } else {
194030
- ({ outroMessage } = await commandFn());
194031
196493
  }
196494
+ const { outroMessage } = await commandFn();
194032
196495
  Le(outroMessage || "");
194033
196496
  } catch (error48) {
194034
196497
  const errorMessage = error48 instanceof Error ? error48.message : String(error48);
@@ -194063,7 +196526,8 @@ async function runTask(startMessage, operation, options) {
194063
196526
  }
194064
196527
  // src/cli/utils/urls.ts
194065
196528
  function getDashboardUrl(projectId) {
194066
- return `${getBase44ApiUrl()}/apps/${projectId}/editor/workspace/overview`;
196529
+ const id = projectId ?? getAppConfig().id;
196530
+ return `${getBase44ApiUrl()}/apps/${id}/editor/workspace/overview`;
194067
196531
  }
194068
196532
  // src/cli/commands/agents/pull.ts
194069
196533
  async function pullAgentsAction() {
@@ -194966,8 +197430,8 @@ function getConnectorsCommand(context) {
194966
197430
  }
194967
197431
 
194968
197432
  // src/cli/commands/dashboard/open.ts
194969
- async function openDashboard(isNonInteractive, appId) {
194970
- const dashboardUrl = getDashboardUrl(appId);
197433
+ async function openDashboard(isNonInteractive) {
197434
+ const dashboardUrl = getDashboardUrl();
194971
197435
  if (!isNonInteractive) {
194972
197436
  await open_default(dashboardUrl);
194973
197437
  }
@@ -194975,7 +197439,7 @@ async function openDashboard(isNonInteractive, appId) {
194975
197439
  }
194976
197440
  function getDashboardOpenCommand(context) {
194977
197441
  return new Command("open").description("Open the app dashboard in your browser").action(async () => {
194978
- await runCommand(() => openDashboard(context.isNonInteractive, context.appConfig.id), { requireAuth: true }, context);
197442
+ await runCommand(() => openDashboard(context.isNonInteractive), { requireAuth: true }, context);
194979
197443
  });
194980
197444
  }
194981
197445
 
@@ -195153,77 +197617,73 @@ async function executeCreate({
195153
197617
  successMessage: theme.colors.base44Orange("Project created successfully"),
195154
197618
  errorMessage: "Failed to create project"
195155
197619
  });
195156
- return await withAppConfig({ id: projectId, projectRoot: resolvedPath }, async () => {
195157
- const { project: project2, entities } = await readProjectConfig(resolvedPath);
195158
- let finalAppUrl;
195159
- if (entities.length > 0) {
195160
- let shouldPushEntities;
195161
- if (isInteractive) {
195162
- const result = await Re({
195163
- message: "Set up the backend data now? (This pushes the data models used by the template to Base44)"
195164
- });
195165
- shouldPushEntities = !Ct(result) && result;
195166
- } else {
195167
- shouldPushEntities = !!deploy5;
195168
- }
195169
- if (shouldPushEntities) {
195170
- await runTask(`Pushing ${entities.length} data models to Base44...`, async () => {
195171
- await pushEntities(entities);
195172
- }, {
195173
- successMessage: theme.colors.base44Orange("Data models pushed successfully"),
195174
- errorMessage: "Failed to push data models"
195175
- });
195176
- }
195177
- }
195178
- if (project2.site) {
195179
- const { installCommand, buildCommand, outputDirectory } = project2.site;
195180
- let shouldDeploy;
195181
- if (isInteractive) {
195182
- const result = await Re({
195183
- message: "Would you like to deploy the site now? (Hosted on Base44)"
195184
- });
195185
- shouldDeploy = !Ct(result) && result;
195186
- } else {
195187
- shouldDeploy = !!deploy5;
195188
- }
195189
- if (shouldDeploy && installCommand && buildCommand && outputDirectory) {
195190
- const { appUrl } = await runTask("Installing dependencies...", async (updateMessage) => {
195191
- await execa({
195192
- cwd: resolvedPath,
195193
- shell: true
195194
- })`${installCommand}`;
195195
- updateMessage("Building project...");
195196
- await execa({ cwd: resolvedPath, shell: true })`${buildCommand}`;
195197
- updateMessage("Deploying site...");
195198
- return await deploySite(join11(resolvedPath, outputDirectory));
195199
- }, {
195200
- successMessage: theme.colors.base44Orange("Site deployed successfully"),
195201
- errorMessage: "Failed to deploy site"
195202
- });
195203
- finalAppUrl = appUrl;
195204
- }
197620
+ setAppConfig({ id: projectId, projectRoot: resolvedPath });
197621
+ const { project: project2, entities } = await readProjectConfig(resolvedPath);
197622
+ let finalAppUrl;
197623
+ if (entities.length > 0) {
197624
+ let shouldPushEntities;
197625
+ if (isInteractive) {
197626
+ const result = await Re({
197627
+ message: "Set up the backend data now? (This pushes the data models used by the template to Base44)"
197628
+ });
197629
+ shouldPushEntities = !Ct(result) && result;
197630
+ } else {
197631
+ shouldPushEntities = !!deploy5;
195205
197632
  }
195206
- const shouldAddSkills = skills;
195207
- if (shouldAddSkills) {
195208
- try {
195209
- await runTask("Installing AI agent skills...", async () => {
195210
- await execa("npx", ["-y", "skills", "add", "base44/skills", "-y"], {
195211
- cwd: resolvedPath,
195212
- shell: true
195213
- });
195214
- }, {
195215
- successMessage: theme.colors.base44Orange("AI agent skills added successfully"),
195216
- errorMessage: "Failed to add AI agent skills - you can add them later with: npx skills add base44/skills"
195217
- });
195218
- } catch {}
197633
+ if (shouldPushEntities) {
197634
+ await runTask(`Pushing ${entities.length} data models to Base44...`, async () => {
197635
+ await pushEntities(entities);
197636
+ }, {
197637
+ successMessage: theme.colors.base44Orange("Data models pushed successfully"),
197638
+ errorMessage: "Failed to push data models"
197639
+ });
195219
197640
  }
195220
- R2.message(`${theme.styles.header("Project")}: ${theme.colors.base44Orange(name2)}`);
195221
- R2.message(`${theme.styles.header("Dashboard")}: ${theme.colors.links(getDashboardUrl(projectId))}`);
195222
- if (finalAppUrl) {
195223
- R2.message(`${theme.styles.header("Site")}: ${theme.colors.links(finalAppUrl)}`);
197641
+ }
197642
+ if (project2.site) {
197643
+ const { installCommand, buildCommand, outputDirectory } = project2.site;
197644
+ let shouldDeploy;
197645
+ if (isInteractive) {
197646
+ const result = await Re({
197647
+ message: "Would you like to deploy the site now? (Hosted on Base44)"
197648
+ });
197649
+ shouldDeploy = !Ct(result) && result;
197650
+ } else {
197651
+ shouldDeploy = !!deploy5;
197652
+ }
197653
+ if (shouldDeploy && installCommand && buildCommand && outputDirectory) {
197654
+ const { appUrl } = await runTask("Installing dependencies...", async (updateMessage) => {
197655
+ await execa({ cwd: resolvedPath, shell: true })`${installCommand}`;
197656
+ updateMessage("Building project...");
197657
+ await execa({ cwd: resolvedPath, shell: true })`${buildCommand}`;
197658
+ updateMessage("Deploying site...");
197659
+ return await deploySite(join11(resolvedPath, outputDirectory));
197660
+ }, {
197661
+ successMessage: theme.colors.base44Orange("Site deployed successfully"),
197662
+ errorMessage: "Failed to deploy site"
197663
+ });
197664
+ finalAppUrl = appUrl;
195224
197665
  }
195225
- return { outroMessage: "Your project is set up and ready to use" };
195226
- });
197666
+ }
197667
+ const shouldAddSkills = skills;
197668
+ if (shouldAddSkills) {
197669
+ try {
197670
+ await runTask("Installing AI agent skills...", async () => {
197671
+ await execa("npx", ["-y", "skills", "add", "base44/skills", "-y"], {
197672
+ cwd: resolvedPath,
197673
+ shell: true
197674
+ });
197675
+ }, {
197676
+ successMessage: theme.colors.base44Orange("AI agent skills added successfully"),
197677
+ errorMessage: "Failed to add AI agent skills - you can add them later with: npx skills add base44/skills"
197678
+ });
197679
+ } catch {}
197680
+ }
197681
+ R2.message(`${theme.styles.header("Project")}: ${theme.colors.base44Orange(name2)}`);
197682
+ R2.message(`${theme.styles.header("Dashboard")}: ${theme.colors.links(getDashboardUrl(projectId))}`);
197683
+ if (finalAppUrl) {
197684
+ R2.message(`${theme.styles.header("Site")}: ${theme.colors.links(finalAppUrl)}`);
197685
+ }
197686
+ return { outroMessage: "Your project is set up and ready to use" };
195227
197687
  }
195228
197688
  function getCreateCommand(context) {
195229
197689
  return new Command("create").description("Create a new Base44 project").addArgument(new Argument("name", "Project name").argOptional()).option("-p, --path <path>", "Path where to create the project").option("-t, --template <id>", "Template ID (e.g., backend-only, backend-and-client)").option("--deploy", "Build and deploy the site").option("--no-skills", "Skip AI agent skills installation").hook("preAction", validateNonInteractiveFlags).action(async (name2, options) => {
@@ -195292,7 +197752,7 @@ ${summaryLines.join(`
195292
197752
  R2.info("Some connectors still require authorization. Run 'base44 connectors push' or open the links above in your browser.");
195293
197753
  }
195294
197754
  }
195295
- R2.message(`${theme.styles.header("Dashboard")}: ${theme.colors.links(getDashboardUrl(options.appId))}`);
197755
+ R2.message(`${theme.styles.header("Dashboard")}: ${theme.colors.links(getDashboardUrl())}`);
195296
197756
  if (result.appUrl) {
195297
197757
  R2.message(`${theme.styles.header("App URL")}: ${theme.colors.links(result.appUrl)}`);
195298
197758
  }
@@ -195302,8 +197762,7 @@ function getDeployCommand(context) {
195302
197762
  return new Command("deploy").description("Deploy all project resources (entities, functions, agents, connectors, and site)").option("-y, --yes", "Skip confirmation prompt").action(async (options) => {
195303
197763
  await runCommand(() => deployAction({
195304
197764
  ...options,
195305
- isNonInteractive: context.isNonInteractive,
195306
- appId: context.appConfig.id
197765
+ isNonInteractive: context.isNonInteractive
195307
197766
  }), { requireAuth: true }, context);
195308
197767
  });
195309
197768
  }
@@ -195426,6 +197885,7 @@ async function link(options) {
195426
197885
  }
195427
197886
  await runTask("Linking project...", async () => {
195428
197887
  await writeAppConfig(projectRoot.root, projectId);
197888
+ setAppConfig({ id: projectId, projectRoot: projectRoot.root });
195429
197889
  }, {
195430
197890
  successMessage: "Project linked successfully",
195431
197891
  errorMessage: "Failed to link project"
@@ -195441,6 +197901,7 @@ async function link(options) {
195441
197901
  errorMessage: "Failed to create project"
195442
197902
  });
195443
197903
  await writeAppConfig(projectRoot.root, projectId);
197904
+ setAppConfig({ id: projectId, projectRoot: projectRoot.root });
195444
197905
  finalProjectId = projectId;
195445
197906
  }
195446
197907
  R2.message(`${theme.styles.header("Dashboard")}: ${theme.colors.links(getDashboardUrl(finalProjectId))}`);
@@ -195646,7 +198107,7 @@ import { dirname as dirname12, join as join16 } from "node:path";
195646
198107
 
195647
198108
  // src/cli/dev/dev-server/main.ts
195648
198109
  var import_cors = __toESM(require_lib4(), 1);
195649
- var import_express2 = __toESM(require_express(), 1);
198110
+ var import_express3 = __toESM(require_express(), 1);
195650
198111
 
195651
198112
  // node_modules/get-port/index.js
195652
198113
  import net from "node:net";
@@ -195980,14 +198441,278 @@ function createFunctionRouter(manager, logger) {
195980
198441
  return router;
195981
198442
  }
195982
198443
 
198444
+ // src/cli/dev/dev-server/database.ts
198445
+ var import_nedb = __toESM(require_nedb(), 1);
198446
+
198447
+ class Database {
198448
+ collections;
198449
+ constructor(entities) {
198450
+ this.collections = new Map;
198451
+ for (const entity2 of entities) {
198452
+ this.collections.set(entity2.name, new import_nedb.default);
198453
+ }
198454
+ }
198455
+ getCollection(name2) {
198456
+ return this.collections.get(name2);
198457
+ }
198458
+ hasCollection(name2) {
198459
+ return this.collections.has(name2);
198460
+ }
198461
+ getEntityNames() {
198462
+ return [...this.collections.keys()];
198463
+ }
198464
+ }
198465
+
198466
+ // src/cli/dev/dev-server/routes/entities.ts
198467
+ var import_express2 = __toESM(require_express(), 1);
198468
+
198469
+ // node_modules/nanoid/index.js
198470
+ import { webcrypto as crypto } from "node:crypto";
198471
+
198472
+ // node_modules/nanoid/url-alphabet/index.js
198473
+ var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
198474
+
198475
+ // node_modules/nanoid/index.js
198476
+ var POOL_SIZE_MULTIPLIER = 128;
198477
+ var pool;
198478
+ var poolOffset;
198479
+ function fillPool(bytes) {
198480
+ if (!pool || pool.length < bytes) {
198481
+ pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
198482
+ crypto.getRandomValues(pool);
198483
+ poolOffset = 0;
198484
+ } else if (poolOffset + bytes > pool.length) {
198485
+ crypto.getRandomValues(pool);
198486
+ poolOffset = 0;
198487
+ }
198488
+ poolOffset += bytes;
198489
+ }
198490
+ function nanoid3(size = 21) {
198491
+ fillPool(size |= 0);
198492
+ let id2 = "";
198493
+ for (let i5 = poolOffset - size;i5 < poolOffset; i5++) {
198494
+ id2 += urlAlphabet[pool[i5] & 63];
198495
+ }
198496
+ return id2;
198497
+ }
198498
+
198499
+ // src/cli/dev/dev-server/routes/entities.ts
198500
+ function parseSort(sort) {
198501
+ if (!sort) {
198502
+ return;
198503
+ }
198504
+ if (sort.startsWith("-")) {
198505
+ return { [sort.slice(1)]: -1 };
198506
+ }
198507
+ return { [sort]: 1 };
198508
+ }
198509
+ function parseFields(fields) {
198510
+ if (!fields) {
198511
+ return;
198512
+ }
198513
+ const projection = {};
198514
+ for (const field of fields.split(",")) {
198515
+ const trimmed = field.trim();
198516
+ if (trimmed) {
198517
+ projection[trimmed] = 1;
198518
+ }
198519
+ }
198520
+ return Object.keys(projection).length > 0 ? projection : undefined;
198521
+ }
198522
+ function createEntityRoutes(db2, logger, remoteProxy) {
198523
+ const router = import_express2.Router({ mergeParams: true });
198524
+ const parseBody = import_express2.json();
198525
+ router.get("/User/me", (req, res, next) => {
198526
+ req.url = req.originalUrl;
198527
+ remoteProxy(req, res, next);
198528
+ });
198529
+ router.get("/:entityName/:id", async (req, res) => {
198530
+ const { entityName, id: id2 } = req.params;
198531
+ const collection = db2.getCollection(entityName);
198532
+ if (!collection) {
198533
+ res.status(404).json({ error: `Entity "${entityName}" not found` });
198534
+ return;
198535
+ }
198536
+ try {
198537
+ const doc2 = await collection.findOneAsync({ id: id2 });
198538
+ if (!doc2) {
198539
+ res.status(404).json({ error: `Record with id "${id2}" not found` });
198540
+ return;
198541
+ }
198542
+ res.json(doc2);
198543
+ } catch (error48) {
198544
+ logger.error(`Error in GET /${entityName}/${id2}:`, error48);
198545
+ res.status(500).json({ error: "Internal server error" });
198546
+ }
198547
+ });
198548
+ router.get("/:entityName", async (req, res) => {
198549
+ const { entityName } = req.params;
198550
+ const collection = db2.getCollection(entityName);
198551
+ if (!collection) {
198552
+ res.status(404).json({ error: `Entity "${entityName}" not found` });
198553
+ return;
198554
+ }
198555
+ try {
198556
+ const { sort, limit, skip: skip2, fields, q: q13 } = req.query;
198557
+ let query = {};
198558
+ if (q13 && typeof q13 === "string") {
198559
+ try {
198560
+ query = JSON.parse(q13);
198561
+ } catch {
198562
+ res.status(400).json({ error: "Invalid query parameter 'q'" });
198563
+ return;
198564
+ }
198565
+ }
198566
+ let cursor3 = collection.findAsync(query);
198567
+ const sortObj = parseSort(sort);
198568
+ if (sortObj) {
198569
+ cursor3 = cursor3.sort(sortObj);
198570
+ }
198571
+ if (skip2) {
198572
+ const skipNum = parseInt(skip2, 10);
198573
+ if (!Number.isNaN(skipNum)) {
198574
+ cursor3 = cursor3.skip(skipNum);
198575
+ }
198576
+ }
198577
+ if (limit) {
198578
+ const limitNum = parseInt(limit, 10);
198579
+ if (!Number.isNaN(limitNum)) {
198580
+ cursor3 = cursor3.limit(limitNum);
198581
+ }
198582
+ }
198583
+ const projection = parseFields(fields);
198584
+ if (projection) {
198585
+ cursor3 = cursor3.projection(projection);
198586
+ }
198587
+ const docs = await cursor3;
198588
+ res.json(docs);
198589
+ } catch (error48) {
198590
+ logger.error(`Error in GET /${entityName}:`, error48);
198591
+ res.status(500).json({ error: "Internal server error" });
198592
+ }
198593
+ });
198594
+ router.post("/:entityName", parseBody, async (req, res) => {
198595
+ const { entityName } = req.params;
198596
+ const collection = db2.getCollection(entityName);
198597
+ if (!collection) {
198598
+ res.status(404).json({ error: `Entity "${entityName}" not found` });
198599
+ return;
198600
+ }
198601
+ try {
198602
+ const now = new Date().toISOString();
198603
+ const record2 = {
198604
+ ...req.body,
198605
+ id: nanoid3(),
198606
+ created_date: now,
198607
+ updated_date: now
198608
+ };
198609
+ const inserted = await collection.insertAsync(record2);
198610
+ res.status(201).json(inserted);
198611
+ } catch (error48) {
198612
+ logger.error(`Error in POST /${entityName}:`, error48);
198613
+ res.status(500).json({ error: "Internal server error" });
198614
+ }
198615
+ });
198616
+ router.post("/:entityName/bulk", parseBody, async (req, res) => {
198617
+ const { entityName } = req.params;
198618
+ const collection = db2.getCollection(entityName);
198619
+ if (!collection) {
198620
+ res.status(404).json({ error: `Entity "${entityName}" not found` });
198621
+ return;
198622
+ }
198623
+ if (!Array.isArray(req.body)) {
198624
+ res.status(400).json({ error: "Request body must be an array" });
198625
+ return;
198626
+ }
198627
+ try {
198628
+ const now = new Date().toISOString();
198629
+ const records = req.body.map((item) => ({
198630
+ ...item,
198631
+ id: nanoid3(),
198632
+ created_date: now,
198633
+ updated_date: now
198634
+ }));
198635
+ const inserted = [];
198636
+ for (const record2 of records) {
198637
+ const doc2 = await collection.insertAsync(record2);
198638
+ inserted.push(doc2);
198639
+ }
198640
+ res.status(201).json(inserted);
198641
+ } catch (error48) {
198642
+ logger.error(`Error in POST /${entityName}/bulk:`, error48);
198643
+ res.status(500).json({ error: "Internal server error" });
198644
+ }
198645
+ });
198646
+ router.put("/:entityName/:id", parseBody, async (req, res) => {
198647
+ const { entityName, id: id2 } = req.params;
198648
+ const collection = db2.getCollection(entityName);
198649
+ if (!collection) {
198650
+ res.status(404).json({ error: `Entity "${entityName}" not found` });
198651
+ return;
198652
+ }
198653
+ try {
198654
+ const updateData = {
198655
+ ...req.body,
198656
+ updated_date: new Date().toISOString()
198657
+ };
198658
+ const result = await collection.updateAsync({ id: id2 }, { $set: updateData }, { returnUpdatedDocs: false });
198659
+ if (result.numAffected === 0) {
198660
+ res.status(404).json({ error: `Record with id "${id2}" not found` });
198661
+ return;
198662
+ }
198663
+ const updated = await collection.findOneAsync({ id: id2 });
198664
+ res.json(updated);
198665
+ } catch (error48) {
198666
+ logger.error(`Error in PUT /${entityName}/${id2}:`, error48);
198667
+ res.status(500).json({ error: "Internal server error" });
198668
+ }
198669
+ });
198670
+ router.delete("/:entityName/:id", async (req, res) => {
198671
+ const { entityName, id: id2 } = req.params;
198672
+ const collection = db2.getCollection(entityName);
198673
+ if (!collection) {
198674
+ res.status(404).json({ error: `Entity "${entityName}" not found` });
198675
+ return;
198676
+ }
198677
+ try {
198678
+ const numRemoved = await collection.removeAsync({ id: id2 }, { multi: false });
198679
+ if (numRemoved === 0) {
198680
+ res.status(404).json({ error: `Record with id "${id2}" not found` });
198681
+ return;
198682
+ }
198683
+ res.json({ deleted: numRemoved });
198684
+ } catch (error48) {
198685
+ logger.error(`Error in DELETE /${entityName}/${id2}:`, error48);
198686
+ res.status(500).json({ error: "Internal server error" });
198687
+ }
198688
+ });
198689
+ router.delete("/:entityName", parseBody, async (req, res) => {
198690
+ const { entityName } = req.params;
198691
+ const collection = db2.getCollection(entityName);
198692
+ if (!collection) {
198693
+ res.status(404).json({ error: `Entity "${entityName}" not found` });
198694
+ return;
198695
+ }
198696
+ try {
198697
+ const query = req.body || {};
198698
+ const numRemoved = await collection.removeAsync(query, { multi: true });
198699
+ res.json({ deleted: numRemoved });
198700
+ } catch (error48) {
198701
+ logger.error(`Error in DELETE /${entityName}:`, error48);
198702
+ res.status(500).json({ error: "Internal server error" });
198703
+ }
198704
+ });
198705
+ return router;
198706
+ }
198707
+
195983
198708
  // src/cli/dev/dev-server/main.ts
195984
198709
  var DEFAULT_PORT = 4400;
195985
198710
  var BASE44_APP_URL = "https://base44.app";
195986
198711
  async function createDevServer(options8) {
195987
198712
  const { port: userPort } = options8;
195988
198713
  const port = userPort ?? await getPorts({ port: DEFAULT_PORT });
195989
- const { functions } = await options8.loadResources();
195990
- const app = import_express2.default();
198714
+ const { functions, entities } = await options8.loadResources();
198715
+ const app = import_express3.default();
195991
198716
  const remoteProxy = import_http_proxy_middleware2.createProxyMiddleware({
195992
198717
  target: BASE44_APP_URL,
195993
198718
  changeOrigin: true
@@ -196011,6 +198736,9 @@ async function createDevServer(options8) {
196011
198736
  const functionRoutes = createFunctionRouter(functionManager, devLogger);
196012
198737
  app.use("/api/apps/:appId/functions", functionRoutes);
196013
198738
  }
198739
+ const db2 = new Database(entities);
198740
+ const entityRoutes = createEntityRoutes(db2, devLogger, remoteProxy);
198741
+ app.use("/api/apps/:appId/entities", entityRoutes);
196014
198742
  app.use((req, res, next) => {
196015
198743
  return remoteProxy(req, res, next);
196016
198744
  });
@@ -196046,8 +198774,11 @@ async function devAction(options8) {
196046
198774
  loadResources: async () => {
196047
198775
  const { project: project2 } = await readProjectConfig();
196048
198776
  const configDir = dirname12(project2.configPath);
196049
- const functions = await functionResource.readAll(join16(configDir, project2.functionsDir));
196050
- return { functions };
198777
+ const [functions, entities] = await Promise.all([
198778
+ functionResource.readAll(join16(configDir, project2.functionsDir)),
198779
+ entityResource.readAll(join16(configDir, project2.entitiesDir))
198780
+ ]);
198781
+ return { functions, entities };
196051
198782
  }
196052
198783
  });
196053
198784
  return {
@@ -196108,51 +198839,42 @@ async function eject(options8) {
196108
198839
  throw new CLIExitError(0);
196109
198840
  }
196110
198841
  const resolvedPath = resolve5(selectedPath);
196111
- const newProjectId = await runTask("Downloading your project's code...", async (updateMessage) => {
198842
+ await runTask("Downloading your project's code...", async (updateMessage) => {
196112
198843
  await createProjectFilesForExistingProject({
196113
198844
  projectId,
196114
198845
  projectPath: resolvedPath
196115
198846
  });
196116
198847
  updateMessage("Creating a new project...");
196117
198848
  const newProjectName = `${selectedProject.name} Copy`;
196118
- const { projectId: createdId } = await createProject(newProjectName, selectedProject.userDescription ?? undefined);
198849
+ const { projectId: newProjectId } = await createProject(newProjectName, selectedProject.userDescription ?? undefined);
196119
198850
  updateMessage("Linking the project...");
196120
- await writeAppConfig(resolvedPath, createdId);
196121
- await writeFile(`${resolvedPath}/.env.local`, `VITE_BASE44_APP_ID=${createdId}`);
196122
- return createdId;
198851
+ await writeAppConfig(resolvedPath, newProjectId);
198852
+ await writeFile(`${resolvedPath}/.env.local`, `VITE_BASE44_APP_ID=${newProjectId}`);
198853
+ setAppConfig({ id: newProjectId, projectRoot: resolvedPath });
196123
198854
  }, {
196124
198855
  successMessage: theme.colors.base44Orange("Project pulled successfully"),
196125
198856
  errorMessage: "Failed to pull project"
196126
198857
  });
196127
- return await withAppConfig({ id: newProjectId, projectRoot: resolvedPath }, async () => {
196128
- const { project: project2 } = await readProjectConfig(resolvedPath);
196129
- const installCommand = project2.site?.installCommand;
196130
- const buildCommand = project2.site?.buildCommand;
196131
- if (installCommand && buildCommand) {
196132
- const shouldDeploy = options8.yes ? true : await Re({
196133
- message: "Would you like to deploy your project now?"
198858
+ const { project: project2 } = await readProjectConfig(resolvedPath);
198859
+ const installCommand = project2.site?.installCommand;
198860
+ const buildCommand = project2.site?.buildCommand;
198861
+ if (installCommand && buildCommand) {
198862
+ const shouldDeploy = options8.yes ? true : await Re({
198863
+ message: "Would you like to deploy your project now?"
198864
+ });
198865
+ if (!Ct(shouldDeploy) && shouldDeploy) {
198866
+ await runTask("Installing dependencies...", async (updateMessage) => {
198867
+ await execa({ cwd: resolvedPath, shell: true })`${installCommand}`;
198868
+ updateMessage("Building project...");
198869
+ await execa({ cwd: resolvedPath, shell: true })`${buildCommand}`;
198870
+ }, {
198871
+ successMessage: theme.colors.base44Orange("Project built successfully"),
198872
+ errorMessage: "Failed to build project"
196134
198873
  });
196135
- if (!Ct(shouldDeploy) && shouldDeploy) {
196136
- await runTask("Installing dependencies...", async (updateMessage) => {
196137
- await execa({
196138
- cwd: resolvedPath,
196139
- shell: true
196140
- })`${installCommand}`;
196141
- updateMessage("Building project...");
196142
- await execa({ cwd: resolvedPath, shell: true })`${buildCommand}`;
196143
- }, {
196144
- successMessage: theme.colors.base44Orange("Project built successfully"),
196145
- errorMessage: "Failed to build project"
196146
- });
196147
- await deployAction({
196148
- yes: true,
196149
- projectRoot: resolvedPath,
196150
- appId: newProjectId
196151
- });
196152
- }
198874
+ await deployAction({ yes: true, projectRoot: resolvedPath });
196153
198875
  }
196154
- return { outroMessage: "Your new project is set and ready to use" };
196155
- });
198876
+ }
198877
+ return { outroMessage: "Your new project is set and ready to use" };
196156
198878
  }
196157
198879
  function getEjectCommand(context) {
196158
198880
  return new Command("eject").description("Download the code for an existing Base44 project").option("-p, --path <path>", "Path where to write the project").option("--project-id <id>", "Project ID to eject (skips interactive selection)").option("-y, --yes", "Skip confirmation prompts").action(async (options8) => {
@@ -196189,36 +198911,6 @@ function createProgram(context) {
196189
198911
  var import_detect_agent = __toESM(require_dist3(), 1);
196190
198912
  import { release, type } from "node:os";
196191
198913
 
196192
- // node_modules/nanoid/index.js
196193
- import { webcrypto as crypto } from "node:crypto";
196194
-
196195
- // node_modules/nanoid/url-alphabet/index.js
196196
- var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
196197
-
196198
- // node_modules/nanoid/index.js
196199
- var POOL_SIZE_MULTIPLIER = 128;
196200
- var pool;
196201
- var poolOffset;
196202
- function fillPool(bytes) {
196203
- if (!pool || pool.length < bytes) {
196204
- pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
196205
- crypto.getRandomValues(pool);
196206
- poolOffset = 0;
196207
- } else if (poolOffset + bytes > pool.length) {
196208
- crypto.getRandomValues(pool);
196209
- poolOffset = 0;
196210
- }
196211
- poolOffset += bytes;
196212
- }
196213
- function nanoid3(size = 21) {
196214
- fillPool(size |= 0);
196215
- let id2 = "";
196216
- for (let i5 = poolOffset - size;i5 < poolOffset; i5++) {
196217
- id2 += urlAlphabet[pool[i5] & 63];
196218
- }
196219
- return id2;
196220
- }
196221
-
196222
198914
  // node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
196223
198915
  import { dirname as dirname13, posix, sep } from "path";
196224
198916
  function createModulerModifier() {
@@ -198497,8 +201189,8 @@ async function addSourceContext(frames) {
198497
201189
  const ranges = makeLineReaderRanges(filesToLineRanges);
198498
201190
  if (ranges.every((r5) => rangeExistsInContentCache(file2, r5)))
198499
201191
  continue;
198500
- const cache3 = emplace(LRU_FILE_CONTENTS_CACHE, file2, {});
198501
- readlinePromises.push(getContextLinesFromFile(file2, ranges, cache3));
201192
+ const cache4 = emplace(LRU_FILE_CONTENTS_CACHE, file2, {});
201193
+ readlinePromises.push(getContextLinesFromFile(file2, ranges, cache4));
198502
201194
  }
198503
201195
  await Promise.all(readlinePromises).catch(() => {});
198504
201196
  if (frames && frames.length > 0)
@@ -198556,10 +201248,10 @@ function getContextLinesFromFile(path18, ranges, output) {
198556
201248
  });
198557
201249
  });
198558
201250
  }
198559
- function addSourceContextToFrames(frames, cache3) {
201251
+ function addSourceContextToFrames(frames, cache4) {
198560
201252
  for (const frame of frames)
198561
201253
  if (frame.filename && frame.context_line === undefined && typeof frame.lineno == "number") {
198562
- const contents = cache3.get(frame.filename);
201254
+ const contents = cache4.get(frame.filename);
198563
201255
  if (contents === undefined)
198564
201256
  continue;
198565
201257
  addContextToFrame(frame.lineno, frame, contents);
@@ -200446,4 +203138,4 @@ export {
200446
203138
  CLIExitError
200447
203139
  };
200448
203140
 
200449
- //# debugId=4720A2778B079F1264756E2164756E21
203141
+ //# debugId=580F767BBE8B23BE64756E2164756E21