@moostjs/otel 0.4.21 → 0.4.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.cjs +1967 -18
  2. package/dist/index.mjs +1967 -18
  3. package/package.json +2 -2
package/dist/index.cjs CHANGED
@@ -347,8 +347,8 @@ function isConstructor(v) {
347
347
  return typeof v === 'function' && Object.getOwnPropertyNames(v).includes('prototype') && !Object.getOwnPropertyNames(v).includes('caller') && !!v.name;
348
348
  }
349
349
 
350
- const classMetadata = new WeakMap();
351
- const paramMetadata = new WeakMap();
350
+ let classMetadata = new WeakMap();
351
+ let paramMetadata = new WeakMap();
352
352
  const root = typeof global === 'object' ? global : typeof self === 'object' ? self : {};
353
353
  function getMetaObject(target, prop) {
354
354
  const isParam = typeof prop !== 'undefined';
@@ -378,6 +378,10 @@ const _reflect = {
378
378
  Reflect$1.defineMetadata(key, data, target, propKey);
379
379
  });
380
380
  },
381
+ _cleanup: (() => {
382
+ classMetadata = new WeakMap();
383
+ paramMetadata = new WeakMap();
384
+ }),
381
385
  };
382
386
  if (!root.Reflect) {
383
387
  root.Reflect = _reflect;
@@ -397,31 +401,42 @@ else {
397
401
  }
398
402
  const Reflect$1 = _reflect;
399
403
 
400
- const Reflect = (global === null || global === void 0 ? void 0 : global.Reflect) || (self === null || self === void 0 ? void 0 : self.Reflect) || Reflect$1;
404
+ const Reflect$2 = ((global === null || global === void 0 ? void 0 : global.Reflect) ||
405
+ (self === null || self === void 0 ? void 0 : self.Reflect) ||
406
+ Reflect$1);
401
407
  class Mate {
402
408
  constructor(workspace, options = {}) {
403
409
  this.workspace = workspace;
404
410
  this.options = options;
405
411
  this.logger = options.logger || console;
406
412
  }
413
+ _cleanup() {
414
+ var _a;
415
+ (_a = Reflect$2._cleanup) === null || _a === void 0 ? void 0 : _a.call(Reflect$2);
416
+ }
407
417
  set(args, key, value, isArray) {
408
418
  var _a;
409
419
  let level = 'CLASS';
410
- const newArgs = args.level === 'CLASS' ? { target: args.target }
411
- : args.level === 'PROP' ? { target: args.target, propKey: args.propKey }
420
+ const newArgs = args.level === 'CLASS'
421
+ ? { target: args.target }
422
+ : args.level === 'PROP'
423
+ ? { target: args.target, propKey: args.propKey }
412
424
  : args;
413
- let meta = (Reflect.getOwnMetadata(this.workspace, newArgs.target, newArgs.propKey) || {});
414
- if (newArgs.propKey && this.options.readReturnType && !meta.returnType && args.descriptor) {
415
- meta.returnType = Reflect.getOwnMetadata('design:returntype', newArgs.target, newArgs.propKey);
425
+ let meta = (Reflect$2.getOwnMetadata(this.workspace, newArgs.target, newArgs.propKey) || {});
426
+ if (newArgs.propKey &&
427
+ this.options.readReturnType &&
428
+ !meta.returnType &&
429
+ args.descriptor) {
430
+ meta.returnType = Reflect$2.getOwnMetadata('design:returntype', newArgs.target, newArgs.propKey);
416
431
  }
417
432
  if (newArgs.propKey && this.options.readType && !meta.type) {
418
- meta.type = Reflect.getOwnMetadata('design:type', newArgs.target, newArgs.propKey);
433
+ meta.type = Reflect$2.getOwnMetadata('design:type', newArgs.target, newArgs.propKey);
419
434
  }
420
435
  const { index } = newArgs;
421
436
  const cb = typeof key === 'function' ? key : undefined;
422
437
  let data = meta;
423
438
  if (!data.params) {
424
- data.params = (_a = Reflect.getOwnMetadata('design:paramtypes', newArgs.target, newArgs.propKey)) === null || _a === void 0 ? void 0 : _a.map((f) => ({ type: f }));
439
+ data.params = (_a = Reflect$2.getOwnMetadata('design:paramtypes', newArgs.target, newArgs.propKey)) === null || _a === void 0 ? void 0 : _a.map((f) => ({ type: f }));
425
440
  }
426
441
  if (typeof index === 'number') {
427
442
  level = 'PARAM';
@@ -436,7 +451,11 @@ class Mate {
436
451
  data = data.params[index];
437
452
  }
438
453
  }
439
- else if (!index && !args.descriptor && args.propKey && this.options.collectPropKeys && args.level !== 'CLASS') {
454
+ else if (!index &&
455
+ !args.descriptor &&
456
+ args.propKey &&
457
+ this.options.collectPropKeys &&
458
+ args.level !== 'CLASS') {
440
459
  this.set({ ...args, level: 'CLASS' }, (meta) => {
441
460
  if (!meta.properties) {
442
461
  meta.properties = [args.propKey];
@@ -447,7 +466,14 @@ class Mate {
447
466
  return meta;
448
467
  });
449
468
  }
450
- level = typeof index === 'number' ? 'PARAM' : newArgs.propKey && newArgs.descriptor ? 'METHOD' : newArgs.propKey ? 'PROP' : 'CLASS';
469
+ level =
470
+ typeof index === 'number'
471
+ ? 'PARAM'
472
+ : newArgs.propKey && newArgs.descriptor
473
+ ? 'METHOD'
474
+ : newArgs.propKey
475
+ ? 'PROP'
476
+ : 'CLASS';
451
477
  if (typeof key !== 'function') {
452
478
  if (isArray) {
453
479
  const newArray = (data[key] || []);
@@ -464,14 +490,14 @@ class Mate {
464
490
  else if (cb && typeof index !== 'number') {
465
491
  meta = cb(data, level, args.propKey, typeof args.index === 'number' ? args.index : undefined);
466
492
  }
467
- Reflect.defineMetadata(this.workspace, meta, newArgs.target, newArgs.propKey);
493
+ Reflect$2.defineMetadata(this.workspace, meta, newArgs.target, newArgs.propKey);
468
494
  }
469
495
  read(target, propKey) {
470
496
  var _a;
471
497
  const isConstr = isConstructor(target);
472
498
  const constructor = isConstr ? target : getConstructor$1(target);
473
499
  const proto = constructor.prototype;
474
- let ownMeta = Reflect.getOwnMetadata(this.workspace, typeof propKey === 'string' ? proto : constructor, propKey);
500
+ let ownMeta = Reflect$2.getOwnMetadata(this.workspace, typeof propKey === 'string' ? proto : constructor, propKey);
475
501
  if (ownMeta && propKey === undefined && ownMeta.params === undefined) {
476
502
  const parent = Object.getPrototypeOf(constructor);
477
503
  if (typeof parent === 'function' &&
@@ -487,7 +513,7 @@ class Mate {
487
513
  let shouldInherit = this.options.inherit;
488
514
  if (inheritFn) {
489
515
  if (typeof propKey === 'string') {
490
- const classMeta = Reflect.getOwnMetadata(this.workspace, constructor);
516
+ const classMeta = Reflect$2.getOwnMetadata(this.workspace, constructor);
491
517
  shouldInherit = inheritFn(classMeta, ownMeta, 'PROP', propKey);
492
518
  }
493
519
  else {
@@ -507,8 +533,7 @@ class Mate {
507
533
  ownParams &&
508
534
  (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params)) {
509
535
  for (let i = 0; i < ownParams.length; i++) {
510
- if (typeof (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i]) !==
511
- 'undefined') {
536
+ if (typeof (inheritedMeta === null || inheritedMeta === void 0 ? void 0 : inheritedMeta.params[i]) !== 'undefined') {
512
537
  const ownParam = ownParams[i];
513
538
  if (ownMeta.params &&
514
539
  inheritFn &&
@@ -550,7 +575,13 @@ class Mate {
550
575
  decorateConditional(ccb) {
551
576
  return ((target, propKey, descriptor) => {
552
577
  const hasIndex = typeof descriptor === 'number';
553
- const decoratorLevel = hasIndex ? 'PARAM' : propKey && descriptor ? 'METHOD' : propKey ? 'PROP' : 'CLASS';
578
+ const decoratorLevel = hasIndex
579
+ ? 'PARAM'
580
+ : propKey && descriptor
581
+ ? 'METHOD'
582
+ : propKey
583
+ ? 'PROP'
584
+ : 'CLASS';
554
585
  const d = ccb(decoratorLevel);
555
586
  if (d) {
556
587
  d(target, propKey, descriptor);
@@ -718,6 +749,11 @@ class Infact {
718
749
  this._silent = false;
719
750
  this.logger = options.logger || console;
720
751
  }
752
+ _cleanup() {
753
+ this.registry = {};
754
+ this.instanceRegistries = new WeakMap();
755
+ this.scopes = {};
756
+ }
721
757
  setLogger(logger) {
722
758
  this.logger = logger;
723
759
  }
@@ -1164,6 +1200,1919 @@ const resolvePipe = definePipeFn((_value, metas, level) => {
1164
1200
  },
1165
1201
  ];
1166
1202
 
1203
+ function getAugmentedNamespace(n) {
1204
+ if (n.__esModule) return n;
1205
+ var f = n.default;
1206
+ if (typeof f == "function") {
1207
+ var a = function a () {
1208
+ if (this instanceof a) {
1209
+ return Reflect.construct(f, arguments, this.constructor);
1210
+ }
1211
+ return f.apply(this, arguments);
1212
+ };
1213
+ a.prototype = f.prototype;
1214
+ } else a = {};
1215
+ Object.defineProperty(a, '__esModule', {value: true});
1216
+ Object.keys(n).forEach(function (k) {
1217
+ var d = Object.getOwnPropertyDescriptor(n, k);
1218
+ Object.defineProperty(a, k, d.get ? d : {
1219
+ enumerable: true,
1220
+ get: function () {
1221
+ return n[k];
1222
+ }
1223
+ });
1224
+ });
1225
+ return a;
1226
+ }
1227
+
1228
+ var router_cjs_prod = {};
1229
+
1230
+ class ProstoCache {
1231
+ constructor(options) {
1232
+ this.data = {};
1233
+ this.limits = [];
1234
+ this.expireOrder = [];
1235
+ this.expireSeries = {};
1236
+ this.options = {
1237
+ limit: 1000,
1238
+ ...options,
1239
+ };
1240
+ }
1241
+ set(key, value) {
1242
+ var _a, _b, _c;
1243
+ if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.limit) === 0)
1244
+ return;
1245
+ const expires = ((_b = this.options) === null || _b === void 0 ? void 0 : _b.ttl) ? Math.round(new Date().getTime() / 1) + ((_c = this.options) === null || _c === void 0 ? void 0 : _c.ttl) : null;
1246
+ if (expires) {
1247
+ this.del(key);
1248
+ }
1249
+ this.data[key] = {
1250
+ value: value,
1251
+ expires,
1252
+ };
1253
+ if (expires) {
1254
+ this.pushExpires(key, expires);
1255
+ }
1256
+ this.pushLimit(key);
1257
+ }
1258
+ get(key) {
1259
+ var _a;
1260
+ return (_a = this.data[key]) === null || _a === void 0 ? void 0 : _a.value;
1261
+ }
1262
+ del(key) {
1263
+ const entry = this.data[key];
1264
+ if (entry) {
1265
+ delete this.data[key];
1266
+ if (entry.expires) {
1267
+ let es = this.expireSeries[entry.expires];
1268
+ if (es) {
1269
+ es = this.expireSeries[entry.expires] = es.filter(k => k !== key);
1270
+ }
1271
+ if (!es || !es.length) {
1272
+ delete this.expireSeries[entry.expires];
1273
+ const { found, index } = this.searchExpireOrder(entry.expires);
1274
+ if (found) {
1275
+ this.expireOrder.splice(index, 1);
1276
+ if (index === 0) {
1277
+ console.log('calling prepareTimeout');
1278
+ this.prepareTimeout();
1279
+ }
1280
+ }
1281
+ }
1282
+ }
1283
+ }
1284
+ }
1285
+ reset() {
1286
+ this.data = {};
1287
+ if (this.nextTimeout) {
1288
+ clearTimeout(this.nextTimeout);
1289
+ }
1290
+ this.expireOrder = [];
1291
+ this.expireSeries = {};
1292
+ this.limits = [];
1293
+ }
1294
+ searchExpireOrder(time) {
1295
+ return binarySearch(this.expireOrder, time);
1296
+ }
1297
+ pushLimit(key) {
1298
+ var _a;
1299
+ const limit = (_a = this.options) === null || _a === void 0 ? void 0 : _a.limit;
1300
+ if (limit) {
1301
+ const newObj = [key, ...(this.limits.filter(item => item !== key && this.data[item]))];
1302
+ const tail = newObj.slice(limit);
1303
+ this.limits = newObj.slice(0, limit);
1304
+ if (tail.length) {
1305
+ tail.forEach(tailItem => {
1306
+ this.del(tailItem);
1307
+ });
1308
+ }
1309
+ }
1310
+ }
1311
+ prepareTimeout() {
1312
+ if (this.nextTimeout) {
1313
+ clearTimeout(this.nextTimeout);
1314
+ }
1315
+ const time = this.expireOrder[0];
1316
+ const del = (time) => {
1317
+ for (const key of (this.expireSeries[time] || [])) {
1318
+ delete this.data[key];
1319
+ }
1320
+ delete this.expireSeries[time];
1321
+ this.expireOrder = this.expireOrder.slice(1);
1322
+ this.prepareTimeout();
1323
+ };
1324
+ if (time) {
1325
+ const delta = time - Math.round(new Date().getTime() / 1);
1326
+ if (delta > 0) {
1327
+ this.nextTimeout = setTimeout(() => {
1328
+ del(time);
1329
+ }, delta);
1330
+ }
1331
+ else {
1332
+ del(time);
1333
+ }
1334
+ }
1335
+ }
1336
+ pushExpires(key, time) {
1337
+ const { found, index } = this.searchExpireOrder(time);
1338
+ if (!found) {
1339
+ this.expireOrder.splice(index, 0, time);
1340
+ }
1341
+ const e = this.expireSeries[time] = this.expireSeries[time] || [];
1342
+ e.push(key);
1343
+ if (!found && index === 0) {
1344
+ this.prepareTimeout();
1345
+ }
1346
+ }
1347
+ }
1348
+ function binarySearch(a, n) {
1349
+ let start = 0;
1350
+ let end = a.length - 1;
1351
+ let mid = 0;
1352
+ while (start <= end) {
1353
+ mid = Math.floor((start + end) / 2);
1354
+ if (a[mid] === n) {
1355
+ return {
1356
+ found: true,
1357
+ index: mid,
1358
+ };
1359
+ }
1360
+ if (n < a[mid]) {
1361
+ end = mid - 1;
1362
+ mid--;
1363
+ }
1364
+ else {
1365
+ start = mid + 1;
1366
+ mid++;
1367
+ }
1368
+ }
1369
+ return {
1370
+ found: false,
1371
+ index: mid,
1372
+ };
1373
+ }
1374
+
1375
+ var cache_esmBundler = /*#__PURE__*/Object.freeze({
1376
+ __proto__: null,
1377
+ ProstoCache: ProstoCache
1378
+ });
1379
+
1380
+ var require$$0 = /*@__PURE__*/getAugmentedNamespace(cache_esmBundler);
1381
+
1382
+ const dim = '';
1383
+ const reset = '';
1384
+ class ProstoTree {
1385
+ constructor(options) {
1386
+ var _a, _b, _c, _d;
1387
+ const label = (options === null || options === void 0 ? void 0 : options.label) || 'label';
1388
+ const children = (options === null || options === void 0 ? void 0 : options.children) || 'children';
1389
+ const branchWidth = typeof (options === null || options === void 0 ? void 0 : options.branchWidth) === 'number' ? options === null || options === void 0 ? void 0 : options.branchWidth : 2;
1390
+ const hLine = (((_a = options === null || options === void 0 ? void 0 : options.branches) === null || _a === void 0 ? void 0 : _a.hLine) || '─').repeat(branchWidth - 1);
1391
+ const branches = {
1392
+ end: ((_b = options === null || options === void 0 ? void 0 : options.branches) === null || _b === void 0 ? void 0 : _b.end) || dim + '└',
1393
+ middle: ((_c = options === null || options === void 0 ? void 0 : options.branches) === null || _c === void 0 ? void 0 : _c.middle) || dim + '├',
1394
+ vLine: ((_d = options === null || options === void 0 ? void 0 : options.branches) === null || _d === void 0 ? void 0 : _d.vLine) || dim + '│',
1395
+ hLine,
1396
+ };
1397
+ this.options = {
1398
+ label: label,
1399
+ children: children,
1400
+ renderLabel: (options === null || options === void 0 ? void 0 : options.renderLabel) || (n => typeof n === 'string' ? n : n[label]),
1401
+ branches,
1402
+ branchWidth,
1403
+ };
1404
+ }
1405
+ _render(root, opts) {
1406
+ const { children, renderLabel } = this.options;
1407
+ let s = `${renderLabel(root, '')}\n`;
1408
+ const { end, middle, vLine, hLine } = this.options.branches;
1409
+ const endBranch = end + hLine + reset + ' ';
1410
+ const middleBranch = middle + hLine + reset + ' ';
1411
+ const { branchWidth } = this.options;
1412
+ if (root) {
1413
+ treeNode(root);
1414
+ }
1415
+ function treeNode(node, behind = '', level = 1) {
1416
+ const items = (node && node[children]);
1417
+ const count = items && items.length || 0;
1418
+ if (items) {
1419
+ if ((opts === null || opts === void 0 ? void 0 : opts.level) && opts.level < level) {
1420
+ s += behind + endBranch + renderCollapsedChildren(items.length) + '\n';
1421
+ }
1422
+ else {
1423
+ let itemsToRender = items;
1424
+ const collapsedCount = Math.max(0, count - ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) || count));
1425
+ if ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) && count > opts.childrenLimit) {
1426
+ itemsToRender = opts.showLast ? items.slice(count - opts.childrenLimit) : items.slice(0, opts.childrenLimit);
1427
+ }
1428
+ if (collapsedCount && (opts === null || opts === void 0 ? void 0 : opts.showLast))
1429
+ s += behind + middleBranch + renderCollapsedChildren(collapsedCount) + '\n';
1430
+ itemsToRender.forEach((childNode, i) => {
1431
+ const last = i + 1 === count;
1432
+ const branch = last ? endBranch : middleBranch;
1433
+ const nextBehind = behind + (last ? ' ' : vLine) + ' '.repeat(branchWidth);
1434
+ s += behind + branch + renderLabel(childNode, nextBehind) + '\n';
1435
+ if (typeof childNode === 'object') {
1436
+ treeNode(childNode, nextBehind, level + 1);
1437
+ }
1438
+ });
1439
+ if (collapsedCount && !(opts === null || opts === void 0 ? void 0 : opts.showLast))
1440
+ s += behind + endBranch + renderCollapsedChildren(collapsedCount) + '\n';
1441
+ }
1442
+ }
1443
+ }
1444
+ return s;
1445
+ }
1446
+ render(root, opts) {
1447
+ return this._render(root, opts);
1448
+ }
1449
+ print(root, opts) {
1450
+ const s = this.render(root, opts);
1451
+ console.log(s);
1452
+ return s;
1453
+ }
1454
+ }
1455
+ function renderCollapsedChildren(count) {
1456
+ return dim + '+ ' + '' + count.toString() + ` item${count === 1 ? '' : 's'}` + reset;
1457
+ }
1458
+
1459
+ var tree_esmBundler = /*#__PURE__*/Object.freeze({
1460
+ __proto__: null,
1461
+ ProstoTree: ProstoTree
1462
+ });
1463
+
1464
+ function renderCodeFragment(lines, options) {
1465
+ const row = (options.row || 1) - 1;
1466
+ const rowEnd = options.rowEnd ? options.rowEnd - 1 : -1;
1467
+ const limit = Math.min(options.limit || 6, lines.length);
1468
+ const offset = Math.min(options.offset || 3, lines.length);
1469
+ const error = options.error;
1470
+ const errorEnd = options.errorEnd;
1471
+ let output = '';
1472
+ const delta = rowEnd - row;
1473
+ const maxIndex = lines.length;
1474
+ if (delta > limit) {
1475
+ let longestLine = 0;
1476
+ const newLimit = Math.floor(limit / 2);
1477
+ for (let i = 0; i < newLimit + offset; i++) {
1478
+ const index = row + i - offset;
1479
+ const line = lines[index] || '';
1480
+ longestLine = Math.max(line.length, longestLine);
1481
+ output += renderLine(line, index < maxIndex ? index + 1 : '', index === row ? error : undefined, index === row || index === rowEnd ? 'bold' : '');
1482
+ }
1483
+ let output2 = '';
1484
+ for (let i = newLimit + offset; i > 0; i--) {
1485
+ const index = rowEnd - i + offset;
1486
+ const line = lines[index] || '';
1487
+ longestLine = Math.max(line.length, longestLine);
1488
+ output2 += renderLine(line, index < maxIndex ? index + 1 : '', index === rowEnd ? errorEnd : undefined, index === row || index === rowEnd ? 'bold' : '');
1489
+ }
1490
+ output += renderLine('—'.repeat(longestLine), '———', undefined, 'dim') + output2;
1491
+ }
1492
+ else {
1493
+ for (let i = 0; i < limit + offset; i++) {
1494
+ const index = row + i - offset;
1495
+ if (index <= lines.length + 1) {
1496
+ const errorCol = index === row ? error : index === rowEnd ? errorEnd : undefined;
1497
+ output += renderLine(lines[index], index < maxIndex ? index + 1 : '', errorCol, index === row || index === rowEnd ? 'bold' : '');
1498
+ }
1499
+ }
1500
+ }
1501
+ return output;
1502
+ }
1503
+ function lineStyles(s) {
1504
+ return '' + (s || '')
1505
+ .replace(/([a-z_]+)/ig, '' + '$1' + '\x1b[39;33m')
1506
+ .replace(/([\=\.\/'"`\:\+]+)/ig, '' + '$1' + '');
1507
+ }
1508
+ function lineStylesError(s) {
1509
+ return '' + (s || '') + '';
1510
+ }
1511
+ function renderLine(line, index, error, style = '') {
1512
+ const st = (style === 'bold' ? '' : '') + (style === 'dim' ? '' : '');
1513
+ if (typeof error === 'number') {
1514
+ const errorLength = (/[\.-\s\(\)\*\/\+\{\}\[\]\?\'\"\`\<\>]/.exec(line.slice(error + 1)) || { index: line.length - error }).index + 1;
1515
+ return renderLineNumber(index, true) +
1516
+ st +
1517
+ lineStyles(line.slice(0, error)) +
1518
+ lineStylesError(line.slice(error, error + errorLength)) +
1519
+ lineStyles(line.slice(error + errorLength)) +
1520
+ renderLineNumber('', true) + ' '.repeat(error) + '' + '' + '~'.repeat(Math.max(1, errorLength));
1521
+ }
1522
+ return renderLineNumber(index, undefined, style === 'bold') + st + lineStyles(line);
1523
+ }
1524
+ function renderLineNumber(i, isError = false, bold = false) {
1525
+ let s = ' ';
1526
+ const sep = i === '———';
1527
+ if (i && i > 0 || typeof i === 'string') {
1528
+ s = ' ' + String(i);
1529
+ }
1530
+ s = s.slice(s.length - 5);
1531
+ return '\n' + '' + (sep ? '' : '') +
1532
+ (isError ? '' + '' : (bold ? '' : '')) +
1533
+ s + (sep ? i : ' | ') + '';
1534
+ }
1535
+
1536
+ function escapeRegex(s) {
1537
+ return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
1538
+ }
1539
+
1540
+ class ProstoParserNodeBase {
1541
+ addRecognizes(...args) {
1542
+ for (const node of args) {
1543
+ if (!this.options.recognizes)
1544
+ this.options.recognizes = [];
1545
+ if (!this.options.recognizes.includes(node)) {
1546
+ this.options.recognizes.push(node);
1547
+ }
1548
+ }
1549
+ return this;
1550
+ }
1551
+ addAbsorbs(node, rule = 'append') {
1552
+ this.options.absorbs = this.options.absorbs || {};
1553
+ if (Array.isArray(node)) {
1554
+ node.forEach(n => {
1555
+ this.options.absorbs[n.id] = rule;
1556
+ this.addRecognizes(n);
1557
+ });
1558
+ }
1559
+ else {
1560
+ this.options.absorbs[node.id] = rule;
1561
+ this.addRecognizes(node);
1562
+ }
1563
+ return this;
1564
+ }
1565
+ addPopsAfterNode(...args) {
1566
+ for (const node of args) {
1567
+ if (!this.options.popsAfterNode)
1568
+ this.options.popsAfterNode = [];
1569
+ if (!this.options.popsAfterNode.includes(node)) {
1570
+ this.options.popsAfterNode.push(node);
1571
+ }
1572
+ }
1573
+ this.addRecognizes(...args);
1574
+ return this;
1575
+ }
1576
+ addHoistChildren(...args) {
1577
+ if (!this.options.hoistChildren)
1578
+ this.options.hoistChildren = [];
1579
+ this.options.hoistChildren.push(...args);
1580
+ return this;
1581
+ }
1582
+ set icon(value) {
1583
+ this.options.icon = value;
1584
+ }
1585
+ set label(value) {
1586
+ this.options.label = value;
1587
+ }
1588
+ get startsWith() {
1589
+ return this.options.startsWith;
1590
+ }
1591
+ set startsWith(value) {
1592
+ this.options.startsWith = value;
1593
+ }
1594
+ get endsWith() {
1595
+ return this.options.endsWith;
1596
+ }
1597
+ set endsWith(value) {
1598
+ this.options.endsWith = value;
1599
+ }
1600
+ getPopsAtEOFSource() {
1601
+ return this.options.popsAtEOFSource;
1602
+ }
1603
+ popsAtEOFSource(value) {
1604
+ this.options.popsAtEOFSource = value;
1605
+ return this;
1606
+ }
1607
+ get absorbs() {
1608
+ return this.options.absorbs;
1609
+ }
1610
+ get badToken() {
1611
+ return this.options.badToken;
1612
+ }
1613
+ set badToken(value) {
1614
+ this.options.badToken = value;
1615
+ }
1616
+ get skipToken() {
1617
+ return this.options.skipToken;
1618
+ }
1619
+ set skipToken(value) {
1620
+ this.options.skipToken = value;
1621
+ }
1622
+ get recognizes() {
1623
+ return this.options.recognizes || [];
1624
+ }
1625
+ set recognizes(value) {
1626
+ this.options.recognizes = value;
1627
+ }
1628
+ get hoistChildren() {
1629
+ return this.options.hoistChildren || [];
1630
+ }
1631
+ set hoistChildren(value) {
1632
+ this.options.hoistChildren = value;
1633
+ }
1634
+ getMapContent() {
1635
+ return this.options.mapContent;
1636
+ }
1637
+ mapContent(key, value = 'copy') {
1638
+ this.options.mapContent = this.options.mapContent || {};
1639
+ this.options.mapContent[key] = value;
1640
+ return this;
1641
+ }
1642
+ onMatch(value) {
1643
+ this.options.onMatch = value;
1644
+ return this;
1645
+ }
1646
+ onAppendContent(value) {
1647
+ this.options.onAppendContent = value;
1648
+ return this;
1649
+ }
1650
+ onAfterChildParse(value) {
1651
+ this.options.onAfterChildParse = value;
1652
+ return this;
1653
+ }
1654
+ onBeforeChildParse(value) {
1655
+ this.options.onBeforeChildParse = value;
1656
+ return this;
1657
+ }
1658
+ onMatchStartToken(value) {
1659
+ if (this.options.startsWith) {
1660
+ this.options.startsWith.onMatchToken = value;
1661
+ }
1662
+ return this;
1663
+ }
1664
+ onMatchEndToken(value) {
1665
+ if (this.options.endsWith) {
1666
+ this.options.endsWith.onMatchToken = value;
1667
+ }
1668
+ return this;
1669
+ }
1670
+ initCustomData(value) {
1671
+ this.options.initCustomData = value;
1672
+ return this;
1673
+ }
1674
+ onPop(value) {
1675
+ this.options.onPop = value;
1676
+ return this;
1677
+ }
1678
+ get popsAfterNode() {
1679
+ return this.options.popsAfterNode || [];
1680
+ }
1681
+ set popsAfterNode(nodes) {
1682
+ this.options.popsAfterNode = nodes;
1683
+ }
1684
+ clearStartsWith() {
1685
+ delete this.options.startsWith;
1686
+ return this;
1687
+ }
1688
+ clearEndsWith() {
1689
+ delete this.options.endsWith;
1690
+ return this;
1691
+ }
1692
+ clearPopsAtEOFSource() {
1693
+ delete this.options.popsAtEOFSource;
1694
+ return this;
1695
+ }
1696
+ clearBadToken() {
1697
+ delete this.options.badToken;
1698
+ return this;
1699
+ }
1700
+ clearSkipToken() {
1701
+ delete this.options.skipToken;
1702
+ return this;
1703
+ }
1704
+ clearAbsorbs(node) {
1705
+ if (this.options.absorbs) {
1706
+ if (node && Array.isArray(node)) {
1707
+ for (const n of node) {
1708
+ delete this.options.absorbs[n.id];
1709
+ }
1710
+ }
1711
+ else if (node) {
1712
+ delete this.options.absorbs[node.id];
1713
+ }
1714
+ else {
1715
+ this.options.absorbs = {};
1716
+ }
1717
+ }
1718
+ return this;
1719
+ }
1720
+ clearRecognizes(...args) {
1721
+ var _a;
1722
+ if (args.length) {
1723
+ this.options.recognizes = (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.filter(n => !args.includes(n));
1724
+ }
1725
+ else {
1726
+ this.options.recognizes = [];
1727
+ }
1728
+ return this;
1729
+ }
1730
+ clearHoistChildren() {
1731
+ delete this.options.hoistChildren;
1732
+ return this;
1733
+ }
1734
+ clearMapContent() {
1735
+ delete this.options.mapContent;
1736
+ return this;
1737
+ }
1738
+ removeOnPop() {
1739
+ delete this.options.onPop;
1740
+ return this;
1741
+ }
1742
+ removeOnMatch() {
1743
+ delete this.options.onMatch;
1744
+ return this;
1745
+ }
1746
+ removeOnAppendContent() {
1747
+ delete this.options.onAppendContent;
1748
+ return this;
1749
+ }
1750
+ removeOnBeforeChildParse() {
1751
+ delete this.options.onBeforeChildParse;
1752
+ return this;
1753
+ }
1754
+ removeOnAfterChildParse() {
1755
+ delete this.options.onAfterChildParse;
1756
+ return this;
1757
+ }
1758
+ fireNodeMatched(matched, cbData) {
1759
+ return this.options.startsWith ? this.fireMatched(this.options.startsWith, matched, cbData) : { confirmed: true };
1760
+ }
1761
+ fireNodeEndMatched(matched, cbData) {
1762
+ return this.options.endsWith ? this.fireMatched(this.options.endsWith, matched, cbData) : { confirmed: true };
1763
+ }
1764
+ fireMatched(descr, matched, cbData) {
1765
+ const { omit, eject, onMatchToken } = descr;
1766
+ let cbResult = true;
1767
+ if (onMatchToken) {
1768
+ cbResult = onMatchToken({
1769
+ ...cbData,
1770
+ matched,
1771
+ });
1772
+ }
1773
+ const cbOmit = typeof cbResult === 'object' ? cbResult.omit : undefined;
1774
+ const cbEject = typeof cbResult === 'object' ? cbResult.eject : undefined;
1775
+ return {
1776
+ omit: cbOmit !== undefined ? cbOmit : omit,
1777
+ eject: cbEject !== undefined ? cbEject : eject,
1778
+ confirmed: cbResult !== false,
1779
+ };
1780
+ }
1781
+ getStartTokenRg() {
1782
+ return this.getRgOutOfTokenDescriptor(this.options.startsWith);
1783
+ }
1784
+ getEndTokenRg() {
1785
+ return this.getRgOutOfTokenDescriptor(this.options.endsWith);
1786
+ }
1787
+ getConstraintTokens() {
1788
+ return {
1789
+ skip: this.getRgOutOfTokenDescriptor(this.options.skipToken ? { token: this.options.skipToken } : undefined) || undefined,
1790
+ bad: this.getRgOutOfTokenDescriptor(this.options.badToken ? { token: this.options.badToken } : undefined) || undefined,
1791
+ };
1792
+ }
1793
+ getRgOutOfTokenDescriptor(descr) {
1794
+ if (descr) {
1795
+ const prefix = descr.ignoreBackSlashed ? /(?<=(?:^|[^\\])(?:\\\\)*)/.source : '';
1796
+ let token;
1797
+ if (typeof descr.token === 'function') {
1798
+ token = descr.token(this);
1799
+ }
1800
+ else {
1801
+ token = descr.token;
1802
+ }
1803
+ if (token instanceof RegExp) {
1804
+ return new RegExp(prefix + token.source, token.flags);
1805
+ }
1806
+ else {
1807
+ return new RegExp(`${prefix}(?:${[token].flat().map(t => escapeRegex(t)).join('|')})`);
1808
+ }
1809
+ }
1810
+ }
1811
+ }
1812
+
1813
+ class ProstoHoistManager {
1814
+ constructor() {
1815
+ this.data = {};
1816
+ }
1817
+ addHoistOptions(ctx) {
1818
+ if (ctx.hoistChildren) {
1819
+ ctx.hoistChildren.forEach(options => {
1820
+ const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
1821
+ const hoist = this.data[nodeId] = (this.data[nodeId] || {});
1822
+ if (hoist) {
1823
+ hoist[ctx.index] = {
1824
+ options,
1825
+ context: ctx,
1826
+ };
1827
+ }
1828
+ });
1829
+ }
1830
+ }
1831
+ removeHoistOptions(ctx) {
1832
+ if (ctx.hoistChildren) {
1833
+ ctx.hoistChildren.forEach(options => {
1834
+ const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
1835
+ const hoist = this.data[nodeId];
1836
+ if (hoist) {
1837
+ delete hoist[ctx.index];
1838
+ }
1839
+ });
1840
+ }
1841
+ }
1842
+ processHoistOptions(ctx) {
1843
+ const id = ctx.node.id;
1844
+ const hoist = this.data[id];
1845
+ if (hoist) {
1846
+ Object.keys(hoist).map(i => hoist[i]).forEach(({ options, context }) => {
1847
+ const customData = context.getCustomData();
1848
+ if (options.deep === true || Number(options.deep) >= (ctx.level - context.level)) {
1849
+ if (options.asArray) {
1850
+ const hoisted = customData[options.as] = (customData[options.as] || []);
1851
+ if (!Array.isArray(hoisted)) {
1852
+ if (!options.onConflict || options.onConflict === 'error') {
1853
+ throw new Error(`Can not hoist "${ctx.node.name}" to "${context.node.name}" as "${options.as}". "${options.as}" already exists and it is not an Array Type.`);
1854
+ }
1855
+ else if (options.onConflict === 'overwrite') {
1856
+ customData[options.as] = [doTheMapRule(options, ctx)];
1857
+ }
1858
+ else if (options.onConflict !== 'ignore') {
1859
+ throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
1860
+ }
1861
+ }
1862
+ else {
1863
+ hoisted.push(doTheMapRule(options, ctx));
1864
+ }
1865
+ }
1866
+ else {
1867
+ if (customData[options.as]) {
1868
+ if (!options.onConflict || options.onConflict === 'error') {
1869
+ throw new Error(`Can not hoist multiple "${ctx.node.name}" to "${context.node.name}" as "${options.as}". "${options.as}" already exists.`);
1870
+ }
1871
+ else if (options.onConflict === 'overwrite') {
1872
+ customData[options.as] = doTheMapRule(options, ctx);
1873
+ }
1874
+ else if (options.onConflict !== 'ignore') {
1875
+ throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
1876
+ }
1877
+ }
1878
+ else {
1879
+ customData[options.as] = doTheMapRule(options, ctx);
1880
+ }
1881
+ }
1882
+ if (options.removeChildFromContent) {
1883
+ context.content = context.content.filter(c => c !== ctx);
1884
+ }
1885
+ }
1886
+ });
1887
+ }
1888
+ function doTheMapRule(options, ctx) {
1889
+ var _a;
1890
+ if (typeof options.mapRule === 'function') {
1891
+ return options.mapRule(ctx);
1892
+ }
1893
+ if (options.mapRule === 'content.join') {
1894
+ return ctx.content.join('');
1895
+ }
1896
+ if ((_a = options.mapRule) === null || _a === void 0 ? void 0 : _a.startsWith('customData')) {
1897
+ const key = options.mapRule.slice(11);
1898
+ if (key) {
1899
+ return ctx.getCustomData()[key];
1900
+ }
1901
+ else {
1902
+ return ctx.getCustomData();
1903
+ }
1904
+ }
1905
+ return ctx;
1906
+ }
1907
+ }
1908
+ }
1909
+
1910
+ const banner = '' + '[parser]' + '';
1911
+ class ProstoParserContext {
1912
+ constructor(root) {
1913
+ this.root = root;
1914
+ this.nodes = {};
1915
+ this.pos = 0;
1916
+ this.index = 0;
1917
+ this.behind = '';
1918
+ this.here = '';
1919
+ this.src = '';
1920
+ this.stack = [];
1921
+ this.l = 0;
1922
+ this.hoistManager = new ProstoHoistManager();
1923
+ this.context = root;
1924
+ }
1925
+ parse(src) {
1926
+ this.src = src,
1927
+ this.here = src,
1928
+ this.l = src.length;
1929
+ const cache = {};
1930
+ while (this.pos < this.l) {
1931
+ const searchTokens = this.context.getSearchTokens();
1932
+ let closestIndex = Number.MAX_SAFE_INTEGER;
1933
+ let closestToken;
1934
+ let matched;
1935
+ for (const t of searchTokens) {
1936
+ const key = t.g.source;
1937
+ t.g.lastIndex = this.pos;
1938
+ let cached = cache[key];
1939
+ if (cached === null)
1940
+ continue;
1941
+ if (cached && cached.index < this.pos) {
1942
+ cached = null;
1943
+ delete cache[key];
1944
+ }
1945
+ if (!cached) {
1946
+ cached = t.g.exec(this.src);
1947
+ if (cached || (this.pos === 0 && !cached)) {
1948
+ cache[key] = cached;
1949
+ }
1950
+ }
1951
+ if (cached && cached.index < closestIndex) {
1952
+ closestIndex = cached.index;
1953
+ matched = cached;
1954
+ closestToken = t;
1955
+ if (closestIndex === this.pos)
1956
+ break;
1957
+ }
1958
+ }
1959
+ if (closestToken && matched) {
1960
+ const toAppend = this.src.slice(this.pos, closestIndex);
1961
+ if (toAppend) {
1962
+ this.context.appendContent(toAppend);
1963
+ this.jump(toAppend.length);
1964
+ }
1965
+ const matchedToken = matched[0];
1966
+ if (closestToken.node) {
1967
+ const { omit, eject, confirmed } = closestToken.node.fireNodeMatched(matched, this.getCallbackData(matched));
1968
+ if (!confirmed)
1969
+ continue;
1970
+ let toAppend = '';
1971
+ if (eject) {
1972
+ this.context.appendContent(matchedToken);
1973
+ }
1974
+ else if (!omit) {
1975
+ toAppend = matchedToken;
1976
+ }
1977
+ this.jump(matchedToken.length);
1978
+ this.pushNewContext(closestToken.node, toAppend ? [toAppend] : []);
1979
+ this.context.fireOnMatch(matched);
1980
+ continue;
1981
+ }
1982
+ else {
1983
+ const { omit, eject, confirmed } = this.context.fireNodeEndMatched(matched, this.getCallbackData(matched));
1984
+ if (!confirmed)
1985
+ continue;
1986
+ if (!eject && !omit) {
1987
+ this.context.appendContent(matchedToken);
1988
+ }
1989
+ if (!eject) {
1990
+ this.jump(matchedToken.length);
1991
+ }
1992
+ this.context.mapNamedGroups(matched);
1993
+ this.pop();
1994
+ continue;
1995
+ }
1996
+ }
1997
+ else {
1998
+ this.context.appendContent(this.here);
1999
+ this.jump(this.here.length);
2000
+ }
2001
+ }
2002
+ if (this.context !== this.root) {
2003
+ while (this.context.getPopsAtEOFSource() && this.stack.length > 0)
2004
+ this.pop();
2005
+ }
2006
+ if (this.context !== this.root) {
2007
+ this.panicBlock(`Unexpected end of the source string while parsing "${this.context.node.name}" (${this.context.index}) node.`);
2008
+ }
2009
+ return this.root;
2010
+ }
2011
+ pop() {
2012
+ const parentContext = this.stack.pop();
2013
+ this.context.fireOnPop();
2014
+ if (parentContext) {
2015
+ parentContext.fireAfterChildParse(this.context);
2016
+ parentContext.fireAbsorb(this.context);
2017
+ this.context.cleanup();
2018
+ const node = this.context.node;
2019
+ this.context = parentContext;
2020
+ if (parentContext.popsAfterNode.includes(node)) {
2021
+ this.pop();
2022
+ }
2023
+ }
2024
+ else {
2025
+ this.context.cleanup();
2026
+ }
2027
+ }
2028
+ pushNewContext(newNode, content) {
2029
+ this.index++;
2030
+ const ctx = newNode.createContext(this.index, this.stack.length + 1, this);
2031
+ ctx.content = content;
2032
+ this.context.fireBeforeChildParse(ctx);
2033
+ this.context.pushChild(ctx);
2034
+ this.stack.push(this.context);
2035
+ this.hoistManager.addHoistOptions(this.context);
2036
+ this.context = ctx;
2037
+ return ctx;
2038
+ }
2039
+ fromStack(depth = 0) {
2040
+ return this.stack[this.stack.length - depth - 1];
2041
+ }
2042
+ jump(n = 1) {
2043
+ this.pos += n;
2044
+ this.behind = this.src.slice(0, this.pos);
2045
+ this.here = this.src.slice(this.pos, this.l);
2046
+ return this.pos;
2047
+ }
2048
+ getCallbackData(matched) {
2049
+ return {
2050
+ parserContext: this,
2051
+ context: this.context,
2052
+ matched,
2053
+ customData: this.context.getCustomData(),
2054
+ };
2055
+ }
2056
+ getPosition(offset = 0) {
2057
+ var _a;
2058
+ const past = this.src.slice(0, this.pos + offset).split('\n');
2059
+ const row = past.length;
2060
+ const col = ((_a = past.pop()) === null || _a === void 0 ? void 0 : _a.length) || 0;
2061
+ return {
2062
+ row, col, pos: this.pos,
2063
+ };
2064
+ }
2065
+ panic(message, errorBackOffset = 0) {
2066
+ if (this.pos > 0) {
2067
+ const { row, col } = this.getPosition(-errorBackOffset);
2068
+ console.error(banner + '', message, '');
2069
+ console.log(this.context.toTree({ childrenLimit: 5, showLast: true, level: 1 }));
2070
+ console.error(renderCodeFragment(this.src.split('\n'), {
2071
+ row: row,
2072
+ error: col,
2073
+ }));
2074
+ }
2075
+ throw new Error(message);
2076
+ }
2077
+ panicBlock(message, topBackOffset = 0, bottomBackOffset = 0) {
2078
+ if (this.pos > 0) {
2079
+ const { row, col } = this.getPosition(-bottomBackOffset);
2080
+ console.error(banner + '', message, '');
2081
+ console.log(this.context.toTree({ childrenLimit: 13, showLast: true, level: 12 }));
2082
+ console.error(renderCodeFragment(this.src.split('\n'), {
2083
+ row: this.context.startPos.row,
2084
+ error: this.context.startPos.col - topBackOffset,
2085
+ rowEnd: row,
2086
+ errorEnd: col,
2087
+ }));
2088
+ }
2089
+ throw new Error(message);
2090
+ }
2091
+ }
2092
+
2093
+ const styles = {
2094
+ banner: (s) => '' + s + '',
2095
+ text: (s) => '' + s + '',
2096
+ valuesDim: (s) => '' + '' + s + '' + '',
2097
+ boolean: (s) => '' + s + '',
2098
+ booleanDim: (s) => '' + '' + s + '' + '',
2099
+ underscore: (s) => '' + s + '',
2100
+ values: (s) => (typeof s === 'string' ? '' : '') + cut(s.toString(), 30) + '',
2101
+ nodeDim: (s) => '' + '' + s + '' + '',
2102
+ node: (s) => '' + s + '',
2103
+ };
2104
+ const stringOutputLimit = 70;
2105
+ const parserTree = new ProstoTree({
2106
+ children: 'content',
2107
+ renderLabel: (context) => {
2108
+ if (typeof context === 'string') {
2109
+ return styles.text('«' + cut(context, stringOutputLimit) + '' + '»');
2110
+ }
2111
+ else if (typeof context === 'object' && context instanceof ProstoParserNodeContext) {
2112
+ let keys = '';
2113
+ const data = context.getCustomData();
2114
+ Object.keys(data).forEach(key => {
2115
+ const val = data[key];
2116
+ if (typeof val === 'string' || typeof val === 'number') {
2117
+ keys += ' ' + styles.valuesDim(key + '(') + styles.values(val) + styles.valuesDim(')');
2118
+ }
2119
+ else if (Array.isArray(val)) {
2120
+ keys += ' ' + styles.valuesDim(key + `[${val.length}]`);
2121
+ }
2122
+ else if (typeof val === 'object') {
2123
+ keys += ' ' + styles.valuesDim(`{ ${key} }`);
2124
+ }
2125
+ else if (typeof val === 'boolean' && val) {
2126
+ const st = key ? styles.boolean : styles.booleanDim;
2127
+ keys += ' ' + `${styles.underscore(st(key))}${st(val ? '☑' : '☐')}`;
2128
+ }
2129
+ });
2130
+ return styles.node(context.icon + (context.label ? ' ' : '')) + styles.nodeDim(context.label) + keys;
2131
+ }
2132
+ return '';
2133
+ },
2134
+ });
2135
+ function cut(s, n) {
2136
+ const c = s.replace(/\n/g, '\\n');
2137
+ if (c.length <= n)
2138
+ return c;
2139
+ return c.slice(0, n) + '' + '…';
2140
+ }
2141
+
2142
+ class ProstoParserNodeContext extends ProstoParserNodeBase {
2143
+ constructor(_node, index, level, parserContext) {
2144
+ super();
2145
+ this._node = _node;
2146
+ this.index = index;
2147
+ this.level = level;
2148
+ this.content = [];
2149
+ this._customData = {};
2150
+ this.hasNodes = [];
2151
+ this.count = {};
2152
+ this.mapContentRules = {
2153
+ 'first': (content) => content[0],
2154
+ 'shift': (content) => content.shift(),
2155
+ 'pop': (content) => content.pop(),
2156
+ 'last': (content) => content[content.length - 1],
2157
+ 'join': (content) => content.join(''),
2158
+ 'join-clear': (content) => content.splice(0).join(''),
2159
+ 'copy': (content) => content,
2160
+ };
2161
+ this.options = _node.getOptions();
2162
+ if (this.options.initCustomData) {
2163
+ this._customData = this.options.initCustomData();
2164
+ }
2165
+ this._label = this.options.label || '';
2166
+ this._icon = this.options.icon || '◦';
2167
+ this.parserContext = parserContext || new ProstoParserContext(this);
2168
+ if (parserContext) {
2169
+ this.parent = parserContext.context || parserContext.root;
2170
+ }
2171
+ this.startPos = this.parserContext.getPosition();
2172
+ this.endPos = this.parserContext.getPosition();
2173
+ }
2174
+ getOptions() {
2175
+ return this.options;
2176
+ }
2177
+ extractCustomDataTree() {
2178
+ let content = this.content;
2179
+ if (this.contentCopiedTo) {
2180
+ content = this.customData[this.contentCopiedTo];
2181
+ }
2182
+ if (Array.isArray(content)) {
2183
+ return content.map(c => {
2184
+ if (typeof c === 'string') {
2185
+ return c;
2186
+ }
2187
+ else {
2188
+ return extract(c);
2189
+ }
2190
+ });
2191
+ }
2192
+ else {
2193
+ const c = content;
2194
+ if (c instanceof ProstoParserNodeContext) {
2195
+ return extract(c);
2196
+ }
2197
+ else {
2198
+ return content;
2199
+ }
2200
+ }
2201
+ function extract(c) {
2202
+ const cd = { ...c.getCustomData() };
2203
+ if (c.contentCopiedTo) {
2204
+ cd[c.contentCopiedTo] = c.extractCustomDataTree();
2205
+ }
2206
+ return cd;
2207
+ }
2208
+ }
2209
+ getPrevNode(n = 1) {
2210
+ if (this.parent) {
2211
+ const index = this.parent.content.findIndex(n => n === this) - n;
2212
+ if (index >= 0)
2213
+ return this.parent.content[index];
2214
+ }
2215
+ }
2216
+ getPrevContext(n = 1) {
2217
+ if (this.parent) {
2218
+ const contexts = this.parent.content.filter(n => n instanceof ProstoParserNodeContext);
2219
+ const index = contexts.findIndex(n => n === this) - n;
2220
+ if (index >= 0)
2221
+ return contexts[index];
2222
+ }
2223
+ }
2224
+ set icon(value) {
2225
+ this._icon = value;
2226
+ }
2227
+ get icon() {
2228
+ return this._icon;
2229
+ }
2230
+ set label(value) {
2231
+ this._label = value;
2232
+ }
2233
+ get label() {
2234
+ return this._label;
2235
+ }
2236
+ getCustomData() {
2237
+ return this._customData;
2238
+ }
2239
+ get customData() {
2240
+ return this._customData;
2241
+ }
2242
+ get nodeId() {
2243
+ return this._node.id;
2244
+ }
2245
+ get node() {
2246
+ return this._node;
2247
+ }
2248
+ toTree(options) {
2249
+ return parserTree.render(this, options);
2250
+ }
2251
+ getSearchTokens() {
2252
+ var _a;
2253
+ const rg = this.getEndTokenRg();
2254
+ const tokens = rg ? [{
2255
+ rg,
2256
+ y: addFlag(rg, 'y'),
2257
+ g: addFlag(rg, 'g'),
2258
+ }] : [];
2259
+ (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.forEach(node => {
2260
+ const rg = node.getStartTokenRg();
2261
+ if (rg) {
2262
+ tokens.push({
2263
+ rg,
2264
+ y: addFlag(rg, 'y'),
2265
+ g: addFlag(rg, 'g'),
2266
+ node,
2267
+ });
2268
+ }
2269
+ });
2270
+ function addFlag(rg, f) {
2271
+ return new RegExp(rg.source, rg.flags + f);
2272
+ }
2273
+ return tokens;
2274
+ }
2275
+ appendContent(input) {
2276
+ let s = input;
2277
+ this.endPos = this.parserContext.getPosition();
2278
+ let { skip, bad } = this.getConstraintTokens();
2279
+ skip = skip ? new RegExp(skip.source, skip.flags + 'g') : skip;
2280
+ bad = bad ? new RegExp(bad.source, bad.flags + 'g') : bad;
2281
+ if (skip) {
2282
+ s = s.replace(skip, '');
2283
+ }
2284
+ if (bad) {
2285
+ const m = bad.exec(s);
2286
+ if (m) {
2287
+ this.parserContext.jump(m.index);
2288
+ this.parserContext.panic(`The token "${m[0].replace(/"/g, '\\"')}" is not allowed in "${this.node.name}".`);
2289
+ }
2290
+ }
2291
+ s = this.fireOnAppendContent(s);
2292
+ if (s) {
2293
+ this.content.push(s);
2294
+ }
2295
+ }
2296
+ cleanup() {
2297
+ this.options = null;
2298
+ }
2299
+ pushChild(child) {
2300
+ const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
2301
+ if (!absorbRule) {
2302
+ this.content.push(child);
2303
+ }
2304
+ }
2305
+ fireAbsorb(child) {
2306
+ const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
2307
+ if (absorbRule) {
2308
+ switch (absorbRule) {
2309
+ case 'append':
2310
+ this.content.push(...child.content);
2311
+ break;
2312
+ case 'join':
2313
+ this.appendContent(child.content.join(''));
2314
+ break;
2315
+ default:
2316
+ const [action, target] = absorbRule.split('->');
2317
+ const cd = this.getCustomData();
2318
+ if (action === 'copy') {
2319
+ cd[target] = child.content;
2320
+ }
2321
+ else if (action === 'join') {
2322
+ cd[target] = child.content.join('');
2323
+ }
2324
+ else {
2325
+ this.parserContext.panic(`Absorb action "${action}" is not supported.`);
2326
+ }
2327
+ }
2328
+ }
2329
+ }
2330
+ has(node) {
2331
+ return this.hasNodes.includes(node);
2332
+ }
2333
+ countOf(node) {
2334
+ return this.count[node.id] || 0;
2335
+ }
2336
+ mapNamedGroups(matched) {
2337
+ if (matched.groups) {
2338
+ const cd = this.getCustomData();
2339
+ for (const [key, value] of Object.entries(matched.groups)) {
2340
+ if (key === 'content') {
2341
+ this.appendContent(value);
2342
+ }
2343
+ else {
2344
+ cd[key] = value;
2345
+ }
2346
+ }
2347
+ }
2348
+ }
2349
+ fireOnPop() {
2350
+ this.endPos = this.parserContext.getPosition();
2351
+ this.processMappings();
2352
+ const data = this.parserContext.getCallbackData();
2353
+ this.node.beforeOnPop(data);
2354
+ if (this.options.onPop) {
2355
+ this.options.onPop(data);
2356
+ }
2357
+ }
2358
+ fireOnMatch(matched) {
2359
+ this.mapNamedGroups(matched);
2360
+ const data = this.parserContext.getCallbackData(matched);
2361
+ this.node.beforeOnMatch(data);
2362
+ if (this.options.onMatch) {
2363
+ return this.options.onMatch(data);
2364
+ }
2365
+ }
2366
+ fireBeforeChildParse(child) {
2367
+ const data = this.parserContext.getCallbackData();
2368
+ this.node.beforeOnBeforeChildParse(child, data);
2369
+ if (this.options.onBeforeChildParse) {
2370
+ return this.options.onBeforeChildParse(child, data);
2371
+ }
2372
+ }
2373
+ fireAfterChildParse(child) {
2374
+ if (!this.hasNodes.includes(child.node)) {
2375
+ this.hasNodes.push(child.node);
2376
+ }
2377
+ this.count[child.node.id] = this.count[child.node.id] || 0;
2378
+ this.count[child.node.id]++;
2379
+ const data = this.parserContext.getCallbackData();
2380
+ this.node.beforeOnAfterChildParse(child, data);
2381
+ if (this.options.onAfterChildParse) {
2382
+ return this.options.onAfterChildParse(child, data);
2383
+ }
2384
+ }
2385
+ fireOnAppendContent(s) {
2386
+ let _s = s;
2387
+ const data = this.parserContext.getCallbackData();
2388
+ _s = this.node.beforeOnAppendContent(_s, data);
2389
+ if (this.options.onAppendContent) {
2390
+ _s = this.options.onAppendContent(_s, data);
2391
+ }
2392
+ return _s;
2393
+ }
2394
+ processMappings() {
2395
+ this.parserContext.hoistManager.removeHoistOptions(this);
2396
+ this.parserContext.hoistManager.processHoistOptions(this);
2397
+ this.processMapContent();
2398
+ }
2399
+ processMapContent() {
2400
+ const targetNodeOptions = this.options;
2401
+ if (targetNodeOptions.mapContent) {
2402
+ Object.keys(targetNodeOptions.mapContent).forEach((key) => {
2403
+ const keyOfT = key;
2404
+ if (targetNodeOptions.mapContent && targetNodeOptions.mapContent[keyOfT]) {
2405
+ const mapRule = targetNodeOptions.mapContent[keyOfT];
2406
+ if (typeof mapRule === 'function') {
2407
+ this._customData[keyOfT] = mapRule(this.content);
2408
+ }
2409
+ else {
2410
+ const ruleKey = mapRule;
2411
+ if (ruleKey === 'copy')
2412
+ this.contentCopiedTo = keyOfT;
2413
+ this._customData[keyOfT] = this.mapContentRules[ruleKey](this.content);
2414
+ }
2415
+ if (!this.contentCopiedTo && (typeof mapRule === 'function' || ['first', 'shift', 'pop', 'last'].includes(mapRule))) {
2416
+ this.contentCopiedTo = keyOfT;
2417
+ }
2418
+ }
2419
+ });
2420
+ }
2421
+ }
2422
+ }
2423
+
2424
+ let idCounter = 0;
2425
+ class ProstoParserNode extends ProstoParserNodeBase {
2426
+ constructor(options) {
2427
+ super();
2428
+ this.options = options;
2429
+ this.id = idCounter++;
2430
+ }
2431
+ getOptions() {
2432
+ return {
2433
+ label: this.options.label || '',
2434
+ icon: this.options.icon || '',
2435
+ startsWith: (this.options.startsWith ? { ...this.options.startsWith } : this.options.startsWith),
2436
+ endsWith: (this.options.endsWith ? { ...this.options.endsWith } : this.options.endsWith),
2437
+ popsAfterNode: [...(this.options.popsAfterNode || [])],
2438
+ popsAtEOFSource: this.options.popsAtEOFSource || false,
2439
+ badToken: this.options.badToken || '',
2440
+ skipToken: this.options.skipToken || '',
2441
+ recognizes: [...(this.options.recognizes || [])],
2442
+ hoistChildren: [...(this.options.hoistChildren || [])],
2443
+ mapContent: {
2444
+ ...this.options.mapContent,
2445
+ },
2446
+ onPop: this.options.onPop,
2447
+ onMatch: this.options.onMatch,
2448
+ onAppendContent: this.options.onAppendContent,
2449
+ onAfterChildParse: this.options.onAfterChildParse,
2450
+ onBeforeChildParse: this.options.onBeforeChildParse,
2451
+ initCustomData: this.options.initCustomData,
2452
+ absorbs: this.options.absorbs,
2453
+ };
2454
+ }
2455
+ createContext(index, level, rootContext) {
2456
+ return new ProstoParserNodeContext(this, index, level, rootContext);
2457
+ }
2458
+ get name() {
2459
+ return this.constructor.name + '[' + this.id.toString() + ']' + '(' + (this.options.label || this.options.icon || '') + ')';
2460
+ }
2461
+ parse(source) {
2462
+ return this.createContext(0, 0).parserContext.parse(source);
2463
+ }
2464
+ beforeOnPop(data) {
2465
+ }
2466
+ beforeOnMatch(data) {
2467
+ }
2468
+ beforeOnAppendContent(s, data) {
2469
+ return s;
2470
+ }
2471
+ beforeOnAfterChildParse(child, data) {
2472
+ }
2473
+ beforeOnBeforeChildParse(child, data) {
2474
+ }
2475
+ }
2476
+
2477
+ class BasicNode extends ProstoParserNode {
2478
+ constructor(options) {
2479
+ var _a, _b;
2480
+ const startsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[0] } : undefined;
2481
+ const endsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[1] } : undefined;
2482
+ const [startOption, endOption] = ((_a = options.tokenOE) === null || _a === void 0 ? void 0 : _a.split('-')) || [];
2483
+ const [startBSlash, endBSlash] = ((_b = options.backSlash) === null || _b === void 0 ? void 0 : _b.split('-')) || [];
2484
+ if (startsWith) {
2485
+ startsWith.omit = startOption === 'omit';
2486
+ startsWith.eject = startOption === 'eject';
2487
+ startsWith.ignoreBackSlashed = startBSlash === 'ignore';
2488
+ }
2489
+ if (endsWith) {
2490
+ endsWith.omit = endOption === 'omit';
2491
+ endsWith.eject = endOption === 'eject';
2492
+ endsWith.ignoreBackSlashed = endBSlash === 'ignore';
2493
+ }
2494
+ super({
2495
+ icon: options.icon || '',
2496
+ label: typeof options.label === 'string' ? options.label : '',
2497
+ startsWith,
2498
+ endsWith,
2499
+ badToken: options.badToken,
2500
+ skipToken: options.skipToken,
2501
+ });
2502
+ if (options.recursive) {
2503
+ this.addAbsorbs(this, 'join');
2504
+ }
2505
+ }
2506
+ }
2507
+
2508
+ var parser_esmBundler = /*#__PURE__*/Object.freeze({
2509
+ __proto__: null,
2510
+ BasicNode: BasicNode,
2511
+ ProstoParserContext: ProstoParserContext,
2512
+ ProstoParserNode: ProstoParserNode,
2513
+ ProstoParserNodeContext: ProstoParserNodeContext,
2514
+ renderCodeFragment: renderCodeFragment
2515
+ });
2516
+
2517
+ var require$$1 = /*@__PURE__*/getAugmentedNamespace(parser_esmBundler);
2518
+
2519
+ var require$$2 = /*@__PURE__*/getAugmentedNamespace(tree_esmBundler);
2520
+
2521
+ (function (exports) {
2522
+
2523
+ Object.defineProperty(exports, '__esModule', { value: true });
2524
+
2525
+ var cache = require$$0;
2526
+ var parser$1 = require$$1;
2527
+ var tree = require$$2;
2528
+
2529
+ function parsePath(expr) {
2530
+ return parser.parse(expr).extractCustomDataTree();
2531
+ }
2532
+ class ParametricNodeWithRegex extends parser$1.BasicNode {
2533
+ constructor(options, rgNode) {
2534
+ super(options);
2535
+ const hoistRegex = {
2536
+ as: 'regex',
2537
+ node: regexNode,
2538
+ onConflict: 'overwrite',
2539
+ removeChildFromContent: true,
2540
+ deep: 1,
2541
+ mapRule: ({ content }) => content.join('').replace(/^\(\^/, '(').replace(/\$\)$/, ')'),
2542
+ };
2543
+ this.mapContent('name', 'join')
2544
+ .mapContent('value', content => content.shift())
2545
+ .popsAtEOFSource(true)
2546
+ .addRecognizes(rgNode)
2547
+ .addPopsAfterNode(rgNode)
2548
+ .addHoistChildren(hoistRegex);
2549
+ }
2550
+ beforeOnPop(data) {
2551
+ if (data.customData.name.endsWith('?')) {
2552
+ data.customData.name = data.customData.name.slice(0, -1);
2553
+ data.customData.value = data.customData.name;
2554
+ data.customData.optional = true;
2555
+ }
2556
+ else if (data.parserContext.here[0] === '?') {
2557
+ data.customData.optional = true;
2558
+ data.parserContext.jump();
2559
+ }
2560
+ }
2561
+ }
2562
+ const regexNode = new parser$1.BasicNode({
2563
+ label: 'RegEx',
2564
+ tokens: ['(', ')'],
2565
+ backSlash: 'ignore-ignore',
2566
+ recursive: true,
2567
+ }).onMatch(({ parserContext, context }) => {
2568
+ var _a;
2569
+ if (((_a = parserContext.fromStack()) === null || _a === void 0 ? void 0 : _a.node) === context.node) {
2570
+ if (!parserContext.here.startsWith('?:')) {
2571
+ context.content[0] += '?:';
2572
+ }
2573
+ }
2574
+ });
2575
+ const paramNode = new ParametricNodeWithRegex({
2576
+ label: 'Parameter',
2577
+ tokens: [':', /[\/\-]/],
2578
+ tokenOE: 'omit-eject',
2579
+ backSlash: 'ignore-',
2580
+ }, regexNode).initCustomData(() => ({ type: exports.EPathSegmentType.VARIABLE, value: '', regex: '([^\\/]*)', name: '' }));
2581
+ const wildcardNode = new ParametricNodeWithRegex({
2582
+ label: 'Wildcard',
2583
+ tokens: ['*', /[^*\()]/],
2584
+ tokenOE: '-eject',
2585
+ }, regexNode).initCustomData(() => ({ type: exports.EPathSegmentType.WILDCARD, value: '*', regex: '(.*)', name: '' }));
2586
+ const staticNode = new parser$1.BasicNode({
2587
+ label: 'Static',
2588
+ tokens: [/[^:\*]/, /[:\*]/],
2589
+ backSlash: '-ignore',
2590
+ tokenOE: '-eject',
2591
+ }).initCustomData(() => ({ type: exports.EPathSegmentType.STATIC, value: '' }))
2592
+ .mapContent('value', content => content.splice(0).join('').replace(/\\:/g, ':'))
2593
+ .popsAtEOFSource(true);
2594
+ const parser = new parser$1.BasicNode({}).addRecognizes(staticNode, paramNode, wildcardNode);
2595
+
2596
+ exports.EPathSegmentType = void 0;
2597
+ (function (EPathSegmentType) {
2598
+ EPathSegmentType[EPathSegmentType["STATIC"] = 0] = "STATIC";
2599
+ EPathSegmentType[EPathSegmentType["VARIABLE"] = 1] = "VARIABLE";
2600
+ EPathSegmentType[EPathSegmentType["REGEX"] = 2] = "REGEX";
2601
+ EPathSegmentType[EPathSegmentType["WILDCARD"] = 3] = "WILDCARD";
2602
+ })(exports.EPathSegmentType || (exports.EPathSegmentType = {}));
2603
+
2604
+ function safeDecode(f, v) {
2605
+ try {
2606
+ return f(v);
2607
+ }
2608
+ catch (e) {
2609
+ return v;
2610
+ }
2611
+ }
2612
+ function safeDecodeURIComponent(uri) {
2613
+ if (!uri || uri.indexOf('%') < 0)
2614
+ return uri;
2615
+ return safeDecode(decodeURIComponent, uri);
2616
+ }
2617
+ function safeDecodeURI(uri) {
2618
+ if (!uri || uri.indexOf('%') < 0)
2619
+ return uri;
2620
+ return safeDecode(decodeURI, uri);
2621
+ }
2622
+
2623
+ function countOfSlashes(s) {
2624
+ let last = 0;
2625
+ let count = 0;
2626
+ let index = s.indexOf('/');
2627
+ last = index + 1;
2628
+ while (index >= 0) {
2629
+ count++;
2630
+ index = s.indexOf('/', last);
2631
+ last = index + 1;
2632
+ }
2633
+ return count;
2634
+ }
2635
+
2636
+ class CodeString {
2637
+ constructor() {
2638
+ this.code = '';
2639
+ }
2640
+ append(s, newLine = false) {
2641
+ this.code += ['', s].flat().join(newLine ? '\n' : '');
2642
+ }
2643
+ prepend(s, newLine = false) {
2644
+ this.code = [s, ''].flat().join(newLine ? '\n' : '') + this.code;
2645
+ }
2646
+ generateFunction(...args) {
2647
+ return new Function(args.join(','), this.code);
2648
+ }
2649
+ toString() {
2650
+ return this.code;
2651
+ }
2652
+ }
2653
+
2654
+ function escapeRegex(s) {
2655
+ return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
2656
+ }
2657
+
2658
+ function generateFullMatchRegex(segments, nonCapturing = false) {
2659
+ let regex = '';
2660
+ let optional = false;
2661
+ segments.forEach(segment => {
2662
+ switch (segment.type) {
2663
+ case exports.EPathSegmentType.STATIC:
2664
+ if (optional) {
2665
+ if (['-', '/'].includes(segment.value)) {
2666
+ regex += escapeRegex(segment.value) + '?';
2667
+ }
2668
+ else {
2669
+ throw new Error(`Static route segment "${segment.value}" is not allowed after optional parameters.`);
2670
+ }
2671
+ }
2672
+ else {
2673
+ regex += escapeRegex(segment.value);
2674
+ }
2675
+ break;
2676
+ case exports.EPathSegmentType.VARIABLE:
2677
+ case exports.EPathSegmentType.WILDCARD:
2678
+ if (optional && !segment.optional)
2679
+ throw new Error('Obligatory route parameters are not allowed after optional parameters. Use "?" to mark it as an optional route parameter.');
2680
+ if (segment.optional && !optional) {
2681
+ if (regex.endsWith('/')) {
2682
+ regex += '?';
2683
+ }
2684
+ }
2685
+ regex += nonCapturing ? segment.regex.replace(/^\(/, '(?:') : segment.regex;
2686
+ if (segment.optional) {
2687
+ optional = true;
2688
+ regex += '?';
2689
+ }
2690
+ }
2691
+ });
2692
+ return regex;
2693
+ }
2694
+ function generateFullMatchFunc(segments, ignoreCase = false) {
2695
+ const str = new CodeString();
2696
+ const regex = generateFullMatchRegex(segments);
2697
+ let index = 0;
2698
+ const obj = {};
2699
+ segments.forEach(segment => {
2700
+ switch (segment.type) {
2701
+ case exports.EPathSegmentType.VARIABLE:
2702
+ case exports.EPathSegmentType.WILDCARD:
2703
+ index++;
2704
+ obj[segment.value] = obj[segment.value] || [];
2705
+ obj[segment.value].push(index);
2706
+ }
2707
+ });
2708
+ Object.keys(obj).forEach(key => {
2709
+ str.append(obj[key].length > 1
2710
+ ? `\tparams['${key}'] = [${obj[key].map(i => `utils.safeDecodeURIComponent(a[${i}])`).join(', ')}]`
2711
+ : `\tparams['${key}'] = utils.safeDecodeURIComponent(a[${obj[key][0]}])`, true);
2712
+ });
2713
+ str.prepend([`const a = path.match(/^${regex}$/${ignoreCase ? 'i' : ''})`, 'if (a) {'], true);
2714
+ str.append(['}', 'return a'], true);
2715
+ return str.generateFunction('path', 'params', 'utils');
2716
+ }
2717
+ function generatePathBuilder(segments) {
2718
+ const str = new CodeString();
2719
+ const obj = {};
2720
+ const index = {};
2721
+ segments.forEach(segment => {
2722
+ switch (segment.type) {
2723
+ case exports.EPathSegmentType.VARIABLE:
2724
+ case exports.EPathSegmentType.WILDCARD:
2725
+ obj[segment.value] = obj[segment.value] || 0;
2726
+ obj[segment.value]++;
2727
+ index[segment.value] = 0;
2728
+ }
2729
+ });
2730
+ str.append('return `');
2731
+ segments.forEach(segment => {
2732
+ switch (segment.type) {
2733
+ case exports.EPathSegmentType.STATIC:
2734
+ str.append(segment.value.replace(/`/g, '\\`'));
2735
+ break;
2736
+ case exports.EPathSegmentType.VARIABLE:
2737
+ case exports.EPathSegmentType.WILDCARD:
2738
+ if (obj[segment.value] > 1) {
2739
+ str.append('${ params[\'' + segment.value + `\'][${index[segment.value]}] }`);
2740
+ index[segment.value]++;
2741
+ }
2742
+ else {
2743
+ str.append('${ params[\'' + segment.value + '\'] }');
2744
+ }
2745
+ }
2746
+ });
2747
+ str.append('`');
2748
+ return str.generateFunction('params');
2749
+ }
2750
+
2751
+ const banner = () => `[prostojs/router][${new Date().toISOString().replace('T', ' ').replace(/\.\d{3}z$/i, '')}] `;
2752
+
2753
+ const methods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
2754
+ const matcherFuncUtils = {
2755
+ safeDecodeURIComponent,
2756
+ };
2757
+ class ProstoRouter {
2758
+ constructor(_options) {
2759
+ this.root = {};
2760
+ this.routes = [];
2761
+ this.routesRegistry = {};
2762
+ this._options = {
2763
+ ..._options,
2764
+ };
2765
+ if (!this._options.silent) {
2766
+ consoleInfo('The Router Initialized');
2767
+ }
2768
+ const cacheOpts = {
2769
+ limit: (_options === null || _options === void 0 ? void 0 : _options.cacheLimit) || 0,
2770
+ };
2771
+ if (_options === null || _options === void 0 ? void 0 : _options.cacheLimit) {
2772
+ this.cache = {
2773
+ GET: new cache.ProstoCache(cacheOpts),
2774
+ PUT: new cache.ProstoCache(cacheOpts),
2775
+ POST: new cache.ProstoCache(cacheOpts),
2776
+ PATCH: new cache.ProstoCache(cacheOpts),
2777
+ DELETE: new cache.ProstoCache(cacheOpts),
2778
+ HEAD: new cache.ProstoCache(cacheOpts),
2779
+ OPTIONS: new cache.ProstoCache(cacheOpts),
2780
+ };
2781
+ }
2782
+ }
2783
+ refreshCache(method) {
2784
+ if (this._options.cacheLimit && this.cache) {
2785
+ if (method === '*') {
2786
+ this.cache.GET.reset();
2787
+ this.cache.PUT.reset();
2788
+ this.cache.POST.reset();
2789
+ this.cache.PATCH.reset();
2790
+ this.cache.DELETE.reset();
2791
+ this.cache.HEAD.reset();
2792
+ this.cache.OPTIONS.reset();
2793
+ }
2794
+ else if (this.cache && this.cache[method]) {
2795
+ this.cache[method].reset();
2796
+ }
2797
+ }
2798
+ }
2799
+ registerRoute(method, path, options, handler) {
2800
+ this.refreshCache(method);
2801
+ const opts = this.mergeOptions(options);
2802
+ const normalPath = ('/' + path)
2803
+ .replace(/^\/\//, '/')
2804
+ .replace(/\/$/, '')
2805
+ .replace(/%/g, '%25');
2806
+ const { root } = this;
2807
+ const segments = parsePath(normalPath);
2808
+ if (!root[method]) {
2809
+ root[method] = {
2810
+ statics: {},
2811
+ parametrics: {
2812
+ byParts: [],
2813
+ },
2814
+ wildcards: [],
2815
+ };
2816
+ }
2817
+ const rootMethod = root[method];
2818
+ const generalized = method + ':' + segments.map(s => {
2819
+ switch (s.type) {
2820
+ case exports.EPathSegmentType.STATIC: return s.value;
2821
+ case exports.EPathSegmentType.VARIABLE: return '<VAR' + (s.regex === '([^-\\/]*)' ? '' : s.regex) + '>';
2822
+ case exports.EPathSegmentType.WILDCARD: return s.value;
2823
+ }
2824
+ }).join('');
2825
+ let route = this.routesRegistry[generalized];
2826
+ if (route) {
2827
+ if (this._options.disableDuplicatePath) {
2828
+ const error = `Attempt to register duplicated path: "${path}". Duplicate paths are disabled.\nYou can enable duplicated paths removing 'disableDuplicatePath' option.`;
2829
+ consoleError(error);
2830
+ throw new Error(error);
2831
+ }
2832
+ if (route.handlers.includes(handler)) {
2833
+ consoleError('Duplicate route with same handler ignored ' + generalized);
2834
+ }
2835
+ else {
2836
+ consoleWarn('Duplicate route registered ' + generalized);
2837
+ route.handlers.push(handler);
2838
+ }
2839
+ }
2840
+ else {
2841
+ const isStatic = segments.length === 1 && segments[0].type === exports.EPathSegmentType.STATIC || segments.length === 0;
2842
+ const isParametric = !!segments.find(p => p.type === exports.EPathSegmentType.VARIABLE);
2843
+ const firstOptional = segments.findIndex(p => p.optional);
2844
+ const isOptional = firstOptional >= 0;
2845
+ const isWildcard = !!segments.find(p => p.type === exports.EPathSegmentType.WILDCARD);
2846
+ const lengths = segments.slice(0, firstOptional >= 0 ? firstOptional : undefined).map(s => s.type === exports.EPathSegmentType.STATIC ? s.value.length : 0);
2847
+ const normalPathCase = segments[0] ? (this._options.ignoreCase ? segments[0].value.toLowerCase() : segments[0].value) : '/';
2848
+ this.routesRegistry[generalized] = route = {
2849
+ method,
2850
+ options: opts,
2851
+ path: normalPath,
2852
+ handlers: [handler],
2853
+ isStatic,
2854
+ isParametric,
2855
+ isOptional,
2856
+ isWildcard,
2857
+ segments,
2858
+ lengths,
2859
+ minLength: lengths.reduce((a, b) => a + b, 0),
2860
+ firstLength: lengths[0],
2861
+ firstStatic: normalPathCase.slice(0, lengths[0]),
2862
+ generalized,
2863
+ fullMatch: generateFullMatchFunc(segments, this._options.ignoreCase),
2864
+ pathBuilder: generatePathBuilder(segments),
2865
+ };
2866
+ this.routes.push(route);
2867
+ if (route.isStatic) {
2868
+ rootMethod.statics[normalPathCase] = route;
2869
+ }
2870
+ else {
2871
+ if (route.isParametric && !route.isWildcard && !route.isOptional) {
2872
+ const countOfParts = route.segments
2873
+ .filter(s => s.type === exports.EPathSegmentType.STATIC)
2874
+ .map(s => countOfSlashes(s.value)).reduce((a, b) => a + b, 1);
2875
+ const byParts = rootMethod.parametrics.byParts[countOfParts] = rootMethod.parametrics.byParts[countOfParts] || [];
2876
+ byParts.push(route);
2877
+ rootMethod.parametrics.byParts[countOfParts] = byParts.sort(routeSorter);
2878
+ }
2879
+ else if (route.isWildcard || route.isOptional) {
2880
+ if (route.isOptional && route.firstStatic.endsWith('/')) {
2881
+ route.firstStatic = route.firstStatic.slice(0, -1);
2882
+ route.firstLength--;
2883
+ route.minLength = Math.min(route.minLength, route.firstLength);
2884
+ }
2885
+ rootMethod.wildcards.push(route);
2886
+ rootMethod.wildcards = rootMethod.wildcards.sort(routeSorter);
2887
+ }
2888
+ }
2889
+ }
2890
+ return {
2891
+ getPath: route.pathBuilder,
2892
+ getArgs: () => route.segments.filter(p => p.type === exports.EPathSegmentType.VARIABLE || p.type === exports.EPathSegmentType.WILDCARD).map(s => s.name),
2893
+ getStaticPart: () => route.firstStatic,
2894
+ test: route.fullMatch,
2895
+ isStatic: route.isStatic,
2896
+ isParametric: route.isParametric,
2897
+ isWildcard: route.isWildcard,
2898
+ generalized,
2899
+ };
2900
+ }
2901
+ mergeOptions(options) {
2902
+ return {
2903
+ ...options,
2904
+ };
2905
+ }
2906
+ sanitizePath(path, ignoreTrailingSlash) {
2907
+ const end = path.indexOf('?');
2908
+ let slicedPath = end >= 0 ? path.slice(0, end) : path;
2909
+ if ((ignoreTrailingSlash || this._options.ignoreTrailingSlash) && slicedPath[slicedPath.length - 1] === '/') {
2910
+ slicedPath = slicedPath.slice(0, slicedPath.length - 1);
2911
+ }
2912
+ const normalPath = safeDecodeURI(slicedPath
2913
+ .replace(/%25/g, '%2525'));
2914
+ return {
2915
+ normalPath,
2916
+ normalPathWithCase: this._options.ignoreCase ? normalPath.toLowerCase() : normalPath,
2917
+ };
2918
+ }
2919
+ lookup(method, path, ignoreTrailingSlash) {
2920
+ if (this._options.cacheLimit && this.cache && this.cache[method]) {
2921
+ const cached = this.cache[method].get(path);
2922
+ if (cached)
2923
+ return cached;
2924
+ }
2925
+ const { normalPath, normalPathWithCase } = this.sanitizePath(path, ignoreTrailingSlash);
2926
+ const rootMethod = this.root[method];
2927
+ const lookupResult = {
2928
+ route: null,
2929
+ ctx: { params: {} },
2930
+ };
2931
+ const cache = (result) => {
2932
+ if (this._options.cacheLimit && this.cache && this.cache[method]) {
2933
+ this.cache[method].set(path, result);
2934
+ }
2935
+ return result;
2936
+ };
2937
+ if (rootMethod) {
2938
+ lookupResult.route = rootMethod.statics[normalPathWithCase];
2939
+ if (lookupResult.route)
2940
+ return cache(lookupResult);
2941
+ const pathSegmentsCount = countOfSlashes(normalPath) + 1;
2942
+ const pathLength = normalPath.length;
2943
+ const { parametrics } = rootMethod;
2944
+ const bySegments = parametrics.byParts[pathSegmentsCount];
2945
+ if (bySegments) {
2946
+ for (let i = 0; i < bySegments.length; i++) {
2947
+ lookupResult.route = bySegments[i];
2948
+ if (pathLength >= lookupResult.route.minLength) {
2949
+ if (normalPathWithCase.startsWith(lookupResult.route.firstStatic)
2950
+ && lookupResult.route.fullMatch(normalPath, lookupResult.ctx.params, matcherFuncUtils)) {
2951
+ return cache(lookupResult);
2952
+ }
2953
+ }
2954
+ }
2955
+ }
2956
+ const { wildcards } = rootMethod;
2957
+ for (let i = 0; i < wildcards.length; i++) {
2958
+ lookupResult.route = wildcards[i];
2959
+ if (pathLength >= lookupResult.route.minLength) {
2960
+ if (normalPathWithCase.startsWith(lookupResult.route.firstStatic)
2961
+ && lookupResult.route.fullMatch(normalPath, lookupResult.ctx.params, matcherFuncUtils)) {
2962
+ return cache(lookupResult);
2963
+ }
2964
+ }
2965
+ }
2966
+ }
2967
+ }
2968
+ find(method, path) {
2969
+ return this.lookup(method, path);
2970
+ }
2971
+ on(method, path, options, handler) {
2972
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2973
+ if (method === '*') {
2974
+ return methods.map(m => this.registerRoute(m, path, opts, func))[0];
2975
+ }
2976
+ return this.registerRoute(method, path, opts, func);
2977
+ }
2978
+ all(path, options, handler) {
2979
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2980
+ return this.on('*', path, opts, func);
2981
+ }
2982
+ get(path, options, handler) {
2983
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2984
+ return this.on('GET', path, opts, func);
2985
+ }
2986
+ put(path, options, handler) {
2987
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2988
+ return this.on('PUT', path, opts, func);
2989
+ }
2990
+ post(path, options, handler) {
2991
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2992
+ return this.on('POST', path, opts, func);
2993
+ }
2994
+ patch(path, options, handler) {
2995
+ const { opts, func } = extractOptionsAndHandler(options, handler);
2996
+ return this.on('PATCH', path, opts, func);
2997
+ }
2998
+ delete(path, options, handler) {
2999
+ const { opts, func } = extractOptionsAndHandler(options, handler);
3000
+ return this.on('DELETE', path, opts, func);
3001
+ }
3002
+ options(path, options, handler) {
3003
+ const { opts, func } = extractOptionsAndHandler(options, handler);
3004
+ return this.on('OPTIONS', path, opts, func);
3005
+ }
3006
+ head(path, options, handler) {
3007
+ const { opts, func } = extractOptionsAndHandler(options, handler);
3008
+ return this.on('HEAD', path, opts, func);
3009
+ }
3010
+ getRoutes() {
3011
+ return this.routes;
3012
+ }
3013
+ toTree() {
3014
+ const rootStyle = (v) => '' + v + '';
3015
+ const paramStyle = (v) => '' + '' + ':' + v + '' + '';
3016
+ const regexStyle = (v) => '' + '' + v + '' + '';
3017
+ const handlerStyle = (v) => '' + '' + '→ ' + '' + '' + v;
3018
+ const methodStyle = (v) => '' + '' + '• (' + v + ') ' + '';
3019
+ const data = {
3020
+ label: '⁕ Router',
3021
+ stylist: rootStyle,
3022
+ methods: [],
3023
+ children: [],
3024
+ };
3025
+ function toChild(d, label, stylist) {
3026
+ let found = d.children.find(c => c.label === label);
3027
+ if (!found) {
3028
+ found = {
3029
+ label,
3030
+ stylist,
3031
+ methods: [],
3032
+ children: [],
3033
+ };
3034
+ d.children.push(found);
3035
+ }
3036
+ return found;
3037
+ }
3038
+ this.routes.sort((a, b) => a.path > b.path ? 1 : -1).forEach(route => {
3039
+ let cur = data;
3040
+ let last = '';
3041
+ route.segments.forEach(s => {
3042
+ let parts;
3043
+ switch (s.type) {
3044
+ case exports.EPathSegmentType.STATIC:
3045
+ parts = s.value.split('/');
3046
+ last += parts.shift();
3047
+ for (let i = 0; i < parts.length; i++) {
3048
+ if (last) {
3049
+ cur = toChild(cur, last);
3050
+ }
3051
+ last = '/' + parts[i];
3052
+ }
3053
+ break;
3054
+ case exports.EPathSegmentType.VARIABLE:
3055
+ case exports.EPathSegmentType.WILDCARD:
3056
+ last += `${paramStyle(s.value)}${regexStyle(s.regex)}`;
3057
+ }
3058
+ });
3059
+ if (last) {
3060
+ cur = toChild(cur, last, handlerStyle);
3061
+ cur.methods.push(route.method);
3062
+ }
3063
+ });
3064
+ new tree.ProstoTree({
3065
+ renderLabel: (node, behind) => {
3066
+ const styledLabel = node.stylist ? node.stylist(node.label) : node.label;
3067
+ if (node.methods.length) {
3068
+ return styledLabel + '\n' + behind + node.methods.map(m => methodStyle(m)).join('\n' + behind);
3069
+ }
3070
+ return styledLabel;
3071
+ },
3072
+ }).print(data);
3073
+ }
3074
+ }
3075
+ function extractOptionsAndHandler(options, handler) {
3076
+ let opts = {};
3077
+ let func = handler;
3078
+ if (typeof options === 'function') {
3079
+ func = options;
3080
+ }
3081
+ else {
3082
+ opts = options;
3083
+ }
3084
+ return { opts, func };
3085
+ }
3086
+ function routeSorter(a, b) {
3087
+ if (a.isWildcard !== b.isWildcard) {
3088
+ return a.isWildcard ? 1 : -1;
3089
+ }
3090
+ const len = b.minLength - a.minLength;
3091
+ if (len)
3092
+ return len;
3093
+ for (let i = 0; i < a.lengths.length; i++) {
3094
+ const len = b.lengths[i] - a.lengths[i];
3095
+ if (len)
3096
+ return len;
3097
+ }
3098
+ return 0;
3099
+ }
3100
+ function consoleError(v) {
3101
+ console.info('' + banner() + v + '');
3102
+ }
3103
+ function consoleWarn(v) {
3104
+ console.info('' + banner() + v + '');
3105
+ }
3106
+ function consoleInfo(v) {
3107
+ console.info('' + '' + banner() + v + '' + '');
3108
+ }
3109
+
3110
+ exports.ProstoRouter = ProstoRouter;
3111
+ exports.escapeRegex = escapeRegex;
3112
+ exports.safeDecodeURI = safeDecodeURI;
3113
+ exports.safeDecodeURIComponent = safeDecodeURIComponent;
3114
+ } (router_cjs_prod));
3115
+
1167
3116
  function getOtelMate() {
1168
3117
  return getMoostMate();
1169
3118
  }