@orion-js/services 4.0.0-next.5 → 4.0.0-next.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -4,9 +4,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __getProtoOf = Object.getPrototypeOf;
6
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __commonJS = (cb, mod) => function __require() {
8
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
- };
10
7
  var __export = (target, all) => {
11
8
  for (var name in all)
12
9
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -29,384 +26,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
29
26
  ));
30
27
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
28
 
32
- // ../../node_modules/.pnpm/object-hash@2.2.0/node_modules/object-hash/index.js
33
- var require_object_hash = __commonJS({
34
- "../../node_modules/.pnpm/object-hash@2.2.0/node_modules/object-hash/index.js"(exports2, module2) {
35
- "use strict";
36
- var crypto2 = require("crypto");
37
- exports2 = module2.exports = objectHash;
38
- function objectHash(object, options) {
39
- options = applyDefaults(object, options);
40
- return hash2(object, options);
41
- }
42
- exports2.sha1 = function(object) {
43
- return objectHash(object);
44
- };
45
- exports2.keys = function(object) {
46
- return objectHash(object, { excludeValues: true, algorithm: "sha1", encoding: "hex" });
47
- };
48
- exports2.MD5 = function(object) {
49
- return objectHash(object, { algorithm: "md5", encoding: "hex" });
50
- };
51
- exports2.keysMD5 = function(object) {
52
- return objectHash(object, { algorithm: "md5", encoding: "hex", excludeValues: true });
53
- };
54
- var hashes = crypto2.getHashes ? crypto2.getHashes().slice() : ["sha1", "md5"];
55
- hashes.push("passthrough");
56
- var encodings = ["buffer", "hex", "binary", "base64"];
57
- function applyDefaults(object, sourceOptions) {
58
- sourceOptions = sourceOptions || {};
59
- var options = {};
60
- options.algorithm = sourceOptions.algorithm || "sha1";
61
- options.encoding = sourceOptions.encoding || "hex";
62
- options.excludeValues = sourceOptions.excludeValues ? true : false;
63
- options.algorithm = options.algorithm.toLowerCase();
64
- options.encoding = options.encoding.toLowerCase();
65
- options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true;
66
- options.respectType = sourceOptions.respectType === false ? false : true;
67
- options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true;
68
- options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true;
69
- options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true;
70
- options.unorderedSets = sourceOptions.unorderedSets === false ? false : true;
71
- options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true;
72
- options.replacer = sourceOptions.replacer || void 0;
73
- options.excludeKeys = sourceOptions.excludeKeys || void 0;
74
- if (typeof object === "undefined") {
75
- throw new Error("Object argument required.");
76
- }
77
- for (var i = 0; i < hashes.length; ++i) {
78
- if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) {
79
- options.algorithm = hashes[i];
80
- }
81
- }
82
- if (hashes.indexOf(options.algorithm) === -1) {
83
- throw new Error('Algorithm "' + options.algorithm + '" not supported. supported values: ' + hashes.join(", "));
84
- }
85
- if (encodings.indexOf(options.encoding) === -1 && options.algorithm !== "passthrough") {
86
- throw new Error('Encoding "' + options.encoding + '" not supported. supported values: ' + encodings.join(", "));
87
- }
88
- return options;
89
- }
90
- function isNativeFunction(f) {
91
- if (typeof f !== "function") {
92
- return false;
93
- }
94
- var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i;
95
- return exp.exec(Function.prototype.toString.call(f)) != null;
96
- }
97
- function hash2(object, options) {
98
- var hashingStream;
99
- if (options.algorithm !== "passthrough") {
100
- hashingStream = crypto2.createHash(options.algorithm);
101
- } else {
102
- hashingStream = new PassThrough();
103
- }
104
- if (typeof hashingStream.write === "undefined") {
105
- hashingStream.write = hashingStream.update;
106
- hashingStream.end = hashingStream.update;
107
- }
108
- var hasher = typeHasher(options, hashingStream);
109
- hasher.dispatch(object);
110
- if (!hashingStream.update) {
111
- hashingStream.end("");
112
- }
113
- if (hashingStream.digest) {
114
- return hashingStream.digest(options.encoding === "buffer" ? void 0 : options.encoding);
115
- }
116
- var buf = hashingStream.read();
117
- if (options.encoding === "buffer") {
118
- return buf;
119
- }
120
- return buf.toString(options.encoding);
121
- }
122
- exports2.writeToStream = function(object, options, stream) {
123
- if (typeof stream === "undefined") {
124
- stream = options;
125
- options = {};
126
- }
127
- options = applyDefaults(object, options);
128
- return typeHasher(options, stream).dispatch(object);
129
- };
130
- function typeHasher(options, writeTo, context) {
131
- context = context || [];
132
- var write = function(str) {
133
- if (writeTo.update) {
134
- return writeTo.update(str, "utf8");
135
- } else {
136
- return writeTo.write(str, "utf8");
137
- }
138
- };
139
- return {
140
- dispatch: function(value) {
141
- if (options.replacer) {
142
- value = options.replacer(value);
143
- }
144
- var type = typeof value;
145
- if (value === null) {
146
- type = "null";
147
- }
148
- return this["_" + type](value);
149
- },
150
- _object: function(object) {
151
- var pattern = /\[object (.*)\]/i;
152
- var objString = Object.prototype.toString.call(object);
153
- var objType = pattern.exec(objString);
154
- if (!objType) {
155
- objType = "unknown:[" + objString + "]";
156
- } else {
157
- objType = objType[1];
158
- }
159
- objType = objType.toLowerCase();
160
- var objectNumber = null;
161
- if ((objectNumber = context.indexOf(object)) >= 0) {
162
- return this.dispatch("[CIRCULAR:" + objectNumber + "]");
163
- } else {
164
- context.push(object);
165
- }
166
- if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) {
167
- write("buffer:");
168
- return write(object);
169
- }
170
- if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") {
171
- if (this["_" + objType]) {
172
- this["_" + objType](object);
173
- } else if (options.ignoreUnknown) {
174
- return write("[" + objType + "]");
175
- } else {
176
- throw new Error('Unknown object type "' + objType + '"');
177
- }
178
- } else {
179
- var keys = Object.keys(object);
180
- if (options.unorderedObjects) {
181
- keys = keys.sort();
182
- }
183
- if (options.respectType !== false && !isNativeFunction(object)) {
184
- keys.splice(0, 0, "prototype", "__proto__", "constructor");
185
- }
186
- if (options.excludeKeys) {
187
- keys = keys.filter(function(key) {
188
- return !options.excludeKeys(key);
189
- });
190
- }
191
- write("object:" + keys.length + ":");
192
- var self = this;
193
- return keys.forEach(function(key) {
194
- self.dispatch(key);
195
- write(":");
196
- if (!options.excludeValues) {
197
- self.dispatch(object[key]);
198
- }
199
- write(",");
200
- });
201
- }
202
- },
203
- _array: function(arr, unordered) {
204
- unordered = typeof unordered !== "undefined" ? unordered : options.unorderedArrays !== false;
205
- var self = this;
206
- write("array:" + arr.length + ":");
207
- if (!unordered || arr.length <= 1) {
208
- return arr.forEach(function(entry) {
209
- return self.dispatch(entry);
210
- });
211
- }
212
- var contextAdditions = [];
213
- var entries = arr.map(function(entry) {
214
- var strm = new PassThrough();
215
- var localContext = context.slice();
216
- var hasher = typeHasher(options, strm, localContext);
217
- hasher.dispatch(entry);
218
- contextAdditions = contextAdditions.concat(localContext.slice(context.length));
219
- return strm.read().toString();
220
- });
221
- context = context.concat(contextAdditions);
222
- entries.sort();
223
- return this._array(entries, false);
224
- },
225
- _date: function(date) {
226
- return write("date:" + date.toJSON());
227
- },
228
- _symbol: function(sym) {
229
- return write("symbol:" + sym.toString());
230
- },
231
- _error: function(err) {
232
- return write("error:" + err.toString());
233
- },
234
- _boolean: function(bool) {
235
- return write("bool:" + bool.toString());
236
- },
237
- _string: function(string) {
238
- write("string:" + string.length + ":");
239
- write(string.toString());
240
- },
241
- _function: function(fn) {
242
- write("fn:");
243
- if (isNativeFunction(fn)) {
244
- this.dispatch("[native]");
245
- } else {
246
- this.dispatch(fn.toString());
247
- }
248
- if (options.respectFunctionNames !== false) {
249
- this.dispatch("function-name:" + String(fn.name));
250
- }
251
- if (options.respectFunctionProperties) {
252
- this._object(fn);
253
- }
254
- },
255
- _number: function(number) {
256
- return write("number:" + number.toString());
257
- },
258
- _xml: function(xml) {
259
- return write("xml:" + xml.toString());
260
- },
261
- _null: function() {
262
- return write("Null");
263
- },
264
- _undefined: function() {
265
- return write("Undefined");
266
- },
267
- _regexp: function(regex) {
268
- return write("regex:" + regex.toString());
269
- },
270
- _uint8array: function(arr) {
271
- write("uint8array:");
272
- return this.dispatch(Array.prototype.slice.call(arr));
273
- },
274
- _uint8clampedarray: function(arr) {
275
- write("uint8clampedarray:");
276
- return this.dispatch(Array.prototype.slice.call(arr));
277
- },
278
- _int8array: function(arr) {
279
- write("uint8array:");
280
- return this.dispatch(Array.prototype.slice.call(arr));
281
- },
282
- _uint16array: function(arr) {
283
- write("uint16array:");
284
- return this.dispatch(Array.prototype.slice.call(arr));
285
- },
286
- _int16array: function(arr) {
287
- write("uint16array:");
288
- return this.dispatch(Array.prototype.slice.call(arr));
289
- },
290
- _uint32array: function(arr) {
291
- write("uint32array:");
292
- return this.dispatch(Array.prototype.slice.call(arr));
293
- },
294
- _int32array: function(arr) {
295
- write("uint32array:");
296
- return this.dispatch(Array.prototype.slice.call(arr));
297
- },
298
- _float32array: function(arr) {
299
- write("float32array:");
300
- return this.dispatch(Array.prototype.slice.call(arr));
301
- },
302
- _float64array: function(arr) {
303
- write("float64array:");
304
- return this.dispatch(Array.prototype.slice.call(arr));
305
- },
306
- _arraybuffer: function(arr) {
307
- write("arraybuffer:");
308
- return this.dispatch(new Uint8Array(arr));
309
- },
310
- _url: function(url) {
311
- return write("url:" + url.toString(), "utf8");
312
- },
313
- _map: function(map) {
314
- write("map:");
315
- var arr = Array.from(map);
316
- return this._array(arr, options.unorderedSets !== false);
317
- },
318
- _set: function(set) {
319
- write("set:");
320
- var arr = Array.from(set);
321
- return this._array(arr, options.unorderedSets !== false);
322
- },
323
- _file: function(file) {
324
- write("file:");
325
- return this.dispatch([file.name, file.size, file.type, file.lastModfied]);
326
- },
327
- _blob: function() {
328
- if (options.ignoreUnknown) {
329
- return write("[blob]");
330
- }
331
- throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n');
332
- },
333
- _domwindow: function() {
334
- return write("domwindow");
335
- },
336
- _bigint: function(number) {
337
- return write("bigint:" + number.toString());
338
- },
339
- /* Node.js standard native objects */
340
- _process: function() {
341
- return write("process");
342
- },
343
- _timer: function() {
344
- return write("timer");
345
- },
346
- _pipe: function() {
347
- return write("pipe");
348
- },
349
- _tcp: function() {
350
- return write("tcp");
351
- },
352
- _udp: function() {
353
- return write("udp");
354
- },
355
- _tty: function() {
356
- return write("tty");
357
- },
358
- _statwatcher: function() {
359
- return write("statwatcher");
360
- },
361
- _securecontext: function() {
362
- return write("securecontext");
363
- },
364
- _connection: function() {
365
- return write("connection");
366
- },
367
- _zlib: function() {
368
- return write("zlib");
369
- },
370
- _context: function() {
371
- return write("context");
372
- },
373
- _nodescript: function() {
374
- return write("nodescript");
375
- },
376
- _httpparser: function() {
377
- return write("httpparser");
378
- },
379
- _dataview: function() {
380
- return write("dataview");
381
- },
382
- _signal: function() {
383
- return write("signal");
384
- },
385
- _fsevent: function() {
386
- return write("fsevent");
387
- },
388
- _tlswrap: function() {
389
- return write("tlswrap");
390
- }
391
- };
392
- }
393
- function PassThrough() {
394
- return {
395
- buf: "",
396
- write: function(b) {
397
- this.buf += b;
398
- },
399
- end: function(b) {
400
- this.buf += b;
401
- },
402
- read: function() {
403
- return this.buf;
404
- }
405
- };
406
- }
407
- }
408
- });
409
-
410
29
  // src/index.ts
411
30
  var index_exports = {};
412
31
  __export(index_exports, {
@@ -417,7 +36,6 @@ __export(index_exports, {
417
36
  module.exports = __toCommonJS(index_exports);
418
37
 
419
38
  // ../helpers/dist/index.js
420
- var import_object_hash = __toESM(require_object_hash(), 1);
421
39
  var import_crypto = __toESM(require("crypto"), 1);
422
40
  var UNMISTAKABLE_CHARS = "23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghjkmnopqrstuvwxyz";
423
41
  var hexString = function(digits) {
@@ -453,6 +71,7 @@ function generateId(charsCount, chars = UNMISTAKABLE_CHARS) {
453
71
  }
454
72
  return randomString(charsCount, chars);
455
73
  }
74
+ var { isArray } = Array;
456
75
 
457
76
  // src/di.ts
458
77
  var instances = /* @__PURE__ */ new Map();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/object-hash@2.2.0/node_modules/object-hash/index.js","../src/index.ts","../../helpers/src/sleep.ts","../../helpers/src/hashObject.ts","../../helpers/src/generateId.ts","../../helpers/src/createMap.ts","../../helpers/src/createMapArray.ts","../../helpers/src/Errors/OrionError.ts","../../helpers/src/Errors/PermissionsError.ts","../../helpers/src/Errors/UserError.ts","../../helpers/src/Errors/index.ts","../../helpers/src/composeMiddlewares.ts","../../helpers/src/retries.ts","../../helpers/src/generateUUID.ts","../../helpers/src/normalize.ts","../../helpers/src/searchTokens.ts","../../helpers/src/shortenMongoId.ts","../src/di.ts"],"sourcesContent":["'use strict';\n\nvar crypto = require('crypto');\n\n/**\n * Exported function\n *\n * Options:\n *\n * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5'\n * - `excludeValues` {true|*false} hash object keys, values ignored\n * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64'\n * - `ignoreUnknown` {true|*false} ignore unknown object types\n * - `replacer` optional function that replaces values before hashing\n * - `respectFunctionProperties` {*true|false} consider function properties when hashing\n * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing\n * - `respectType` {*true|false} Respect special properties (prototype, constructor)\n * when hashing to distinguish between types\n * - `unorderedArrays` {true|*false} Sort all arrays before hashing\n * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing\n * * = default\n *\n * @param {object} object value to hash\n * @param {object} options hashing options\n * @return {string} hash value\n * @api public\n */\nexports = module.exports = objectHash;\n\nfunction objectHash(object, options){\n options = applyDefaults(object, options);\n\n return hash(object, options);\n}\n\n/**\n * Exported sugar methods\n *\n * @param {object} object value to hash\n * @return {string} hash value\n * @api public\n */\nexports.sha1 = function(object){\n return objectHash(object);\n};\nexports.keys = function(object){\n return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'});\n};\nexports.MD5 = function(object){\n return objectHash(object, {algorithm: 'md5', encoding: 'hex'});\n};\nexports.keysMD5 = function(object){\n return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true});\n};\n\n// Internals\nvar hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5'];\nhashes.push('passthrough');\nvar encodings = ['buffer', 'hex', 'binary', 'base64'];\n\nfunction applyDefaults(object, sourceOptions){\n sourceOptions = sourceOptions || {};\n\n // create a copy rather than mutating\n var options = {};\n options.algorithm = sourceOptions.algorithm || 'sha1';\n options.encoding = sourceOptions.encoding || 'hex';\n options.excludeValues = sourceOptions.excludeValues ? true : false;\n options.algorithm = options.algorithm.toLowerCase();\n options.encoding = options.encoding.toLowerCase();\n options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false\n options.respectType = sourceOptions.respectType === false ? false : true; // default to true\n options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true;\n options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true;\n options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false\n options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false\n options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true\n options.replacer = sourceOptions.replacer || undefined;\n options.excludeKeys = sourceOptions.excludeKeys || undefined;\n\n if(typeof object === 'undefined') {\n throw new Error('Object argument required.');\n }\n\n // if there is a case-insensitive match in the hashes list, accept it\n // (i.e. SHA256 for sha256)\n for (var i = 0; i < hashes.length; ++i) {\n if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) {\n options.algorithm = hashes[i];\n }\n }\n\n if(hashes.indexOf(options.algorithm) === -1){\n throw new Error('Algorithm \"' + options.algorithm + '\" not supported. ' +\n 'supported values: ' + hashes.join(', '));\n }\n\n if(encodings.indexOf(options.encoding) === -1 &&\n options.algorithm !== 'passthrough'){\n throw new Error('Encoding \"' + options.encoding + '\" not supported. ' +\n 'supported values: ' + encodings.join(', '));\n }\n\n return options;\n}\n\n/** Check if the given function is a native function */\nfunction isNativeFunction(f) {\n if ((typeof f) !== 'function') {\n return false;\n }\n var exp = /^function\\s+\\w*\\s*\\(\\s*\\)\\s*{\\s+\\[native code\\]\\s+}$/i;\n return exp.exec(Function.prototype.toString.call(f)) != null;\n}\n\nfunction hash(object, options) {\n var hashingStream;\n\n if (options.algorithm !== 'passthrough') {\n hashingStream = crypto.createHash(options.algorithm);\n } else {\n hashingStream = new PassThrough();\n }\n\n if (typeof hashingStream.write === 'undefined') {\n hashingStream.write = hashingStream.update;\n hashingStream.end = hashingStream.update;\n }\n\n var hasher = typeHasher(options, hashingStream);\n hasher.dispatch(object);\n if (!hashingStream.update) {\n hashingStream.end('');\n }\n\n if (hashingStream.digest) {\n return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding);\n }\n\n var buf = hashingStream.read();\n if (options.encoding === 'buffer') {\n return buf;\n }\n\n return buf.toString(options.encoding);\n}\n\n/**\n * Expose streaming API\n *\n * @param {object} object Value to serialize\n * @param {object} options Options, as for hash()\n * @param {object} stream A stream to write the serializiation to\n * @api public\n */\nexports.writeToStream = function(object, options, stream) {\n if (typeof stream === 'undefined') {\n stream = options;\n options = {};\n }\n\n options = applyDefaults(object, options);\n\n return typeHasher(options, stream).dispatch(object);\n};\n\nfunction typeHasher(options, writeTo, context){\n context = context || [];\n var write = function(str) {\n if (writeTo.update) {\n return writeTo.update(str, 'utf8');\n } else {\n return writeTo.write(str, 'utf8');\n }\n };\n\n return {\n dispatch: function(value){\n if (options.replacer) {\n value = options.replacer(value);\n }\n\n var type = typeof value;\n if (value === null) {\n type = 'null';\n }\n\n //console.log(\"[DEBUG] Dispatch: \", value, \"->\", type, \" -> \", \"_\" + type);\n\n return this['_' + type](value);\n },\n _object: function(object) {\n var pattern = (/\\[object (.*)\\]/i);\n var objString = Object.prototype.toString.call(object);\n var objType = pattern.exec(objString);\n if (!objType) { // object type did not match [object ...]\n objType = 'unknown:[' + objString + ']';\n } else {\n objType = objType[1]; // take only the class name\n }\n\n objType = objType.toLowerCase();\n\n var objectNumber = null;\n\n if ((objectNumber = context.indexOf(object)) >= 0) {\n return this.dispatch('[CIRCULAR:' + objectNumber + ']');\n } else {\n context.push(object);\n }\n\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) {\n write('buffer:');\n return write(object);\n }\n\n if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') {\n if(this['_' + objType]) {\n this['_' + objType](object);\n } else if (options.ignoreUnknown) {\n return write('[' + objType + ']');\n } else {\n throw new Error('Unknown object type \"' + objType + '\"');\n }\n }else{\n var keys = Object.keys(object);\n if (options.unorderedObjects) {\n keys = keys.sort();\n }\n // Make sure to incorporate special properties, so\n // Types with different prototypes will produce\n // a different hash and objects derived from\n // different functions (`new Foo`, `new Bar`) will\n // produce different hashes.\n // We never do this for native functions since some\n // seem to break because of that.\n if (options.respectType !== false && !isNativeFunction(object)) {\n keys.splice(0, 0, 'prototype', '__proto__', 'constructor');\n }\n\n if (options.excludeKeys) {\n keys = keys.filter(function(key) { return !options.excludeKeys(key); });\n }\n\n write('object:' + keys.length + ':');\n var self = this;\n return keys.forEach(function(key){\n self.dispatch(key);\n write(':');\n if(!options.excludeValues) {\n self.dispatch(object[key]);\n }\n write(',');\n });\n }\n },\n _array: function(arr, unordered){\n unordered = typeof unordered !== 'undefined' ? unordered :\n options.unorderedArrays !== false; // default to options.unorderedArrays\n\n var self = this;\n write('array:' + arr.length + ':');\n if (!unordered || arr.length <= 1) {\n return arr.forEach(function(entry) {\n return self.dispatch(entry);\n });\n }\n\n // the unordered case is a little more complicated:\n // since there is no canonical ordering on objects,\n // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false,\n // we first serialize each entry using a PassThrough stream\n // before sorting.\n // also: we can’t use the same context array for all entries\n // since the order of hashing should *not* matter. instead,\n // we keep track of the additions to a copy of the context array\n // and add all of them to the global context array when we’re done\n var contextAdditions = [];\n var entries = arr.map(function(entry) {\n var strm = new PassThrough();\n var localContext = context.slice(); // make copy\n var hasher = typeHasher(options, strm, localContext);\n hasher.dispatch(entry);\n // take only what was added to localContext and append it to contextAdditions\n contextAdditions = contextAdditions.concat(localContext.slice(context.length));\n return strm.read().toString();\n });\n context = context.concat(contextAdditions);\n entries.sort();\n return this._array(entries, false);\n },\n _date: function(date){\n return write('date:' + date.toJSON());\n },\n _symbol: function(sym){\n return write('symbol:' + sym.toString());\n },\n _error: function(err){\n return write('error:' + err.toString());\n },\n _boolean: function(bool){\n return write('bool:' + bool.toString());\n },\n _string: function(string){\n write('string:' + string.length + ':');\n write(string.toString());\n },\n _function: function(fn){\n write('fn:');\n if (isNativeFunction(fn)) {\n this.dispatch('[native]');\n } else {\n this.dispatch(fn.toString());\n }\n\n if (options.respectFunctionNames !== false) {\n // Make sure we can still distinguish native functions\n // by their name, otherwise String and Function will\n // have the same hash\n this.dispatch(\"function-name:\" + String(fn.name));\n }\n\n if (options.respectFunctionProperties) {\n this._object(fn);\n }\n },\n _number: function(number){\n return write('number:' + number.toString());\n },\n _xml: function(xml){\n return write('xml:' + xml.toString());\n },\n _null: function() {\n return write('Null');\n },\n _undefined: function() {\n return write('Undefined');\n },\n _regexp: function(regex){\n return write('regex:' + regex.toString());\n },\n _uint8array: function(arr){\n write('uint8array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _uint8clampedarray: function(arr){\n write('uint8clampedarray:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _int8array: function(arr){\n write('uint8array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _uint16array: function(arr){\n write('uint16array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _int16array: function(arr){\n write('uint16array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _uint32array: function(arr){\n write('uint32array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _int32array: function(arr){\n write('uint32array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _float32array: function(arr){\n write('float32array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _float64array: function(arr){\n write('float64array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _arraybuffer: function(arr){\n write('arraybuffer:');\n return this.dispatch(new Uint8Array(arr));\n },\n _url: function(url) {\n return write('url:' + url.toString(), 'utf8');\n },\n _map: function(map) {\n write('map:');\n var arr = Array.from(map);\n return this._array(arr, options.unorderedSets !== false);\n },\n _set: function(set) {\n write('set:');\n var arr = Array.from(set);\n return this._array(arr, options.unorderedSets !== false);\n },\n _file: function(file) {\n write('file:');\n return this.dispatch([file.name, file.size, file.type, file.lastModfied]);\n },\n _blob: function() {\n if (options.ignoreUnknown) {\n return write('[blob]');\n }\n\n throw Error('Hashing Blob objects is currently not supported\\n' +\n '(see https://github.com/puleos/object-hash/issues/26)\\n' +\n 'Use \"options.replacer\" or \"options.ignoreUnknown\"\\n');\n },\n _domwindow: function() { return write('domwindow'); },\n _bigint: function(number){\n return write('bigint:' + number.toString());\n },\n /* Node.js standard native objects */\n _process: function() { return write('process'); },\n _timer: function() { return write('timer'); },\n _pipe: function() { return write('pipe'); },\n _tcp: function() { return write('tcp'); },\n _udp: function() { return write('udp'); },\n _tty: function() { return write('tty'); },\n _statwatcher: function() { return write('statwatcher'); },\n _securecontext: function() { return write('securecontext'); },\n _connection: function() { return write('connection'); },\n _zlib: function() { return write('zlib'); },\n _context: function() { return write('context'); },\n _nodescript: function() { return write('nodescript'); },\n _httpparser: function() { return write('httpparser'); },\n _dataview: function() { return write('dataview'); },\n _signal: function() { return write('signal'); },\n _fsevent: function() { return write('fsevent'); },\n _tlswrap: function() { return write('tlswrap'); },\n };\n}\n\n// Mini-implementation of stream.PassThrough\n// We are far from having need for the full implementation, and we can\n// make assumptions like \"many writes, then only one final read\"\n// and we can ignore encoding specifics\nfunction PassThrough() {\n return {\n buf: '',\n\n write: function(b) {\n this.buf += b;\n },\n\n end: function(b) {\n this.buf += b;\n },\n\n read: function() {\n return this.buf;\n }\n };\n}\n","export * from './di'\n","/**\n * Creates a timeout with a promise\n */\nexport default (time: number): Promise<void> => {\n return new Promise(resolve => setTimeout(resolve, time))\n}\n","import hash from 'object-hash'\n\nexport default function (object: any): string {\n return hash(object)\n}\n","import crypto from 'crypto'\n\nconst UNMISTAKABLE_CHARS = '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghjkmnopqrstuvwxyz'\n\nconst hexString = function (digits) {\n var numBytes = Math.ceil(digits / 2)\n var bytes\n // Try to get cryptographically strong randomness. Fall back to\n // non-cryptographically strong if not available.\n try {\n bytes = crypto.randomBytes(numBytes)\n } catch (e) {\n // XXX should re-throw any error except insufficient entropy\n bytes = crypto.pseudoRandomBytes(numBytes)\n }\n var result = bytes.toString('hex')\n // If the number of digits is odd, we'll have generated an extra 4 bits\n // of randomness, so we need to trim the last digit.\n return result.substring(0, digits)\n}\n\nconst fraction = function () {\n var numerator = parseInt(hexString(8), 16)\n return numerator * 2.3283064365386963e-10 // 2^-32\n}\n\nconst choice = function (arrayOrString) {\n var index = Math.floor(fraction() * arrayOrString.length)\n if (typeof arrayOrString === 'string') return arrayOrString.substr(index, 1)\n else return arrayOrString[index]\n}\n\nconst randomString = function (charsCount, alphabet) {\n var digits = []\n for (var i = 0; i < charsCount; i++) {\n digits[i] = choice(alphabet)\n }\n return digits.join('')\n}\n\n/**\n * Returns a random ID\n * @param charsCount length of the ID\n * @param chars characters used to generate the ID\n */\nexport default function generateId(\n charsCount?: number,\n chars: string = UNMISTAKABLE_CHARS,\n): string {\n if (!charsCount) {\n charsCount = 17\n }\n\n return randomString(charsCount, chars)\n}\n","/**\n * Creates a map (object) from an array of items, using a specified property as the key.\n *\n * This utility transforms an array of objects into a lookup object/dictionary where\n * each item in the array becomes a value in the map, indexed by the specified property.\n * If multiple items have the same key value, only the last one will be preserved.\n *\n * @template T The type of items in the input array\n * @param array - The input array of items to transform into a map\n * @param key - The property name to use as keys in the resulting map (defaults to '_id')\n * @returns A record object where keys are values of the specified property and values are the original items\n *\n * @example\n * // Returns { '1': { id: 1, name: 'Item 1' }, '2': { id: 2, name: 'Item 2' } }\n * createMap([{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }], 'id')\n */\nexport default function createMap<T>(array: Array<T>, key: string = '_id'): Record<string, T> {\n const map = {}\n\n for (const item of array) {\n map[item[key]] = item\n }\n\n return map\n}\n","/**\n * Creates a grouped map from an array of items, using a specified property as the key.\n *\n * This utility transforms an array of objects into a lookup object/dictionary where\n * each value is an array of items sharing the same key value. Unlike createMap,\n * this function preserves all items with the same key by grouping them in arrays.\n *\n * @template T The type of items in the input array\n * @param array - The input array of items to transform into a grouped map\n * @param key - The property name to use as keys in the resulting map (defaults to '_id')\n * @returns A record object where keys are values of the specified property and values are arrays of items\n *\n * @example\n * // Returns { 'category1': [{ id: 1, category: 'category1' }, { id: 3, category: 'category1' }],\n * // 'category2': [{ id: 2, category: 'category2' }] }\n * createMapArray([\n * { id: 1, category: 'category1' },\n * { id: 2, category: 'category2' },\n * { id: 3, category: 'category1' }\n * ], 'category')\n */\nexport default function createMapArray<T>(\n array: Array<T>,\n key: string = '_id',\n): Record<string, Array<T>> {\n const map = {}\n\n for (const item of array) {\n map[item[key]] = map[item[key]] || []\n map[item[key]].push(item)\n }\n\n return map\n}\n","/**\n * Interface representing the standardized error information structure for Orion errors.\n * This is used by the getInfo method to provide consistent error reporting.\n */\nexport interface OrionErrorInformation {\n /** The error code or identifier */\n error: string\n /** Human-readable error message */\n message: string\n /** Additional error metadata or context */\n extra: any\n /** The sub-type of error. For example for permissions errors it could be 'read', 'write', 'admin' */\n type?: string\n}\n\n/**\n * Base error class for all Orion-specific errors.\n *\n * This abstract class provides common properties and methods for all error types\n * used in the Orion framework. It's extended by more specific error classes\n * like UserError and PermissionsError.\n *\n * @property isOrionError - Flag indicating this is an Orion error (always true)\n * @property isUserError - Flag indicating if this is a user-facing error\n * @property isPermissionsError - Flag indicating if this is a permissions-related error\n * @property code - Error code for identifying the error type\n * @property extra - Additional error context or metadata\n */\nexport class OrionError extends Error {\n isOrionError = true\n\n isUserError: boolean\n isPermissionsError: boolean\n code: string\n extra: any\n\n /**\n * Returns a standardized representation of the error information.\n * @returns An object containing error details in a consistent format\n */\n getInfo: () => OrionErrorInformation\n}\n","import {OrionError} from './OrionError'\n\n/**\n * Error class for permission-related errors in the Orion framework.\n *\n * PermissionsError represents authorization failures where a user or client\n * attempts to perform an action they don't have permission to execute.\n * This is used to distinguish security/permissions errors from other types\n * of errors for proper error handling and user feedback.\n *\n * @extends OrionError\n */\nexport default class PermissionsError extends OrionError {\n /**\n * Creates a new PermissionsError instance.\n *\n * @param permissionErrorType - Identifies the specific permission that was violated\n * (e.g., 'read', 'write', 'admin')\n * @param extra - Additional error context or metadata. Can include a custom message\n * via the message property.\n *\n * @example\n * // Basic usage\n * throw new PermissionsError('delete_document')\n *\n * @example\n * // With custom message\n * throw new PermissionsError('access_admin', { message: 'Admin access required' })\n *\n * @example\n * // With additional context\n * throw new PermissionsError('edit_user', {\n * userId: 'user123',\n * requiredRole: 'admin'\n * })\n */\n constructor(permissionErrorType, extra: any = {}) {\n // Calling parent constructor of base Error class.\n const message =\n extra.message || `Client is not allowed to perform this action [${permissionErrorType}]`\n\n super(message)\n Error.captureStackTrace(this, this.constructor)\n\n this.isOrionError = true\n this.isPermissionsError = true\n this.code = 'PermissionsError'\n this.extra = extra\n\n this.getInfo = () => {\n return {\n ...extra,\n error: 'PermissionsError',\n message,\n type: permissionErrorType,\n }\n }\n }\n}\n","import {OrionError} from './OrionError'\n\n/**\n * Error class for user-facing errors in the Orion framework.\n *\n * UserError is designed to represent errors that should be displayed to end users,\n * as opposed to system errors or unexpected failures. These errors typically represent\n * validation issues, business rule violations, or other expected error conditions.\n *\n * @extends OrionError\n */\nexport default class UserError extends OrionError {\n /**\n * Creates a new UserError instance.\n *\n * @param code - Error code identifier. If only one parameter is provided,\n * this will be used as the message and code will default to 'error'.\n * @param message - Human-readable error message. Optional if code is provided.\n * @param extra - Additional error context or metadata.\n *\n * @example\n * // Basic usage\n * throw new UserError('invalid_input', 'The provided email is invalid')\n *\n * @example\n * // Using only a message (code will be 'error')\n * throw new UserError('Input validation failed')\n *\n * @example\n * // With extra metadata\n * throw new UserError('rate_limit', 'Too many requests', { maxRequests: 100 })\n */\n constructor(code: string, message?: string, extra?: any) {\n if (!message && code) {\n message = code\n code = 'error'\n }\n\n super(message)\n Error.captureStackTrace(this, this.constructor)\n\n this.isOrionError = true\n this.isUserError = true\n this.code = code\n this.extra = extra\n\n this.getInfo = () => {\n return {\n error: code,\n message,\n extra,\n }\n }\n }\n}\n","/**\n * @file Exports all error classes used in the Orion framework\n */\n\nimport {OrionError} from './OrionError'\nimport type {OrionErrorInformation} from './OrionError'\nimport PermissionsError from './PermissionsError'\nimport UserError from './UserError'\n\n/**\n * Re-export all error types for convenient importing\n */\nexport {OrionError, PermissionsError, UserError}\nexport type {OrionErrorInformation}\n\n/**\n * Type guard to check if an error is an OrionError\n *\n * @param error - Any error object to test\n * @returns True if the error is an OrionError instance\n *\n * @example\n * try {\n * // some code that might throw\n * } catch (error) {\n * if (isOrionError(error)) {\n * // Handle Orion-specific error\n * console.log(error.code, error.getInfo())\n * } else {\n * // Handle general error\n * }\n * }\n */\nexport function isOrionError(error: any): error is OrionError {\n return Boolean(error && typeof error === 'object' && error.isOrionError === true)\n}\n\n/**\n * Type guard to check if an error is a UserError\n *\n * @param error - Any error object to test\n * @returns True if the error is a UserError instance\n */\nexport function isUserError(error: any): error is UserError {\n return Boolean(\n error && typeof error === 'object' && error.isOrionError === true && error.isUserError === true,\n )\n}\n\n/**\n * Type guard to check if an error is a PermissionsError\n *\n * @param error - Any error object to test\n * @returns True if the error is a PermissionsError instance\n */\nexport function isPermissionsError(error: any): error is PermissionsError {\n return Boolean(\n error &&\n typeof error === 'object' &&\n error.isOrionError === true &&\n error.isPermissionsError === true,\n )\n}\n","// from https://github.com/koajs/compose/blob/master/index.js\n\n/**\n * Compose `middleware` returning\n * a fully valid middleware comprised\n * of all those which are passed.\n */\nexport function composeMiddlewares(middleware) {\n if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')\n for (const fn of middleware) {\n if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')\n }\n\n /**\n * @param {Object} context\n * @return {Promise}\n * @api public\n */\n\n return function (context, next?) {\n // last called middleware #\n let index = -1\n return dispatch(0)\n function dispatch(i) {\n if (i <= index) return Promise.reject(new Error('next() called multiple times'))\n index = i\n let fn = middleware[i]\n if (i === middleware.length) fn = next\n if (!fn) return Promise.resolve()\n try {\n return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))\n } catch (err) {\n return Promise.reject(err)\n }\n }\n }\n}\n","/**\n * Executes an asynchronous function with automatic retries on failure.\n *\n * This utility attempts to execute the provided function and automatically\n * retries if it fails, with a specified delay between attempts. It will\n * continue retrying until either the function succeeds or the maximum\n * number of retries is reached.\n *\n * @template TFunc Type of the function to execute (must return a Promise)\n * @param fn - The asynchronous function to execute\n * @param retries - The maximum number of retry attempts after the initial attempt\n * @param timeout - The delay in milliseconds between retry attempts\n * @returns A promise that resolves with the result of the function or rejects with the last error\n *\n * @example\n * // Retry an API call up to 3 times with 1 second between attempts\n * const result = await executeWithRetries(\n * () => fetchDataFromApi(),\n * 3,\n * 1000\n * );\n */\nexport function executeWithRetries<TFunc extends () => Promise<any>>(\n fn: TFunc,\n retries: number,\n timeout: number,\n): Promise<ReturnType<TFunc>> {\n return new Promise((resolve, reject) => {\n const retry = async (retries: number) => {\n try {\n const result = await fn()\n resolve(result)\n } catch (error) {\n if (retries > 0) {\n setTimeout(() => retry(retries - 1), timeout)\n } else {\n reject(error)\n }\n }\n }\n retry(retries)\n })\n}\n","import {v4 as uuidv4} from 'uuid'\n\nexport function generateUUID() {\n return uuidv4()\n}\n\nexport function generateUUIDWithPrefix(prefix: string) {\n return `${prefix}-${generateUUID()}`\n}\n","/**\n * Removes diacritical marks (accents) from text without any other modifications.\n * This is the most basic normalization function that others build upon.\n *\n * @param text - The input string to process\n * @returns String with accents removed but otherwise unchanged\n */\nexport function removeAccentsOnly(text: string) {\n if (!text) return ''\n // biome-ignore lint/suspicious/noMisleadingCharacterClass: Removes diacritical marks (accents)\n return text.normalize('NFD').replace(/[\\u0300-\\u036f]/g, '')\n}\n\n/**\n * Normalizes text by removing diacritical marks (accents) and trimming whitespace.\n * Builds on removeAccentsOnly and adds whitespace trimming.\n *\n * @param text - The input string to normalize\n * @returns Normalized string with accents removed and whitespace trimmed\n */\nexport function removeAccentsAndTrim(text: string) {\n if (!text) return ''\n return removeAccentsOnly(text).trim()\n}\n\n/**\n * Normalizes text for search purposes by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n *\n * Builds on removeAccentsAndTrim and adds lowercase conversion.\n * Useful for case-insensitive and accent-insensitive text searching.\n *\n * @param text - The input string to normalize for search\n * @returns Search-optimized string in lowercase with accents removed\n */\nexport function normalizeForSearch(text: string) {\n if (!text) return ''\n return removeAccentsAndTrim(text).toLowerCase()\n}\n\n/**\n * Normalizes text for search purposes by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n * - Removing all spaces\n *\n * Builds on normalizeForSearch and removes all whitespace.\n * Useful for compact search indexes or when spaces should be ignored in searches.\n *\n * @param text - The input string to normalize for compact search\n * @returns Compact search-optimized string with no spaces\n */\nexport function normalizeForCompactSearch(text: string) {\n if (!text) return ''\n return normalizeForSearch(text).replace(/\\s/g, '')\n}\n\n/**\n * Normalizes text for search token processing by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n * - Replacing all non-alphanumeric characters with spaces\n *\n * Builds on normalizeForSearch and replaces non-alphanumeric characters with spaces.\n * Useful for tokenizing search terms where special characters should be treated as word separators.\n *\n * @param text - The input string to normalize for tokenized search\n * @returns Search token string with only alphanumeric characters and spaces\n */\nexport function normalizeForSearchToken(text: string) {\n if (!text) return ''\n return normalizeForSearch(text).replace(/[^0-9a-z]/gi, ' ')\n}\n\n/**\n * Normalizes a string specifically for use as a file key (e.g., in S3 or other storage systems).\n * Performs the following transformations:\n * - Removes accents/diacritical marks\n * - Replaces special characters with hyphens\n * - Ensures only alphanumeric characters, hyphens, periods, and underscores remain\n * - Replaces multiple consecutive hyphens with a single hyphen\n * - Removes leading/trailing hyphens\n *\n * @param text - The input string to normalize for file key usage\n * @returns A storage-safe string suitable for use as a file key\n */\nexport function normalizeForFileKey(text: string) {\n if (!text) return ''\n return (\n removeAccentsOnly(text)\n // Replace spaces and unwanted characters with hyphens\n .replace(/[^a-zA-Z0-9-._]/g, '-')\n // Replace multiple consecutive hyphens with single hyphen\n .replace(/-+/g, '-')\n // Remove leading/trailing hyphens\n .trim()\n .replace(/^-+|-+$/g, '')\n )\n}\n","import {normalizeForSearchToken} from './normalize'\n\n/**\n * Generates an array of search tokens from input text and optional metadata.\n *\n * This function processes text by:\n * 1. Converting it to an array of strings (if not already)\n * 2. Filtering out falsy values\n * 3. Normalizing each string (removing accents, special characters)\n * 4. Splitting by spaces to create individual tokens\n * 5. Optionally adding metadata tokens in the format \"_key:value\"\n *\n * @param text - String or array of strings to tokenize\n * @param meta - Optional metadata object where each key-value pair becomes a token\n * @returns Array of normalized search tokens\n *\n * @example\n * // Returns ['hello', 'world']\n * getSearchTokens('Hello, World!')\n *\n * @example\n * // Returns ['hello', 'world', '_id:123']\n * getSearchTokens('Hello, World!', { id: '123' })\n */\nexport function getSearchTokens(text: string[] | string, meta?: Record<string, string>) {\n const stringArray = Array.isArray(text) ? text : [text]\n const tokens = stringArray\n .filter(Boolean)\n .map(text => String(text))\n .flatMap(word => {\n return normalizeForSearchToken(word).split(' ').filter(Boolean)\n })\n\n if (meta) {\n for (const key in meta) {\n tokens.push(`_${key}:${meta[key]}`)\n }\n }\n\n return tokens\n}\n\n/**\n * Interface for parameters used in generating search queries from tokens.\n *\n * @property filter - Optional string to filter search results\n * @property [key: string] - Additional key-value pairs for metadata filtering\n */\nexport interface SearchQueryForTokensParams {\n filter?: string\n [key: string]: string\n}\n\n/**\n * Options for customizing the search query generation behavior.\n * Currently empty but provided for future extensibility.\n */\nexport type SearchQueryForTokensOptions = {}\n\n/**\n * Generates a MongoDB-compatible query object based on the provided parameters.\n *\n * This function:\n * 1. Processes any filter text into RegExp tokens for prefix matching\n * 2. Adds metadata filters based on additional properties in the params object\n * 3. Returns a query object with the $all operator for MongoDB queries\n *\n * @param params - Parameters for generating the search query\n * @param _options - Options for customizing search behavior (reserved for future use)\n * @returns A MongoDB-compatible query object with format { $all: [...tokens] }\n *\n * @example\n * // Returns { $all: [/^hello/, /^world/] }\n * getSearchQueryForTokens({ filter: 'Hello World' })\n *\n * @example\n * // Returns { $all: [/^search/, '_category:books'] }\n * getSearchQueryForTokens({ filter: 'search', category: 'books' })\n */\nexport function getSearchQueryForTokens(\n params: SearchQueryForTokensParams = {},\n _options: SearchQueryForTokensOptions = {},\n) {\n const searchTokens: (string | RegExp)[] = []\n\n if (params.filter) {\n const filterTokens = getSearchTokens(params.filter).map(token => new RegExp(`^${token}`))\n searchTokens.push(...filterTokens)\n }\n\n for (const key in params) {\n if (key === 'filter') continue\n if (!params[key]) continue\n searchTokens.push(`_${key}:${params[key]}`)\n }\n\n return {$all: searchTokens}\n}\n","function lastOfString(string: string, last: number) {\n return string.substring(string.length - last, string.length)\n}\n\nexport function shortenMongoId(string: string) {\n return lastOfString(string, 5).toUpperCase()\n}\n","import {generateId} from '../../helpers/dist'\n\ntype Token<T> = {new (...args: any[]): T}\n\nconst instances = new Map<Token<any>, any>()\nconst serviceMetadata = new WeakMap<object, {id: string; name: string}>()\nconst injectionMetadata = new WeakMap<object, Record<string | symbol, () => Token<any>>>()\n\nexport function Service() {\n return (_target: Function, context: ClassDecoratorContext) => {\n serviceMetadata.set(context, {\n id: generateId(12),\n name: context.name,\n })\n }\n}\n\nexport function Inject<T>(getDependency: () => Token<T>) {\n return (_: undefined, context: ClassFieldDecoratorContext) => {\n context.addInitializer(function (this: any) {\n const metadata = injectionMetadata.get(this) || {}\n metadata[context.name] = getDependency\n injectionMetadata.set(this, metadata)\n })\n }\n}\n\nexport function getInstance<T extends object>(token: Token<T>): T {\n if (!instances.has(token)) {\n const instance = new token()\n instances.set(token, instance)\n\n const injections = injectionMetadata.get(instance)\n if (injections) {\n for (const [propertyKey, getDependency] of Object.entries(injections)) {\n instance[propertyKey] = getInstance(getDependency())\n }\n }\n }\n return instances.get(token)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,iFAAAA,UAAAC,SAAA;AAAA;AAEA,QAAIC,UAAS,QAAQ,QAAQ;AAyB7B,IAAAF,WAAUC,QAAO,UAAU;AAE3B,aAAS,WAAW,QAAQ,SAAQ;AAClC,gBAAU,cAAc,QAAQ,OAAO;AAEvC,aAAOE,MAAK,QAAQ,OAAO;AAAA,IAC7B;AASA,IAAAH,SAAQ,OAAO,SAAS,QAAO;AAC7B,aAAO,WAAW,MAAM;AAAA,IAC1B;AACA,IAAAA,SAAQ,OAAO,SAAS,QAAO;AAC7B,aAAO,WAAW,QAAQ,EAAC,eAAe,MAAM,WAAW,QAAQ,UAAU,MAAK,CAAC;AAAA,IACrF;AACA,IAAAA,SAAQ,MAAM,SAAS,QAAO;AAC5B,aAAO,WAAW,QAAQ,EAAC,WAAW,OAAO,UAAU,MAAK,CAAC;AAAA,IAC/D;AACA,IAAAA,SAAQ,UAAU,SAAS,QAAO;AAChC,aAAO,WAAW,QAAQ,EAAC,WAAW,OAAO,UAAU,OAAO,eAAe,KAAI,CAAC;AAAA,IACpF;AAGA,QAAI,SAASE,QAAO,YAAYA,QAAO,UAAU,EAAE,MAAM,IAAI,CAAC,QAAQ,KAAK;AAC3E,WA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AAI,KAAK,GAAG;AACzB,UAAM,WAAW,IAAI,MAAM;AAC3B,cAAU,IAAI,OAAO,QAAQ;AAE7B,UAAM,aAAa,kBAAkB,IAAI,QAAQ;AACjD,QAAI,YAAY;AACd,iBAAW,CAAC,aAAa,aAAa,KAAK,OAAO,QAAQ,UAAU,GAAG;AACrE,iBAAS,WAAW,IAAI,YAAY,cAAc,CAAC;AAAA,MACrD;AAAA,IACF;AAAA,EACF;AACA,SAAO,UAAU,IAAI,KAAK;AAC5B;","names":["exports","module","crypto","hash","crypto"]}
1
+ {"version":3,"sources":["../src/index.ts","../../helpers/src/sleep.ts","../../helpers/src/hashObject.ts","../../helpers/src/generateId.ts","../../helpers/src/createMap.ts","../../helpers/src/createMapArray.ts","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/isArray.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isType.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/clone.js","../../helpers/src/clone.ts","../../helpers/src/Errors/OrionError.ts","../../helpers/src/Errors/PermissionsError.ts","../../helpers/src/Errors/UserError.ts","../../helpers/src/Errors/index.ts","../../helpers/src/composeMiddlewares.ts","../../helpers/src/retries.ts","../../helpers/src/generateUUID.ts","../../helpers/src/normalize.ts","../../helpers/src/searchTokens.ts","../../helpers/src/shortenMongoId.ts","../src/di.ts"],"sourcesContent":["export * from './di'\n","/**\n * Creates a timeout with a promise\n */\nexport default (time: number): Promise<void> => {\n return new Promise(resolve => setTimeout(resolve, time))\n}\n","import crypto from 'node:crypto'\n\n/**\n * Receives any javascript object, string, number, boolean, array, or object and returns a hash of it.\n */\nexport default function hashObject(object: any): string {\n const string = objectToString(object)\n return crypto.createHash('sha256').update(string).digest('hex')\n}\n\nfunction objectToString(object: any): string {\n if (object === null || object === undefined) {\n return 'null'\n }\n\n if (typeof object === 'string') {\n return object\n }\n\n if (typeof object === 'number' || typeof object === 'boolean') {\n return String(object)\n }\n\n if (object instanceof Date) {\n return object.toISOString()\n }\n\n if (Array.isArray(object)) {\n const arrayHash = object.map(item => hashObject(item)).join(',')\n return `[${arrayHash}]`\n }\n\n if (typeof object === 'object') {\n const keys = Object.keys(object).sort()\n const objectHash = keys.map(key => `${key}:${hashObject(object[key])}`).join(',')\n return `{${objectHash}}`\n }\n\n // Fallback for functions or other types\n return String(object)\n}\n","import crypto from 'crypto'\n\nconst UNMISTAKABLE_CHARS = '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghjkmnopqrstuvwxyz'\n\nconst hexString = function (digits) {\n var numBytes = Math.ceil(digits / 2)\n var bytes\n // Try to get cryptographically strong randomness. Fall back to\n // non-cryptographically strong if not available.\n try {\n bytes = crypto.randomBytes(numBytes)\n } catch (e) {\n // XXX should re-throw any error except insufficient entropy\n bytes = crypto.pseudoRandomBytes(numBytes)\n }\n var result = bytes.toString('hex')\n // If the number of digits is odd, we'll have generated an extra 4 bits\n // of randomness, so we need to trim the last digit.\n return result.substring(0, digits)\n}\n\nconst fraction = function () {\n var numerator = parseInt(hexString(8), 16)\n return numerator * 2.3283064365386963e-10 // 2^-32\n}\n\nconst choice = function (arrayOrString) {\n var index = Math.floor(fraction() * arrayOrString.length)\n if (typeof arrayOrString === 'string') return arrayOrString.substr(index, 1)\n else return arrayOrString[index]\n}\n\nconst randomString = function (charsCount, alphabet) {\n var digits = []\n for (var i = 0; i < charsCount; i++) {\n digits[i] = choice(alphabet)\n }\n return digits.join('')\n}\n\n/**\n * Returns a random ID\n * @param charsCount length of the ID\n * @param chars characters used to generate the ID\n */\nexport default function generateId(\n charsCount?: number,\n chars: string = UNMISTAKABLE_CHARS,\n): string {\n if (!charsCount) {\n charsCount = 17\n }\n\n return randomString(charsCount, chars)\n}\n","/**\n * Creates a map (object) from an array of items, using a specified property as the key.\n *\n * This utility transforms an array of objects into a lookup object/dictionary where\n * each item in the array becomes a value in the map, indexed by the specified property.\n * If multiple items have the same key value, only the last one will be preserved.\n *\n * @template T The type of items in the input array\n * @param array - The input array of items to transform into a map\n * @param key - The property name to use as keys in the resulting map (defaults to '_id')\n * @returns A record object where keys are values of the specified property and values are the original items\n *\n * @example\n * // Returns { '1': { id: 1, name: 'Item 1' }, '2': { id: 2, name: 'Item 2' } }\n * createMap([{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }], 'id')\n */\nexport default function createMap<T>(array: Array<T>, key: string = '_id'): Record<string, T> {\n const map = {}\n\n for (const item of array) {\n map[item[key]] = item\n }\n\n return map\n}\n","/**\n * Creates a grouped map from an array of items, using a specified property as the key.\n *\n * This utility transforms an array of objects into a lookup object/dictionary where\n * each value is an array of items sharing the same key value. Unlike createMap,\n * this function preserves all items with the same key by grouping them in arrays.\n *\n * @template T The type of items in the input array\n * @param array - The input array of items to transform into a grouped map\n * @param key - The property name to use as keys in the resulting map (defaults to '_id')\n * @returns A record object where keys are values of the specified property and values are arrays of items\n *\n * @example\n * // Returns { 'category1': [{ id: 1, category: 'category1' }, { id: 3, category: 'category1' }],\n * // 'category2': [{ id: 2, category: 'category2' }] }\n * createMapArray([\n * { id: 1, category: 'category1' },\n * { id: 2, category: 'category2' },\n * { id: 3, category: 'category1' }\n * ], 'category')\n */\nexport default function createMapArray<T>(\n array: Array<T>,\n key: string = '_id',\n): Record<string, Array<T>> {\n const map = {}\n\n for (const item of array) {\n map[item[key]] = map[item[key]] || []\n map[item[key]].push(item)\n }\n\n return map\n}\n","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","export const { isArray } = Array\n","import { type } from './type.js'\n\nexport function isType(xType, x){\n if (arguments.length === 1){\n return xHolder => isType(xType, xHolder)\n }\n\n return type(x) === xType\n}\n","import { isArray } from './_internals/isArray.js'\n\nexport function clone(input){\n const out = isArray(input) ? Array(input.length) : {}\n if (input && input.getTime) return new Date(input.getTime())\n\n for (const key in input){\n const v = input[ key ]\n out[ key ] =\n typeof v === 'object' && v !== null ?\n v.getTime ?\n new Date(v.getTime()) :\n clone(v) :\n v\n }\n\n return out\n}\n","import {isType, clone as cloneRambdax} from 'rambdax'\n\nexport function clone<T>(value: T): T {\n if (isType('Object', value)) {\n return cloneRambdax(value)\n }\n\n if (Array.isArray(value)) {\n return cloneRambdax(value)\n }\n\n return value\n}\n","/**\n * Interface representing the standardized error information structure for Orion errors.\n * This is used by the getInfo method to provide consistent error reporting.\n */\nexport interface OrionErrorInformation {\n /** The error code or identifier */\n error: string\n /** Human-readable error message */\n message: string\n /** Additional error metadata or context */\n extra: any\n /** The sub-type of error. For example for permissions errors it could be 'read', 'write', 'admin' */\n type?: string\n}\n\n/**\n * Base error class for all Orion-specific errors.\n *\n * This abstract class provides common properties and methods for all error types\n * used in the Orion framework. It's extended by more specific error classes\n * like UserError and PermissionsError.\n *\n * @property isOrionError - Flag indicating this is an Orion error (always true)\n * @property isUserError - Flag indicating if this is a user-facing error\n * @property isPermissionsError - Flag indicating if this is a permissions-related error\n * @property code - Error code for identifying the error type\n * @property extra - Additional error context or metadata\n */\nexport class OrionError extends Error {\n isOrionError = true\n\n isUserError: boolean\n isPermissionsError: boolean\n code: string\n extra: any\n\n /**\n * Returns a standardized representation of the error information.\n * @returns An object containing error details in a consistent format\n */\n getInfo: () => OrionErrorInformation\n}\n","import {OrionError} from './OrionError'\n\n/**\n * Error class for permission-related errors in the Orion framework.\n *\n * PermissionsError represents authorization failures where a user or client\n * attempts to perform an action they don't have permission to execute.\n * This is used to distinguish security/permissions errors from other types\n * of errors for proper error handling and user feedback.\n *\n * @extends OrionError\n */\nexport default class PermissionsError extends OrionError {\n /**\n * Creates a new PermissionsError instance.\n *\n * @param permissionErrorType - Identifies the specific permission that was violated\n * (e.g., 'read', 'write', 'admin')\n * @param extra - Additional error context or metadata. Can include a custom message\n * via the message property.\n *\n * @example\n * // Basic usage\n * throw new PermissionsError('delete_document')\n *\n * @example\n * // With custom message\n * throw new PermissionsError('access_admin', { message: 'Admin access required' })\n *\n * @example\n * // With additional context\n * throw new PermissionsError('edit_user', {\n * userId: 'user123',\n * requiredRole: 'admin'\n * })\n */\n constructor(permissionErrorType, extra: any = {}) {\n // Calling parent constructor of base Error class.\n const message =\n extra.message || `Client is not allowed to perform this action [${permissionErrorType}]`\n\n super(message)\n Error.captureStackTrace(this, this.constructor)\n\n this.isOrionError = true\n this.isPermissionsError = true\n this.code = 'PermissionsError'\n this.extra = extra\n\n this.getInfo = () => {\n return {\n ...extra,\n error: 'PermissionsError',\n message,\n type: permissionErrorType,\n }\n }\n }\n}\n","import {OrionError} from './OrionError'\n\n/**\n * Error class for user-facing errors in the Orion framework.\n *\n * UserError is designed to represent errors that should be displayed to end users,\n * as opposed to system errors or unexpected failures. These errors typically represent\n * validation issues, business rule violations, or other expected error conditions.\n *\n * @extends OrionError\n */\nexport default class UserError extends OrionError {\n /**\n * Creates a new UserError instance.\n *\n * @param code - Error code identifier. If only one parameter is provided,\n * this will be used as the message and code will default to 'error'.\n * @param message - Human-readable error message. Optional if code is provided.\n * @param extra - Additional error context or metadata.\n *\n * @example\n * // Basic usage\n * throw new UserError('invalid_input', 'The provided email is invalid')\n *\n * @example\n * // Using only a message (code will be 'error')\n * throw new UserError('Input validation failed')\n *\n * @example\n * // With extra metadata\n * throw new UserError('rate_limit', 'Too many requests', { maxRequests: 100 })\n */\n constructor(code: string, message?: string, extra?: any) {\n if (!message && code) {\n message = code\n code = 'error'\n }\n\n super(message)\n Error.captureStackTrace(this, this.constructor)\n\n this.isOrionError = true\n this.isUserError = true\n this.code = code\n this.extra = extra\n\n this.getInfo = () => {\n return {\n error: code,\n message,\n extra,\n }\n }\n }\n}\n","/**\n * @file Exports all error classes used in the Orion framework\n */\n\nimport {OrionError} from './OrionError'\nimport type {OrionErrorInformation} from './OrionError'\nimport PermissionsError from './PermissionsError'\nimport UserError from './UserError'\n\n/**\n * Re-export all error types for convenient importing\n */\nexport {OrionError, PermissionsError, UserError}\nexport type {OrionErrorInformation}\n\n/**\n * Type guard to check if an error is an OrionError\n *\n * @param error - Any error object to test\n * @returns True if the error is an OrionError instance\n *\n * @example\n * try {\n * // some code that might throw\n * } catch (error) {\n * if (isOrionError(error)) {\n * // Handle Orion-specific error\n * console.log(error.code, error.getInfo())\n * } else {\n * // Handle general error\n * }\n * }\n */\nexport function isOrionError(error: any): error is OrionError {\n return Boolean(error && typeof error === 'object' && error.isOrionError === true)\n}\n\n/**\n * Type guard to check if an error is a UserError\n *\n * @param error - Any error object to test\n * @returns True if the error is a UserError instance\n */\nexport function isUserError(error: any): error is UserError {\n return Boolean(\n error && typeof error === 'object' && error.isOrionError === true && error.isUserError === true,\n )\n}\n\n/**\n * Type guard to check if an error is a PermissionsError\n *\n * @param error - Any error object to test\n * @returns True if the error is a PermissionsError instance\n */\nexport function isPermissionsError(error: any): error is PermissionsError {\n return Boolean(\n error &&\n typeof error === 'object' &&\n error.isOrionError === true &&\n error.isPermissionsError === true,\n )\n}\n","// from https://github.com/koajs/compose/blob/master/index.js\n\n/**\n * Compose `middleware` returning\n * a fully valid middleware comprised\n * of all those which are passed.\n */\nexport function composeMiddlewares(middleware) {\n if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')\n for (const fn of middleware) {\n if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')\n }\n\n /**\n * @param {Object} context\n * @return {Promise}\n * @api public\n */\n\n return function (context, next?) {\n // last called middleware #\n let index = -1\n return dispatch(0)\n function dispatch(i) {\n if (i <= index) return Promise.reject(new Error('next() called multiple times'))\n index = i\n let fn = middleware[i]\n if (i === middleware.length) fn = next\n if (!fn) return Promise.resolve()\n try {\n return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))\n } catch (err) {\n return Promise.reject(err)\n }\n }\n }\n}\n","/**\n * Executes an asynchronous function with automatic retries on failure.\n *\n * This utility attempts to execute the provided function and automatically\n * retries if it fails, with a specified delay between attempts. It will\n * continue retrying until either the function succeeds or the maximum\n * number of retries is reached.\n *\n * @template TFunc Type of the function to execute (must return a Promise)\n * @param fn - The asynchronous function to execute\n * @param retries - The maximum number of retry attempts after the initial attempt\n * @param timeout - The delay in milliseconds between retry attempts\n * @returns A promise that resolves with the result of the function or rejects with the last error\n *\n * @example\n * // Retry an API call up to 3 times with 1 second between attempts\n * const result = await executeWithRetries(\n * () => fetchDataFromApi(),\n * 3,\n * 1000\n * );\n */\nexport function executeWithRetries<TFunc extends () => Promise<any>>(\n fn: TFunc,\n retries: number,\n timeout: number,\n): Promise<ReturnType<TFunc>> {\n return new Promise((resolve, reject) => {\n const retry = async (retries: number) => {\n try {\n const result = await fn()\n resolve(result)\n } catch (error) {\n if (retries > 0) {\n setTimeout(() => retry(retries - 1), timeout)\n } else {\n reject(error)\n }\n }\n }\n retry(retries)\n })\n}\n","import {v4 as uuidv4} from 'uuid'\n\nexport function generateUUID() {\n return uuidv4()\n}\n\nexport function generateUUIDWithPrefix(prefix: string) {\n return `${prefix}-${generateUUID()}`\n}\n","/**\n * Removes diacritical marks (accents) from text without any other modifications.\n * This is the most basic normalization function that others build upon.\n *\n * @param text - The input string to process\n * @returns String with accents removed but otherwise unchanged\n */\nexport function removeAccentsOnly(text: string) {\n if (!text) return ''\n // biome-ignore lint/suspicious/noMisleadingCharacterClass: Removes diacritical marks (accents)\n return text.normalize('NFD').replace(/[\\u0300-\\u036f]/g, '')\n}\n\n/**\n * Normalizes text by removing diacritical marks (accents) and trimming whitespace.\n * Builds on removeAccentsOnly and adds whitespace trimming.\n *\n * @param text - The input string to normalize\n * @returns Normalized string with accents removed and whitespace trimmed\n */\nexport function removeAccentsAndTrim(text: string) {\n if (!text) return ''\n return removeAccentsOnly(text).trim()\n}\n\n/**\n * Normalizes text for search purposes by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n *\n * Builds on removeAccentsAndTrim and adds lowercase conversion.\n * Useful for case-insensitive and accent-insensitive text searching.\n *\n * @param text - The input string to normalize for search\n * @returns Search-optimized string in lowercase with accents removed\n */\nexport function normalizeForSearch(text: string) {\n if (!text) return ''\n return removeAccentsAndTrim(text).toLowerCase()\n}\n\n/**\n * Normalizes text for search purposes by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n * - Removing all spaces\n *\n * Builds on normalizeForSearch and removes all whitespace.\n * Useful for compact search indexes or when spaces should be ignored in searches.\n *\n * @param text - The input string to normalize for compact search\n * @returns Compact search-optimized string with no spaces\n */\nexport function normalizeForCompactSearch(text: string) {\n if (!text) return ''\n return normalizeForSearch(text).replace(/\\s/g, '')\n}\n\n/**\n * Normalizes text for search token processing by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n * - Replacing all non-alphanumeric characters with spaces\n *\n * Builds on normalizeForSearch and replaces non-alphanumeric characters with spaces.\n * Useful for tokenizing search terms where special characters should be treated as word separators.\n *\n * @param text - The input string to normalize for tokenized search\n * @returns Search token string with only alphanumeric characters and spaces\n */\nexport function normalizeForSearchToken(text: string) {\n if (!text) return ''\n return normalizeForSearch(text).replace(/[^0-9a-z]/gi, ' ')\n}\n\n/**\n * Normalizes a string specifically for use as a file key (e.g., in S3 or other storage systems).\n * Performs the following transformations:\n * - Removes accents/diacritical marks\n * - Replaces special characters with hyphens\n * - Ensures only alphanumeric characters, hyphens, periods, and underscores remain\n * - Replaces multiple consecutive hyphens with a single hyphen\n * - Removes leading/trailing hyphens\n *\n * @param text - The input string to normalize for file key usage\n * @returns A storage-safe string suitable for use as a file key\n */\nexport function normalizeForFileKey(text: string) {\n if (!text) return ''\n return (\n removeAccentsOnly(text)\n // Replace spaces and unwanted characters with hyphens\n .replace(/[^a-zA-Z0-9-._]/g, '-')\n // Replace multiple consecutive hyphens with single hyphen\n .replace(/-+/g, '-')\n // Remove leading/trailing hyphens\n .trim()\n .replace(/^-+|-+$/g, '')\n )\n}\n","import {normalizeForSearchToken} from './normalize'\n\n/**\n * Generates an array of search tokens from input text and optional metadata.\n *\n * This function processes text by:\n * 1. Converting it to an array of strings (if not already)\n * 2. Filtering out falsy values\n * 3. Normalizing each string (removing accents, special characters)\n * 4. Splitting by spaces to create individual tokens\n * 5. Optionally adding metadata tokens in the format \"_key:value\"\n *\n * @param text - String or array of strings to tokenize\n * @param meta - Optional metadata object where each key-value pair becomes a token\n * @returns Array of normalized search tokens\n *\n * @example\n * // Returns ['hello', 'world']\n * getSearchTokens('Hello, World!')\n *\n * @example\n * // Returns ['hello', 'world', '_id:123']\n * getSearchTokens('Hello, World!', { id: '123' })\n */\nexport function getSearchTokens(text: string[] | string, meta?: Record<string, string>) {\n const stringArray = Array.isArray(text) ? text : [text]\n const tokens = stringArray\n .filter(Boolean)\n .map(text => String(text))\n .flatMap(word => {\n return normalizeForSearchToken(word).split(' ').filter(Boolean)\n })\n\n if (meta) {\n for (const key in meta) {\n tokens.push(`_${key}:${meta[key]}`)\n }\n }\n\n return tokens\n}\n\n/**\n * Interface for parameters used in generating search queries from tokens.\n *\n * @property filter - Optional string to filter search results\n * @property [key: string] - Additional key-value pairs for metadata filtering\n */\nexport interface SearchQueryForTokensParams {\n filter?: string\n [key: string]: string\n}\n\n/**\n * Options for customizing the search query generation behavior.\n * Currently empty but provided for future extensibility.\n */\nexport type SearchQueryForTokensOptions = {}\n\n/**\n * Generates a MongoDB-compatible query object based on the provided parameters.\n *\n * This function:\n * 1. Processes any filter text into RegExp tokens for prefix matching\n * 2. Adds metadata filters based on additional properties in the params object\n * 3. Returns a query object with the $all operator for MongoDB queries\n *\n * @param params - Parameters for generating the search query\n * @param _options - Options for customizing search behavior (reserved for future use)\n * @returns A MongoDB-compatible query object with format { $all: [...tokens] }\n *\n * @example\n * // Returns { $all: [/^hello/, /^world/] }\n * getSearchQueryForTokens({ filter: 'Hello World' })\n *\n * @example\n * // Returns { $all: [/^search/, '_category:books'] }\n * getSearchQueryForTokens({ filter: 'search', category: 'books' })\n */\nexport function getSearchQueryForTokens(\n params: SearchQueryForTokensParams = {},\n _options: SearchQueryForTokensOptions = {},\n) {\n const searchTokens: (string | RegExp)[] = []\n\n if (params.filter) {\n const filterTokens = getSearchTokens(params.filter).map(token => new RegExp(`^${token}`))\n searchTokens.push(...filterTokens)\n }\n\n for (const key in params) {\n if (key === 'filter') continue\n if (!params[key]) continue\n searchTokens.push(`_${key}:${params[key]}`)\n }\n\n return {$all: searchTokens}\n}\n","function lastOfString(string: string, last: number) {\n return string.substring(string.length - last, string.length)\n}\n\nexport function shortenMongoId(string: string) {\n return lastOfString(string, 5).toUpperCase()\n}\n","import {generateId} from '../../helpers/dist'\n\ntype Token<T> = {new (...args: any[]): T}\n\nconst instances = new Map<Token<any>, any>()\nconst serviceMetadata = new WeakMap<object, {id: string; name: string}>()\nconst injectionMetadata = new WeakMap<object, Record<string | symbol, () => Token<any>>>()\n\nexport function Service() {\n return (_target: Function, context: ClassDecoratorContext) => {\n serviceMetadata.set(context, {\n id: generateId(12),\n name: context.name,\n })\n }\n}\n\nexport function Inject<T>(getDependency: () => Token<T>) {\n return (_: undefined, context: ClassFieldDecoratorContext) => {\n context.addInitializer(function (this: any) {\n const metadata = injectionMetadata.get(this) || {}\n metadata[context.name] = getDependency\n injectionMetadata.set(this, metadata)\n })\n }\n}\n\nexport function getInstance<T extends object>(token: Token<T>): T {\n if (!instances.has(token)) {\n const instance = new token()\n instances.set(token, instance)\n\n const injections = injectionMetadata.get(instance)\n if (injections) {\n for (const [propertyKey, getDependency] of Object.entries(injections)) {\n instance[propertyKey] = getInstance(getDependency())\n }\n }\n }\n return instances.get(token)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AGAA,oBAAmB;AAEnB,IAAM,qBAAqB;AAE3B,IAAM,YAAY,SAAU,QAAQ;AAClC,MAAI,WAAW,KAAK,KAAK,SAAS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eAAS,QAAQ,IAAI,IAAI;AACzB,wBAAkB,IAAI,MAAM,QAAQ;AAAA,IACtC,CAAC;AAAA,EACH;AACF;AAEO,SAAS,YAA8B,OAAoB;AAChE,MAAI,CAAC,UAAU,IAAI,KAAK,GAAG;AACzB,UAAM,WAAW,IAAI,MAAM;AAC3B,cAAU,IAAI,OAAO,QAAQ;AAE7B,UAAM,aAAa,kBAAkB,IAAI,QAAQ;AACjD,QAAI,YAAY;AACd,iBAAW,CAAC,aAAa,aAAa,KAAK,OAAO,QAAQ,UAAU,GAAG;AACrE,iBAAS,WAAW,IAAI,YAAY,cAAc,CAAC;AAAA,MACrD;AAAA,IACF;AAAA,EACF;AACA,SAAO,UAAU,IAAI,KAAK;AAC5B;","names":["crypto"]}
package/dist/index.js CHANGED
@@ -1,424 +1,13 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
- }) : x)(function(x) {
10
- if (typeof require !== "undefined") return require.apply(this, arguments);
11
- throw Error('Dynamic require of "' + x + '" is not supported');
12
- });
13
- var __commonJS = (cb, mod) => function __require2() {
14
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
- };
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from))
19
- if (!__hasOwnProp.call(to, key) && key !== except)
20
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
- }
22
- return to;
23
- };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
- // If the importer is in node compatibility mode or this is not an ESM
26
- // file that has been converted to a CommonJS file using a Babel-
27
- // compatible transform (i.e. "__esModule" has not been set), then set
28
- // "default" to the CommonJS "module.exports" for node compatibility.
29
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
- mod
31
- ));
32
-
33
- // ../../node_modules/.pnpm/object-hash@2.2.0/node_modules/object-hash/index.js
34
- var require_object_hash = __commonJS({
35
- "../../node_modules/.pnpm/object-hash@2.2.0/node_modules/object-hash/index.js"(exports, module) {
36
- "use strict";
37
- var crypto2 = __require("crypto");
38
- exports = module.exports = objectHash;
39
- function objectHash(object, options) {
40
- options = applyDefaults(object, options);
41
- return hash2(object, options);
42
- }
43
- exports.sha1 = function(object) {
44
- return objectHash(object);
45
- };
46
- exports.keys = function(object) {
47
- return objectHash(object, { excludeValues: true, algorithm: "sha1", encoding: "hex" });
48
- };
49
- exports.MD5 = function(object) {
50
- return objectHash(object, { algorithm: "md5", encoding: "hex" });
51
- };
52
- exports.keysMD5 = function(object) {
53
- return objectHash(object, { algorithm: "md5", encoding: "hex", excludeValues: true });
54
- };
55
- var hashes = crypto2.getHashes ? crypto2.getHashes().slice() : ["sha1", "md5"];
56
- hashes.push("passthrough");
57
- var encodings = ["buffer", "hex", "binary", "base64"];
58
- function applyDefaults(object, sourceOptions) {
59
- sourceOptions = sourceOptions || {};
60
- var options = {};
61
- options.algorithm = sourceOptions.algorithm || "sha1";
62
- options.encoding = sourceOptions.encoding || "hex";
63
- options.excludeValues = sourceOptions.excludeValues ? true : false;
64
- options.algorithm = options.algorithm.toLowerCase();
65
- options.encoding = options.encoding.toLowerCase();
66
- options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true;
67
- options.respectType = sourceOptions.respectType === false ? false : true;
68
- options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true;
69
- options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true;
70
- options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true;
71
- options.unorderedSets = sourceOptions.unorderedSets === false ? false : true;
72
- options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true;
73
- options.replacer = sourceOptions.replacer || void 0;
74
- options.excludeKeys = sourceOptions.excludeKeys || void 0;
75
- if (typeof object === "undefined") {
76
- throw new Error("Object argument required.");
77
- }
78
- for (var i = 0; i < hashes.length; ++i) {
79
- if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) {
80
- options.algorithm = hashes[i];
81
- }
82
- }
83
- if (hashes.indexOf(options.algorithm) === -1) {
84
- throw new Error('Algorithm "' + options.algorithm + '" not supported. supported values: ' + hashes.join(", "));
85
- }
86
- if (encodings.indexOf(options.encoding) === -1 && options.algorithm !== "passthrough") {
87
- throw new Error('Encoding "' + options.encoding + '" not supported. supported values: ' + encodings.join(", "));
88
- }
89
- return options;
90
- }
91
- function isNativeFunction(f) {
92
- if (typeof f !== "function") {
93
- return false;
94
- }
95
- var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i;
96
- return exp.exec(Function.prototype.toString.call(f)) != null;
97
- }
98
- function hash2(object, options) {
99
- var hashingStream;
100
- if (options.algorithm !== "passthrough") {
101
- hashingStream = crypto2.createHash(options.algorithm);
102
- } else {
103
- hashingStream = new PassThrough();
104
- }
105
- if (typeof hashingStream.write === "undefined") {
106
- hashingStream.write = hashingStream.update;
107
- hashingStream.end = hashingStream.update;
108
- }
109
- var hasher = typeHasher(options, hashingStream);
110
- hasher.dispatch(object);
111
- if (!hashingStream.update) {
112
- hashingStream.end("");
113
- }
114
- if (hashingStream.digest) {
115
- return hashingStream.digest(options.encoding === "buffer" ? void 0 : options.encoding);
116
- }
117
- var buf = hashingStream.read();
118
- if (options.encoding === "buffer") {
119
- return buf;
120
- }
121
- return buf.toString(options.encoding);
122
- }
123
- exports.writeToStream = function(object, options, stream) {
124
- if (typeof stream === "undefined") {
125
- stream = options;
126
- options = {};
127
- }
128
- options = applyDefaults(object, options);
129
- return typeHasher(options, stream).dispatch(object);
130
- };
131
- function typeHasher(options, writeTo, context) {
132
- context = context || [];
133
- var write = function(str) {
134
- if (writeTo.update) {
135
- return writeTo.update(str, "utf8");
136
- } else {
137
- return writeTo.write(str, "utf8");
138
- }
139
- };
140
- return {
141
- dispatch: function(value) {
142
- if (options.replacer) {
143
- value = options.replacer(value);
144
- }
145
- var type = typeof value;
146
- if (value === null) {
147
- type = "null";
148
- }
149
- return this["_" + type](value);
150
- },
151
- _object: function(object) {
152
- var pattern = /\[object (.*)\]/i;
153
- var objString = Object.prototype.toString.call(object);
154
- var objType = pattern.exec(objString);
155
- if (!objType) {
156
- objType = "unknown:[" + objString + "]";
157
- } else {
158
- objType = objType[1];
159
- }
160
- objType = objType.toLowerCase();
161
- var objectNumber = null;
162
- if ((objectNumber = context.indexOf(object)) >= 0) {
163
- return this.dispatch("[CIRCULAR:" + objectNumber + "]");
164
- } else {
165
- context.push(object);
166
- }
167
- if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) {
168
- write("buffer:");
169
- return write(object);
170
- }
171
- if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") {
172
- if (this["_" + objType]) {
173
- this["_" + objType](object);
174
- } else if (options.ignoreUnknown) {
175
- return write("[" + objType + "]");
176
- } else {
177
- throw new Error('Unknown object type "' + objType + '"');
178
- }
179
- } else {
180
- var keys = Object.keys(object);
181
- if (options.unorderedObjects) {
182
- keys = keys.sort();
183
- }
184
- if (options.respectType !== false && !isNativeFunction(object)) {
185
- keys.splice(0, 0, "prototype", "__proto__", "constructor");
186
- }
187
- if (options.excludeKeys) {
188
- keys = keys.filter(function(key) {
189
- return !options.excludeKeys(key);
190
- });
191
- }
192
- write("object:" + keys.length + ":");
193
- var self = this;
194
- return keys.forEach(function(key) {
195
- self.dispatch(key);
196
- write(":");
197
- if (!options.excludeValues) {
198
- self.dispatch(object[key]);
199
- }
200
- write(",");
201
- });
202
- }
203
- },
204
- _array: function(arr, unordered) {
205
- unordered = typeof unordered !== "undefined" ? unordered : options.unorderedArrays !== false;
206
- var self = this;
207
- write("array:" + arr.length + ":");
208
- if (!unordered || arr.length <= 1) {
209
- return arr.forEach(function(entry) {
210
- return self.dispatch(entry);
211
- });
212
- }
213
- var contextAdditions = [];
214
- var entries = arr.map(function(entry) {
215
- var strm = new PassThrough();
216
- var localContext = context.slice();
217
- var hasher = typeHasher(options, strm, localContext);
218
- hasher.dispatch(entry);
219
- contextAdditions = contextAdditions.concat(localContext.slice(context.length));
220
- return strm.read().toString();
221
- });
222
- context = context.concat(contextAdditions);
223
- entries.sort();
224
- return this._array(entries, false);
225
- },
226
- _date: function(date) {
227
- return write("date:" + date.toJSON());
228
- },
229
- _symbol: function(sym) {
230
- return write("symbol:" + sym.toString());
231
- },
232
- _error: function(err) {
233
- return write("error:" + err.toString());
234
- },
235
- _boolean: function(bool) {
236
- return write("bool:" + bool.toString());
237
- },
238
- _string: function(string) {
239
- write("string:" + string.length + ":");
240
- write(string.toString());
241
- },
242
- _function: function(fn) {
243
- write("fn:");
244
- if (isNativeFunction(fn)) {
245
- this.dispatch("[native]");
246
- } else {
247
- this.dispatch(fn.toString());
248
- }
249
- if (options.respectFunctionNames !== false) {
250
- this.dispatch("function-name:" + String(fn.name));
251
- }
252
- if (options.respectFunctionProperties) {
253
- this._object(fn);
254
- }
255
- },
256
- _number: function(number) {
257
- return write("number:" + number.toString());
258
- },
259
- _xml: function(xml) {
260
- return write("xml:" + xml.toString());
261
- },
262
- _null: function() {
263
- return write("Null");
264
- },
265
- _undefined: function() {
266
- return write("Undefined");
267
- },
268
- _regexp: function(regex) {
269
- return write("regex:" + regex.toString());
270
- },
271
- _uint8array: function(arr) {
272
- write("uint8array:");
273
- return this.dispatch(Array.prototype.slice.call(arr));
274
- },
275
- _uint8clampedarray: function(arr) {
276
- write("uint8clampedarray:");
277
- return this.dispatch(Array.prototype.slice.call(arr));
278
- },
279
- _int8array: function(arr) {
280
- write("uint8array:");
281
- return this.dispatch(Array.prototype.slice.call(arr));
282
- },
283
- _uint16array: function(arr) {
284
- write("uint16array:");
285
- return this.dispatch(Array.prototype.slice.call(arr));
286
- },
287
- _int16array: function(arr) {
288
- write("uint16array:");
289
- return this.dispatch(Array.prototype.slice.call(arr));
290
- },
291
- _uint32array: function(arr) {
292
- write("uint32array:");
293
- return this.dispatch(Array.prototype.slice.call(arr));
294
- },
295
- _int32array: function(arr) {
296
- write("uint32array:");
297
- return this.dispatch(Array.prototype.slice.call(arr));
298
- },
299
- _float32array: function(arr) {
300
- write("float32array:");
301
- return this.dispatch(Array.prototype.slice.call(arr));
302
- },
303
- _float64array: function(arr) {
304
- write("float64array:");
305
- return this.dispatch(Array.prototype.slice.call(arr));
306
- },
307
- _arraybuffer: function(arr) {
308
- write("arraybuffer:");
309
- return this.dispatch(new Uint8Array(arr));
310
- },
311
- _url: function(url) {
312
- return write("url:" + url.toString(), "utf8");
313
- },
314
- _map: function(map) {
315
- write("map:");
316
- var arr = Array.from(map);
317
- return this._array(arr, options.unorderedSets !== false);
318
- },
319
- _set: function(set) {
320
- write("set:");
321
- var arr = Array.from(set);
322
- return this._array(arr, options.unorderedSets !== false);
323
- },
324
- _file: function(file) {
325
- write("file:");
326
- return this.dispatch([file.name, file.size, file.type, file.lastModfied]);
327
- },
328
- _blob: function() {
329
- if (options.ignoreUnknown) {
330
- return write("[blob]");
331
- }
332
- throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n');
333
- },
334
- _domwindow: function() {
335
- return write("domwindow");
336
- },
337
- _bigint: function(number) {
338
- return write("bigint:" + number.toString());
339
- },
340
- /* Node.js standard native objects */
341
- _process: function() {
342
- return write("process");
343
- },
344
- _timer: function() {
345
- return write("timer");
346
- },
347
- _pipe: function() {
348
- return write("pipe");
349
- },
350
- _tcp: function() {
351
- return write("tcp");
352
- },
353
- _udp: function() {
354
- return write("udp");
355
- },
356
- _tty: function() {
357
- return write("tty");
358
- },
359
- _statwatcher: function() {
360
- return write("statwatcher");
361
- },
362
- _securecontext: function() {
363
- return write("securecontext");
364
- },
365
- _connection: function() {
366
- return write("connection");
367
- },
368
- _zlib: function() {
369
- return write("zlib");
370
- },
371
- _context: function() {
372
- return write("context");
373
- },
374
- _nodescript: function() {
375
- return write("nodescript");
376
- },
377
- _httpparser: function() {
378
- return write("httpparser");
379
- },
380
- _dataview: function() {
381
- return write("dataview");
382
- },
383
- _signal: function() {
384
- return write("signal");
385
- },
386
- _fsevent: function() {
387
- return write("fsevent");
388
- },
389
- _tlswrap: function() {
390
- return write("tlswrap");
391
- }
392
- };
393
- }
394
- function PassThrough() {
395
- return {
396
- buf: "",
397
- write: function(b) {
398
- this.buf += b;
399
- },
400
- end: function(b) {
401
- this.buf += b;
402
- },
403
- read: function() {
404
- return this.buf;
405
- }
406
- };
407
- }
408
- }
409
- });
410
-
411
1
  // ../helpers/dist/index.js
412
- var import_object_hash = __toESM(require_object_hash(), 1);
413
- import crypto from "crypto";
2
+ import crypto2 from "crypto";
414
3
  var UNMISTAKABLE_CHARS = "23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghjkmnopqrstuvwxyz";
415
4
  var hexString = function(digits) {
416
5
  var numBytes = Math.ceil(digits / 2);
417
6
  var bytes;
418
7
  try {
419
- bytes = crypto.randomBytes(numBytes);
8
+ bytes = crypto2.randomBytes(numBytes);
420
9
  } catch (e) {
421
- bytes = crypto.pseudoRandomBytes(numBytes);
10
+ bytes = crypto2.pseudoRandomBytes(numBytes);
422
11
  }
423
12
  var result = bytes.toString("hex");
424
13
  return result.substring(0, digits);
@@ -445,6 +34,7 @@ function generateId(charsCount, chars = UNMISTAKABLE_CHARS) {
445
34
  }
446
35
  return randomString(charsCount, chars);
447
36
  }
37
+ var { isArray } = Array;
448
38
 
449
39
  // src/di.ts
450
40
  var instances = /* @__PURE__ */ new Map();
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/object-hash@2.2.0/node_modules/object-hash/index.js","../../helpers/src/sleep.ts","../../helpers/src/hashObject.ts","../../helpers/src/generateId.ts","../../helpers/src/createMap.ts","../../helpers/src/createMapArray.ts","../../helpers/src/Errors/OrionError.ts","../../helpers/src/Errors/PermissionsError.ts","../../helpers/src/Errors/UserError.ts","../../helpers/src/Errors/index.ts","../../helpers/src/composeMiddlewares.ts","../../helpers/src/retries.ts","../../helpers/src/generateUUID.ts","../../helpers/src/normalize.ts","../../helpers/src/searchTokens.ts","../../helpers/src/shortenMongoId.ts","../src/di.ts"],"sourcesContent":["'use strict';\n\nvar crypto = require('crypto');\n\n/**\n * Exported function\n *\n * Options:\n *\n * - `algorithm` hash algo to be used by this instance: *'sha1', 'md5'\n * - `excludeValues` {true|*false} hash object keys, values ignored\n * - `encoding` hash encoding, supports 'buffer', '*hex', 'binary', 'base64'\n * - `ignoreUnknown` {true|*false} ignore unknown object types\n * - `replacer` optional function that replaces values before hashing\n * - `respectFunctionProperties` {*true|false} consider function properties when hashing\n * - `respectFunctionNames` {*true|false} consider 'name' property of functions for hashing\n * - `respectType` {*true|false} Respect special properties (prototype, constructor)\n * when hashing to distinguish between types\n * - `unorderedArrays` {true|*false} Sort all arrays before hashing\n * - `unorderedSets` {*true|false} Sort `Set` and `Map` instances before hashing\n * * = default\n *\n * @param {object} object value to hash\n * @param {object} options hashing options\n * @return {string} hash value\n * @api public\n */\nexports = module.exports = objectHash;\n\nfunction objectHash(object, options){\n options = applyDefaults(object, options);\n\n return hash(object, options);\n}\n\n/**\n * Exported sugar methods\n *\n * @param {object} object value to hash\n * @return {string} hash value\n * @api public\n */\nexports.sha1 = function(object){\n return objectHash(object);\n};\nexports.keys = function(object){\n return objectHash(object, {excludeValues: true, algorithm: 'sha1', encoding: 'hex'});\n};\nexports.MD5 = function(object){\n return objectHash(object, {algorithm: 'md5', encoding: 'hex'});\n};\nexports.keysMD5 = function(object){\n return objectHash(object, {algorithm: 'md5', encoding: 'hex', excludeValues: true});\n};\n\n// Internals\nvar hashes = crypto.getHashes ? crypto.getHashes().slice() : ['sha1', 'md5'];\nhashes.push('passthrough');\nvar encodings = ['buffer', 'hex', 'binary', 'base64'];\n\nfunction applyDefaults(object, sourceOptions){\n sourceOptions = sourceOptions || {};\n\n // create a copy rather than mutating\n var options = {};\n options.algorithm = sourceOptions.algorithm || 'sha1';\n options.encoding = sourceOptions.encoding || 'hex';\n options.excludeValues = sourceOptions.excludeValues ? true : false;\n options.algorithm = options.algorithm.toLowerCase();\n options.encoding = options.encoding.toLowerCase();\n options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true; // default to false\n options.respectType = sourceOptions.respectType === false ? false : true; // default to true\n options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true;\n options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true;\n options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true; // default to false\n options.unorderedSets = sourceOptions.unorderedSets === false ? false : true; // default to false\n options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true; // default to true\n options.replacer = sourceOptions.replacer || undefined;\n options.excludeKeys = sourceOptions.excludeKeys || undefined;\n\n if(typeof object === 'undefined') {\n throw new Error('Object argument required.');\n }\n\n // if there is a case-insensitive match in the hashes list, accept it\n // (i.e. SHA256 for sha256)\n for (var i = 0; i < hashes.length; ++i) {\n if (hashes[i].toLowerCase() === options.algorithm.toLowerCase()) {\n options.algorithm = hashes[i];\n }\n }\n\n if(hashes.indexOf(options.algorithm) === -1){\n throw new Error('Algorithm \"' + options.algorithm + '\" not supported. ' +\n 'supported values: ' + hashes.join(', '));\n }\n\n if(encodings.indexOf(options.encoding) === -1 &&\n options.algorithm !== 'passthrough'){\n throw new Error('Encoding \"' + options.encoding + '\" not supported. ' +\n 'supported values: ' + encodings.join(', '));\n }\n\n return options;\n}\n\n/** Check if the given function is a native function */\nfunction isNativeFunction(f) {\n if ((typeof f) !== 'function') {\n return false;\n }\n var exp = /^function\\s+\\w*\\s*\\(\\s*\\)\\s*{\\s+\\[native code\\]\\s+}$/i;\n return exp.exec(Function.prototype.toString.call(f)) != null;\n}\n\nfunction hash(object, options) {\n var hashingStream;\n\n if (options.algorithm !== 'passthrough') {\n hashingStream = crypto.createHash(options.algorithm);\n } else {\n hashingStream = new PassThrough();\n }\n\n if (typeof hashingStream.write === 'undefined') {\n hashingStream.write = hashingStream.update;\n hashingStream.end = hashingStream.update;\n }\n\n var hasher = typeHasher(options, hashingStream);\n hasher.dispatch(object);\n if (!hashingStream.update) {\n hashingStream.end('');\n }\n\n if (hashingStream.digest) {\n return hashingStream.digest(options.encoding === 'buffer' ? undefined : options.encoding);\n }\n\n var buf = hashingStream.read();\n if (options.encoding === 'buffer') {\n return buf;\n }\n\n return buf.toString(options.encoding);\n}\n\n/**\n * Expose streaming API\n *\n * @param {object} object Value to serialize\n * @param {object} options Options, as for hash()\n * @param {object} stream A stream to write the serializiation to\n * @api public\n */\nexports.writeToStream = function(object, options, stream) {\n if (typeof stream === 'undefined') {\n stream = options;\n options = {};\n }\n\n options = applyDefaults(object, options);\n\n return typeHasher(options, stream).dispatch(object);\n};\n\nfunction typeHasher(options, writeTo, context){\n context = context || [];\n var write = function(str) {\n if (writeTo.update) {\n return writeTo.update(str, 'utf8');\n } else {\n return writeTo.write(str, 'utf8');\n }\n };\n\n return {\n dispatch: function(value){\n if (options.replacer) {\n value = options.replacer(value);\n }\n\n var type = typeof value;\n if (value === null) {\n type = 'null';\n }\n\n //console.log(\"[DEBUG] Dispatch: \", value, \"->\", type, \" -> \", \"_\" + type);\n\n return this['_' + type](value);\n },\n _object: function(object) {\n var pattern = (/\\[object (.*)\\]/i);\n var objString = Object.prototype.toString.call(object);\n var objType = pattern.exec(objString);\n if (!objType) { // object type did not match [object ...]\n objType = 'unknown:[' + objString + ']';\n } else {\n objType = objType[1]; // take only the class name\n }\n\n objType = objType.toLowerCase();\n\n var objectNumber = null;\n\n if ((objectNumber = context.indexOf(object)) >= 0) {\n return this.dispatch('[CIRCULAR:' + objectNumber + ']');\n } else {\n context.push(object);\n }\n\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(object)) {\n write('buffer:');\n return write(object);\n }\n\n if(objType !== 'object' && objType !== 'function' && objType !== 'asyncfunction') {\n if(this['_' + objType]) {\n this['_' + objType](object);\n } else if (options.ignoreUnknown) {\n return write('[' + objType + ']');\n } else {\n throw new Error('Unknown object type \"' + objType + '\"');\n }\n }else{\n var keys = Object.keys(object);\n if (options.unorderedObjects) {\n keys = keys.sort();\n }\n // Make sure to incorporate special properties, so\n // Types with different prototypes will produce\n // a different hash and objects derived from\n // different functions (`new Foo`, `new Bar`) will\n // produce different hashes.\n // We never do this for native functions since some\n // seem to break because of that.\n if (options.respectType !== false && !isNativeFunction(object)) {\n keys.splice(0, 0, 'prototype', '__proto__', 'constructor');\n }\n\n if (options.excludeKeys) {\n keys = keys.filter(function(key) { return !options.excludeKeys(key); });\n }\n\n write('object:' + keys.length + ':');\n var self = this;\n return keys.forEach(function(key){\n self.dispatch(key);\n write(':');\n if(!options.excludeValues) {\n self.dispatch(object[key]);\n }\n write(',');\n });\n }\n },\n _array: function(arr, unordered){\n unordered = typeof unordered !== 'undefined' ? unordered :\n options.unorderedArrays !== false; // default to options.unorderedArrays\n\n var self = this;\n write('array:' + arr.length + ':');\n if (!unordered || arr.length <= 1) {\n return arr.forEach(function(entry) {\n return self.dispatch(entry);\n });\n }\n\n // the unordered case is a little more complicated:\n // since there is no canonical ordering on objects,\n // i.e. {a:1} < {a:2} and {a:1} > {a:2} are both false,\n // we first serialize each entry using a PassThrough stream\n // before sorting.\n // also: we can’t use the same context array for all entries\n // since the order of hashing should *not* matter. instead,\n // we keep track of the additions to a copy of the context array\n // and add all of them to the global context array when we’re done\n var contextAdditions = [];\n var entries = arr.map(function(entry) {\n var strm = new PassThrough();\n var localContext = context.slice(); // make copy\n var hasher = typeHasher(options, strm, localContext);\n hasher.dispatch(entry);\n // take only what was added to localContext and append it to contextAdditions\n contextAdditions = contextAdditions.concat(localContext.slice(context.length));\n return strm.read().toString();\n });\n context = context.concat(contextAdditions);\n entries.sort();\n return this._array(entries, false);\n },\n _date: function(date){\n return write('date:' + date.toJSON());\n },\n _symbol: function(sym){\n return write('symbol:' + sym.toString());\n },\n _error: function(err){\n return write('error:' + err.toString());\n },\n _boolean: function(bool){\n return write('bool:' + bool.toString());\n },\n _string: function(string){\n write('string:' + string.length + ':');\n write(string.toString());\n },\n _function: function(fn){\n write('fn:');\n if (isNativeFunction(fn)) {\n this.dispatch('[native]');\n } else {\n this.dispatch(fn.toString());\n }\n\n if (options.respectFunctionNames !== false) {\n // Make sure we can still distinguish native functions\n // by their name, otherwise String and Function will\n // have the same hash\n this.dispatch(\"function-name:\" + String(fn.name));\n }\n\n if (options.respectFunctionProperties) {\n this._object(fn);\n }\n },\n _number: function(number){\n return write('number:' + number.toString());\n },\n _xml: function(xml){\n return write('xml:' + xml.toString());\n },\n _null: function() {\n return write('Null');\n },\n _undefined: function() {\n return write('Undefined');\n },\n _regexp: function(regex){\n return write('regex:' + regex.toString());\n },\n _uint8array: function(arr){\n write('uint8array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _uint8clampedarray: function(arr){\n write('uint8clampedarray:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _int8array: function(arr){\n write('uint8array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _uint16array: function(arr){\n write('uint16array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _int16array: function(arr){\n write('uint16array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _uint32array: function(arr){\n write('uint32array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _int32array: function(arr){\n write('uint32array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _float32array: function(arr){\n write('float32array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _float64array: function(arr){\n write('float64array:');\n return this.dispatch(Array.prototype.slice.call(arr));\n },\n _arraybuffer: function(arr){\n write('arraybuffer:');\n return this.dispatch(new Uint8Array(arr));\n },\n _url: function(url) {\n return write('url:' + url.toString(), 'utf8');\n },\n _map: function(map) {\n write('map:');\n var arr = Array.from(map);\n return this._array(arr, options.unorderedSets !== false);\n },\n _set: function(set) {\n write('set:');\n var arr = Array.from(set);\n return this._array(arr, options.unorderedSets !== false);\n },\n _file: function(file) {\n write('file:');\n return this.dispatch([file.name, file.size, file.type, file.lastModfied]);\n },\n _blob: function() {\n if (options.ignoreUnknown) {\n return write('[blob]');\n }\n\n throw Error('Hashing Blob objects is currently not supported\\n' +\n '(see https://github.com/puleos/object-hash/issues/26)\\n' +\n 'Use \"options.replacer\" or \"options.ignoreUnknown\"\\n');\n },\n _domwindow: function() { return write('domwindow'); },\n _bigint: function(number){\n return write('bigint:' + number.toString());\n },\n /* Node.js standard native objects */\n _process: function() { return write('process'); },\n _timer: function() { return write('timer'); },\n _pipe: function() { return write('pipe'); },\n _tcp: function() { return write('tcp'); },\n _udp: function() { return write('udp'); },\n _tty: function() { return write('tty'); },\n _statwatcher: function() { return write('statwatcher'); },\n _securecontext: function() { return write('securecontext'); },\n _connection: function() { return write('connection'); },\n _zlib: function() { return write('zlib'); },\n _context: function() { return write('context'); },\n _nodescript: function() { return write('nodescript'); },\n _httpparser: function() { return write('httpparser'); },\n _dataview: function() { return write('dataview'); },\n _signal: function() { return write('signal'); },\n _fsevent: function() { return write('fsevent'); },\n _tlswrap: function() { return write('tlswrap'); },\n };\n}\n\n// Mini-implementation of stream.PassThrough\n// We are far from having need for the full implementation, and we can\n// make assumptions like \"many writes, then only one final read\"\n// and we can ignore encoding specifics\nfunction PassThrough() {\n return {\n buf: '',\n\n write: function(b) {\n this.buf += b;\n },\n\n end: function(b) {\n this.buf += b;\n },\n\n read: function() {\n return this.buf;\n }\n };\n}\n","/**\n * Creates a timeout with a promise\n */\nexport default (time: number): Promise<void> => {\n return new Promise(resolve => setTimeout(resolve, time))\n}\n","import hash from 'object-hash'\n\nexport default function (object: any): string {\n return hash(object)\n}\n","import crypto from 'crypto'\n\nconst UNMISTAKABLE_CHARS = '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghjkmnopqrstuvwxyz'\n\nconst hexString = function (digits) {\n var numBytes = Math.ceil(digits / 2)\n var bytes\n // Try to get cryptographically strong randomness. Fall back to\n // non-cryptographically strong if not available.\n try {\n bytes = crypto.randomBytes(numBytes)\n } catch (e) {\n // XXX should re-throw any error except insufficient entropy\n bytes = crypto.pseudoRandomBytes(numBytes)\n }\n var result = bytes.toString('hex')\n // If the number of digits is odd, we'll have generated an extra 4 bits\n // of randomness, so we need to trim the last digit.\n return result.substring(0, digits)\n}\n\nconst fraction = function () {\n var numerator = parseInt(hexString(8), 16)\n return numerator * 2.3283064365386963e-10 // 2^-32\n}\n\nconst choice = function (arrayOrString) {\n var index = Math.floor(fraction() * arrayOrString.length)\n if (typeof arrayOrString === 'string') return arrayOrString.substr(index, 1)\n else return arrayOrString[index]\n}\n\nconst randomString = function (charsCount, alphabet) {\n var digits = []\n for (var i = 0; i < charsCount; i++) {\n digits[i] = choice(alphabet)\n }\n return digits.join('')\n}\n\n/**\n * Returns a random ID\n * @param charsCount length of the ID\n * @param chars characters used to generate the ID\n */\nexport default function generateId(\n charsCount?: number,\n chars: string = UNMISTAKABLE_CHARS,\n): string {\n if (!charsCount) {\n charsCount = 17\n }\n\n return randomString(charsCount, chars)\n}\n","/**\n * Creates a map (object) from an array of items, using a specified property as the key.\n *\n * This utility transforms an array of objects into a lookup object/dictionary where\n * each item in the array becomes a value in the map, indexed by the specified property.\n * If multiple items have the same key value, only the last one will be preserved.\n *\n * @template T The type of items in the input array\n * @param array - The input array of items to transform into a map\n * @param key - The property name to use as keys in the resulting map (defaults to '_id')\n * @returns A record object where keys are values of the specified property and values are the original items\n *\n * @example\n * // Returns { '1': { id: 1, name: 'Item 1' }, '2': { id: 2, name: 'Item 2' } }\n * createMap([{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }], 'id')\n */\nexport default function createMap<T>(array: Array<T>, key: string = '_id'): Record<string, T> {\n const map = {}\n\n for (const item of array) {\n map[item[key]] = item\n }\n\n return map\n}\n","/**\n * Creates a grouped map from an array of items, using a specified property as the key.\n *\n * This utility transforms an array of objects into a lookup object/dictionary where\n * each value is an array of items sharing the same key value. Unlike createMap,\n * this function preserves all items with the same key by grouping them in arrays.\n *\n * @template T The type of items in the input array\n * @param array - The input array of items to transform into a grouped map\n * @param key - The property name to use as keys in the resulting map (defaults to '_id')\n * @returns A record object where keys are values of the specified property and values are arrays of items\n *\n * @example\n * // Returns { 'category1': [{ id: 1, category: 'category1' }, { id: 3, category: 'category1' }],\n * // 'category2': [{ id: 2, category: 'category2' }] }\n * createMapArray([\n * { id: 1, category: 'category1' },\n * { id: 2, category: 'category2' },\n * { id: 3, category: 'category1' }\n * ], 'category')\n */\nexport default function createMapArray<T>(\n array: Array<T>,\n key: string = '_id',\n): Record<string, Array<T>> {\n const map = {}\n\n for (const item of array) {\n map[item[key]] = map[item[key]] || []\n map[item[key]].push(item)\n }\n\n return map\n}\n","/**\n * Interface representing the standardized error information structure for Orion errors.\n * This is used by the getInfo method to provide consistent error reporting.\n */\nexport interface OrionErrorInformation {\n /** The error code or identifier */\n error: string\n /** Human-readable error message */\n message: string\n /** Additional error metadata or context */\n extra: any\n /** The sub-type of error. For example for permissions errors it could be 'read', 'write', 'admin' */\n type?: string\n}\n\n/**\n * Base error class for all Orion-specific errors.\n *\n * This abstract class provides common properties and methods for all error types\n * used in the Orion framework. It's extended by more specific error classes\n * like UserError and PermissionsError.\n *\n * @property isOrionError - Flag indicating this is an Orion error (always true)\n * @property isUserError - Flag indicating if this is a user-facing error\n * @property isPermissionsError - Flag indicating if this is a permissions-related error\n * @property code - Error code for identifying the error type\n * @property extra - Additional error context or metadata\n */\nexport class OrionError extends Error {\n isOrionError = true\n\n isUserError: boolean\n isPermissionsError: boolean\n code: string\n extra: any\n\n /**\n * Returns a standardized representation of the error information.\n * @returns An object containing error details in a consistent format\n */\n getInfo: () => OrionErrorInformation\n}\n","import {OrionError} from './OrionError'\n\n/**\n * Error class for permission-related errors in the Orion framework.\n *\n * PermissionsError represents authorization failures where a user or client\n * attempts to perform an action they don't have permission to execute.\n * This is used to distinguish security/permissions errors from other types\n * of errors for proper error handling and user feedback.\n *\n * @extends OrionError\n */\nexport default class PermissionsError extends OrionError {\n /**\n * Creates a new PermissionsError instance.\n *\n * @param permissionErrorType - Identifies the specific permission that was violated\n * (e.g., 'read', 'write', 'admin')\n * @param extra - Additional error context or metadata. Can include a custom message\n * via the message property.\n *\n * @example\n * // Basic usage\n * throw new PermissionsError('delete_document')\n *\n * @example\n * // With custom message\n * throw new PermissionsError('access_admin', { message: 'Admin access required' })\n *\n * @example\n * // With additional context\n * throw new PermissionsError('edit_user', {\n * userId: 'user123',\n * requiredRole: 'admin'\n * })\n */\n constructor(permissionErrorType, extra: any = {}) {\n // Calling parent constructor of base Error class.\n const message =\n extra.message || `Client is not allowed to perform this action [${permissionErrorType}]`\n\n super(message)\n Error.captureStackTrace(this, this.constructor)\n\n this.isOrionError = true\n this.isPermissionsError = true\n this.code = 'PermissionsError'\n this.extra = extra\n\n this.getInfo = () => {\n return {\n ...extra,\n error: 'PermissionsError',\n message,\n type: permissionErrorType,\n }\n }\n }\n}\n","import {OrionError} from './OrionError'\n\n/**\n * Error class for user-facing errors in the Orion framework.\n *\n * UserError is designed to represent errors that should be displayed to end users,\n * as opposed to system errors or unexpected failures. These errors typically represent\n * validation issues, business rule violations, or other expected error conditions.\n *\n * @extends OrionError\n */\nexport default class UserError extends OrionError {\n /**\n * Creates a new UserError instance.\n *\n * @param code - Error code identifier. If only one parameter is provided,\n * this will be used as the message and code will default to 'error'.\n * @param message - Human-readable error message. Optional if code is provided.\n * @param extra - Additional error context or metadata.\n *\n * @example\n * // Basic usage\n * throw new UserError('invalid_input', 'The provided email is invalid')\n *\n * @example\n * // Using only a message (code will be 'error')\n * throw new UserError('Input validation failed')\n *\n * @example\n * // With extra metadata\n * throw new UserError('rate_limit', 'Too many requests', { maxRequests: 100 })\n */\n constructor(code: string, message?: string, extra?: any) {\n if (!message && code) {\n message = code\n code = 'error'\n }\n\n super(message)\n Error.captureStackTrace(this, this.constructor)\n\n this.isOrionError = true\n this.isUserError = true\n this.code = code\n this.extra = extra\n\n this.getInfo = () => {\n return {\n error: code,\n message,\n extra,\n }\n }\n }\n}\n","/**\n * @file Exports all error classes used in the Orion framework\n */\n\nimport {OrionError} from './OrionError'\nimport type {OrionErrorInformation} from './OrionError'\nimport PermissionsError from './PermissionsError'\nimport UserError from './UserError'\n\n/**\n * Re-export all error types for convenient importing\n */\nexport {OrionError, PermissionsError, UserError}\nexport type {OrionErrorInformation}\n\n/**\n * Type guard to check if an error is an OrionError\n *\n * @param error - Any error object to test\n * @returns True if the error is an OrionError instance\n *\n * @example\n * try {\n * // some code that might throw\n * } catch (error) {\n * if (isOrionError(error)) {\n * // Handle Orion-specific error\n * console.log(error.code, error.getInfo())\n * } else {\n * // Handle general error\n * }\n * }\n */\nexport function isOrionError(error: any): error is OrionError {\n return Boolean(error && typeof error === 'object' && error.isOrionError === true)\n}\n\n/**\n * Type guard to check if an error is a UserError\n *\n * @param error - Any error object to test\n * @returns True if the error is a UserError instance\n */\nexport function isUserError(error: any): error is UserError {\n return Boolean(\n error && typeof error === 'object' && error.isOrionError === true && error.isUserError === true,\n )\n}\n\n/**\n * Type guard to check if an error is a PermissionsError\n *\n * @param error - Any error object to test\n * @returns True if the error is a PermissionsError instance\n */\nexport function isPermissionsError(error: any): error is PermissionsError {\n return Boolean(\n error &&\n typeof error === 'object' &&\n error.isOrionError === true &&\n error.isPermissionsError === true,\n )\n}\n","// from https://github.com/koajs/compose/blob/master/index.js\n\n/**\n * Compose `middleware` returning\n * a fully valid middleware comprised\n * of all those which are passed.\n */\nexport function composeMiddlewares(middleware) {\n if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')\n for (const fn of middleware) {\n if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')\n }\n\n /**\n * @param {Object} context\n * @return {Promise}\n * @api public\n */\n\n return function (context, next?) {\n // last called middleware #\n let index = -1\n return dispatch(0)\n function dispatch(i) {\n if (i <= index) return Promise.reject(new Error('next() called multiple times'))\n index = i\n let fn = middleware[i]\n if (i === middleware.length) fn = next\n if (!fn) return Promise.resolve()\n try {\n return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))\n } catch (err) {\n return Promise.reject(err)\n }\n }\n }\n}\n","/**\n * Executes an asynchronous function with automatic retries on failure.\n *\n * This utility attempts to execute the provided function and automatically\n * retries if it fails, with a specified delay between attempts. It will\n * continue retrying until either the function succeeds or the maximum\n * number of retries is reached.\n *\n * @template TFunc Type of the function to execute (must return a Promise)\n * @param fn - The asynchronous function to execute\n * @param retries - The maximum number of retry attempts after the initial attempt\n * @param timeout - The delay in milliseconds between retry attempts\n * @returns A promise that resolves with the result of the function or rejects with the last error\n *\n * @example\n * // Retry an API call up to 3 times with 1 second between attempts\n * const result = await executeWithRetries(\n * () => fetchDataFromApi(),\n * 3,\n * 1000\n * );\n */\nexport function executeWithRetries<TFunc extends () => Promise<any>>(\n fn: TFunc,\n retries: number,\n timeout: number,\n): Promise<ReturnType<TFunc>> {\n return new Promise((resolve, reject) => {\n const retry = async (retries: number) => {\n try {\n const result = await fn()\n resolve(result)\n } catch (error) {\n if (retries > 0) {\n setTimeout(() => retry(retries - 1), timeout)\n } else {\n reject(error)\n }\n }\n }\n retry(retries)\n })\n}\n","import {v4 as uuidv4} from 'uuid'\n\nexport function generateUUID() {\n return uuidv4()\n}\n\nexport function generateUUIDWithPrefix(prefix: string) {\n return `${prefix}-${generateUUID()}`\n}\n","/**\n * Removes diacritical marks (accents) from text without any other modifications.\n * This is the most basic normalization function that others build upon.\n *\n * @param text - The input string to process\n * @returns String with accents removed but otherwise unchanged\n */\nexport function removeAccentsOnly(text: string) {\n if (!text) return ''\n // biome-ignore lint/suspicious/noMisleadingCharacterClass: Removes diacritical marks (accents)\n return text.normalize('NFD').replace(/[\\u0300-\\u036f]/g, '')\n}\n\n/**\n * Normalizes text by removing diacritical marks (accents) and trimming whitespace.\n * Builds on removeAccentsOnly and adds whitespace trimming.\n *\n * @param text - The input string to normalize\n * @returns Normalized string with accents removed and whitespace trimmed\n */\nexport function removeAccentsAndTrim(text: string) {\n if (!text) return ''\n return removeAccentsOnly(text).trim()\n}\n\n/**\n * Normalizes text for search purposes by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n *\n * Builds on removeAccentsAndTrim and adds lowercase conversion.\n * Useful for case-insensitive and accent-insensitive text searching.\n *\n * @param text - The input string to normalize for search\n * @returns Search-optimized string in lowercase with accents removed\n */\nexport function normalizeForSearch(text: string) {\n if (!text) return ''\n return removeAccentsAndTrim(text).toLowerCase()\n}\n\n/**\n * Normalizes text for search purposes by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n * - Removing all spaces\n *\n * Builds on normalizeForSearch and removes all whitespace.\n * Useful for compact search indexes or when spaces should be ignored in searches.\n *\n * @param text - The input string to normalize for compact search\n * @returns Compact search-optimized string with no spaces\n */\nexport function normalizeForCompactSearch(text: string) {\n if (!text) return ''\n return normalizeForSearch(text).replace(/\\s/g, '')\n}\n\n/**\n * Normalizes text for search token processing by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n * - Replacing all non-alphanumeric characters with spaces\n *\n * Builds on normalizeForSearch and replaces non-alphanumeric characters with spaces.\n * Useful for tokenizing search terms where special characters should be treated as word separators.\n *\n * @param text - The input string to normalize for tokenized search\n * @returns Search token string with only alphanumeric characters and spaces\n */\nexport function normalizeForSearchToken(text: string) {\n if (!text) return ''\n return normalizeForSearch(text).replace(/[^0-9a-z]/gi, ' ')\n}\n\n/**\n * Normalizes a string specifically for use as a file key (e.g., in S3 or other storage systems).\n * Performs the following transformations:\n * - Removes accents/diacritical marks\n * - Replaces special characters with hyphens\n * - Ensures only alphanumeric characters, hyphens, periods, and underscores remain\n * - Replaces multiple consecutive hyphens with a single hyphen\n * - Removes leading/trailing hyphens\n *\n * @param text - The input string to normalize for file key usage\n * @returns A storage-safe string suitable for use as a file key\n */\nexport function normalizeForFileKey(text: string) {\n if (!text) return ''\n return (\n removeAccentsOnly(text)\n // Replace spaces and unwanted characters with hyphens\n .replace(/[^a-zA-Z0-9-._]/g, '-')\n // Replace multiple consecutive hyphens with single hyphen\n .replace(/-+/g, '-')\n // Remove leading/trailing hyphens\n .trim()\n .replace(/^-+|-+$/g, '')\n )\n}\n","import {normalizeForSearchToken} from './normalize'\n\n/**\n * Generates an array of search tokens from input text and optional metadata.\n *\n * This function processes text by:\n * 1. Converting it to an array of strings (if not already)\n * 2. Filtering out falsy values\n * 3. Normalizing each string (removing accents, special characters)\n * 4. Splitting by spaces to create individual tokens\n * 5. Optionally adding metadata tokens in the format \"_key:value\"\n *\n * @param text - String or array of strings to tokenize\n * @param meta - Optional metadata object where each key-value pair becomes a token\n * @returns Array of normalized search tokens\n *\n * @example\n * // Returns ['hello', 'world']\n * getSearchTokens('Hello, World!')\n *\n * @example\n * // Returns ['hello', 'world', '_id:123']\n * getSearchTokens('Hello, World!', { id: '123' })\n */\nexport function getSearchTokens(text: string[] | string, meta?: Record<string, string>) {\n const stringArray = Array.isArray(text) ? text : [text]\n const tokens = stringArray\n .filter(Boolean)\n .map(text => String(text))\n .flatMap(word => {\n return normalizeForSearchToken(word).split(' ').filter(Boolean)\n })\n\n if (meta) {\n for (const key in meta) {\n tokens.push(`_${key}:${meta[key]}`)\n }\n }\n\n return tokens\n}\n\n/**\n * Interface for parameters used in generating search queries from tokens.\n *\n * @property filter - Optional string to filter search results\n * @property [key: string] - Additional key-value pairs for metadata filtering\n */\nexport interface SearchQueryForTokensParams {\n filter?: string\n [key: string]: string\n}\n\n/**\n * Options for customizing the search query generation behavior.\n * Currently empty but provided for future extensibility.\n */\nexport type SearchQueryForTokensOptions = {}\n\n/**\n * Generates a MongoDB-compatible query object based on the provided parameters.\n *\n * This function:\n * 1. Processes any filter text into RegExp tokens for prefix matching\n * 2. Adds metadata filters based on additional properties in the params object\n * 3. Returns a query object with the $all operator for MongoDB queries\n *\n * @param params - Parameters for generating the search query\n * @param _options - Options for customizing search behavior (reserved for future use)\n * @returns A MongoDB-compatible query object with format { $all: [...tokens] }\n *\n * @example\n * // Returns { $all: [/^hello/, /^world/] }\n * getSearchQueryForTokens({ filter: 'Hello World' })\n *\n * @example\n * // Returns { $all: [/^search/, '_category:books'] }\n * getSearchQueryForTokens({ filter: 'search', category: 'books' })\n */\nexport function getSearchQueryForTokens(\n params: SearchQueryForTokensParams = {},\n _options: SearchQueryForTokensOptions = {},\n) {\n const searchTokens: (string | RegExp)[] = []\n\n if (params.filter) {\n const filterTokens = getSearchTokens(params.filter).map(token => new RegExp(`^${token}`))\n searchTokens.push(...filterTokens)\n }\n\n for (const key in params) {\n if (key === 'filter') continue\n if (!params[key]) continue\n searchTokens.push(`_${key}:${params[key]}`)\n }\n\n return {$all: searchTokens}\n}\n","function lastOfString(string: string, last: number) {\n return string.substring(string.length - last, string.length)\n}\n\nexport function shortenMongoId(string: string) {\n return lastOfString(string, 5).toUpperCase()\n}\n","import {generateId} from '../../helpers/dist'\n\ntype Token<T> = {new (...args: any[]): T}\n\nconst instances = new Map<Token<any>, any>()\nconst serviceMetadata = new WeakMap<object, {id: string; name: string}>()\nconst injectionMetadata = new WeakMap<object, Record<string | symbol, () => Token<any>>>()\n\nexport function Service() {\n return (_target: Function, context: ClassDecoratorContext) => {\n serviceMetadata.set(context, {\n id: generateId(12),\n name: context.name,\n })\n }\n}\n\nexport function Inject<T>(getDependency: () => Token<T>) {\n return (_: undefined, context: ClassFieldDecoratorContext) => {\n context.addInitializer(function (this: any) {\n const metadata = injectionMetadata.get(this) || {}\n metadata[context.name] = getDependency\n injectionMetadata.set(this, metadata)\n })\n }\n}\n\nexport function getInstance<T extends object>(token: Token<T>): T {\n if (!instances.has(token)) {\n const instance = new token()\n instances.set(token, instance)\n\n const injections = injectionMetadata.get(instance)\n if (injections) {\n for (const [propertyKey, getDependency] of Object.entries(injections)) {\n instance[propertyKey] = getInstance(getDependency())\n }\n }\n }\n return instances.get(token)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,QAAIA,UAAS,UAAQ,QAAQ;AAyB7B,cAAU,OAAO,UAAU;AAE3B,aAAS,WAAW,QAAQ,SAAQ;AAClC,gBAAU,cAAc,QAAQ,OAAO;AAEvC,aAAOC,MAAK,QAAQ,OAAO;AAAA,IAC7B;AASA,YAAQ,OAAO,SAAS,QAAO;AAC7B,aAAO,WAAW,MAAM;AAAA,IAC1B;AACA,YAAQ,OAAO,SAAS,QAAO;AAC7B,aAAO,WAAW,QAAQ,EAAC,eAAe,MAAM,WAAW,QAAQ,UAAU,MAAK,CAAC;AAAA,IACrF;AACA,YAAQ,MAAM,SAAS,QAAO;AAC5B,aAAO,WAAW,QAAQ,EAAC,WAAW,OAAO,UAAU,MAAK,CAAC;AAAA,IAC/D;AACA,YAAQ,UAAU,SAAS,QAAO;AAChC,aAAO,WAAW,QAAQ,EAAC,WAAW,OAAO,UAAU,OAAO,eAAe,KAAI,CAAC;AAAA,IACpF;AAGA,QAAI,SAASD,QAAO,YAAYA,QAAO,UAAU,EAAE,MAAM,IAAI,CAAC,QAAQ,KAAK;AAC3E,WAAO,KAAK,aAAa;AACzB,QAAI,YAAY,CAAC,UAAU,OAAO,UAAU,QAAQ;AAEpD,aAAS,cAAc,QAAQ,eAAc;AAC3C,sBAAgB,iBAAiB,CAAC;AAGlC,UAAI,UAAU,CAAC;AACf,cAAQ,YAAY,cAAc,aAAa;AAC/C,cAAQ,WAAW,cAAc,YAAY;AAC7C,cAAQ,gBAAgB,cAAc,gBAAgB,OAAO;AAC7D,cAAQ,YAAY,QAAQ,UAAU,YA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sleep.ts","../../helpers/src/hashObject.ts","../../helpers/src/generateId.ts","../../helpers/src/createMap.ts","../../helpers/src/createMapArray.ts","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/type.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/_internals/isArray.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/isType.js","../../../node_modules/.pnpm/rambdax@11.3.1/node_modules/rambdax/src/clone.js","../../helpers/src/clone.ts","../../helpers/src/Errors/OrionError.ts","../../helpers/src/Errors/PermissionsError.ts","../../helpers/src/Errors/UserError.ts","../../helpers/src/Errors/index.ts","../../helpers/src/composeMiddlewares.ts","../../helpers/src/retries.ts","../../helpers/src/generateUUID.ts","../../helpers/src/normalize.ts","../../helpers/src/searchTokens.ts","../../helpers/src/shortenMongoId.ts","../src/di.ts"],"sourcesContent":["/**\n * Creates a timeout with a promise\n */\nexport default (time: number): Promise<void> => {\n return new Promise(resolve => setTimeout(resolve, time))\n}\n","import crypto from 'node:crypto'\n\n/**\n * Receives any javascript object, string, number, boolean, array, or object and returns a hash of it.\n */\nexport default function hashObject(object: any): string {\n const string = objectToString(object)\n return crypto.createHash('sha256').update(string).digest('hex')\n}\n\nfunction objectToString(object: any): string {\n if (object === null || object === undefined) {\n return 'null'\n }\n\n if (typeof object === 'string') {\n return object\n }\n\n if (typeof object === 'number' || typeof object === 'boolean') {\n return String(object)\n }\n\n if (object instanceof Date) {\n return object.toISOString()\n }\n\n if (Array.isArray(object)) {\n const arrayHash = object.map(item => hashObject(item)).join(',')\n return `[${arrayHash}]`\n }\n\n if (typeof object === 'object') {\n const keys = Object.keys(object).sort()\n const objectHash = keys.map(key => `${key}:${hashObject(object[key])}`).join(',')\n return `{${objectHash}}`\n }\n\n // Fallback for functions or other types\n return String(object)\n}\n","import crypto from 'crypto'\n\nconst UNMISTAKABLE_CHARS = '23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghjkmnopqrstuvwxyz'\n\nconst hexString = function (digits) {\n var numBytes = Math.ceil(digits / 2)\n var bytes\n // Try to get cryptographically strong randomness. Fall back to\n // non-cryptographically strong if not available.\n try {\n bytes = crypto.randomBytes(numBytes)\n } catch (e) {\n // XXX should re-throw any error except insufficient entropy\n bytes = crypto.pseudoRandomBytes(numBytes)\n }\n var result = bytes.toString('hex')\n // If the number of digits is odd, we'll have generated an extra 4 bits\n // of randomness, so we need to trim the last digit.\n return result.substring(0, digits)\n}\n\nconst fraction = function () {\n var numerator = parseInt(hexString(8), 16)\n return numerator * 2.3283064365386963e-10 // 2^-32\n}\n\nconst choice = function (arrayOrString) {\n var index = Math.floor(fraction() * arrayOrString.length)\n if (typeof arrayOrString === 'string') return arrayOrString.substr(index, 1)\n else return arrayOrString[index]\n}\n\nconst randomString = function (charsCount, alphabet) {\n var digits = []\n for (var i = 0; i < charsCount; i++) {\n digits[i] = choice(alphabet)\n }\n return digits.join('')\n}\n\n/**\n * Returns a random ID\n * @param charsCount length of the ID\n * @param chars characters used to generate the ID\n */\nexport default function generateId(\n charsCount?: number,\n chars: string = UNMISTAKABLE_CHARS,\n): string {\n if (!charsCount) {\n charsCount = 17\n }\n\n return randomString(charsCount, chars)\n}\n","/**\n * Creates a map (object) from an array of items, using a specified property as the key.\n *\n * This utility transforms an array of objects into a lookup object/dictionary where\n * each item in the array becomes a value in the map, indexed by the specified property.\n * If multiple items have the same key value, only the last one will be preserved.\n *\n * @template T The type of items in the input array\n * @param array - The input array of items to transform into a map\n * @param key - The property name to use as keys in the resulting map (defaults to '_id')\n * @returns A record object where keys are values of the specified property and values are the original items\n *\n * @example\n * // Returns { '1': { id: 1, name: 'Item 1' }, '2': { id: 2, name: 'Item 2' } }\n * createMap([{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }], 'id')\n */\nexport default function createMap<T>(array: Array<T>, key: string = '_id'): Record<string, T> {\n const map = {}\n\n for (const item of array) {\n map[item[key]] = item\n }\n\n return map\n}\n","/**\n * Creates a grouped map from an array of items, using a specified property as the key.\n *\n * This utility transforms an array of objects into a lookup object/dictionary where\n * each value is an array of items sharing the same key value. Unlike createMap,\n * this function preserves all items with the same key by grouping them in arrays.\n *\n * @template T The type of items in the input array\n * @param array - The input array of items to transform into a grouped map\n * @param key - The property name to use as keys in the resulting map (defaults to '_id')\n * @returns A record object where keys are values of the specified property and values are arrays of items\n *\n * @example\n * // Returns { 'category1': [{ id: 1, category: 'category1' }, { id: 3, category: 'category1' }],\n * // 'category2': [{ id: 2, category: 'category2' }] }\n * createMapArray([\n * { id: 1, category: 'category1' },\n * { id: 2, category: 'category2' },\n * { id: 3, category: 'category1' }\n * ], 'category')\n */\nexport default function createMapArray<T>(\n array: Array<T>,\n key: string = '_id',\n): Record<string, Array<T>> {\n const map = {}\n\n for (const item of array) {\n map[item[key]] = map[item[key]] || []\n map[item[key]].push(item)\n }\n\n return map\n}\n","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","export const { isArray } = Array\n","import { type } from './type.js'\n\nexport function isType(xType, x){\n if (arguments.length === 1){\n return xHolder => isType(xType, xHolder)\n }\n\n return type(x) === xType\n}\n","import { isArray } from './_internals/isArray.js'\n\nexport function clone(input){\n const out = isArray(input) ? Array(input.length) : {}\n if (input && input.getTime) return new Date(input.getTime())\n\n for (const key in input){\n const v = input[ key ]\n out[ key ] =\n typeof v === 'object' && v !== null ?\n v.getTime ?\n new Date(v.getTime()) :\n clone(v) :\n v\n }\n\n return out\n}\n","import {isType, clone as cloneRambdax} from 'rambdax'\n\nexport function clone<T>(value: T): T {\n if (isType('Object', value)) {\n return cloneRambdax(value)\n }\n\n if (Array.isArray(value)) {\n return cloneRambdax(value)\n }\n\n return value\n}\n","/**\n * Interface representing the standardized error information structure for Orion errors.\n * This is used by the getInfo method to provide consistent error reporting.\n */\nexport interface OrionErrorInformation {\n /** The error code or identifier */\n error: string\n /** Human-readable error message */\n message: string\n /** Additional error metadata or context */\n extra: any\n /** The sub-type of error. For example for permissions errors it could be 'read', 'write', 'admin' */\n type?: string\n}\n\n/**\n * Base error class for all Orion-specific errors.\n *\n * This abstract class provides common properties and methods for all error types\n * used in the Orion framework. It's extended by more specific error classes\n * like UserError and PermissionsError.\n *\n * @property isOrionError - Flag indicating this is an Orion error (always true)\n * @property isUserError - Flag indicating if this is a user-facing error\n * @property isPermissionsError - Flag indicating if this is a permissions-related error\n * @property code - Error code for identifying the error type\n * @property extra - Additional error context or metadata\n */\nexport class OrionError extends Error {\n isOrionError = true\n\n isUserError: boolean\n isPermissionsError: boolean\n code: string\n extra: any\n\n /**\n * Returns a standardized representation of the error information.\n * @returns An object containing error details in a consistent format\n */\n getInfo: () => OrionErrorInformation\n}\n","import {OrionError} from './OrionError'\n\n/**\n * Error class for permission-related errors in the Orion framework.\n *\n * PermissionsError represents authorization failures where a user or client\n * attempts to perform an action they don't have permission to execute.\n * This is used to distinguish security/permissions errors from other types\n * of errors for proper error handling and user feedback.\n *\n * @extends OrionError\n */\nexport default class PermissionsError extends OrionError {\n /**\n * Creates a new PermissionsError instance.\n *\n * @param permissionErrorType - Identifies the specific permission that was violated\n * (e.g., 'read', 'write', 'admin')\n * @param extra - Additional error context or metadata. Can include a custom message\n * via the message property.\n *\n * @example\n * // Basic usage\n * throw new PermissionsError('delete_document')\n *\n * @example\n * // With custom message\n * throw new PermissionsError('access_admin', { message: 'Admin access required' })\n *\n * @example\n * // With additional context\n * throw new PermissionsError('edit_user', {\n * userId: 'user123',\n * requiredRole: 'admin'\n * })\n */\n constructor(permissionErrorType, extra: any = {}) {\n // Calling parent constructor of base Error class.\n const message =\n extra.message || `Client is not allowed to perform this action [${permissionErrorType}]`\n\n super(message)\n Error.captureStackTrace(this, this.constructor)\n\n this.isOrionError = true\n this.isPermissionsError = true\n this.code = 'PermissionsError'\n this.extra = extra\n\n this.getInfo = () => {\n return {\n ...extra,\n error: 'PermissionsError',\n message,\n type: permissionErrorType,\n }\n }\n }\n}\n","import {OrionError} from './OrionError'\n\n/**\n * Error class for user-facing errors in the Orion framework.\n *\n * UserError is designed to represent errors that should be displayed to end users,\n * as opposed to system errors or unexpected failures. These errors typically represent\n * validation issues, business rule violations, or other expected error conditions.\n *\n * @extends OrionError\n */\nexport default class UserError extends OrionError {\n /**\n * Creates a new UserError instance.\n *\n * @param code - Error code identifier. If only one parameter is provided,\n * this will be used as the message and code will default to 'error'.\n * @param message - Human-readable error message. Optional if code is provided.\n * @param extra - Additional error context or metadata.\n *\n * @example\n * // Basic usage\n * throw new UserError('invalid_input', 'The provided email is invalid')\n *\n * @example\n * // Using only a message (code will be 'error')\n * throw new UserError('Input validation failed')\n *\n * @example\n * // With extra metadata\n * throw new UserError('rate_limit', 'Too many requests', { maxRequests: 100 })\n */\n constructor(code: string, message?: string, extra?: any) {\n if (!message && code) {\n message = code\n code = 'error'\n }\n\n super(message)\n Error.captureStackTrace(this, this.constructor)\n\n this.isOrionError = true\n this.isUserError = true\n this.code = code\n this.extra = extra\n\n this.getInfo = () => {\n return {\n error: code,\n message,\n extra,\n }\n }\n }\n}\n","/**\n * @file Exports all error classes used in the Orion framework\n */\n\nimport {OrionError} from './OrionError'\nimport type {OrionErrorInformation} from './OrionError'\nimport PermissionsError from './PermissionsError'\nimport UserError from './UserError'\n\n/**\n * Re-export all error types for convenient importing\n */\nexport {OrionError, PermissionsError, UserError}\nexport type {OrionErrorInformation}\n\n/**\n * Type guard to check if an error is an OrionError\n *\n * @param error - Any error object to test\n * @returns True if the error is an OrionError instance\n *\n * @example\n * try {\n * // some code that might throw\n * } catch (error) {\n * if (isOrionError(error)) {\n * // Handle Orion-specific error\n * console.log(error.code, error.getInfo())\n * } else {\n * // Handle general error\n * }\n * }\n */\nexport function isOrionError(error: any): error is OrionError {\n return Boolean(error && typeof error === 'object' && error.isOrionError === true)\n}\n\n/**\n * Type guard to check if an error is a UserError\n *\n * @param error - Any error object to test\n * @returns True if the error is a UserError instance\n */\nexport function isUserError(error: any): error is UserError {\n return Boolean(\n error && typeof error === 'object' && error.isOrionError === true && error.isUserError === true,\n )\n}\n\n/**\n * Type guard to check if an error is a PermissionsError\n *\n * @param error - Any error object to test\n * @returns True if the error is a PermissionsError instance\n */\nexport function isPermissionsError(error: any): error is PermissionsError {\n return Boolean(\n error &&\n typeof error === 'object' &&\n error.isOrionError === true &&\n error.isPermissionsError === true,\n )\n}\n","// from https://github.com/koajs/compose/blob/master/index.js\n\n/**\n * Compose `middleware` returning\n * a fully valid middleware comprised\n * of all those which are passed.\n */\nexport function composeMiddlewares(middleware) {\n if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')\n for (const fn of middleware) {\n if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')\n }\n\n /**\n * @param {Object} context\n * @return {Promise}\n * @api public\n */\n\n return function (context, next?) {\n // last called middleware #\n let index = -1\n return dispatch(0)\n function dispatch(i) {\n if (i <= index) return Promise.reject(new Error('next() called multiple times'))\n index = i\n let fn = middleware[i]\n if (i === middleware.length) fn = next\n if (!fn) return Promise.resolve()\n try {\n return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))\n } catch (err) {\n return Promise.reject(err)\n }\n }\n }\n}\n","/**\n * Executes an asynchronous function with automatic retries on failure.\n *\n * This utility attempts to execute the provided function and automatically\n * retries if it fails, with a specified delay between attempts. It will\n * continue retrying until either the function succeeds or the maximum\n * number of retries is reached.\n *\n * @template TFunc Type of the function to execute (must return a Promise)\n * @param fn - The asynchronous function to execute\n * @param retries - The maximum number of retry attempts after the initial attempt\n * @param timeout - The delay in milliseconds between retry attempts\n * @returns A promise that resolves with the result of the function or rejects with the last error\n *\n * @example\n * // Retry an API call up to 3 times with 1 second between attempts\n * const result = await executeWithRetries(\n * () => fetchDataFromApi(),\n * 3,\n * 1000\n * );\n */\nexport function executeWithRetries<TFunc extends () => Promise<any>>(\n fn: TFunc,\n retries: number,\n timeout: number,\n): Promise<ReturnType<TFunc>> {\n return new Promise((resolve, reject) => {\n const retry = async (retries: number) => {\n try {\n const result = await fn()\n resolve(result)\n } catch (error) {\n if (retries > 0) {\n setTimeout(() => retry(retries - 1), timeout)\n } else {\n reject(error)\n }\n }\n }\n retry(retries)\n })\n}\n","import {v4 as uuidv4} from 'uuid'\n\nexport function generateUUID() {\n return uuidv4()\n}\n\nexport function generateUUIDWithPrefix(prefix: string) {\n return `${prefix}-${generateUUID()}`\n}\n","/**\n * Removes diacritical marks (accents) from text without any other modifications.\n * This is the most basic normalization function that others build upon.\n *\n * @param text - The input string to process\n * @returns String with accents removed but otherwise unchanged\n */\nexport function removeAccentsOnly(text: string) {\n if (!text) return ''\n // biome-ignore lint/suspicious/noMisleadingCharacterClass: Removes diacritical marks (accents)\n return text.normalize('NFD').replace(/[\\u0300-\\u036f]/g, '')\n}\n\n/**\n * Normalizes text by removing diacritical marks (accents) and trimming whitespace.\n * Builds on removeAccentsOnly and adds whitespace trimming.\n *\n * @param text - The input string to normalize\n * @returns Normalized string with accents removed and whitespace trimmed\n */\nexport function removeAccentsAndTrim(text: string) {\n if (!text) return ''\n return removeAccentsOnly(text).trim()\n}\n\n/**\n * Normalizes text for search purposes by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n *\n * Builds on removeAccentsAndTrim and adds lowercase conversion.\n * Useful for case-insensitive and accent-insensitive text searching.\n *\n * @param text - The input string to normalize for search\n * @returns Search-optimized string in lowercase with accents removed\n */\nexport function normalizeForSearch(text: string) {\n if (!text) return ''\n return removeAccentsAndTrim(text).toLowerCase()\n}\n\n/**\n * Normalizes text for search purposes by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n * - Removing all spaces\n *\n * Builds on normalizeForSearch and removes all whitespace.\n * Useful for compact search indexes or when spaces should be ignored in searches.\n *\n * @param text - The input string to normalize for compact search\n * @returns Compact search-optimized string with no spaces\n */\nexport function normalizeForCompactSearch(text: string) {\n if (!text) return ''\n return normalizeForSearch(text).replace(/\\s/g, '')\n}\n\n/**\n * Normalizes text for search token processing by:\n * - Removing diacritical marks (accents)\n * - Converting to lowercase\n * - Trimming whitespace\n * - Replacing all non-alphanumeric characters with spaces\n *\n * Builds on normalizeForSearch and replaces non-alphanumeric characters with spaces.\n * Useful for tokenizing search terms where special characters should be treated as word separators.\n *\n * @param text - The input string to normalize for tokenized search\n * @returns Search token string with only alphanumeric characters and spaces\n */\nexport function normalizeForSearchToken(text: string) {\n if (!text) return ''\n return normalizeForSearch(text).replace(/[^0-9a-z]/gi, ' ')\n}\n\n/**\n * Normalizes a string specifically for use as a file key (e.g., in S3 or other storage systems).\n * Performs the following transformations:\n * - Removes accents/diacritical marks\n * - Replaces special characters with hyphens\n * - Ensures only alphanumeric characters, hyphens, periods, and underscores remain\n * - Replaces multiple consecutive hyphens with a single hyphen\n * - Removes leading/trailing hyphens\n *\n * @param text - The input string to normalize for file key usage\n * @returns A storage-safe string suitable for use as a file key\n */\nexport function normalizeForFileKey(text: string) {\n if (!text) return ''\n return (\n removeAccentsOnly(text)\n // Replace spaces and unwanted characters with hyphens\n .replace(/[^a-zA-Z0-9-._]/g, '-')\n // Replace multiple consecutive hyphens with single hyphen\n .replace(/-+/g, '-')\n // Remove leading/trailing hyphens\n .trim()\n .replace(/^-+|-+$/g, '')\n )\n}\n","import {normalizeForSearchToken} from './normalize'\n\n/**\n * Generates an array of search tokens from input text and optional metadata.\n *\n * This function processes text by:\n * 1. Converting it to an array of strings (if not already)\n * 2. Filtering out falsy values\n * 3. Normalizing each string (removing accents, special characters)\n * 4. Splitting by spaces to create individual tokens\n * 5. Optionally adding metadata tokens in the format \"_key:value\"\n *\n * @param text - String or array of strings to tokenize\n * @param meta - Optional metadata object where each key-value pair becomes a token\n * @returns Array of normalized search tokens\n *\n * @example\n * // Returns ['hello', 'world']\n * getSearchTokens('Hello, World!')\n *\n * @example\n * // Returns ['hello', 'world', '_id:123']\n * getSearchTokens('Hello, World!', { id: '123' })\n */\nexport function getSearchTokens(text: string[] | string, meta?: Record<string, string>) {\n const stringArray = Array.isArray(text) ? text : [text]\n const tokens = stringArray\n .filter(Boolean)\n .map(text => String(text))\n .flatMap(word => {\n return normalizeForSearchToken(word).split(' ').filter(Boolean)\n })\n\n if (meta) {\n for (const key in meta) {\n tokens.push(`_${key}:${meta[key]}`)\n }\n }\n\n return tokens\n}\n\n/**\n * Interface for parameters used in generating search queries from tokens.\n *\n * @property filter - Optional string to filter search results\n * @property [key: string] - Additional key-value pairs for metadata filtering\n */\nexport interface SearchQueryForTokensParams {\n filter?: string\n [key: string]: string\n}\n\n/**\n * Options for customizing the search query generation behavior.\n * Currently empty but provided for future extensibility.\n */\nexport type SearchQueryForTokensOptions = {}\n\n/**\n * Generates a MongoDB-compatible query object based on the provided parameters.\n *\n * This function:\n * 1. Processes any filter text into RegExp tokens for prefix matching\n * 2. Adds metadata filters based on additional properties in the params object\n * 3. Returns a query object with the $all operator for MongoDB queries\n *\n * @param params - Parameters for generating the search query\n * @param _options - Options for customizing search behavior (reserved for future use)\n * @returns A MongoDB-compatible query object with format { $all: [...tokens] }\n *\n * @example\n * // Returns { $all: [/^hello/, /^world/] }\n * getSearchQueryForTokens({ filter: 'Hello World' })\n *\n * @example\n * // Returns { $all: [/^search/, '_category:books'] }\n * getSearchQueryForTokens({ filter: 'search', category: 'books' })\n */\nexport function getSearchQueryForTokens(\n params: SearchQueryForTokensParams = {},\n _options: SearchQueryForTokensOptions = {},\n) {\n const searchTokens: (string | RegExp)[] = []\n\n if (params.filter) {\n const filterTokens = getSearchTokens(params.filter).map(token => new RegExp(`^${token}`))\n searchTokens.push(...filterTokens)\n }\n\n for (const key in params) {\n if (key === 'filter') continue\n if (!params[key]) continue\n searchTokens.push(`_${key}:${params[key]}`)\n }\n\n return {$all: searchTokens}\n}\n","function lastOfString(string: string, last: number) {\n return string.substring(string.length - last, string.length)\n}\n\nexport function shortenMongoId(string: string) {\n return lastOfString(string, 5).toUpperCase()\n}\n","import {generateId} from '../../helpers/dist'\n\ntype Token<T> = {new (...args: any[]): T}\n\nconst instances = new Map<Token<any>, any>()\nconst serviceMetadata = new WeakMap<object, {id: string; name: string}>()\nconst injectionMetadata = new WeakMap<object, Record<string | symbol, () => Token<any>>>()\n\nexport function Service() {\n return (_target: Function, context: ClassDecoratorContext) => {\n serviceMetadata.set(context, {\n id: generateId(12),\n name: context.name,\n })\n }\n}\n\nexport function Inject<T>(getDependency: () => Token<T>) {\n return (_: undefined, context: ClassFieldDecoratorContext) => {\n context.addInitializer(function (this: any) {\n const metadata = injectionMetadata.get(this) || {}\n metadata[context.name] = getDependency\n injectionMetadata.set(this, metadata)\n })\n }\n}\n\nexport function getInstance<T extends object>(token: Token<T>): T {\n if (!instances.has(token)) {\n const instance = new token()\n instances.set(token, instance)\n\n const injections = injectionMetadata.get(instance)\n if (injections) {\n for (const [propertyKey, getDependency] of Object.entries(injections)) {\n instance[propertyKey] = getInstance(getDependency())\n }\n }\n }\n return instances.get(token)\n}\n"],"mappings":";AEAA,OAAOA,aAAY;AAEnB,IAAM,qBAAqB;AAE3B,IAAM,YAAY,SAAU,QAAQ;AAClC,MAAI,WAAW,KAAK,KAAK,SAAS,CAAC;AACnC,MAAI;AAGJ,MAAI;AACF,YAAQC,QAAO,YAAY,QAAQ;EACrC,SAAS,GAAG;AAEV,YAAQA,QAAO,kBAAkB,QAAQ;EAC3C;AACA,MAAI,SAAS,MAAM,SAAS,KAAK;AAGjC,SAAO,OAAO,UAAU,GAAG,MAAM;AACnC;AAEA,IAAM,WAAW,WAAY;AAC3B,MAAI,YAAY,SAAS,UAAU,CAAC,GAAG,EAAE;AACzC,SAAO,YAAY;AACrB;AAEA,IAAM,SAAS,SAAU,eAAe;AACtC,MAAI,QAAQ,KAAK,MAAM,SAAS,IAAI,cAAc,MAAM;AACxD,MAAI,OAAO,kBAAkB,SAAU,QAAO,cAAc,OAAO,OAAO,CAAC;MACtE,QAAO,cA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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orion-js/services",
3
- "version": "4.0.0-next.5",
3
+ "version": "4.0.0-next.7",
4
4
  "main": "./dist/index.cjs",
5
5
  "types": "./dist/index.d.ts",
6
6
  "files": [
@@ -10,14 +10,13 @@
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "typedi": "^0.10.0",
13
- "@orion-js/helpers": "4.0.0-next.5"
13
+ "@orion-js/helpers": "4.0.0-next.7"
14
14
  },
15
15
  "devDependencies": {
16
- "@types/lodash": "4.14.176",
17
16
  "typescript": "^5.4.5",
18
17
  "@types/node": "^18.0.0",
19
18
  "tsup": "^8.0.1",
20
- "vitest": "^1.1.0"
19
+ "vitest": "^3.0.8"
21
20
  },
22
21
  "publishConfig": {
23
22
  "access": "public"