@orion-js/helpers 4.0.0-next.2 → 4.0.0-next.4
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/LICENSE +21 -0
- package/dist/index.cjs +69 -153
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +69 -155
- package/dist/index.js.map +1 -1
- package/package.json +12 -12
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Orionjs Team
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.cjs
CHANGED
|
@@ -4,7 +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 __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
8
7
|
var __export = (target, all) => {
|
|
9
8
|
for (var name in all)
|
|
10
9
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -58,21 +57,20 @@ __export(index_exports, {
|
|
|
58
57
|
module.exports = __toCommonJS(index_exports);
|
|
59
58
|
|
|
60
59
|
// src/sleep.ts
|
|
61
|
-
var sleep_default =
|
|
60
|
+
var sleep_default = (time) => {
|
|
62
61
|
return new Promise((resolve) => setTimeout(resolve, time));
|
|
63
|
-
}
|
|
62
|
+
};
|
|
64
63
|
|
|
65
64
|
// src/hashObject.ts
|
|
66
65
|
var import_object_hash = __toESM(require("object-hash"), 1);
|
|
67
66
|
function hashObject_default(object) {
|
|
68
67
|
return (0, import_object_hash.default)(object);
|
|
69
68
|
}
|
|
70
|
-
__name(hashObject_default, "default");
|
|
71
69
|
|
|
72
70
|
// src/generateId.ts
|
|
73
71
|
var import_crypto = __toESM(require("crypto"), 1);
|
|
74
72
|
var UNMISTAKABLE_CHARS = "23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghjkmnopqrstuvwxyz";
|
|
75
|
-
var hexString =
|
|
73
|
+
var hexString = function(digits) {
|
|
76
74
|
var numBytes = Math.ceil(digits / 2);
|
|
77
75
|
var bytes;
|
|
78
76
|
try {
|
|
@@ -82,30 +80,29 @@ var hexString = /* @__PURE__ */ __name(function(digits) {
|
|
|
82
80
|
}
|
|
83
81
|
var result = bytes.toString("hex");
|
|
84
82
|
return result.substring(0, digits);
|
|
85
|
-
}
|
|
86
|
-
var fraction =
|
|
83
|
+
};
|
|
84
|
+
var fraction = function() {
|
|
87
85
|
var numerator = parseInt(hexString(8), 16);
|
|
88
86
|
return numerator * 23283064365386963e-26;
|
|
89
|
-
}
|
|
90
|
-
var choice =
|
|
87
|
+
};
|
|
88
|
+
var choice = function(arrayOrString) {
|
|
91
89
|
var index = Math.floor(fraction() * arrayOrString.length);
|
|
92
90
|
if (typeof arrayOrString === "string") return arrayOrString.substr(index, 1);
|
|
93
91
|
else return arrayOrString[index];
|
|
94
|
-
}
|
|
95
|
-
var randomString =
|
|
92
|
+
};
|
|
93
|
+
var randomString = function(charsCount, alphabet) {
|
|
96
94
|
var digits = [];
|
|
97
95
|
for (var i = 0; i < charsCount; i++) {
|
|
98
96
|
digits[i] = choice(alphabet);
|
|
99
97
|
}
|
|
100
98
|
return digits.join("");
|
|
101
|
-
}
|
|
99
|
+
};
|
|
102
100
|
function generateId(charsCount, chars = UNMISTAKABLE_CHARS) {
|
|
103
101
|
if (!charsCount) {
|
|
104
102
|
charsCount = 17;
|
|
105
103
|
}
|
|
106
104
|
return randomString(charsCount, chars);
|
|
107
105
|
}
|
|
108
|
-
__name(generateId, "generateId");
|
|
109
106
|
|
|
110
107
|
// src/createMap.ts
|
|
111
108
|
function createMap(array, key = "_id") {
|
|
@@ -115,7 +112,6 @@ function createMap(array, key = "_id") {
|
|
|
115
112
|
}
|
|
116
113
|
return map;
|
|
117
114
|
}
|
|
118
|
-
__name(createMap, "createMap");
|
|
119
115
|
|
|
120
116
|
// src/createMapArray.ts
|
|
121
117
|
function createMapArray(array, key = "_id") {
|
|
@@ -126,49 +122,46 @@ function createMapArray(array, key = "_id") {
|
|
|
126
122
|
}
|
|
127
123
|
return map;
|
|
128
124
|
}
|
|
129
|
-
__name(createMapArray, "createMapArray");
|
|
130
125
|
|
|
131
126
|
// src/Errors/OrionError.ts
|
|
132
|
-
var
|
|
127
|
+
var OrionError = class extends Error {
|
|
133
128
|
isOrionError = true;
|
|
134
129
|
isUserError;
|
|
135
130
|
isPermissionsError;
|
|
136
131
|
code;
|
|
137
132
|
extra;
|
|
138
133
|
/**
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
134
|
+
* Returns a standardized representation of the error information.
|
|
135
|
+
* @returns An object containing error details in a consistent format
|
|
136
|
+
*/
|
|
142
137
|
getInfo;
|
|
143
138
|
};
|
|
144
|
-
__name(_OrionError, "OrionError");
|
|
145
|
-
var OrionError = _OrionError;
|
|
146
139
|
|
|
147
140
|
// src/Errors/PermissionsError.ts
|
|
148
|
-
var
|
|
141
|
+
var PermissionsError = class extends OrionError {
|
|
149
142
|
/**
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
143
|
+
* Creates a new PermissionsError instance.
|
|
144
|
+
*
|
|
145
|
+
* @param permissionErrorType - Identifies the specific permission that was violated
|
|
146
|
+
* (e.g., 'read', 'write', 'admin')
|
|
147
|
+
* @param extra - Additional error context or metadata. Can include a custom message
|
|
148
|
+
* via the message property.
|
|
149
|
+
*
|
|
150
|
+
* @example
|
|
151
|
+
* // Basic usage
|
|
152
|
+
* throw new PermissionsError('delete_document')
|
|
153
|
+
*
|
|
154
|
+
* @example
|
|
155
|
+
* // With custom message
|
|
156
|
+
* throw new PermissionsError('access_admin', { message: 'Admin access required' })
|
|
157
|
+
*
|
|
158
|
+
* @example
|
|
159
|
+
* // With additional context
|
|
160
|
+
* throw new PermissionsError('edit_user', {
|
|
161
|
+
* userId: 'user123',
|
|
162
|
+
* requiredRole: 'admin'
|
|
163
|
+
* })
|
|
164
|
+
*/
|
|
172
165
|
constructor(permissionErrorType, extra = {}) {
|
|
173
166
|
const message = extra.message || `Client is not allowed to perform this action [${permissionErrorType}]`;
|
|
174
167
|
super(message);
|
|
@@ -187,31 +180,29 @@ var _PermissionsError = class _PermissionsError extends OrionError {
|
|
|
187
180
|
};
|
|
188
181
|
}
|
|
189
182
|
};
|
|
190
|
-
__name(_PermissionsError, "PermissionsError");
|
|
191
|
-
var PermissionsError = _PermissionsError;
|
|
192
183
|
|
|
193
184
|
// src/Errors/UserError.ts
|
|
194
|
-
var
|
|
185
|
+
var UserError = class extends OrionError {
|
|
195
186
|
/**
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
187
|
+
* Creates a new UserError instance.
|
|
188
|
+
*
|
|
189
|
+
* @param code - Error code identifier. If only one parameter is provided,
|
|
190
|
+
* this will be used as the message and code will default to 'error'.
|
|
191
|
+
* @param message - Human-readable error message. Optional if code is provided.
|
|
192
|
+
* @param extra - Additional error context or metadata.
|
|
193
|
+
*
|
|
194
|
+
* @example
|
|
195
|
+
* // Basic usage
|
|
196
|
+
* throw new UserError('invalid_input', 'The provided email is invalid')
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* // Using only a message (code will be 'error')
|
|
200
|
+
* throw new UserError('Input validation failed')
|
|
201
|
+
*
|
|
202
|
+
* @example
|
|
203
|
+
* // With extra metadata
|
|
204
|
+
* throw new UserError('rate_limit', 'Too many requests', { maxRequests: 100 })
|
|
205
|
+
*/
|
|
215
206
|
constructor(code, message, extra) {
|
|
216
207
|
if (!message && code) {
|
|
217
208
|
message = code;
|
|
@@ -232,22 +223,21 @@ var _UserError = class _UserError extends OrionError {
|
|
|
232
223
|
};
|
|
233
224
|
}
|
|
234
225
|
};
|
|
235
|
-
__name(_UserError, "UserError");
|
|
236
|
-
var UserError = _UserError;
|
|
237
226
|
|
|
238
227
|
// src/Errors/index.ts
|
|
239
228
|
function isOrionError(error) {
|
|
240
229
|
return Boolean(error && typeof error === "object" && error.isOrionError === true);
|
|
241
230
|
}
|
|
242
|
-
__name(isOrionError, "isOrionError");
|
|
243
231
|
function isUserError(error) {
|
|
244
|
-
return Boolean(
|
|
232
|
+
return Boolean(
|
|
233
|
+
error && typeof error === "object" && error.isOrionError === true && error.isUserError === true
|
|
234
|
+
);
|
|
245
235
|
}
|
|
246
|
-
__name(isUserError, "isUserError");
|
|
247
236
|
function isPermissionsError(error) {
|
|
248
|
-
return Boolean(
|
|
237
|
+
return Boolean(
|
|
238
|
+
error && typeof error === "object" && error.isOrionError === true && error.isPermissionsError === true
|
|
239
|
+
);
|
|
249
240
|
}
|
|
250
|
-
__name(isPermissionsError, "isPermissionsError");
|
|
251
241
|
|
|
252
242
|
// src/composeMiddlewares.ts
|
|
253
243
|
function composeMiddlewares(middleware) {
|
|
@@ -270,15 +260,13 @@ function composeMiddlewares(middleware) {
|
|
|
270
260
|
return Promise.reject(err);
|
|
271
261
|
}
|
|
272
262
|
}
|
|
273
|
-
__name(dispatch, "dispatch");
|
|
274
263
|
};
|
|
275
264
|
}
|
|
276
|
-
__name(composeMiddlewares, "composeMiddlewares");
|
|
277
265
|
|
|
278
266
|
// src/retries.ts
|
|
279
267
|
function executeWithRetries(fn, retries, timeout) {
|
|
280
268
|
return new Promise((resolve, reject) => {
|
|
281
|
-
const retry =
|
|
269
|
+
const retry = async (retries2) => {
|
|
282
270
|
try {
|
|
283
271
|
const result = await fn();
|
|
284
272
|
resolve(result);
|
|
@@ -289,115 +277,49 @@ function executeWithRetries(fn, retries, timeout) {
|
|
|
289
277
|
reject(error);
|
|
290
278
|
}
|
|
291
279
|
}
|
|
292
|
-
}
|
|
280
|
+
};
|
|
293
281
|
retry(retries);
|
|
294
282
|
});
|
|
295
283
|
}
|
|
296
|
-
__name(executeWithRetries, "executeWithRetries");
|
|
297
|
-
|
|
298
|
-
// ../../node_modules/uuid/dist/esm-node/rng.js
|
|
299
|
-
var import_crypto2 = __toESM(require("crypto"));
|
|
300
|
-
var rnds8Pool = new Uint8Array(256);
|
|
301
|
-
var poolPtr = rnds8Pool.length;
|
|
302
|
-
function rng() {
|
|
303
|
-
if (poolPtr > rnds8Pool.length - 16) {
|
|
304
|
-
import_crypto2.default.randomFillSync(rnds8Pool);
|
|
305
|
-
poolPtr = 0;
|
|
306
|
-
}
|
|
307
|
-
return rnds8Pool.slice(poolPtr, poolPtr += 16);
|
|
308
|
-
}
|
|
309
|
-
__name(rng, "rng");
|
|
310
|
-
|
|
311
|
-
// ../../node_modules/uuid/dist/esm-node/regex.js
|
|
312
|
-
var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
|
|
313
|
-
|
|
314
|
-
// ../../node_modules/uuid/dist/esm-node/validate.js
|
|
315
|
-
function validate(uuid) {
|
|
316
|
-
return typeof uuid === "string" && regex_default.test(uuid);
|
|
317
|
-
}
|
|
318
|
-
__name(validate, "validate");
|
|
319
|
-
var validate_default = validate;
|
|
320
|
-
|
|
321
|
-
// ../../node_modules/uuid/dist/esm-node/stringify.js
|
|
322
|
-
var byteToHex = [];
|
|
323
|
-
for (let i = 0; i < 256; ++i) {
|
|
324
|
-
byteToHex.push((i + 256).toString(16).substr(1));
|
|
325
|
-
}
|
|
326
|
-
function stringify(arr, offset = 0) {
|
|
327
|
-
const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
|
|
328
|
-
if (!validate_default(uuid)) {
|
|
329
|
-
throw TypeError("Stringified UUID is invalid");
|
|
330
|
-
}
|
|
331
|
-
return uuid;
|
|
332
|
-
}
|
|
333
|
-
__name(stringify, "stringify");
|
|
334
|
-
var stringify_default = stringify;
|
|
335
|
-
|
|
336
|
-
// ../../node_modules/uuid/dist/esm-node/v4.js
|
|
337
|
-
function v4(options, buf, offset) {
|
|
338
|
-
options = options || {};
|
|
339
|
-
const rnds = options.random || (options.rng || rng)();
|
|
340
|
-
rnds[6] = rnds[6] & 15 | 64;
|
|
341
|
-
rnds[8] = rnds[8] & 63 | 128;
|
|
342
|
-
if (buf) {
|
|
343
|
-
offset = offset || 0;
|
|
344
|
-
for (let i = 0; i < 16; ++i) {
|
|
345
|
-
buf[offset + i] = rnds[i];
|
|
346
|
-
}
|
|
347
|
-
return buf;
|
|
348
|
-
}
|
|
349
|
-
return stringify_default(rnds);
|
|
350
|
-
}
|
|
351
|
-
__name(v4, "v4");
|
|
352
|
-
var v4_default = v4;
|
|
353
284
|
|
|
354
285
|
// src/generateUUID.ts
|
|
286
|
+
var import_uuid = require("uuid");
|
|
355
287
|
function generateUUID() {
|
|
356
|
-
return
|
|
288
|
+
return (0, import_uuid.v4)();
|
|
357
289
|
}
|
|
358
|
-
__name(generateUUID, "generateUUID");
|
|
359
290
|
function generateUUIDWithPrefix(prefix) {
|
|
360
291
|
return `${prefix}-${generateUUID()}`;
|
|
361
292
|
}
|
|
362
|
-
__name(generateUUIDWithPrefix, "generateUUIDWithPrefix");
|
|
363
293
|
|
|
364
294
|
// src/normalize.ts
|
|
365
295
|
function removeAccentsOnly(text) {
|
|
366
296
|
if (!text) return "";
|
|
367
297
|
return text.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
|
368
298
|
}
|
|
369
|
-
__name(removeAccentsOnly, "removeAccentsOnly");
|
|
370
299
|
function removeAccentsAndTrim(text) {
|
|
371
300
|
if (!text) return "";
|
|
372
301
|
return removeAccentsOnly(text).trim();
|
|
373
302
|
}
|
|
374
|
-
__name(removeAccentsAndTrim, "removeAccentsAndTrim");
|
|
375
303
|
function normalizeForSearch(text) {
|
|
376
304
|
if (!text) return "";
|
|
377
305
|
return removeAccentsAndTrim(text).toLowerCase();
|
|
378
306
|
}
|
|
379
|
-
__name(normalizeForSearch, "normalizeForSearch");
|
|
380
307
|
function normalizeForCompactSearch(text) {
|
|
381
308
|
if (!text) return "";
|
|
382
309
|
return normalizeForSearch(text).replace(/\s/g, "");
|
|
383
310
|
}
|
|
384
|
-
__name(normalizeForCompactSearch, "normalizeForCompactSearch");
|
|
385
311
|
function normalizeForSearchToken(text) {
|
|
386
312
|
if (!text) return "";
|
|
387
313
|
return normalizeForSearch(text).replace(/[^0-9a-z]/gi, " ");
|
|
388
314
|
}
|
|
389
|
-
__name(normalizeForSearchToken, "normalizeForSearchToken");
|
|
390
315
|
function normalizeForFileKey(text) {
|
|
391
316
|
if (!text) return "";
|
|
392
317
|
return removeAccentsOnly(text).replace(/[^a-zA-Z0-9-._]/g, "-").replace(/-+/g, "-").trim().replace(/^-+|-+$/g, "");
|
|
393
318
|
}
|
|
394
|
-
__name(normalizeForFileKey, "normalizeForFileKey");
|
|
395
319
|
|
|
396
320
|
// src/searchTokens.ts
|
|
397
321
|
function getSearchTokens(text, meta) {
|
|
398
|
-
const stringArray = Array.isArray(text) ? text : [
|
|
399
|
-
text
|
|
400
|
-
];
|
|
322
|
+
const stringArray = Array.isArray(text) ? text : [text];
|
|
401
323
|
const tokens = stringArray.filter(Boolean).map((text2) => String(text2)).flatMap((word) => {
|
|
402
324
|
return normalizeForSearchToken(word).split(" ").filter(Boolean);
|
|
403
325
|
});
|
|
@@ -408,7 +330,6 @@ function getSearchTokens(text, meta) {
|
|
|
408
330
|
}
|
|
409
331
|
return tokens;
|
|
410
332
|
}
|
|
411
|
-
__name(getSearchTokens, "getSearchTokens");
|
|
412
333
|
function getSearchQueryForTokens(params = {}, _options = {}) {
|
|
413
334
|
const searchTokens = [];
|
|
414
335
|
if (params.filter) {
|
|
@@ -420,21 +341,16 @@ function getSearchQueryForTokens(params = {}, _options = {}) {
|
|
|
420
341
|
if (!params[key]) continue;
|
|
421
342
|
searchTokens.push(`_${key}:${params[key]}`);
|
|
422
343
|
}
|
|
423
|
-
return {
|
|
424
|
-
$all: searchTokens
|
|
425
|
-
};
|
|
344
|
+
return { $all: searchTokens };
|
|
426
345
|
}
|
|
427
|
-
__name(getSearchQueryForTokens, "getSearchQueryForTokens");
|
|
428
346
|
|
|
429
347
|
// src/shortenMongoId.ts
|
|
430
348
|
function lastOfString(string, last) {
|
|
431
349
|
return string.substring(string.length - last, string.length);
|
|
432
350
|
}
|
|
433
|
-
__name(lastOfString, "lastOfString");
|
|
434
351
|
function shortenMongoId(string) {
|
|
435
352
|
return lastOfString(string, 5).toUpperCase();
|
|
436
353
|
}
|
|
437
|
-
__name(shortenMongoId, "shortenMongoId");
|
|
438
354
|
// Annotate the CommonJS export names for ESM import in node:
|
|
439
355
|
0 && (module.exports = {
|
|
440
356
|
OrionError,
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/sleep.ts","../src/hashObject.ts","../src/generateId.ts","../src/createMap.ts","../src/createMapArray.ts","../src/Errors/OrionError.ts","../src/Errors/PermissionsError.ts","../src/Errors/UserError.ts","../src/Errors/index.ts","../src/composeMiddlewares.ts","../src/retries.ts","../../../node_modules/uuid/dist/esm-node/rng.js","../../../node_modules/uuid/dist/esm-node/regex.js","../../../node_modules/uuid/dist/esm-node/validate.js","../../../node_modules/uuid/dist/esm-node/stringify.js","../../../node_modules/uuid/dist/esm-node/v4.js","../src/generateUUID.ts","../src/normalize.ts","../src/searchTokens.ts","../src/shortenMongoId.ts"],"sourcesContent":["import sleep from './sleep'\nimport hashObject from './hashObject'\nimport generateId from './generateId'\nimport createMap from './createMap'\nimport createMapArray from './createMapArray'\n\n// Import all error-related exports from the Errors module\nimport {\n OrionError,\n PermissionsError,\n UserError,\n isOrionError,\n isUserError,\n isPermissionsError\n} from './Errors'\nimport type {OrionErrorInformation} from './Errors'\n\nexport * from './composeMiddlewares'\nexport * from './retries'\nexport * from './generateUUID'\nexport * from './normalize'\nexport * from './searchTokens'\nexport * from './shortenMongoId'\nexport {\n // Utility functions\n createMap,\n createMapArray,\n generateId,\n hashObject,\n sleep,\n\n // Error classes\n OrionError,\n PermissionsError,\n UserError,\n\n // Error type guards\n isOrionError,\n isUserError,\n isPermissionsError\n}\n\nexport type {OrionErrorInformation}\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 crypto from 'crypto';\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n crypto.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;","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 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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACGA,IAAA,gBAAe,wBAACA,SAAAA;AACd,SAAO,IAAIC,QAAQC,CAAAA,YAAWC,WAAWD,SAASF,IAAAA,CAAAA;AACpD,GAFe;;;ACHf,yBAAiB;AAEF,SAAf,mBAAyBI,QAAW;AAClC,aAAOC,mBAAAA,SAAKD,MAAAA;AACd;AAFA;;;ACFA,oBAAmB;AAEnB,IAAME,qBAAqB;AAE3B,IAAMC,YAAY,gCAAUC,QAAM;AAChC,MAAIC,WAAWC,KAAKC,KAAKH,SAAS,CAAA;AAClC,MAAII;AAGJ,MAAI;AACFA,YAAQC,cAAAA,QAAOC,YAAYL,QAAAA;EAC7B,SAASM,GAAG;AAEVH,YAAQC,cAAAA,QAAOG,kBAAkBP,QAAAA;EACnC;AACA,MAAIQ,SAASL,MAAMM,SAAS,KAAA;AAG5B,SAAOD,OAAOE,UAAU,GAAGX,MAAAA;AAC7B,GAfkB;AAiBlB,IAAMY,WAAW,kCAAA;AACf,MAAIC,YAAYC,SAASf,UAAU,CAAA,GAAI,EAAA;AACvC,SAAOc,YAAY;AACrB,GAHiB;AAKjB,IAAME,SAAS,gCAAUC,eAAa;AACpC,MAAIC,QAAQf,KAAKgB,MAAMN,SAAAA,IAAaI,cAAcG,MAAM;AACxD,MAAI,OAAOH,kBAAkB,SAAU,QAAOA,cA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BO;;;AClET,SAASC,gBAAgBC,MAAyBC,MAA6B;AACpF,QAAMC,cAAcC,MAAMC,QAAQJ,IAAAA,IAAQA,OAAO;IAACA;;AAClD,QAAMK,SAASH,YACZI,OAAOC,OAAAA,EACPC,IAAIR,CAAAA,UAAQS,OAAOT,KAAAA,CAAAA,EACnBU,QAAQC,CAAAA,SAAAA;AACP,WAAOC,wBAAwBD,IAAAA,EAAME,MAAM,GAAA,EAAKP,OAAOC,OAAAA;EACzD,CAAA;AAEF,MAAIN,MAAM;AACR,eAAWa,OAAOb,MAAM;AACtBI,aAAOU,KAAK,IAAID,GAAAA,IAAOb,KAAKa,GAAAA,CAAI,EAAE;IACpC;EACF;AAEA,SAAOT;AACT;AAhBgBN;AAuDT,SAASiB,wBACdC,SAAqC,CAAC,GACtCC,WAAwC,CAAC,GAAC;AAE1C,QAAMC,eAAoC,CAAA;AAE1C,MAAIF,OAAOX,QAAQ;AACjB,UAAMc,eAAerB,gBAAgBkB,OAAOX,MAAM,EAAEE,IAAIa,CAAAA,UAAS,IAAIC,OAAO,IAAID,KAAAA,EAAO,CAAA;AACvFF,iBAAaJ,KAAI,GAAIK,YAAAA;EACvB;AAEA,aAAWN,OAAOG,QAAQ;AACxB,QAAIH,QAAQ,SAAU;AACtB,QAAI,CAACG,OAAOH,GAAAA,EAAM;AAClBK,iBAAaJ,KAAK,IAAID,GAAAA,IAAOG,OAAOH,GAAAA,CAAI,EAAE;EAC5C;AAEA,SAAO;IAAES,MAAMJ;EAAa;AAC9B;AAlBgBH;;;AC/EhB,SAASQ,aAAaC,QAAgBC,MAAY;AAChD,SAAOD,OAAOE,UAAUF,OAAOG,SAASF,MAAMD,OAAOG,MAAM;AAC7D;AAFSJ;AAIF,SAASK,eAAeJ,QAAc;AAC3C,SAAOD,aAAaC,QAAQ,CAAA,EAAGK,YAAW;AAC5C;AAFgBD;","names":["time","Promise","resolve","setTimeout","object","hash","UNMISTAKABLE_CHARS","hexString","digits","numBytes","Math","ceil","bytes","crypto","randomBytes","e","pseudoRandomBytes","result","toString","substring","fraction","numerator","parseInt","choice","arrayOrString","index","floor","length","substr","randomString","charsCount","alphabet","i","join","chars","generateId","array","key","map","item","createMap","array","key","map","item","push","createMapArray","OrionError","Error","isOrionError","isUserError","isPermissionsError","code","extra","getInfo","PermissionsError","OrionError","constructor","permissionErrorType","extra","message","Error","captureStackTrace","isOrionError","isPermissionsError","code","getInfo","error","type","UserError","OrionError","constructor","code","message","extra","Error","captureStackTrace","isOrionError","isUserError","getInfo","error","isOrionError","error","Boolean","isUserError","isPermissionsError","composeMiddlewares","middleware","Array","isArray","TypeError","fn","context","next","index","dispatch","i","Promise","reject","Error","length","resolve","bind","err","executeWithRetries","fn","retries","timeout","Promise","resolve","reject","retry","result","error","setTimeout","import_crypto","rnds8Pool","Uint8Array","poolPtr","length","rng","crypto","randomFillSync","slice","validate","uuid","REGEX","test","byteToHex","i","push","toString","substr","stringify","arr","offset","uuid","toLowerCase","validate","TypeError","v4","options","buf","offset","rnds","random","rng","i","stringify","generateUUID","uuidv4","generateUUIDWithPrefix","prefix","removeAccentsOnly","text","normalize","replace","removeAccentsAndTrim","trim","normalizeForSearch","toLowerCase","normalizeForCompactSearch","normalizeForSearchToken","normalizeForFileKey","getSearchTokens","text","meta","stringArray","Array","isArray","tokens","filter","Boolean","map","String","flatMap","word","normalizeForSearchToken","split","key","push","getSearchQueryForTokens","params","_options","searchTokens","filterTokens","token","RegExp","$all","lastOfString","string","last","substring","length","shortenMongoId","toUpperCase"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/sleep.ts","../src/hashObject.ts","../src/generateId.ts","../src/createMap.ts","../src/createMapArray.ts","../src/Errors/OrionError.ts","../src/Errors/PermissionsError.ts","../src/Errors/UserError.ts","../src/Errors/index.ts","../src/composeMiddlewares.ts","../src/retries.ts","../src/generateUUID.ts","../src/normalize.ts","../src/searchTokens.ts","../src/shortenMongoId.ts"],"sourcesContent":["import sleep from './sleep'\nimport hashObject from './hashObject'\nimport generateId from './generateId'\nimport createMap from './createMap'\nimport createMapArray from './createMapArray'\n\n// Import all error-related exports from the Errors module\nimport {\n OrionError,\n PermissionsError,\n UserError,\n isOrionError,\n isUserError,\n isPermissionsError,\n} from './Errors'\nimport type {OrionErrorInformation} from './Errors'\n\nexport * from './composeMiddlewares'\nexport * from './retries'\nexport * from './generateUUID'\nexport * from './normalize'\nexport * from './searchTokens'\nexport * from './shortenMongoId'\nexport {\n // Utility functions\n createMap,\n createMapArray,\n generateId,\n hashObject,\n sleep,\n // Error classes\n OrionError,\n PermissionsError,\n UserError,\n // Error type guards\n isOrionError,\n isUserError,\n isPermissionsError,\n}\n\nexport type {OrionErrorInformation}\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}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,OAAO,SAAS,MAAM,OAAO,MAAM;AAC7D;AAEO,SAAS,eAAe,QAAgB;AAC7C,SAAO,aAAa,QAAQ,CAAC,EAAE,YAAY;AAC7C;","names":["hash","crypto","retries","uuidv4","text"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -232,7 +232,7 @@ declare function composeMiddlewares(middleware: any): (context: any, next?: any)
|
|
|
232
232
|
*/
|
|
233
233
|
declare function executeWithRetries<TFunc extends () => Promise<any>>(fn: TFunc, retries: number, timeout: number): Promise<ReturnType<TFunc>>;
|
|
234
234
|
|
|
235
|
-
declare function generateUUID():
|
|
235
|
+
declare function generateUUID(): string;
|
|
236
236
|
declare function generateUUIDWithPrefix(prefix: string): string;
|
|
237
237
|
|
|
238
238
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -232,7 +232,7 @@ declare function composeMiddlewares(middleware: any): (context: any, next?: any)
|
|
|
232
232
|
*/
|
|
233
233
|
declare function executeWithRetries<TFunc extends () => Promise<any>>(fn: TFunc, retries: number, timeout: number): Promise<ReturnType<TFunc>>;
|
|
234
234
|
|
|
235
|
-
declare function generateUUID():
|
|
235
|
+
declare function generateUUID(): string;
|
|
236
236
|
declare function generateUUIDWithPrefix(prefix: string): string;
|
|
237
237
|
|
|
238
238
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1,22 +1,18 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
-
|
|
4
1
|
// src/sleep.ts
|
|
5
|
-
var sleep_default =
|
|
2
|
+
var sleep_default = (time) => {
|
|
6
3
|
return new Promise((resolve) => setTimeout(resolve, time));
|
|
7
|
-
}
|
|
4
|
+
};
|
|
8
5
|
|
|
9
6
|
// src/hashObject.ts
|
|
10
7
|
import hash from "object-hash";
|
|
11
8
|
function hashObject_default(object) {
|
|
12
9
|
return hash(object);
|
|
13
10
|
}
|
|
14
|
-
__name(hashObject_default, "default");
|
|
15
11
|
|
|
16
12
|
// src/generateId.ts
|
|
17
13
|
import crypto from "crypto";
|
|
18
14
|
var UNMISTAKABLE_CHARS = "23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghjkmnopqrstuvwxyz";
|
|
19
|
-
var hexString =
|
|
15
|
+
var hexString = function(digits) {
|
|
20
16
|
var numBytes = Math.ceil(digits / 2);
|
|
21
17
|
var bytes;
|
|
22
18
|
try {
|
|
@@ -26,30 +22,29 @@ var hexString = /* @__PURE__ */ __name(function(digits) {
|
|
|
26
22
|
}
|
|
27
23
|
var result = bytes.toString("hex");
|
|
28
24
|
return result.substring(0, digits);
|
|
29
|
-
}
|
|
30
|
-
var fraction =
|
|
25
|
+
};
|
|
26
|
+
var fraction = function() {
|
|
31
27
|
var numerator = parseInt(hexString(8), 16);
|
|
32
28
|
return numerator * 23283064365386963e-26;
|
|
33
|
-
}
|
|
34
|
-
var choice =
|
|
29
|
+
};
|
|
30
|
+
var choice = function(arrayOrString) {
|
|
35
31
|
var index = Math.floor(fraction() * arrayOrString.length);
|
|
36
32
|
if (typeof arrayOrString === "string") return arrayOrString.substr(index, 1);
|
|
37
33
|
else return arrayOrString[index];
|
|
38
|
-
}
|
|
39
|
-
var randomString =
|
|
34
|
+
};
|
|
35
|
+
var randomString = function(charsCount, alphabet) {
|
|
40
36
|
var digits = [];
|
|
41
37
|
for (var i = 0; i < charsCount; i++) {
|
|
42
38
|
digits[i] = choice(alphabet);
|
|
43
39
|
}
|
|
44
40
|
return digits.join("");
|
|
45
|
-
}
|
|
41
|
+
};
|
|
46
42
|
function generateId(charsCount, chars = UNMISTAKABLE_CHARS) {
|
|
47
43
|
if (!charsCount) {
|
|
48
44
|
charsCount = 17;
|
|
49
45
|
}
|
|
50
46
|
return randomString(charsCount, chars);
|
|
51
47
|
}
|
|
52
|
-
__name(generateId, "generateId");
|
|
53
48
|
|
|
54
49
|
// src/createMap.ts
|
|
55
50
|
function createMap(array, key = "_id") {
|
|
@@ -59,7 +54,6 @@ function createMap(array, key = "_id") {
|
|
|
59
54
|
}
|
|
60
55
|
return map;
|
|
61
56
|
}
|
|
62
|
-
__name(createMap, "createMap");
|
|
63
57
|
|
|
64
58
|
// src/createMapArray.ts
|
|
65
59
|
function createMapArray(array, key = "_id") {
|
|
@@ -70,49 +64,46 @@ function createMapArray(array, key = "_id") {
|
|
|
70
64
|
}
|
|
71
65
|
return map;
|
|
72
66
|
}
|
|
73
|
-
__name(createMapArray, "createMapArray");
|
|
74
67
|
|
|
75
68
|
// src/Errors/OrionError.ts
|
|
76
|
-
var
|
|
69
|
+
var OrionError = class extends Error {
|
|
77
70
|
isOrionError = true;
|
|
78
71
|
isUserError;
|
|
79
72
|
isPermissionsError;
|
|
80
73
|
code;
|
|
81
74
|
extra;
|
|
82
75
|
/**
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
76
|
+
* Returns a standardized representation of the error information.
|
|
77
|
+
* @returns An object containing error details in a consistent format
|
|
78
|
+
*/
|
|
86
79
|
getInfo;
|
|
87
80
|
};
|
|
88
|
-
__name(_OrionError, "OrionError");
|
|
89
|
-
var OrionError = _OrionError;
|
|
90
81
|
|
|
91
82
|
// src/Errors/PermissionsError.ts
|
|
92
|
-
var
|
|
83
|
+
var PermissionsError = class extends OrionError {
|
|
93
84
|
/**
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
85
|
+
* Creates a new PermissionsError instance.
|
|
86
|
+
*
|
|
87
|
+
* @param permissionErrorType - Identifies the specific permission that was violated
|
|
88
|
+
* (e.g., 'read', 'write', 'admin')
|
|
89
|
+
* @param extra - Additional error context or metadata. Can include a custom message
|
|
90
|
+
* via the message property.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* // Basic usage
|
|
94
|
+
* throw new PermissionsError('delete_document')
|
|
95
|
+
*
|
|
96
|
+
* @example
|
|
97
|
+
* // With custom message
|
|
98
|
+
* throw new PermissionsError('access_admin', { message: 'Admin access required' })
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* // With additional context
|
|
102
|
+
* throw new PermissionsError('edit_user', {
|
|
103
|
+
* userId: 'user123',
|
|
104
|
+
* requiredRole: 'admin'
|
|
105
|
+
* })
|
|
106
|
+
*/
|
|
116
107
|
constructor(permissionErrorType, extra = {}) {
|
|
117
108
|
const message = extra.message || `Client is not allowed to perform this action [${permissionErrorType}]`;
|
|
118
109
|
super(message);
|
|
@@ -131,31 +122,29 @@ var _PermissionsError = class _PermissionsError extends OrionError {
|
|
|
131
122
|
};
|
|
132
123
|
}
|
|
133
124
|
};
|
|
134
|
-
__name(_PermissionsError, "PermissionsError");
|
|
135
|
-
var PermissionsError = _PermissionsError;
|
|
136
125
|
|
|
137
126
|
// src/Errors/UserError.ts
|
|
138
|
-
var
|
|
127
|
+
var UserError = class extends OrionError {
|
|
139
128
|
/**
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
129
|
+
* Creates a new UserError instance.
|
|
130
|
+
*
|
|
131
|
+
* @param code - Error code identifier. If only one parameter is provided,
|
|
132
|
+
* this will be used as the message and code will default to 'error'.
|
|
133
|
+
* @param message - Human-readable error message. Optional if code is provided.
|
|
134
|
+
* @param extra - Additional error context or metadata.
|
|
135
|
+
*
|
|
136
|
+
* @example
|
|
137
|
+
* // Basic usage
|
|
138
|
+
* throw new UserError('invalid_input', 'The provided email is invalid')
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* // Using only a message (code will be 'error')
|
|
142
|
+
* throw new UserError('Input validation failed')
|
|
143
|
+
*
|
|
144
|
+
* @example
|
|
145
|
+
* // With extra metadata
|
|
146
|
+
* throw new UserError('rate_limit', 'Too many requests', { maxRequests: 100 })
|
|
147
|
+
*/
|
|
159
148
|
constructor(code, message, extra) {
|
|
160
149
|
if (!message && code) {
|
|
161
150
|
message = code;
|
|
@@ -176,22 +165,21 @@ var _UserError = class _UserError extends OrionError {
|
|
|
176
165
|
};
|
|
177
166
|
}
|
|
178
167
|
};
|
|
179
|
-
__name(_UserError, "UserError");
|
|
180
|
-
var UserError = _UserError;
|
|
181
168
|
|
|
182
169
|
// src/Errors/index.ts
|
|
183
170
|
function isOrionError(error) {
|
|
184
171
|
return Boolean(error && typeof error === "object" && error.isOrionError === true);
|
|
185
172
|
}
|
|
186
|
-
__name(isOrionError, "isOrionError");
|
|
187
173
|
function isUserError(error) {
|
|
188
|
-
return Boolean(
|
|
174
|
+
return Boolean(
|
|
175
|
+
error && typeof error === "object" && error.isOrionError === true && error.isUserError === true
|
|
176
|
+
);
|
|
189
177
|
}
|
|
190
|
-
__name(isUserError, "isUserError");
|
|
191
178
|
function isPermissionsError(error) {
|
|
192
|
-
return Boolean(
|
|
179
|
+
return Boolean(
|
|
180
|
+
error && typeof error === "object" && error.isOrionError === true && error.isPermissionsError === true
|
|
181
|
+
);
|
|
193
182
|
}
|
|
194
|
-
__name(isPermissionsError, "isPermissionsError");
|
|
195
183
|
|
|
196
184
|
// src/composeMiddlewares.ts
|
|
197
185
|
function composeMiddlewares(middleware) {
|
|
@@ -214,15 +202,13 @@ function composeMiddlewares(middleware) {
|
|
|
214
202
|
return Promise.reject(err);
|
|
215
203
|
}
|
|
216
204
|
}
|
|
217
|
-
__name(dispatch, "dispatch");
|
|
218
205
|
};
|
|
219
206
|
}
|
|
220
|
-
__name(composeMiddlewares, "composeMiddlewares");
|
|
221
207
|
|
|
222
208
|
// src/retries.ts
|
|
223
209
|
function executeWithRetries(fn, retries, timeout) {
|
|
224
210
|
return new Promise((resolve, reject) => {
|
|
225
|
-
const retry =
|
|
211
|
+
const retry = async (retries2) => {
|
|
226
212
|
try {
|
|
227
213
|
const result = await fn();
|
|
228
214
|
resolve(result);
|
|
@@ -233,115 +219,49 @@ function executeWithRetries(fn, retries, timeout) {
|
|
|
233
219
|
reject(error);
|
|
234
220
|
}
|
|
235
221
|
}
|
|
236
|
-
}
|
|
222
|
+
};
|
|
237
223
|
retry(retries);
|
|
238
224
|
});
|
|
239
225
|
}
|
|
240
|
-
__name(executeWithRetries, "executeWithRetries");
|
|
241
|
-
|
|
242
|
-
// ../../node_modules/uuid/dist/esm-node/rng.js
|
|
243
|
-
import crypto2 from "crypto";
|
|
244
|
-
var rnds8Pool = new Uint8Array(256);
|
|
245
|
-
var poolPtr = rnds8Pool.length;
|
|
246
|
-
function rng() {
|
|
247
|
-
if (poolPtr > rnds8Pool.length - 16) {
|
|
248
|
-
crypto2.randomFillSync(rnds8Pool);
|
|
249
|
-
poolPtr = 0;
|
|
250
|
-
}
|
|
251
|
-
return rnds8Pool.slice(poolPtr, poolPtr += 16);
|
|
252
|
-
}
|
|
253
|
-
__name(rng, "rng");
|
|
254
|
-
|
|
255
|
-
// ../../node_modules/uuid/dist/esm-node/regex.js
|
|
256
|
-
var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
|
|
257
|
-
|
|
258
|
-
// ../../node_modules/uuid/dist/esm-node/validate.js
|
|
259
|
-
function validate(uuid) {
|
|
260
|
-
return typeof uuid === "string" && regex_default.test(uuid);
|
|
261
|
-
}
|
|
262
|
-
__name(validate, "validate");
|
|
263
|
-
var validate_default = validate;
|
|
264
|
-
|
|
265
|
-
// ../../node_modules/uuid/dist/esm-node/stringify.js
|
|
266
|
-
var byteToHex = [];
|
|
267
|
-
for (let i = 0; i < 256; ++i) {
|
|
268
|
-
byteToHex.push((i + 256).toString(16).substr(1));
|
|
269
|
-
}
|
|
270
|
-
function stringify(arr, offset = 0) {
|
|
271
|
-
const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
|
|
272
|
-
if (!validate_default(uuid)) {
|
|
273
|
-
throw TypeError("Stringified UUID is invalid");
|
|
274
|
-
}
|
|
275
|
-
return uuid;
|
|
276
|
-
}
|
|
277
|
-
__name(stringify, "stringify");
|
|
278
|
-
var stringify_default = stringify;
|
|
279
|
-
|
|
280
|
-
// ../../node_modules/uuid/dist/esm-node/v4.js
|
|
281
|
-
function v4(options, buf, offset) {
|
|
282
|
-
options = options || {};
|
|
283
|
-
const rnds = options.random || (options.rng || rng)();
|
|
284
|
-
rnds[6] = rnds[6] & 15 | 64;
|
|
285
|
-
rnds[8] = rnds[8] & 63 | 128;
|
|
286
|
-
if (buf) {
|
|
287
|
-
offset = offset || 0;
|
|
288
|
-
for (let i = 0; i < 16; ++i) {
|
|
289
|
-
buf[offset + i] = rnds[i];
|
|
290
|
-
}
|
|
291
|
-
return buf;
|
|
292
|
-
}
|
|
293
|
-
return stringify_default(rnds);
|
|
294
|
-
}
|
|
295
|
-
__name(v4, "v4");
|
|
296
|
-
var v4_default = v4;
|
|
297
226
|
|
|
298
227
|
// src/generateUUID.ts
|
|
228
|
+
import { v4 as uuidv4 } from "uuid";
|
|
299
229
|
function generateUUID() {
|
|
300
|
-
return
|
|
230
|
+
return uuidv4();
|
|
301
231
|
}
|
|
302
|
-
__name(generateUUID, "generateUUID");
|
|
303
232
|
function generateUUIDWithPrefix(prefix) {
|
|
304
233
|
return `${prefix}-${generateUUID()}`;
|
|
305
234
|
}
|
|
306
|
-
__name(generateUUIDWithPrefix, "generateUUIDWithPrefix");
|
|
307
235
|
|
|
308
236
|
// src/normalize.ts
|
|
309
237
|
function removeAccentsOnly(text) {
|
|
310
238
|
if (!text) return "";
|
|
311
239
|
return text.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
|
312
240
|
}
|
|
313
|
-
__name(removeAccentsOnly, "removeAccentsOnly");
|
|
314
241
|
function removeAccentsAndTrim(text) {
|
|
315
242
|
if (!text) return "";
|
|
316
243
|
return removeAccentsOnly(text).trim();
|
|
317
244
|
}
|
|
318
|
-
__name(removeAccentsAndTrim, "removeAccentsAndTrim");
|
|
319
245
|
function normalizeForSearch(text) {
|
|
320
246
|
if (!text) return "";
|
|
321
247
|
return removeAccentsAndTrim(text).toLowerCase();
|
|
322
248
|
}
|
|
323
|
-
__name(normalizeForSearch, "normalizeForSearch");
|
|
324
249
|
function normalizeForCompactSearch(text) {
|
|
325
250
|
if (!text) return "";
|
|
326
251
|
return normalizeForSearch(text).replace(/\s/g, "");
|
|
327
252
|
}
|
|
328
|
-
__name(normalizeForCompactSearch, "normalizeForCompactSearch");
|
|
329
253
|
function normalizeForSearchToken(text) {
|
|
330
254
|
if (!text) return "";
|
|
331
255
|
return normalizeForSearch(text).replace(/[^0-9a-z]/gi, " ");
|
|
332
256
|
}
|
|
333
|
-
__name(normalizeForSearchToken, "normalizeForSearchToken");
|
|
334
257
|
function normalizeForFileKey(text) {
|
|
335
258
|
if (!text) return "";
|
|
336
259
|
return removeAccentsOnly(text).replace(/[^a-zA-Z0-9-._]/g, "-").replace(/-+/g, "-").trim().replace(/^-+|-+$/g, "");
|
|
337
260
|
}
|
|
338
|
-
__name(normalizeForFileKey, "normalizeForFileKey");
|
|
339
261
|
|
|
340
262
|
// src/searchTokens.ts
|
|
341
263
|
function getSearchTokens(text, meta) {
|
|
342
|
-
const stringArray = Array.isArray(text) ? text : [
|
|
343
|
-
text
|
|
344
|
-
];
|
|
264
|
+
const stringArray = Array.isArray(text) ? text : [text];
|
|
345
265
|
const tokens = stringArray.filter(Boolean).map((text2) => String(text2)).flatMap((word) => {
|
|
346
266
|
return normalizeForSearchToken(word).split(" ").filter(Boolean);
|
|
347
267
|
});
|
|
@@ -352,7 +272,6 @@ function getSearchTokens(text, meta) {
|
|
|
352
272
|
}
|
|
353
273
|
return tokens;
|
|
354
274
|
}
|
|
355
|
-
__name(getSearchTokens, "getSearchTokens");
|
|
356
275
|
function getSearchQueryForTokens(params = {}, _options = {}) {
|
|
357
276
|
const searchTokens = [];
|
|
358
277
|
if (params.filter) {
|
|
@@ -364,21 +283,16 @@ function getSearchQueryForTokens(params = {}, _options = {}) {
|
|
|
364
283
|
if (!params[key]) continue;
|
|
365
284
|
searchTokens.push(`_${key}:${params[key]}`);
|
|
366
285
|
}
|
|
367
|
-
return {
|
|
368
|
-
$all: searchTokens
|
|
369
|
-
};
|
|
286
|
+
return { $all: searchTokens };
|
|
370
287
|
}
|
|
371
|
-
__name(getSearchQueryForTokens, "getSearchQueryForTokens");
|
|
372
288
|
|
|
373
289
|
// src/shortenMongoId.ts
|
|
374
290
|
function lastOfString(string, last) {
|
|
375
291
|
return string.substring(string.length - last, string.length);
|
|
376
292
|
}
|
|
377
|
-
__name(lastOfString, "lastOfString");
|
|
378
293
|
function shortenMongoId(string) {
|
|
379
294
|
return lastOfString(string, 5).toUpperCase();
|
|
380
295
|
}
|
|
381
|
-
__name(shortenMongoId, "shortenMongoId");
|
|
382
296
|
export {
|
|
383
297
|
OrionError,
|
|
384
298
|
PermissionsError,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sleep.ts","../src/hashObject.ts","../src/generateId.ts","../src/createMap.ts","../src/createMapArray.ts","../src/Errors/OrionError.ts","../src/Errors/PermissionsError.ts","../src/Errors/UserError.ts","../src/Errors/index.ts","../src/composeMiddlewares.ts","../src/retries.ts","../../../node_modules/uuid/dist/esm-node/rng.js","../../../node_modules/uuid/dist/esm-node/regex.js","../../../node_modules/uuid/dist/esm-node/validate.js","../../../node_modules/uuid/dist/esm-node/stringify.js","../../../node_modules/uuid/dist/esm-node/v4.js","../src/generateUUID.ts","../src/normalize.ts","../src/searchTokens.ts","../src/shortenMongoId.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 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 crypto from 'crypto';\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\n\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n crypto.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;","import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).substr(1));\n}\n\nfunction stringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import rng from './rng.js';\nimport stringify from './stringify.js';\n\nfunction v4(options, buf, offset) {\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return stringify(rnds);\n}\n\nexport default v4;","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 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","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"],"mappings":";;;;AAGA,IAAA,gBAAe,wBAACA,SAAAA;AACd,SAAO,IAAIC,QAAQC,CAAAA,YAAWC,WAAWD,SAASF,IAAAA,CAAAA;AACpD,GAFe;;;ACHf,OAAOI,UAAU;AAEF,SAAf,mBAAyBC,QAAW;AAClC,SAAOC,KAAKD,MAAAA;AACd;AAFA;;;ACFA,OAAOE,YAAY;AAEnB,IAAMC,qBAAqB;AAE3B,IAAMC,YAAY,gCAAUC,QAAM;AAChC,MAAIC,WAAWC,KAAKC,KAAKH,SAAS,CAAA;AAClC,MAAII;AAGJ,MAAI;AACFA,YAAQC,OAAOC,YAAYL,QAAAA;EAC7B,SAASM,GAAG;AAEVH,YAAQC,OAAOG,kBAAkBP,QAAAA;EACnC;AACA,MAAIQ,SAASL,MAAMM,SAAS,KAAA;AAG5B,SAAOD,OAAOE,UAAU,GAAGX,MAAAA;AAC7B,GAfkB;AAiBlB,IAAMY,WAAW,kCAAA;AACf,MAAIC,YAAYC,SAASf,UAAU,CAAA,GAAI,EAAA;AACvC,SAAOc,YAAY;AACrB,GAHiB;AAKjB,IAAME,SAAS,gCAAUC,eAAa;AACpC,MAAIC,QAAQf,KAAKgB,MAAMN,SAAAA,IAAaI,cAAcG,MAAM;AACxD,MAAI,OAAOH,kBAAkB,SAAU,QAAOA,cAAcI,OAAOH,OAAO,CAAA;MACrE,QAAOD,cAAcC,KAAAA;AAC5B,GAJe;AAMf,IAAMI,eAAe,gCAAUC,YAAYC,UA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AAClD,QAAMK,SAASH,YACZI,OAAOC,OAAAA,EACPC,IAAIR,CAAAA,UAAQS,OAAOT,KAAAA,CAAAA,EACnBU,QAAQC,CAAAA,SAAAA;AACP,WAAOC,wBAAwBD,IAAAA,EAAME,MAAM,GAAA,EAAKP,OAAOC,OAAAA;EACzD,CAAA;AAEF,MAAIN,MAAM;AACR,eAAWa,OAAOb,MAAM;AACtBI,aAAOU,KAAK,IAAID,GAAAA,IAAOb,KAAKa,GAAAA,CAAI,EAAE;IACpC;EACF;AAEA,SAAOT;AACT;AAhBgBN;AAuDT,SAASiB,wBACdC,SAAqC,CAAC,GACtCC,WAAwC,CAAC,GAAC;AAE1C,QAAMC,eAAoC,CAAA;AAE1C,MAAIF,OAAOX,QAAQ;AACjB,UAAMc,eAAerB,gBAAgBkB,OAAOX,MAAM,EAAEE,IAAIa,CAAAA,UAAS,IAAIC,OAAO,IAAID,KAAAA,EAAO,CAAA;AACvFF,iBAAaJ,KAAI,GAAIK,YAAAA;EACvB;AAEA,aAAWN,OAAOG,QAAQ;AACxB,QAAIH,QAAQ,SAAU;AACtB,QAAI,CAACG,OAAOH,GAAAA,EAAM;AAClBK,iBAAaJ,KAAK,IAAID,GAAAA,IAAOG,OAAOH,GAAAA,CAAI,EAAE;EAC5C;AAEA,SAAO;IAAES,MAAMJ;EAAa;AAC9B;AAlBgBH;;;AC/EhB,SAASQ,aAAaC,QAAgBC,MAAY;AAChD,SAAOD,OAAOE,UAAUF,OAAOG,SAASF,MAAMD,OAAOG,MAAM;AAC7D;AAFSJ;AAIF,SAASK,eAAeJ,QAAc;AAC3C,SAAOD,aAAaC,QAAQ,CAAA,EAAGK,YAAW;AAC5C;AAFgBD;","names":["time","Promise","resolve","setTimeout","hash","object","hash","crypto","UNMISTAKABLE_CHARS","hexString","digits","numBytes","Math","ceil","bytes","crypto","randomBytes","e","pseudoRandomBytes","result","toString","substring","fraction","numerator","parseInt","choice","arrayOrString","index","floor","length","substr","randomString","charsCount","alphabet","i","join","chars","generateId","array","key","map","item","createMap","array","key","map","item","push","createMapArray","OrionError","Error","isOrionError","isUserError","isPermissionsError","code","extra","getInfo","PermissionsError","OrionError","constructor","permissionErrorType","extra","message","Error","captureStackTrace","isOrionError","isPermissionsError","code","getInfo","error","type","UserError","OrionError","constructor","code","message","extra","Error","captureStackTrace","isOrionError","isUserError","getInfo","error","isOrionError","error","Boolean","isUserError","isPermissionsError","composeMiddlewares","middleware","Array","isArray","TypeError","fn","context","next","index","dispatch","i","Promise","reject","Error","length","resolve","bind","err","executeWithRetries","fn","retries","timeout","Promise","resolve","reject","retry","result","error","setTimeout","crypto","rnds8Pool","Uint8Array","poolPtr","length","rng","crypto","randomFillSync","slice","validate","uuid","REGEX","test","byteToHex","i","push","toString","substr","stringify","arr","offset","uuid","toLowerCase","validate","TypeError","v4","options","buf","offset","rnds","random","rng","i","stringify","generateUUID","uuidv4","generateUUIDWithPrefix","prefix","removeAccentsOnly","text","normalize","replace","removeAccentsAndTrim","trim","normalizeForSearch","toLowerCase","normalizeForCompactSearch","normalizeForSearchToken","normalizeForFileKey","getSearchTokens","text","meta","stringArray","Array","isArray","tokens","filter","Boolean","map","String","flatMap","word","normalizeForSearchToken","split","key","push","getSearchQueryForTokens","params","_options","searchTokens","filterTokens","token","RegExp","$all","lastOfString","string","last","substring","length","shortenMongoId","toUpperCase"]}
|
|
1
|
+
{"version":3,"sources":["../src/sleep.ts","../src/hashObject.ts","../src/generateId.ts","../src/createMap.ts","../src/createMapArray.ts","../src/Errors/OrionError.ts","../src/Errors/PermissionsError.ts","../src/Errors/UserError.ts","../src/Errors/index.ts","../src/composeMiddlewares.ts","../src/retries.ts","../src/generateUUID.ts","../src/normalize.ts","../src/searchTokens.ts","../src/shortenMongoId.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 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"],"mappings":";AAGA,IAAO,gBAAQ,CAAC,SAAgC;AAC9C,SAAO,IAAI,QAAQ,aAAW,WAAW,SAAS,IAAI,CAAC;AACzD;;;ACLA,OAAO,UAAU;AAEF,SAAR,mBAAkB,QAAqB;AAC5C,SAAO,KAAK,MAAM;AACpB;;;ACJA,OAAO,YAAY;AAEnB,IAAM,qBAAqB;AAE3B,IAAM,YAAY,SAAU,QAAQ;AAClC,MAAI,WAAW,KAAK,KAAK,SAAS,CAAC;AACnC,MAAI;AAGJ,MAAI;AACF,YAAQ,OAAO,YAAY,QAAQ;AAAA,EACrC,SAAS,GAAG;AAEV,YAAQ,OAAO,kBAAkB,QAAQ;AAAA,EAC3C;AACA,MAAI,SAAS,MAAM,SAAS,KAAK;AAGjC,SAAO,OAAO,UAAU,GAAG,MAAM;AACnC;AAEA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zC;AACA,QAAM,eAAoC,CAAC;AAE3C,MAAI,OAAO,QAAQ;AACjB,UAAM,eAAe,gBAAgB,OAAO,MAAM,EAAE,IAAI,WAAS,IAAI,OAAO,IAAI,KAAK,EAAE,CAAC;AACxF,iBAAa,KAAK,GAAG,YAAY;AAAA,EACnC;AAEA,aAAW,OAAO,QAAQ;AACxB,QAAI,QAAQ,SAAU;AACtB,QAAI,CAAC,OAAO,GAAG,EAAG;AAClB,iBAAa,KAAK,IAAI,GAAG,IAAI,OAAO,GAAG,CAAC,EAAE;AAAA,EAC5C;AAEA,SAAO,EAAC,MAAM,aAAY;AAC5B;;;ACjGA,SAAS,aAAa,QAAgB,MAAc;AAClD,SAAO,OAAO,UAAU,OAAO,SAAS,MAAM,OAAO,MAAM;AAC7D;AAEO,SAAS,eAAe,QAAgB;AAC7C,SAAO,aAAa,QAAQ,CAAC,EAAE,YAAY;AAC7C;","names":["retries","text"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orion-js/helpers",
|
|
3
|
-
"version": "4.0.0-next.
|
|
3
|
+
"version": "4.0.0-next.4",
|
|
4
4
|
"main": "./dist/index.cjs",
|
|
5
5
|
"module": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -14,26 +14,26 @@
|
|
|
14
14
|
],
|
|
15
15
|
"author": "nicolaslopezj",
|
|
16
16
|
"license": "MIT",
|
|
17
|
-
"scripts": {
|
|
18
|
-
"test": "vitest run",
|
|
19
|
-
"prepare": "pnpm build",
|
|
20
|
-
"clean": "rm -rf ./dist",
|
|
21
|
-
"build": "tsup",
|
|
22
|
-
"upgrade-interactive": "pnpm upgrade --interactive",
|
|
23
|
-
"dev": "tsup --watch"
|
|
24
|
-
},
|
|
25
17
|
"dependencies": {
|
|
26
|
-
"object-hash": "^2.2.0"
|
|
18
|
+
"object-hash": "^2.2.0",
|
|
19
|
+
"uuid": "^11.1.0"
|
|
27
20
|
},
|
|
28
21
|
"devDependencies": {
|
|
29
22
|
"@types/node": "^18.0.0",
|
|
30
|
-
"typescript": "^5.4.5",
|
|
31
23
|
"tsup": "^8.0.1",
|
|
24
|
+
"typescript": "^5.4.5",
|
|
32
25
|
"vitest": "^1.1.0"
|
|
33
26
|
},
|
|
34
27
|
"publishConfig": {
|
|
35
28
|
"access": "public"
|
|
36
29
|
},
|
|
37
30
|
"gitHead": "a485b1fe6a1840ee6cb58fd69d6de62585f1ed10",
|
|
38
|
-
"type": "module"
|
|
31
|
+
"type": "module",
|
|
32
|
+
"scripts": {
|
|
33
|
+
"test": "vitest run",
|
|
34
|
+
"clean": "rm -rf ./dist",
|
|
35
|
+
"build": "tsup",
|
|
36
|
+
"upgrade-interactive": "pnpm upgrade --interactive",
|
|
37
|
+
"dev": "tsup --watch"
|
|
38
|
+
}
|
|
39
39
|
}
|