s3db.js 12.0.1 → 12.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/s3db.cjs.js +148 -3778
- package/dist/s3db.cjs.js.map +1 -1
- package/dist/s3db.es.js +145 -3774
- package/dist/s3db.es.js.map +1 -1
- package/mcp/entrypoint.js +91 -57
- package/package.json +2 -1
- package/src/plugins/plugin.class.js +5 -0
- package/src/plugins/relation.plugin.js +183 -47
- package/src/plugins/ttl.plugin.js +478 -303
- package/dist/s3db-cli.js +0 -55543
package/dist/s3db.cjs.js
CHANGED
|
@@ -5,19 +5,21 @@ Object.defineProperty(exports, '__esModule', { value: true });
|
|
|
5
5
|
var crypto$1 = require('crypto');
|
|
6
6
|
var nanoid = require('nanoid');
|
|
7
7
|
var EventEmitter = require('events');
|
|
8
|
-
var
|
|
9
|
-
var
|
|
10
|
-
var
|
|
8
|
+
var hono = require('hono');
|
|
9
|
+
var nodeServer = require('@hono/node-server');
|
|
10
|
+
var swaggerUi = require('@hono/swagger-ui');
|
|
11
11
|
var promises = require('fs/promises');
|
|
12
12
|
var fs = require('fs');
|
|
13
13
|
var promises$1 = require('stream/promises');
|
|
14
14
|
var path$1 = require('path');
|
|
15
|
+
var stream$1 = require('stream');
|
|
15
16
|
var zlib = require('node:zlib');
|
|
16
17
|
var os = require('os');
|
|
17
18
|
var jsonStableStringify = require('json-stable-stringify');
|
|
18
19
|
var os$1 = require('node:os');
|
|
19
20
|
var promisePool = require('@supercharge/promise-pool');
|
|
20
21
|
var lodashEs = require('lodash-es');
|
|
22
|
+
var http = require('http');
|
|
21
23
|
var https = require('https');
|
|
22
24
|
var nodeHttpHandler = require('@smithy/node-http-handler');
|
|
23
25
|
var clientS3 = require('@aws-sdk/client-s3');
|
|
@@ -31,11 +33,7 @@ var promises$2 = require('node:fs/promises');
|
|
|
31
33
|
var node_events = require('node:events');
|
|
32
34
|
var Stream = require('node:stream');
|
|
33
35
|
var node_string_decoder = require('node:string_decoder');
|
|
34
|
-
var node_module = require('node:module');
|
|
35
|
-
var require$$1 = require('child_process');
|
|
36
|
-
var require$$5 = require('url');
|
|
37
36
|
|
|
38
|
-
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
39
37
|
function _interopNamespaceDefault(e) {
|
|
40
38
|
var n = Object.create(null);
|
|
41
39
|
if (e) {
|
|
@@ -53,21 +51,6 @@ function _interopNamespaceDefault(e) {
|
|
|
53
51
|
return Object.freeze(n);
|
|
54
52
|
}
|
|
55
53
|
|
|
56
|
-
function _mergeNamespaces(n, m) {
|
|
57
|
-
m.forEach(function (e) {
|
|
58
|
-
e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
|
|
59
|
-
if (k !== 'default' && !(k in n)) {
|
|
60
|
-
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
61
|
-
Object.defineProperty(n, k, d.get ? d : {
|
|
62
|
-
enumerable: true,
|
|
63
|
-
get: function () { return e[k]; }
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
});
|
|
67
|
-
});
|
|
68
|
-
return Object.freeze(n);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
54
|
var actualFS__namespace = /*#__PURE__*/_interopNamespaceDefault(actualFS);
|
|
72
55
|
|
|
73
56
|
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
@@ -2400,6 +2383,9 @@ class Plugin extends EventEmitter {
|
|
|
2400
2383
|
* - Pode modificar argumentos/resultados.
|
|
2401
2384
|
*/
|
|
2402
2385
|
addMiddleware(resource, methodName, middleware) {
|
|
2386
|
+
if (typeof resource[methodName] !== "function") {
|
|
2387
|
+
throw new Error(`Cannot add middleware to "${methodName}": method does not exist on resource "${resource.name || "unknown"}"`);
|
|
2388
|
+
}
|
|
2403
2389
|
if (!resource._pluginMiddlewares) {
|
|
2404
2390
|
resource._pluginMiddlewares = {};
|
|
2405
2391
|
}
|
|
@@ -2491,2291 +2477,6 @@ const PluginObject = {
|
|
|
2491
2477
|
}
|
|
2492
2478
|
};
|
|
2493
2479
|
|
|
2494
|
-
// src/compose.ts
|
|
2495
|
-
var compose = (middleware, onError, onNotFound) => {
|
|
2496
|
-
return (context, next) => {
|
|
2497
|
-
let index = -1;
|
|
2498
|
-
return dispatch(0);
|
|
2499
|
-
async function dispatch(i) {
|
|
2500
|
-
if (i <= index) {
|
|
2501
|
-
throw new Error("next() called multiple times");
|
|
2502
|
-
}
|
|
2503
|
-
index = i;
|
|
2504
|
-
let res;
|
|
2505
|
-
let isError = false;
|
|
2506
|
-
let handler;
|
|
2507
|
-
if (middleware[i]) {
|
|
2508
|
-
handler = middleware[i][0][0];
|
|
2509
|
-
context.req.routeIndex = i;
|
|
2510
|
-
} else {
|
|
2511
|
-
handler = i === middleware.length && next || void 0;
|
|
2512
|
-
}
|
|
2513
|
-
if (handler) {
|
|
2514
|
-
try {
|
|
2515
|
-
res = await handler(context, () => dispatch(i + 1));
|
|
2516
|
-
} catch (err) {
|
|
2517
|
-
if (err instanceof Error && onError) {
|
|
2518
|
-
context.error = err;
|
|
2519
|
-
res = await onError(err, context);
|
|
2520
|
-
isError = true;
|
|
2521
|
-
} else {
|
|
2522
|
-
throw err;
|
|
2523
|
-
}
|
|
2524
|
-
}
|
|
2525
|
-
} else {
|
|
2526
|
-
if (context.finalized === false && onNotFound) {
|
|
2527
|
-
res = await onNotFound(context);
|
|
2528
|
-
}
|
|
2529
|
-
}
|
|
2530
|
-
if (res && (context.finalized === false || isError)) {
|
|
2531
|
-
context.res = res;
|
|
2532
|
-
}
|
|
2533
|
-
return context;
|
|
2534
|
-
}
|
|
2535
|
-
};
|
|
2536
|
-
};
|
|
2537
|
-
|
|
2538
|
-
// src/request/constants.ts
|
|
2539
|
-
var GET_MATCH_RESULT = Symbol();
|
|
2540
|
-
|
|
2541
|
-
// src/utils/body.ts
|
|
2542
|
-
var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
|
|
2543
|
-
const { all = false, dot = false } = options;
|
|
2544
|
-
const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
|
|
2545
|
-
const contentType = headers.get("Content-Type");
|
|
2546
|
-
if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
|
|
2547
|
-
return parseFormData(request, { all, dot });
|
|
2548
|
-
}
|
|
2549
|
-
return {};
|
|
2550
|
-
};
|
|
2551
|
-
async function parseFormData(request, options) {
|
|
2552
|
-
const formData = await request.formData();
|
|
2553
|
-
if (formData) {
|
|
2554
|
-
return convertFormDataToBodyData(formData, options);
|
|
2555
|
-
}
|
|
2556
|
-
return {};
|
|
2557
|
-
}
|
|
2558
|
-
function convertFormDataToBodyData(formData, options) {
|
|
2559
|
-
const form = /* @__PURE__ */ Object.create(null);
|
|
2560
|
-
formData.forEach((value, key) => {
|
|
2561
|
-
const shouldParseAllValues = options.all || key.endsWith("[]");
|
|
2562
|
-
if (!shouldParseAllValues) {
|
|
2563
|
-
form[key] = value;
|
|
2564
|
-
} else {
|
|
2565
|
-
handleParsingAllValues(form, key, value);
|
|
2566
|
-
}
|
|
2567
|
-
});
|
|
2568
|
-
if (options.dot) {
|
|
2569
|
-
Object.entries(form).forEach(([key, value]) => {
|
|
2570
|
-
const shouldParseDotValues = key.includes(".");
|
|
2571
|
-
if (shouldParseDotValues) {
|
|
2572
|
-
handleParsingNestedValues(form, key, value);
|
|
2573
|
-
delete form[key];
|
|
2574
|
-
}
|
|
2575
|
-
});
|
|
2576
|
-
}
|
|
2577
|
-
return form;
|
|
2578
|
-
}
|
|
2579
|
-
var handleParsingAllValues = (form, key, value) => {
|
|
2580
|
-
if (form[key] !== void 0) {
|
|
2581
|
-
if (Array.isArray(form[key])) {
|
|
2582
|
-
form[key].push(value);
|
|
2583
|
-
} else {
|
|
2584
|
-
form[key] = [form[key], value];
|
|
2585
|
-
}
|
|
2586
|
-
} else {
|
|
2587
|
-
if (!key.endsWith("[]")) {
|
|
2588
|
-
form[key] = value;
|
|
2589
|
-
} else {
|
|
2590
|
-
form[key] = [value];
|
|
2591
|
-
}
|
|
2592
|
-
}
|
|
2593
|
-
};
|
|
2594
|
-
var handleParsingNestedValues = (form, key, value) => {
|
|
2595
|
-
let nestedForm = form;
|
|
2596
|
-
const keys = key.split(".");
|
|
2597
|
-
keys.forEach((key2, index) => {
|
|
2598
|
-
if (index === keys.length - 1) {
|
|
2599
|
-
nestedForm[key2] = value;
|
|
2600
|
-
} else {
|
|
2601
|
-
if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
|
|
2602
|
-
nestedForm[key2] = /* @__PURE__ */ Object.create(null);
|
|
2603
|
-
}
|
|
2604
|
-
nestedForm = nestedForm[key2];
|
|
2605
|
-
}
|
|
2606
|
-
});
|
|
2607
|
-
};
|
|
2608
|
-
|
|
2609
|
-
// src/utils/url.ts
|
|
2610
|
-
var splitPath = (path) => {
|
|
2611
|
-
const paths = path.split("/");
|
|
2612
|
-
if (paths[0] === "") {
|
|
2613
|
-
paths.shift();
|
|
2614
|
-
}
|
|
2615
|
-
return paths;
|
|
2616
|
-
};
|
|
2617
|
-
var splitRoutingPath = (routePath) => {
|
|
2618
|
-
const { groups, path } = extractGroupsFromPath(routePath);
|
|
2619
|
-
const paths = splitPath(path);
|
|
2620
|
-
return replaceGroupMarks(paths, groups);
|
|
2621
|
-
};
|
|
2622
|
-
var extractGroupsFromPath = (path) => {
|
|
2623
|
-
const groups = [];
|
|
2624
|
-
path = path.replace(/\{[^}]+\}/g, (match, index) => {
|
|
2625
|
-
const mark = `@${index}`;
|
|
2626
|
-
groups.push([mark, match]);
|
|
2627
|
-
return mark;
|
|
2628
|
-
});
|
|
2629
|
-
return { groups, path };
|
|
2630
|
-
};
|
|
2631
|
-
var replaceGroupMarks = (paths, groups) => {
|
|
2632
|
-
for (let i = groups.length - 1; i >= 0; i--) {
|
|
2633
|
-
const [mark] = groups[i];
|
|
2634
|
-
for (let j = paths.length - 1; j >= 0; j--) {
|
|
2635
|
-
if (paths[j].includes(mark)) {
|
|
2636
|
-
paths[j] = paths[j].replace(mark, groups[i][1]);
|
|
2637
|
-
break;
|
|
2638
|
-
}
|
|
2639
|
-
}
|
|
2640
|
-
}
|
|
2641
|
-
return paths;
|
|
2642
|
-
};
|
|
2643
|
-
var patternCache = {};
|
|
2644
|
-
var getPattern = (label, next) => {
|
|
2645
|
-
if (label === "*") {
|
|
2646
|
-
return "*";
|
|
2647
|
-
}
|
|
2648
|
-
const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
2649
|
-
if (match) {
|
|
2650
|
-
const cacheKey = `${label}#${next}`;
|
|
2651
|
-
if (!patternCache[cacheKey]) {
|
|
2652
|
-
if (match[2]) {
|
|
2653
|
-
patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
|
|
2654
|
-
} else {
|
|
2655
|
-
patternCache[cacheKey] = [label, match[1], true];
|
|
2656
|
-
}
|
|
2657
|
-
}
|
|
2658
|
-
return patternCache[cacheKey];
|
|
2659
|
-
}
|
|
2660
|
-
return null;
|
|
2661
|
-
};
|
|
2662
|
-
var tryDecode = (str, decoder) => {
|
|
2663
|
-
try {
|
|
2664
|
-
return decoder(str);
|
|
2665
|
-
} catch {
|
|
2666
|
-
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
|
|
2667
|
-
try {
|
|
2668
|
-
return decoder(match);
|
|
2669
|
-
} catch {
|
|
2670
|
-
return match;
|
|
2671
|
-
}
|
|
2672
|
-
});
|
|
2673
|
-
}
|
|
2674
|
-
};
|
|
2675
|
-
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
|
2676
|
-
var getPath = (request) => {
|
|
2677
|
-
const url = request.url;
|
|
2678
|
-
const start = url.indexOf("/", url.indexOf(":") + 4);
|
|
2679
|
-
let i = start;
|
|
2680
|
-
for (; i < url.length; i++) {
|
|
2681
|
-
const charCode = url.charCodeAt(i);
|
|
2682
|
-
if (charCode === 37) {
|
|
2683
|
-
const queryIndex = url.indexOf("?", i);
|
|
2684
|
-
const path = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
|
|
2685
|
-
return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
|
|
2686
|
-
} else if (charCode === 63) {
|
|
2687
|
-
break;
|
|
2688
|
-
}
|
|
2689
|
-
}
|
|
2690
|
-
return url.slice(start, i);
|
|
2691
|
-
};
|
|
2692
|
-
var getPathNoStrict = (request) => {
|
|
2693
|
-
const result = getPath(request);
|
|
2694
|
-
return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
|
|
2695
|
-
};
|
|
2696
|
-
var mergePath = (base, sub, ...rest) => {
|
|
2697
|
-
if (rest.length) {
|
|
2698
|
-
sub = mergePath(sub, ...rest);
|
|
2699
|
-
}
|
|
2700
|
-
return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
|
|
2701
|
-
};
|
|
2702
|
-
var checkOptionalParameter = (path) => {
|
|
2703
|
-
if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
|
|
2704
|
-
return null;
|
|
2705
|
-
}
|
|
2706
|
-
const segments = path.split("/");
|
|
2707
|
-
const results = [];
|
|
2708
|
-
let basePath = "";
|
|
2709
|
-
segments.forEach((segment) => {
|
|
2710
|
-
if (segment !== "" && !/\:/.test(segment)) {
|
|
2711
|
-
basePath += "/" + segment;
|
|
2712
|
-
} else if (/\:/.test(segment)) {
|
|
2713
|
-
if (/\?/.test(segment)) {
|
|
2714
|
-
if (results.length === 0 && basePath === "") {
|
|
2715
|
-
results.push("/");
|
|
2716
|
-
} else {
|
|
2717
|
-
results.push(basePath);
|
|
2718
|
-
}
|
|
2719
|
-
const optionalSegment = segment.replace("?", "");
|
|
2720
|
-
basePath += "/" + optionalSegment;
|
|
2721
|
-
results.push(basePath);
|
|
2722
|
-
} else {
|
|
2723
|
-
basePath += "/" + segment;
|
|
2724
|
-
}
|
|
2725
|
-
}
|
|
2726
|
-
});
|
|
2727
|
-
return results.filter((v, i, a) => a.indexOf(v) === i);
|
|
2728
|
-
};
|
|
2729
|
-
var _decodeURI = (value) => {
|
|
2730
|
-
if (!/[%+]/.test(value)) {
|
|
2731
|
-
return value;
|
|
2732
|
-
}
|
|
2733
|
-
if (value.indexOf("+") !== -1) {
|
|
2734
|
-
value = value.replace(/\+/g, " ");
|
|
2735
|
-
}
|
|
2736
|
-
return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
|
|
2737
|
-
};
|
|
2738
|
-
var _getQueryParam = (url, key, multiple) => {
|
|
2739
|
-
let encoded;
|
|
2740
|
-
if (!multiple && key && !/[%+]/.test(key)) {
|
|
2741
|
-
let keyIndex2 = url.indexOf(`?${key}`, 8);
|
|
2742
|
-
if (keyIndex2 === -1) {
|
|
2743
|
-
keyIndex2 = url.indexOf(`&${key}`, 8);
|
|
2744
|
-
}
|
|
2745
|
-
while (keyIndex2 !== -1) {
|
|
2746
|
-
const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
|
|
2747
|
-
if (trailingKeyCode === 61) {
|
|
2748
|
-
const valueIndex = keyIndex2 + key.length + 2;
|
|
2749
|
-
const endIndex = url.indexOf("&", valueIndex);
|
|
2750
|
-
return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
|
|
2751
|
-
} else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
|
|
2752
|
-
return "";
|
|
2753
|
-
}
|
|
2754
|
-
keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
|
|
2755
|
-
}
|
|
2756
|
-
encoded = /[%+]/.test(url);
|
|
2757
|
-
if (!encoded) {
|
|
2758
|
-
return void 0;
|
|
2759
|
-
}
|
|
2760
|
-
}
|
|
2761
|
-
const results = {};
|
|
2762
|
-
encoded ??= /[%+]/.test(url);
|
|
2763
|
-
let keyIndex = url.indexOf("?", 8);
|
|
2764
|
-
while (keyIndex !== -1) {
|
|
2765
|
-
const nextKeyIndex = url.indexOf("&", keyIndex + 1);
|
|
2766
|
-
let valueIndex = url.indexOf("=", keyIndex);
|
|
2767
|
-
if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
|
|
2768
|
-
valueIndex = -1;
|
|
2769
|
-
}
|
|
2770
|
-
let name = url.slice(
|
|
2771
|
-
keyIndex + 1,
|
|
2772
|
-
valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
|
|
2773
|
-
);
|
|
2774
|
-
if (encoded) {
|
|
2775
|
-
name = _decodeURI(name);
|
|
2776
|
-
}
|
|
2777
|
-
keyIndex = nextKeyIndex;
|
|
2778
|
-
if (name === "") {
|
|
2779
|
-
continue;
|
|
2780
|
-
}
|
|
2781
|
-
let value;
|
|
2782
|
-
if (valueIndex === -1) {
|
|
2783
|
-
value = "";
|
|
2784
|
-
} else {
|
|
2785
|
-
value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
|
|
2786
|
-
if (encoded) {
|
|
2787
|
-
value = _decodeURI(value);
|
|
2788
|
-
}
|
|
2789
|
-
}
|
|
2790
|
-
if (multiple) {
|
|
2791
|
-
if (!(results[name] && Array.isArray(results[name]))) {
|
|
2792
|
-
results[name] = [];
|
|
2793
|
-
}
|
|
2794
|
-
results[name].push(value);
|
|
2795
|
-
} else {
|
|
2796
|
-
results[name] ??= value;
|
|
2797
|
-
}
|
|
2798
|
-
}
|
|
2799
|
-
return key ? results[key] : results;
|
|
2800
|
-
};
|
|
2801
|
-
var getQueryParam = _getQueryParam;
|
|
2802
|
-
var getQueryParams = (url, key) => {
|
|
2803
|
-
return _getQueryParam(url, key, true);
|
|
2804
|
-
};
|
|
2805
|
-
var decodeURIComponent_ = decodeURIComponent;
|
|
2806
|
-
|
|
2807
|
-
// src/request.ts
|
|
2808
|
-
var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
|
|
2809
|
-
var HonoRequest = class {
|
|
2810
|
-
raw;
|
|
2811
|
-
#validatedData;
|
|
2812
|
-
#matchResult;
|
|
2813
|
-
routeIndex = 0;
|
|
2814
|
-
path;
|
|
2815
|
-
bodyCache = {};
|
|
2816
|
-
constructor(request, path = "/", matchResult = [[]]) {
|
|
2817
|
-
this.raw = request;
|
|
2818
|
-
this.path = path;
|
|
2819
|
-
this.#matchResult = matchResult;
|
|
2820
|
-
this.#validatedData = {};
|
|
2821
|
-
}
|
|
2822
|
-
param(key) {
|
|
2823
|
-
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
|
|
2824
|
-
}
|
|
2825
|
-
#getDecodedParam(key) {
|
|
2826
|
-
const paramKey = this.#matchResult[0][this.routeIndex][1][key];
|
|
2827
|
-
const param = this.#getParamValue(paramKey);
|
|
2828
|
-
return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
|
|
2829
|
-
}
|
|
2830
|
-
#getAllDecodedParams() {
|
|
2831
|
-
const decoded = {};
|
|
2832
|
-
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
|
|
2833
|
-
for (const key of keys) {
|
|
2834
|
-
const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
|
|
2835
|
-
if (value !== void 0) {
|
|
2836
|
-
decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
|
|
2837
|
-
}
|
|
2838
|
-
}
|
|
2839
|
-
return decoded;
|
|
2840
|
-
}
|
|
2841
|
-
#getParamValue(paramKey) {
|
|
2842
|
-
return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
|
|
2843
|
-
}
|
|
2844
|
-
query(key) {
|
|
2845
|
-
return getQueryParam(this.url, key);
|
|
2846
|
-
}
|
|
2847
|
-
queries(key) {
|
|
2848
|
-
return getQueryParams(this.url, key);
|
|
2849
|
-
}
|
|
2850
|
-
header(name) {
|
|
2851
|
-
if (name) {
|
|
2852
|
-
return this.raw.headers.get(name) ?? void 0;
|
|
2853
|
-
}
|
|
2854
|
-
const headerData = {};
|
|
2855
|
-
this.raw.headers.forEach((value, key) => {
|
|
2856
|
-
headerData[key] = value;
|
|
2857
|
-
});
|
|
2858
|
-
return headerData;
|
|
2859
|
-
}
|
|
2860
|
-
async parseBody(options) {
|
|
2861
|
-
return this.bodyCache.parsedBody ??= await parseBody(this, options);
|
|
2862
|
-
}
|
|
2863
|
-
#cachedBody = (key) => {
|
|
2864
|
-
const { bodyCache, raw } = this;
|
|
2865
|
-
const cachedBody = bodyCache[key];
|
|
2866
|
-
if (cachedBody) {
|
|
2867
|
-
return cachedBody;
|
|
2868
|
-
}
|
|
2869
|
-
const anyCachedKey = Object.keys(bodyCache)[0];
|
|
2870
|
-
if (anyCachedKey) {
|
|
2871
|
-
return bodyCache[anyCachedKey].then((body) => {
|
|
2872
|
-
if (anyCachedKey === "json") {
|
|
2873
|
-
body = JSON.stringify(body);
|
|
2874
|
-
}
|
|
2875
|
-
return new Response(body)[key]();
|
|
2876
|
-
});
|
|
2877
|
-
}
|
|
2878
|
-
return bodyCache[key] = raw[key]();
|
|
2879
|
-
};
|
|
2880
|
-
json() {
|
|
2881
|
-
return this.#cachedBody("text").then((text) => JSON.parse(text));
|
|
2882
|
-
}
|
|
2883
|
-
text() {
|
|
2884
|
-
return this.#cachedBody("text");
|
|
2885
|
-
}
|
|
2886
|
-
arrayBuffer() {
|
|
2887
|
-
return this.#cachedBody("arrayBuffer");
|
|
2888
|
-
}
|
|
2889
|
-
blob() {
|
|
2890
|
-
return this.#cachedBody("blob");
|
|
2891
|
-
}
|
|
2892
|
-
formData() {
|
|
2893
|
-
return this.#cachedBody("formData");
|
|
2894
|
-
}
|
|
2895
|
-
addValidatedData(target, data) {
|
|
2896
|
-
this.#validatedData[target] = data;
|
|
2897
|
-
}
|
|
2898
|
-
valid(target) {
|
|
2899
|
-
return this.#validatedData[target];
|
|
2900
|
-
}
|
|
2901
|
-
get url() {
|
|
2902
|
-
return this.raw.url;
|
|
2903
|
-
}
|
|
2904
|
-
get method() {
|
|
2905
|
-
return this.raw.method;
|
|
2906
|
-
}
|
|
2907
|
-
get [GET_MATCH_RESULT]() {
|
|
2908
|
-
return this.#matchResult;
|
|
2909
|
-
}
|
|
2910
|
-
get matchedRoutes() {
|
|
2911
|
-
return this.#matchResult[0].map(([[, route]]) => route);
|
|
2912
|
-
}
|
|
2913
|
-
get routePath() {
|
|
2914
|
-
return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
|
|
2915
|
-
}
|
|
2916
|
-
};
|
|
2917
|
-
|
|
2918
|
-
// src/utils/html.ts
|
|
2919
|
-
var HtmlEscapedCallbackPhase = {
|
|
2920
|
-
Stringify: 1};
|
|
2921
|
-
var raw = (value, callbacks) => {
|
|
2922
|
-
const escapedString = new String(value);
|
|
2923
|
-
escapedString.isEscaped = true;
|
|
2924
|
-
escapedString.callbacks = callbacks;
|
|
2925
|
-
return escapedString;
|
|
2926
|
-
};
|
|
2927
|
-
var escapeRe = /[&<>'"]/;
|
|
2928
|
-
var stringBufferToString = async (buffer, callbacks) => {
|
|
2929
|
-
let str = "";
|
|
2930
|
-
callbacks ||= [];
|
|
2931
|
-
const resolvedBuffer = await Promise.all(buffer);
|
|
2932
|
-
for (let i = resolvedBuffer.length - 1; ; i--) {
|
|
2933
|
-
str += resolvedBuffer[i];
|
|
2934
|
-
i--;
|
|
2935
|
-
if (i < 0) {
|
|
2936
|
-
break;
|
|
2937
|
-
}
|
|
2938
|
-
let r = resolvedBuffer[i];
|
|
2939
|
-
if (typeof r === "object") {
|
|
2940
|
-
callbacks.push(...r.callbacks || []);
|
|
2941
|
-
}
|
|
2942
|
-
const isEscaped = r.isEscaped;
|
|
2943
|
-
r = await (typeof r === "object" ? r.toString() : r);
|
|
2944
|
-
if (typeof r === "object") {
|
|
2945
|
-
callbacks.push(...r.callbacks || []);
|
|
2946
|
-
}
|
|
2947
|
-
if (r.isEscaped ?? isEscaped) {
|
|
2948
|
-
str += r;
|
|
2949
|
-
} else {
|
|
2950
|
-
const buf = [str];
|
|
2951
|
-
escapeToBuffer(r, buf);
|
|
2952
|
-
str = buf[0];
|
|
2953
|
-
}
|
|
2954
|
-
}
|
|
2955
|
-
return raw(str, callbacks);
|
|
2956
|
-
};
|
|
2957
|
-
var escapeToBuffer = (str, buffer) => {
|
|
2958
|
-
const match = str.search(escapeRe);
|
|
2959
|
-
if (match === -1) {
|
|
2960
|
-
buffer[0] += str;
|
|
2961
|
-
return;
|
|
2962
|
-
}
|
|
2963
|
-
let escape;
|
|
2964
|
-
let index;
|
|
2965
|
-
let lastIndex = 0;
|
|
2966
|
-
for (index = match; index < str.length; index++) {
|
|
2967
|
-
switch (str.charCodeAt(index)) {
|
|
2968
|
-
case 34:
|
|
2969
|
-
escape = """;
|
|
2970
|
-
break;
|
|
2971
|
-
case 39:
|
|
2972
|
-
escape = "'";
|
|
2973
|
-
break;
|
|
2974
|
-
case 38:
|
|
2975
|
-
escape = "&";
|
|
2976
|
-
break;
|
|
2977
|
-
case 60:
|
|
2978
|
-
escape = "<";
|
|
2979
|
-
break;
|
|
2980
|
-
case 62:
|
|
2981
|
-
escape = ">";
|
|
2982
|
-
break;
|
|
2983
|
-
default:
|
|
2984
|
-
continue;
|
|
2985
|
-
}
|
|
2986
|
-
buffer[0] += str.substring(lastIndex, index) + escape;
|
|
2987
|
-
lastIndex = index + 1;
|
|
2988
|
-
}
|
|
2989
|
-
buffer[0] += str.substring(lastIndex, index);
|
|
2990
|
-
};
|
|
2991
|
-
var resolveCallbackSync = (str) => {
|
|
2992
|
-
const callbacks = str.callbacks;
|
|
2993
|
-
if (!callbacks?.length) {
|
|
2994
|
-
return str;
|
|
2995
|
-
}
|
|
2996
|
-
const buffer = [str];
|
|
2997
|
-
const context = {};
|
|
2998
|
-
callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));
|
|
2999
|
-
return buffer[0];
|
|
3000
|
-
};
|
|
3001
|
-
var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
|
|
3002
|
-
if (typeof str === "object" && !(str instanceof String)) {
|
|
3003
|
-
if (!(str instanceof Promise)) {
|
|
3004
|
-
str = str.toString();
|
|
3005
|
-
}
|
|
3006
|
-
if (str instanceof Promise) {
|
|
3007
|
-
str = await str;
|
|
3008
|
-
}
|
|
3009
|
-
}
|
|
3010
|
-
const callbacks = str.callbacks;
|
|
3011
|
-
if (!callbacks?.length) {
|
|
3012
|
-
return Promise.resolve(str);
|
|
3013
|
-
}
|
|
3014
|
-
if (buffer) {
|
|
3015
|
-
buffer[0] += str;
|
|
3016
|
-
} else {
|
|
3017
|
-
buffer = [str];
|
|
3018
|
-
}
|
|
3019
|
-
const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
|
|
3020
|
-
(res) => Promise.all(
|
|
3021
|
-
res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
|
|
3022
|
-
).then(() => buffer[0])
|
|
3023
|
-
);
|
|
3024
|
-
{
|
|
3025
|
-
return resStr;
|
|
3026
|
-
}
|
|
3027
|
-
};
|
|
3028
|
-
|
|
3029
|
-
// src/context.ts
|
|
3030
|
-
var TEXT_PLAIN = "text/plain; charset=UTF-8";
|
|
3031
|
-
var setDefaultContentType = (contentType, headers) => {
|
|
3032
|
-
return {
|
|
3033
|
-
"Content-Type": contentType,
|
|
3034
|
-
...headers
|
|
3035
|
-
};
|
|
3036
|
-
};
|
|
3037
|
-
var Context = class {
|
|
3038
|
-
#rawRequest;
|
|
3039
|
-
#req;
|
|
3040
|
-
env = {};
|
|
3041
|
-
#var;
|
|
3042
|
-
finalized = false;
|
|
3043
|
-
error;
|
|
3044
|
-
#status;
|
|
3045
|
-
#executionCtx;
|
|
3046
|
-
#res;
|
|
3047
|
-
#layout;
|
|
3048
|
-
#renderer;
|
|
3049
|
-
#notFoundHandler;
|
|
3050
|
-
#preparedHeaders;
|
|
3051
|
-
#matchResult;
|
|
3052
|
-
#path;
|
|
3053
|
-
constructor(req, options) {
|
|
3054
|
-
this.#rawRequest = req;
|
|
3055
|
-
if (options) {
|
|
3056
|
-
this.#executionCtx = options.executionCtx;
|
|
3057
|
-
this.env = options.env;
|
|
3058
|
-
this.#notFoundHandler = options.notFoundHandler;
|
|
3059
|
-
this.#path = options.path;
|
|
3060
|
-
this.#matchResult = options.matchResult;
|
|
3061
|
-
}
|
|
3062
|
-
}
|
|
3063
|
-
get req() {
|
|
3064
|
-
this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
|
|
3065
|
-
return this.#req;
|
|
3066
|
-
}
|
|
3067
|
-
get event() {
|
|
3068
|
-
if (this.#executionCtx && "respondWith" in this.#executionCtx) {
|
|
3069
|
-
return this.#executionCtx;
|
|
3070
|
-
} else {
|
|
3071
|
-
throw Error("This context has no FetchEvent");
|
|
3072
|
-
}
|
|
3073
|
-
}
|
|
3074
|
-
get executionCtx() {
|
|
3075
|
-
if (this.#executionCtx) {
|
|
3076
|
-
return this.#executionCtx;
|
|
3077
|
-
} else {
|
|
3078
|
-
throw Error("This context has no ExecutionContext");
|
|
3079
|
-
}
|
|
3080
|
-
}
|
|
3081
|
-
get res() {
|
|
3082
|
-
return this.#res ||= new Response(null, {
|
|
3083
|
-
headers: this.#preparedHeaders ??= new Headers()
|
|
3084
|
-
});
|
|
3085
|
-
}
|
|
3086
|
-
set res(_res) {
|
|
3087
|
-
if (this.#res && _res) {
|
|
3088
|
-
_res = new Response(_res.body, _res);
|
|
3089
|
-
for (const [k, v] of this.#res.headers.entries()) {
|
|
3090
|
-
if (k === "content-type") {
|
|
3091
|
-
continue;
|
|
3092
|
-
}
|
|
3093
|
-
if (k === "set-cookie") {
|
|
3094
|
-
const cookies = this.#res.headers.getSetCookie();
|
|
3095
|
-
_res.headers.delete("set-cookie");
|
|
3096
|
-
for (const cookie of cookies) {
|
|
3097
|
-
_res.headers.append("set-cookie", cookie);
|
|
3098
|
-
}
|
|
3099
|
-
} else {
|
|
3100
|
-
_res.headers.set(k, v);
|
|
3101
|
-
}
|
|
3102
|
-
}
|
|
3103
|
-
}
|
|
3104
|
-
this.#res = _res;
|
|
3105
|
-
this.finalized = true;
|
|
3106
|
-
}
|
|
3107
|
-
render = (...args) => {
|
|
3108
|
-
this.#renderer ??= (content) => this.html(content);
|
|
3109
|
-
return this.#renderer(...args);
|
|
3110
|
-
};
|
|
3111
|
-
setLayout = (layout) => this.#layout = layout;
|
|
3112
|
-
getLayout = () => this.#layout;
|
|
3113
|
-
setRenderer = (renderer) => {
|
|
3114
|
-
this.#renderer = renderer;
|
|
3115
|
-
};
|
|
3116
|
-
header = (name, value, options) => {
|
|
3117
|
-
if (this.finalized) {
|
|
3118
|
-
this.#res = new Response(this.#res.body, this.#res);
|
|
3119
|
-
}
|
|
3120
|
-
const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
|
|
3121
|
-
if (value === void 0) {
|
|
3122
|
-
headers.delete(name);
|
|
3123
|
-
} else if (options?.append) {
|
|
3124
|
-
headers.append(name, value);
|
|
3125
|
-
} else {
|
|
3126
|
-
headers.set(name, value);
|
|
3127
|
-
}
|
|
3128
|
-
};
|
|
3129
|
-
status = (status) => {
|
|
3130
|
-
this.#status = status;
|
|
3131
|
-
};
|
|
3132
|
-
set = (key, value) => {
|
|
3133
|
-
this.#var ??= /* @__PURE__ */ new Map();
|
|
3134
|
-
this.#var.set(key, value);
|
|
3135
|
-
};
|
|
3136
|
-
get = (key) => {
|
|
3137
|
-
return this.#var ? this.#var.get(key) : void 0;
|
|
3138
|
-
};
|
|
3139
|
-
get var() {
|
|
3140
|
-
if (!this.#var) {
|
|
3141
|
-
return {};
|
|
3142
|
-
}
|
|
3143
|
-
return Object.fromEntries(this.#var);
|
|
3144
|
-
}
|
|
3145
|
-
#newResponse(data, arg, headers) {
|
|
3146
|
-
const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
|
|
3147
|
-
if (typeof arg === "object" && "headers" in arg) {
|
|
3148
|
-
const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
|
|
3149
|
-
for (const [key, value] of argHeaders) {
|
|
3150
|
-
if (key.toLowerCase() === "set-cookie") {
|
|
3151
|
-
responseHeaders.append(key, value);
|
|
3152
|
-
} else {
|
|
3153
|
-
responseHeaders.set(key, value);
|
|
3154
|
-
}
|
|
3155
|
-
}
|
|
3156
|
-
}
|
|
3157
|
-
if (headers) {
|
|
3158
|
-
for (const [k, v] of Object.entries(headers)) {
|
|
3159
|
-
if (typeof v === "string") {
|
|
3160
|
-
responseHeaders.set(k, v);
|
|
3161
|
-
} else {
|
|
3162
|
-
responseHeaders.delete(k);
|
|
3163
|
-
for (const v2 of v) {
|
|
3164
|
-
responseHeaders.append(k, v2);
|
|
3165
|
-
}
|
|
3166
|
-
}
|
|
3167
|
-
}
|
|
3168
|
-
}
|
|
3169
|
-
const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
|
|
3170
|
-
return new Response(data, { status, headers: responseHeaders });
|
|
3171
|
-
}
|
|
3172
|
-
newResponse = (...args) => this.#newResponse(...args);
|
|
3173
|
-
body = (data, arg, headers) => this.#newResponse(data, arg, headers);
|
|
3174
|
-
text = (text, arg, headers) => {
|
|
3175
|
-
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
|
|
3176
|
-
text,
|
|
3177
|
-
arg,
|
|
3178
|
-
setDefaultContentType(TEXT_PLAIN, headers)
|
|
3179
|
-
);
|
|
3180
|
-
};
|
|
3181
|
-
json = (object, arg, headers) => {
|
|
3182
|
-
return this.#newResponse(
|
|
3183
|
-
JSON.stringify(object),
|
|
3184
|
-
arg,
|
|
3185
|
-
setDefaultContentType("application/json", headers)
|
|
3186
|
-
);
|
|
3187
|
-
};
|
|
3188
|
-
html = (html, arg, headers) => {
|
|
3189
|
-
const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
|
|
3190
|
-
return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
|
|
3191
|
-
};
|
|
3192
|
-
redirect = (location, status) => {
|
|
3193
|
-
const locationString = String(location);
|
|
3194
|
-
this.header(
|
|
3195
|
-
"Location",
|
|
3196
|
-
!/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
|
|
3197
|
-
);
|
|
3198
|
-
return this.newResponse(null, status ?? 302);
|
|
3199
|
-
};
|
|
3200
|
-
notFound = () => {
|
|
3201
|
-
this.#notFoundHandler ??= () => new Response();
|
|
3202
|
-
return this.#notFoundHandler(this);
|
|
3203
|
-
};
|
|
3204
|
-
};
|
|
3205
|
-
|
|
3206
|
-
// src/router.ts
|
|
3207
|
-
var METHOD_NAME_ALL = "ALL";
|
|
3208
|
-
var METHOD_NAME_ALL_LOWERCASE = "all";
|
|
3209
|
-
var METHODS = ["get", "post", "put", "delete", "options", "patch"];
|
|
3210
|
-
var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
|
|
3211
|
-
var UnsupportedPathError = class extends Error {
|
|
3212
|
-
};
|
|
3213
|
-
|
|
3214
|
-
// src/utils/constants.ts
|
|
3215
|
-
var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
|
|
3216
|
-
|
|
3217
|
-
// src/hono-base.ts
|
|
3218
|
-
var notFoundHandler = (c) => {
|
|
3219
|
-
return c.text("404 Not Found", 404);
|
|
3220
|
-
};
|
|
3221
|
-
var errorHandler$1 = (err, c) => {
|
|
3222
|
-
if ("getResponse" in err) {
|
|
3223
|
-
const res = err.getResponse();
|
|
3224
|
-
return c.newResponse(res.body, res);
|
|
3225
|
-
}
|
|
3226
|
-
console.error(err);
|
|
3227
|
-
return c.text("Internal Server Error", 500);
|
|
3228
|
-
};
|
|
3229
|
-
var Hono$1 = class Hono {
|
|
3230
|
-
get;
|
|
3231
|
-
post;
|
|
3232
|
-
put;
|
|
3233
|
-
delete;
|
|
3234
|
-
options;
|
|
3235
|
-
patch;
|
|
3236
|
-
all;
|
|
3237
|
-
on;
|
|
3238
|
-
use;
|
|
3239
|
-
router;
|
|
3240
|
-
getPath;
|
|
3241
|
-
_basePath = "/";
|
|
3242
|
-
#path = "/";
|
|
3243
|
-
routes = [];
|
|
3244
|
-
constructor(options = {}) {
|
|
3245
|
-
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
|
|
3246
|
-
allMethods.forEach((method) => {
|
|
3247
|
-
this[method] = (args1, ...args) => {
|
|
3248
|
-
if (typeof args1 === "string") {
|
|
3249
|
-
this.#path = args1;
|
|
3250
|
-
} else {
|
|
3251
|
-
this.#addRoute(method, this.#path, args1);
|
|
3252
|
-
}
|
|
3253
|
-
args.forEach((handler) => {
|
|
3254
|
-
this.#addRoute(method, this.#path, handler);
|
|
3255
|
-
});
|
|
3256
|
-
return this;
|
|
3257
|
-
};
|
|
3258
|
-
});
|
|
3259
|
-
this.on = (method, path, ...handlers) => {
|
|
3260
|
-
for (const p of [path].flat()) {
|
|
3261
|
-
this.#path = p;
|
|
3262
|
-
for (const m of [method].flat()) {
|
|
3263
|
-
handlers.map((handler) => {
|
|
3264
|
-
this.#addRoute(m.toUpperCase(), this.#path, handler);
|
|
3265
|
-
});
|
|
3266
|
-
}
|
|
3267
|
-
}
|
|
3268
|
-
return this;
|
|
3269
|
-
};
|
|
3270
|
-
this.use = (arg1, ...handlers) => {
|
|
3271
|
-
if (typeof arg1 === "string") {
|
|
3272
|
-
this.#path = arg1;
|
|
3273
|
-
} else {
|
|
3274
|
-
this.#path = "*";
|
|
3275
|
-
handlers.unshift(arg1);
|
|
3276
|
-
}
|
|
3277
|
-
handlers.forEach((handler) => {
|
|
3278
|
-
this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
|
|
3279
|
-
});
|
|
3280
|
-
return this;
|
|
3281
|
-
};
|
|
3282
|
-
const { strict, ...optionsWithoutStrict } = options;
|
|
3283
|
-
Object.assign(this, optionsWithoutStrict);
|
|
3284
|
-
this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
|
|
3285
|
-
}
|
|
3286
|
-
#clone() {
|
|
3287
|
-
const clone = new Hono$1({
|
|
3288
|
-
router: this.router,
|
|
3289
|
-
getPath: this.getPath
|
|
3290
|
-
});
|
|
3291
|
-
clone.errorHandler = this.errorHandler;
|
|
3292
|
-
clone.#notFoundHandler = this.#notFoundHandler;
|
|
3293
|
-
clone.routes = this.routes;
|
|
3294
|
-
return clone;
|
|
3295
|
-
}
|
|
3296
|
-
#notFoundHandler = notFoundHandler;
|
|
3297
|
-
errorHandler = errorHandler$1;
|
|
3298
|
-
route(path, app) {
|
|
3299
|
-
const subApp = this.basePath(path);
|
|
3300
|
-
app.routes.map((r) => {
|
|
3301
|
-
let handler;
|
|
3302
|
-
if (app.errorHandler === errorHandler$1) {
|
|
3303
|
-
handler = r.handler;
|
|
3304
|
-
} else {
|
|
3305
|
-
handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
|
|
3306
|
-
handler[COMPOSED_HANDLER] = r.handler;
|
|
3307
|
-
}
|
|
3308
|
-
subApp.#addRoute(r.method, r.path, handler);
|
|
3309
|
-
});
|
|
3310
|
-
return this;
|
|
3311
|
-
}
|
|
3312
|
-
basePath(path) {
|
|
3313
|
-
const subApp = this.#clone();
|
|
3314
|
-
subApp._basePath = mergePath(this._basePath, path);
|
|
3315
|
-
return subApp;
|
|
3316
|
-
}
|
|
3317
|
-
onError = (handler) => {
|
|
3318
|
-
this.errorHandler = handler;
|
|
3319
|
-
return this;
|
|
3320
|
-
};
|
|
3321
|
-
notFound = (handler) => {
|
|
3322
|
-
this.#notFoundHandler = handler;
|
|
3323
|
-
return this;
|
|
3324
|
-
};
|
|
3325
|
-
mount(path, applicationHandler, options) {
|
|
3326
|
-
let replaceRequest;
|
|
3327
|
-
let optionHandler;
|
|
3328
|
-
if (options) {
|
|
3329
|
-
if (typeof options === "function") {
|
|
3330
|
-
optionHandler = options;
|
|
3331
|
-
} else {
|
|
3332
|
-
optionHandler = options.optionHandler;
|
|
3333
|
-
if (options.replaceRequest === false) {
|
|
3334
|
-
replaceRequest = (request) => request;
|
|
3335
|
-
} else {
|
|
3336
|
-
replaceRequest = options.replaceRequest;
|
|
3337
|
-
}
|
|
3338
|
-
}
|
|
3339
|
-
}
|
|
3340
|
-
const getOptions = optionHandler ? (c) => {
|
|
3341
|
-
const options2 = optionHandler(c);
|
|
3342
|
-
return Array.isArray(options2) ? options2 : [options2];
|
|
3343
|
-
} : (c) => {
|
|
3344
|
-
let executionContext = void 0;
|
|
3345
|
-
try {
|
|
3346
|
-
executionContext = c.executionCtx;
|
|
3347
|
-
} catch {
|
|
3348
|
-
}
|
|
3349
|
-
return [c.env, executionContext];
|
|
3350
|
-
};
|
|
3351
|
-
replaceRequest ||= (() => {
|
|
3352
|
-
const mergedPath = mergePath(this._basePath, path);
|
|
3353
|
-
const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
|
|
3354
|
-
return (request) => {
|
|
3355
|
-
const url = new URL(request.url);
|
|
3356
|
-
url.pathname = url.pathname.slice(pathPrefixLength) || "/";
|
|
3357
|
-
return new Request(url, request);
|
|
3358
|
-
};
|
|
3359
|
-
})();
|
|
3360
|
-
const handler = async (c, next) => {
|
|
3361
|
-
const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
|
|
3362
|
-
if (res) {
|
|
3363
|
-
return res;
|
|
3364
|
-
}
|
|
3365
|
-
await next();
|
|
3366
|
-
};
|
|
3367
|
-
this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
|
|
3368
|
-
return this;
|
|
3369
|
-
}
|
|
3370
|
-
#addRoute(method, path, handler) {
|
|
3371
|
-
method = method.toUpperCase();
|
|
3372
|
-
path = mergePath(this._basePath, path);
|
|
3373
|
-
const r = { basePath: this._basePath, path, method, handler };
|
|
3374
|
-
this.router.add(method, path, [handler, r]);
|
|
3375
|
-
this.routes.push(r);
|
|
3376
|
-
}
|
|
3377
|
-
#handleError(err, c) {
|
|
3378
|
-
if (err instanceof Error) {
|
|
3379
|
-
return this.errorHandler(err, c);
|
|
3380
|
-
}
|
|
3381
|
-
throw err;
|
|
3382
|
-
}
|
|
3383
|
-
#dispatch(request, executionCtx, env, method) {
|
|
3384
|
-
if (method === "HEAD") {
|
|
3385
|
-
return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
|
|
3386
|
-
}
|
|
3387
|
-
const path = this.getPath(request, { env });
|
|
3388
|
-
const matchResult = this.router.match(method, path);
|
|
3389
|
-
const c = new Context(request, {
|
|
3390
|
-
path,
|
|
3391
|
-
matchResult,
|
|
3392
|
-
env,
|
|
3393
|
-
executionCtx,
|
|
3394
|
-
notFoundHandler: this.#notFoundHandler
|
|
3395
|
-
});
|
|
3396
|
-
if (matchResult[0].length === 1) {
|
|
3397
|
-
let res;
|
|
3398
|
-
try {
|
|
3399
|
-
res = matchResult[0][0][0][0](c, async () => {
|
|
3400
|
-
c.res = await this.#notFoundHandler(c);
|
|
3401
|
-
});
|
|
3402
|
-
} catch (err) {
|
|
3403
|
-
return this.#handleError(err, c);
|
|
3404
|
-
}
|
|
3405
|
-
return res instanceof Promise ? res.then(
|
|
3406
|
-
(resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
|
|
3407
|
-
).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
|
|
3408
|
-
}
|
|
3409
|
-
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
|
|
3410
|
-
return (async () => {
|
|
3411
|
-
try {
|
|
3412
|
-
const context = await composed(c);
|
|
3413
|
-
if (!context.finalized) {
|
|
3414
|
-
throw new Error(
|
|
3415
|
-
"Context is not finalized. Did you forget to return a Response object or `await next()`?"
|
|
3416
|
-
);
|
|
3417
|
-
}
|
|
3418
|
-
return context.res;
|
|
3419
|
-
} catch (err) {
|
|
3420
|
-
return this.#handleError(err, c);
|
|
3421
|
-
}
|
|
3422
|
-
})();
|
|
3423
|
-
}
|
|
3424
|
-
fetch = (request, ...rest) => {
|
|
3425
|
-
return this.#dispatch(request, rest[1], rest[0], request.method);
|
|
3426
|
-
};
|
|
3427
|
-
request = (input, requestInit, Env, executionCtx) => {
|
|
3428
|
-
if (input instanceof Request) {
|
|
3429
|
-
return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
|
|
3430
|
-
}
|
|
3431
|
-
input = input.toString();
|
|
3432
|
-
return this.fetch(
|
|
3433
|
-
new Request(
|
|
3434
|
-
/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
|
|
3435
|
-
requestInit
|
|
3436
|
-
),
|
|
3437
|
-
Env,
|
|
3438
|
-
executionCtx
|
|
3439
|
-
);
|
|
3440
|
-
};
|
|
3441
|
-
fire = () => {
|
|
3442
|
-
addEventListener("fetch", (event) => {
|
|
3443
|
-
event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
|
|
3444
|
-
});
|
|
3445
|
-
};
|
|
3446
|
-
};
|
|
3447
|
-
|
|
3448
|
-
// src/router/reg-exp-router/matcher.ts
|
|
3449
|
-
var emptyParam = [];
|
|
3450
|
-
function match$1(method, path) {
|
|
3451
|
-
const matchers = this.buildAllMatchers();
|
|
3452
|
-
const match2 = (method2, path2) => {
|
|
3453
|
-
const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
|
|
3454
|
-
const staticMatch = matcher[2][path2];
|
|
3455
|
-
if (staticMatch) {
|
|
3456
|
-
return staticMatch;
|
|
3457
|
-
}
|
|
3458
|
-
const match3 = path2.match(matcher[0]);
|
|
3459
|
-
if (!match3) {
|
|
3460
|
-
return [[], emptyParam];
|
|
3461
|
-
}
|
|
3462
|
-
const index = match3.indexOf("", 1);
|
|
3463
|
-
return [matcher[1][index], match3];
|
|
3464
|
-
};
|
|
3465
|
-
this.match = match2;
|
|
3466
|
-
return match2(method, path);
|
|
3467
|
-
}
|
|
3468
|
-
|
|
3469
|
-
// src/router/reg-exp-router/node.ts
|
|
3470
|
-
var LABEL_REG_EXP_STR = "[^/]+";
|
|
3471
|
-
var ONLY_WILDCARD_REG_EXP_STR = ".*";
|
|
3472
|
-
var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
|
|
3473
|
-
var PATH_ERROR = Symbol();
|
|
3474
|
-
var regExpMetaChars = new Set(".\\+*[^]$()");
|
|
3475
|
-
function compareKey(a, b) {
|
|
3476
|
-
if (a.length === 1) {
|
|
3477
|
-
return b.length === 1 ? a < b ? -1 : 1 : -1;
|
|
3478
|
-
}
|
|
3479
|
-
if (b.length === 1) {
|
|
3480
|
-
return 1;
|
|
3481
|
-
}
|
|
3482
|
-
if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
|
|
3483
|
-
return 1;
|
|
3484
|
-
} else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
|
|
3485
|
-
return -1;
|
|
3486
|
-
}
|
|
3487
|
-
if (a === LABEL_REG_EXP_STR) {
|
|
3488
|
-
return 1;
|
|
3489
|
-
} else if (b === LABEL_REG_EXP_STR) {
|
|
3490
|
-
return -1;
|
|
3491
|
-
}
|
|
3492
|
-
return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
|
|
3493
|
-
}
|
|
3494
|
-
var Node$1 = class Node {
|
|
3495
|
-
#index;
|
|
3496
|
-
#varIndex;
|
|
3497
|
-
#children = /* @__PURE__ */ Object.create(null);
|
|
3498
|
-
insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
|
|
3499
|
-
if (tokens.length === 0) {
|
|
3500
|
-
if (this.#index !== void 0) {
|
|
3501
|
-
throw PATH_ERROR;
|
|
3502
|
-
}
|
|
3503
|
-
if (pathErrorCheckOnly) {
|
|
3504
|
-
return;
|
|
3505
|
-
}
|
|
3506
|
-
this.#index = index;
|
|
3507
|
-
return;
|
|
3508
|
-
}
|
|
3509
|
-
const [token, ...restTokens] = tokens;
|
|
3510
|
-
const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
|
|
3511
|
-
let node;
|
|
3512
|
-
if (pattern) {
|
|
3513
|
-
const name = pattern[1];
|
|
3514
|
-
let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
|
|
3515
|
-
if (name && pattern[2]) {
|
|
3516
|
-
if (regexpStr === ".*") {
|
|
3517
|
-
throw PATH_ERROR;
|
|
3518
|
-
}
|
|
3519
|
-
regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
|
|
3520
|
-
if (/\((?!\?:)/.test(regexpStr)) {
|
|
3521
|
-
throw PATH_ERROR;
|
|
3522
|
-
}
|
|
3523
|
-
}
|
|
3524
|
-
node = this.#children[regexpStr];
|
|
3525
|
-
if (!node) {
|
|
3526
|
-
if (Object.keys(this.#children).some(
|
|
3527
|
-
(k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
3528
|
-
)) {
|
|
3529
|
-
throw PATH_ERROR;
|
|
3530
|
-
}
|
|
3531
|
-
if (pathErrorCheckOnly) {
|
|
3532
|
-
return;
|
|
3533
|
-
}
|
|
3534
|
-
node = this.#children[regexpStr] = new Node$1();
|
|
3535
|
-
if (name !== "") {
|
|
3536
|
-
node.#varIndex = context.varIndex++;
|
|
3537
|
-
}
|
|
3538
|
-
}
|
|
3539
|
-
if (!pathErrorCheckOnly && name !== "") {
|
|
3540
|
-
paramMap.push([name, node.#varIndex]);
|
|
3541
|
-
}
|
|
3542
|
-
} else {
|
|
3543
|
-
node = this.#children[token];
|
|
3544
|
-
if (!node) {
|
|
3545
|
-
if (Object.keys(this.#children).some(
|
|
3546
|
-
(k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
|
|
3547
|
-
)) {
|
|
3548
|
-
throw PATH_ERROR;
|
|
3549
|
-
}
|
|
3550
|
-
if (pathErrorCheckOnly) {
|
|
3551
|
-
return;
|
|
3552
|
-
}
|
|
3553
|
-
node = this.#children[token] = new Node$1();
|
|
3554
|
-
}
|
|
3555
|
-
}
|
|
3556
|
-
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
|
|
3557
|
-
}
|
|
3558
|
-
buildRegExpStr() {
|
|
3559
|
-
const childKeys = Object.keys(this.#children).sort(compareKey);
|
|
3560
|
-
const strList = childKeys.map((k) => {
|
|
3561
|
-
const c = this.#children[k];
|
|
3562
|
-
return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
|
|
3563
|
-
});
|
|
3564
|
-
if (typeof this.#index === "number") {
|
|
3565
|
-
strList.unshift(`#${this.#index}`);
|
|
3566
|
-
}
|
|
3567
|
-
if (strList.length === 0) {
|
|
3568
|
-
return "";
|
|
3569
|
-
}
|
|
3570
|
-
if (strList.length === 1) {
|
|
3571
|
-
return strList[0];
|
|
3572
|
-
}
|
|
3573
|
-
return "(?:" + strList.join("|") + ")";
|
|
3574
|
-
}
|
|
3575
|
-
};
|
|
3576
|
-
|
|
3577
|
-
// src/router/reg-exp-router/trie.ts
|
|
3578
|
-
var Trie = class {
|
|
3579
|
-
#context = { varIndex: 0 };
|
|
3580
|
-
#root = new Node$1();
|
|
3581
|
-
insert(path, index, pathErrorCheckOnly) {
|
|
3582
|
-
const paramAssoc = [];
|
|
3583
|
-
const groups = [];
|
|
3584
|
-
for (let i = 0; ; ) {
|
|
3585
|
-
let replaced = false;
|
|
3586
|
-
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
3587
|
-
const mark = `@\\${i}`;
|
|
3588
|
-
groups[i] = [mark, m];
|
|
3589
|
-
i++;
|
|
3590
|
-
replaced = true;
|
|
3591
|
-
return mark;
|
|
3592
|
-
});
|
|
3593
|
-
if (!replaced) {
|
|
3594
|
-
break;
|
|
3595
|
-
}
|
|
3596
|
-
}
|
|
3597
|
-
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
|
|
3598
|
-
for (let i = groups.length - 1; i >= 0; i--) {
|
|
3599
|
-
const [mark] = groups[i];
|
|
3600
|
-
for (let j = tokens.length - 1; j >= 0; j--) {
|
|
3601
|
-
if (tokens[j].indexOf(mark) !== -1) {
|
|
3602
|
-
tokens[j] = tokens[j].replace(mark, groups[i][1]);
|
|
3603
|
-
break;
|
|
3604
|
-
}
|
|
3605
|
-
}
|
|
3606
|
-
}
|
|
3607
|
-
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
|
|
3608
|
-
return paramAssoc;
|
|
3609
|
-
}
|
|
3610
|
-
buildRegExp() {
|
|
3611
|
-
let regexp = this.#root.buildRegExpStr();
|
|
3612
|
-
if (regexp === "") {
|
|
3613
|
-
return [/^$/, [], []];
|
|
3614
|
-
}
|
|
3615
|
-
let captureIndex = 0;
|
|
3616
|
-
const indexReplacementMap = [];
|
|
3617
|
-
const paramReplacementMap = [];
|
|
3618
|
-
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
|
|
3619
|
-
if (handlerIndex !== void 0) {
|
|
3620
|
-
indexReplacementMap[++captureIndex] = Number(handlerIndex);
|
|
3621
|
-
return "$()";
|
|
3622
|
-
}
|
|
3623
|
-
if (paramIndex !== void 0) {
|
|
3624
|
-
paramReplacementMap[Number(paramIndex)] = ++captureIndex;
|
|
3625
|
-
return "";
|
|
3626
|
-
}
|
|
3627
|
-
return "";
|
|
3628
|
-
});
|
|
3629
|
-
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
|
|
3630
|
-
}
|
|
3631
|
-
};
|
|
3632
|
-
|
|
3633
|
-
// src/router/reg-exp-router/router.ts
|
|
3634
|
-
var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
|
|
3635
|
-
var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
3636
|
-
function buildWildcardRegExp(path) {
|
|
3637
|
-
return wildcardRegExpCache[path] ??= new RegExp(
|
|
3638
|
-
path === "*" ? "" : `^${path.replace(
|
|
3639
|
-
/\/\*$|([.\\+*[^\]$()])/g,
|
|
3640
|
-
(_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
|
|
3641
|
-
)}$`
|
|
3642
|
-
);
|
|
3643
|
-
}
|
|
3644
|
-
function clearWildcardRegExpCache() {
|
|
3645
|
-
wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
|
|
3646
|
-
}
|
|
3647
|
-
function buildMatcherFromPreprocessedRoutes(routes) {
|
|
3648
|
-
const trie = new Trie();
|
|
3649
|
-
const handlerData = [];
|
|
3650
|
-
if (routes.length === 0) {
|
|
3651
|
-
return nullMatcher;
|
|
3652
|
-
}
|
|
3653
|
-
const routesWithStaticPathFlag = routes.map(
|
|
3654
|
-
(route) => [!/\*|\/:/.test(route[0]), ...route]
|
|
3655
|
-
).sort(
|
|
3656
|
-
([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
|
|
3657
|
-
);
|
|
3658
|
-
const staticMap = /* @__PURE__ */ Object.create(null);
|
|
3659
|
-
for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
|
|
3660
|
-
const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
|
|
3661
|
-
if (pathErrorCheckOnly) {
|
|
3662
|
-
staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
|
|
3663
|
-
} else {
|
|
3664
|
-
j++;
|
|
3665
|
-
}
|
|
3666
|
-
let paramAssoc;
|
|
3667
|
-
try {
|
|
3668
|
-
paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
|
|
3669
|
-
} catch (e) {
|
|
3670
|
-
throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
|
|
3671
|
-
}
|
|
3672
|
-
if (pathErrorCheckOnly) {
|
|
3673
|
-
continue;
|
|
3674
|
-
}
|
|
3675
|
-
handlerData[j] = handlers.map(([h, paramCount]) => {
|
|
3676
|
-
const paramIndexMap = /* @__PURE__ */ Object.create(null);
|
|
3677
|
-
paramCount -= 1;
|
|
3678
|
-
for (; paramCount >= 0; paramCount--) {
|
|
3679
|
-
const [key, value] = paramAssoc[paramCount];
|
|
3680
|
-
paramIndexMap[key] = value;
|
|
3681
|
-
}
|
|
3682
|
-
return [h, paramIndexMap];
|
|
3683
|
-
});
|
|
3684
|
-
}
|
|
3685
|
-
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
|
|
3686
|
-
for (let i = 0, len = handlerData.length; i < len; i++) {
|
|
3687
|
-
for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
|
|
3688
|
-
const map = handlerData[i][j]?.[1];
|
|
3689
|
-
if (!map) {
|
|
3690
|
-
continue;
|
|
3691
|
-
}
|
|
3692
|
-
const keys = Object.keys(map);
|
|
3693
|
-
for (let k = 0, len3 = keys.length; k < len3; k++) {
|
|
3694
|
-
map[keys[k]] = paramReplacementMap[map[keys[k]]];
|
|
3695
|
-
}
|
|
3696
|
-
}
|
|
3697
|
-
}
|
|
3698
|
-
const handlerMap = [];
|
|
3699
|
-
for (const i in indexReplacementMap) {
|
|
3700
|
-
handlerMap[i] = handlerData[indexReplacementMap[i]];
|
|
3701
|
-
}
|
|
3702
|
-
return [regexp, handlerMap, staticMap];
|
|
3703
|
-
}
|
|
3704
|
-
function findMiddleware(middleware, path) {
|
|
3705
|
-
if (!middleware) {
|
|
3706
|
-
return void 0;
|
|
3707
|
-
}
|
|
3708
|
-
for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
|
|
3709
|
-
if (buildWildcardRegExp(k).test(path)) {
|
|
3710
|
-
return [...middleware[k]];
|
|
3711
|
-
}
|
|
3712
|
-
}
|
|
3713
|
-
return void 0;
|
|
3714
|
-
}
|
|
3715
|
-
var RegExpRouter = class {
|
|
3716
|
-
name = "RegExpRouter";
|
|
3717
|
-
#middleware;
|
|
3718
|
-
#routes;
|
|
3719
|
-
constructor() {
|
|
3720
|
-
this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
3721
|
-
this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
|
|
3722
|
-
}
|
|
3723
|
-
add(method, path, handler) {
|
|
3724
|
-
const middleware = this.#middleware;
|
|
3725
|
-
const routes = this.#routes;
|
|
3726
|
-
if (!middleware || !routes) {
|
|
3727
|
-
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
3728
|
-
}
|
|
3729
|
-
if (!middleware[method]) {
|
|
3730
|
-
[middleware, routes].forEach((handlerMap) => {
|
|
3731
|
-
handlerMap[method] = /* @__PURE__ */ Object.create(null);
|
|
3732
|
-
Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
|
|
3733
|
-
handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
|
|
3734
|
-
});
|
|
3735
|
-
});
|
|
3736
|
-
}
|
|
3737
|
-
if (path === "/*") {
|
|
3738
|
-
path = "*";
|
|
3739
|
-
}
|
|
3740
|
-
const paramCount = (path.match(/\/:/g) || []).length;
|
|
3741
|
-
if (/\*$/.test(path)) {
|
|
3742
|
-
const re = buildWildcardRegExp(path);
|
|
3743
|
-
if (method === METHOD_NAME_ALL) {
|
|
3744
|
-
Object.keys(middleware).forEach((m) => {
|
|
3745
|
-
middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
3746
|
-
});
|
|
3747
|
-
} else {
|
|
3748
|
-
middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
|
|
3749
|
-
}
|
|
3750
|
-
Object.keys(middleware).forEach((m) => {
|
|
3751
|
-
if (method === METHOD_NAME_ALL || method === m) {
|
|
3752
|
-
Object.keys(middleware[m]).forEach((p) => {
|
|
3753
|
-
re.test(p) && middleware[m][p].push([handler, paramCount]);
|
|
3754
|
-
});
|
|
3755
|
-
}
|
|
3756
|
-
});
|
|
3757
|
-
Object.keys(routes).forEach((m) => {
|
|
3758
|
-
if (method === METHOD_NAME_ALL || method === m) {
|
|
3759
|
-
Object.keys(routes[m]).forEach(
|
|
3760
|
-
(p) => re.test(p) && routes[m][p].push([handler, paramCount])
|
|
3761
|
-
);
|
|
3762
|
-
}
|
|
3763
|
-
});
|
|
3764
|
-
return;
|
|
3765
|
-
}
|
|
3766
|
-
const paths = checkOptionalParameter(path) || [path];
|
|
3767
|
-
for (let i = 0, len = paths.length; i < len; i++) {
|
|
3768
|
-
const path2 = paths[i];
|
|
3769
|
-
Object.keys(routes).forEach((m) => {
|
|
3770
|
-
if (method === METHOD_NAME_ALL || method === m) {
|
|
3771
|
-
routes[m][path2] ||= [
|
|
3772
|
-
...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
|
|
3773
|
-
];
|
|
3774
|
-
routes[m][path2].push([handler, paramCount - len + i + 1]);
|
|
3775
|
-
}
|
|
3776
|
-
});
|
|
3777
|
-
}
|
|
3778
|
-
}
|
|
3779
|
-
match = match$1;
|
|
3780
|
-
buildAllMatchers() {
|
|
3781
|
-
const matchers = /* @__PURE__ */ Object.create(null);
|
|
3782
|
-
Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
|
|
3783
|
-
matchers[method] ||= this.#buildMatcher(method);
|
|
3784
|
-
});
|
|
3785
|
-
this.#middleware = this.#routes = void 0;
|
|
3786
|
-
clearWildcardRegExpCache();
|
|
3787
|
-
return matchers;
|
|
3788
|
-
}
|
|
3789
|
-
#buildMatcher(method) {
|
|
3790
|
-
const routes = [];
|
|
3791
|
-
let hasOwnRoute = method === METHOD_NAME_ALL;
|
|
3792
|
-
[this.#middleware, this.#routes].forEach((r) => {
|
|
3793
|
-
const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
|
|
3794
|
-
if (ownRoute.length !== 0) {
|
|
3795
|
-
hasOwnRoute ||= true;
|
|
3796
|
-
routes.push(...ownRoute);
|
|
3797
|
-
} else if (method !== METHOD_NAME_ALL) {
|
|
3798
|
-
routes.push(
|
|
3799
|
-
...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
|
|
3800
|
-
);
|
|
3801
|
-
}
|
|
3802
|
-
});
|
|
3803
|
-
if (!hasOwnRoute) {
|
|
3804
|
-
return null;
|
|
3805
|
-
} else {
|
|
3806
|
-
return buildMatcherFromPreprocessedRoutes(routes);
|
|
3807
|
-
}
|
|
3808
|
-
}
|
|
3809
|
-
};
|
|
3810
|
-
|
|
3811
|
-
// src/router/smart-router/router.ts
|
|
3812
|
-
var SmartRouter = class {
|
|
3813
|
-
name = "SmartRouter";
|
|
3814
|
-
#routers = [];
|
|
3815
|
-
#routes = [];
|
|
3816
|
-
constructor(init) {
|
|
3817
|
-
this.#routers = init.routers;
|
|
3818
|
-
}
|
|
3819
|
-
add(method, path, handler) {
|
|
3820
|
-
if (!this.#routes) {
|
|
3821
|
-
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
|
|
3822
|
-
}
|
|
3823
|
-
this.#routes.push([method, path, handler]);
|
|
3824
|
-
}
|
|
3825
|
-
match(method, path) {
|
|
3826
|
-
if (!this.#routes) {
|
|
3827
|
-
throw new Error("Fatal error");
|
|
3828
|
-
}
|
|
3829
|
-
const routers = this.#routers;
|
|
3830
|
-
const routes = this.#routes;
|
|
3831
|
-
const len = routers.length;
|
|
3832
|
-
let i = 0;
|
|
3833
|
-
let res;
|
|
3834
|
-
for (; i < len; i++) {
|
|
3835
|
-
const router = routers[i];
|
|
3836
|
-
try {
|
|
3837
|
-
for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
|
|
3838
|
-
router.add(...routes[i2]);
|
|
3839
|
-
}
|
|
3840
|
-
res = router.match(method, path);
|
|
3841
|
-
} catch (e) {
|
|
3842
|
-
if (e instanceof UnsupportedPathError) {
|
|
3843
|
-
continue;
|
|
3844
|
-
}
|
|
3845
|
-
throw e;
|
|
3846
|
-
}
|
|
3847
|
-
this.match = router.match.bind(router);
|
|
3848
|
-
this.#routers = [router];
|
|
3849
|
-
this.#routes = void 0;
|
|
3850
|
-
break;
|
|
3851
|
-
}
|
|
3852
|
-
if (i === len) {
|
|
3853
|
-
throw new Error("Fatal error");
|
|
3854
|
-
}
|
|
3855
|
-
this.name = `SmartRouter + ${this.activeRouter.name}`;
|
|
3856
|
-
return res;
|
|
3857
|
-
}
|
|
3858
|
-
get activeRouter() {
|
|
3859
|
-
if (this.#routes || this.#routers.length !== 1) {
|
|
3860
|
-
throw new Error("No active router has been determined yet.");
|
|
3861
|
-
}
|
|
3862
|
-
return this.#routers[0];
|
|
3863
|
-
}
|
|
3864
|
-
};
|
|
3865
|
-
|
|
3866
|
-
// src/router/trie-router/node.ts
|
|
3867
|
-
var emptyParams = /* @__PURE__ */ Object.create(null);
|
|
3868
|
-
var Node = class {
|
|
3869
|
-
#methods;
|
|
3870
|
-
#children;
|
|
3871
|
-
#patterns;
|
|
3872
|
-
#order = 0;
|
|
3873
|
-
#params = emptyParams;
|
|
3874
|
-
constructor(method, handler, children) {
|
|
3875
|
-
this.#children = children || /* @__PURE__ */ Object.create(null);
|
|
3876
|
-
this.#methods = [];
|
|
3877
|
-
if (method && handler) {
|
|
3878
|
-
const m = /* @__PURE__ */ Object.create(null);
|
|
3879
|
-
m[method] = { handler, possibleKeys: [], score: 0 };
|
|
3880
|
-
this.#methods = [m];
|
|
3881
|
-
}
|
|
3882
|
-
this.#patterns = [];
|
|
3883
|
-
}
|
|
3884
|
-
insert(method, path, handler) {
|
|
3885
|
-
this.#order = ++this.#order;
|
|
3886
|
-
let curNode = this;
|
|
3887
|
-
const parts = splitRoutingPath(path);
|
|
3888
|
-
const possibleKeys = [];
|
|
3889
|
-
for (let i = 0, len = parts.length; i < len; i++) {
|
|
3890
|
-
const p = parts[i];
|
|
3891
|
-
const nextP = parts[i + 1];
|
|
3892
|
-
const pattern = getPattern(p, nextP);
|
|
3893
|
-
const key = Array.isArray(pattern) ? pattern[0] : p;
|
|
3894
|
-
if (key in curNode.#children) {
|
|
3895
|
-
curNode = curNode.#children[key];
|
|
3896
|
-
if (pattern) {
|
|
3897
|
-
possibleKeys.push(pattern[1]);
|
|
3898
|
-
}
|
|
3899
|
-
continue;
|
|
3900
|
-
}
|
|
3901
|
-
curNode.#children[key] = new Node();
|
|
3902
|
-
if (pattern) {
|
|
3903
|
-
curNode.#patterns.push(pattern);
|
|
3904
|
-
possibleKeys.push(pattern[1]);
|
|
3905
|
-
}
|
|
3906
|
-
curNode = curNode.#children[key];
|
|
3907
|
-
}
|
|
3908
|
-
curNode.#methods.push({
|
|
3909
|
-
[method]: {
|
|
3910
|
-
handler,
|
|
3911
|
-
possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
|
|
3912
|
-
score: this.#order
|
|
3913
|
-
}
|
|
3914
|
-
});
|
|
3915
|
-
return curNode;
|
|
3916
|
-
}
|
|
3917
|
-
#getHandlerSets(node, method, nodeParams, params) {
|
|
3918
|
-
const handlerSets = [];
|
|
3919
|
-
for (let i = 0, len = node.#methods.length; i < len; i++) {
|
|
3920
|
-
const m = node.#methods[i];
|
|
3921
|
-
const handlerSet = m[method] || m[METHOD_NAME_ALL];
|
|
3922
|
-
const processedSet = {};
|
|
3923
|
-
if (handlerSet !== void 0) {
|
|
3924
|
-
handlerSet.params = /* @__PURE__ */ Object.create(null);
|
|
3925
|
-
handlerSets.push(handlerSet);
|
|
3926
|
-
if (nodeParams !== emptyParams || params && params !== emptyParams) {
|
|
3927
|
-
for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
|
|
3928
|
-
const key = handlerSet.possibleKeys[i2];
|
|
3929
|
-
const processed = processedSet[handlerSet.score];
|
|
3930
|
-
handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
|
|
3931
|
-
processedSet[handlerSet.score] = true;
|
|
3932
|
-
}
|
|
3933
|
-
}
|
|
3934
|
-
}
|
|
3935
|
-
}
|
|
3936
|
-
return handlerSets;
|
|
3937
|
-
}
|
|
3938
|
-
search(method, path) {
|
|
3939
|
-
const handlerSets = [];
|
|
3940
|
-
this.#params = emptyParams;
|
|
3941
|
-
const curNode = this;
|
|
3942
|
-
let curNodes = [curNode];
|
|
3943
|
-
const parts = splitPath(path);
|
|
3944
|
-
const curNodesQueue = [];
|
|
3945
|
-
for (let i = 0, len = parts.length; i < len; i++) {
|
|
3946
|
-
const part = parts[i];
|
|
3947
|
-
const isLast = i === len - 1;
|
|
3948
|
-
const tempNodes = [];
|
|
3949
|
-
for (let j = 0, len2 = curNodes.length; j < len2; j++) {
|
|
3950
|
-
const node = curNodes[j];
|
|
3951
|
-
const nextNode = node.#children[part];
|
|
3952
|
-
if (nextNode) {
|
|
3953
|
-
nextNode.#params = node.#params;
|
|
3954
|
-
if (isLast) {
|
|
3955
|
-
if (nextNode.#children["*"]) {
|
|
3956
|
-
handlerSets.push(
|
|
3957
|
-
...this.#getHandlerSets(nextNode.#children["*"], method, node.#params)
|
|
3958
|
-
);
|
|
3959
|
-
}
|
|
3960
|
-
handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
|
|
3961
|
-
} else {
|
|
3962
|
-
tempNodes.push(nextNode);
|
|
3963
|
-
}
|
|
3964
|
-
}
|
|
3965
|
-
for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
|
|
3966
|
-
const pattern = node.#patterns[k];
|
|
3967
|
-
const params = node.#params === emptyParams ? {} : { ...node.#params };
|
|
3968
|
-
if (pattern === "*") {
|
|
3969
|
-
const astNode = node.#children["*"];
|
|
3970
|
-
if (astNode) {
|
|
3971
|
-
handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
|
|
3972
|
-
astNode.#params = params;
|
|
3973
|
-
tempNodes.push(astNode);
|
|
3974
|
-
}
|
|
3975
|
-
continue;
|
|
3976
|
-
}
|
|
3977
|
-
const [key, name, matcher] = pattern;
|
|
3978
|
-
if (!part && !(matcher instanceof RegExp)) {
|
|
3979
|
-
continue;
|
|
3980
|
-
}
|
|
3981
|
-
const child = node.#children[key];
|
|
3982
|
-
const restPathString = parts.slice(i).join("/");
|
|
3983
|
-
if (matcher instanceof RegExp) {
|
|
3984
|
-
const m = matcher.exec(restPathString);
|
|
3985
|
-
if (m) {
|
|
3986
|
-
params[name] = m[0];
|
|
3987
|
-
handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
|
|
3988
|
-
if (Object.keys(child.#children).length) {
|
|
3989
|
-
child.#params = params;
|
|
3990
|
-
const componentCount = m[0].match(/\//)?.length ?? 0;
|
|
3991
|
-
const targetCurNodes = curNodesQueue[componentCount] ||= [];
|
|
3992
|
-
targetCurNodes.push(child);
|
|
3993
|
-
}
|
|
3994
|
-
continue;
|
|
3995
|
-
}
|
|
3996
|
-
}
|
|
3997
|
-
if (matcher === true || matcher.test(part)) {
|
|
3998
|
-
params[name] = part;
|
|
3999
|
-
if (isLast) {
|
|
4000
|
-
handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
|
|
4001
|
-
if (child.#children["*"]) {
|
|
4002
|
-
handlerSets.push(
|
|
4003
|
-
...this.#getHandlerSets(child.#children["*"], method, params, node.#params)
|
|
4004
|
-
);
|
|
4005
|
-
}
|
|
4006
|
-
} else {
|
|
4007
|
-
child.#params = params;
|
|
4008
|
-
tempNodes.push(child);
|
|
4009
|
-
}
|
|
4010
|
-
}
|
|
4011
|
-
}
|
|
4012
|
-
}
|
|
4013
|
-
curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
|
|
4014
|
-
}
|
|
4015
|
-
if (handlerSets.length > 1) {
|
|
4016
|
-
handlerSets.sort((a, b) => {
|
|
4017
|
-
return a.score - b.score;
|
|
4018
|
-
});
|
|
4019
|
-
}
|
|
4020
|
-
return [handlerSets.map(({ handler, params }) => [handler, params])];
|
|
4021
|
-
}
|
|
4022
|
-
};
|
|
4023
|
-
|
|
4024
|
-
// src/router/trie-router/router.ts
|
|
4025
|
-
var TrieRouter = class {
|
|
4026
|
-
name = "TrieRouter";
|
|
4027
|
-
#node;
|
|
4028
|
-
constructor() {
|
|
4029
|
-
this.#node = new Node();
|
|
4030
|
-
}
|
|
4031
|
-
add(method, path, handler) {
|
|
4032
|
-
const results = checkOptionalParameter(path);
|
|
4033
|
-
if (results) {
|
|
4034
|
-
for (let i = 0, len = results.length; i < len; i++) {
|
|
4035
|
-
this.#node.insert(method, results[i], handler);
|
|
4036
|
-
}
|
|
4037
|
-
return;
|
|
4038
|
-
}
|
|
4039
|
-
this.#node.insert(method, path, handler);
|
|
4040
|
-
}
|
|
4041
|
-
match(method, path) {
|
|
4042
|
-
return this.#node.search(method, path);
|
|
4043
|
-
}
|
|
4044
|
-
};
|
|
4045
|
-
|
|
4046
|
-
// src/hono.ts
|
|
4047
|
-
var Hono = class extends Hono$1 {
|
|
4048
|
-
constructor(options = {}) {
|
|
4049
|
-
super(options);
|
|
4050
|
-
this.router = options.router ?? new SmartRouter({
|
|
4051
|
-
routers: [new RegExpRouter(), new TrieRouter()]
|
|
4052
|
-
});
|
|
4053
|
-
}
|
|
4054
|
-
};
|
|
4055
|
-
|
|
4056
|
-
// src/server.ts
|
|
4057
|
-
var RequestError = class extends Error {
|
|
4058
|
-
constructor(message, options) {
|
|
4059
|
-
super(message, options);
|
|
4060
|
-
this.name = "RequestError";
|
|
4061
|
-
}
|
|
4062
|
-
};
|
|
4063
|
-
var toRequestError = (e) => {
|
|
4064
|
-
if (e instanceof RequestError) {
|
|
4065
|
-
return e;
|
|
4066
|
-
}
|
|
4067
|
-
return new RequestError(e.message, { cause: e });
|
|
4068
|
-
};
|
|
4069
|
-
var GlobalRequest = global.Request;
|
|
4070
|
-
var Request$1 = class Request extends GlobalRequest {
|
|
4071
|
-
constructor(input, options) {
|
|
4072
|
-
if (typeof input === "object" && getRequestCache in input) {
|
|
4073
|
-
input = input[getRequestCache]();
|
|
4074
|
-
}
|
|
4075
|
-
if (typeof options?.body?.getReader !== "undefined") {
|
|
4076
|
-
options.duplex ??= "half";
|
|
4077
|
-
}
|
|
4078
|
-
super(input, options);
|
|
4079
|
-
}
|
|
4080
|
-
};
|
|
4081
|
-
var newHeadersFromIncoming = (incoming) => {
|
|
4082
|
-
const headerRecord = [];
|
|
4083
|
-
const rawHeaders = incoming.rawHeaders;
|
|
4084
|
-
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
4085
|
-
const { [i]: key, [i + 1]: value } = rawHeaders;
|
|
4086
|
-
if (key.charCodeAt(0) !== /*:*/
|
|
4087
|
-
58) {
|
|
4088
|
-
headerRecord.push([key, value]);
|
|
4089
|
-
}
|
|
4090
|
-
}
|
|
4091
|
-
return new Headers(headerRecord);
|
|
4092
|
-
};
|
|
4093
|
-
var wrapBodyStream = Symbol("wrapBodyStream");
|
|
4094
|
-
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
|
4095
|
-
const init = {
|
|
4096
|
-
method,
|
|
4097
|
-
headers,
|
|
4098
|
-
signal: abortController.signal
|
|
4099
|
-
};
|
|
4100
|
-
if (method === "TRACE") {
|
|
4101
|
-
init.method = "GET";
|
|
4102
|
-
const req = new Request$1(url, init);
|
|
4103
|
-
Object.defineProperty(req, "method", {
|
|
4104
|
-
get() {
|
|
4105
|
-
return "TRACE";
|
|
4106
|
-
}
|
|
4107
|
-
});
|
|
4108
|
-
return req;
|
|
4109
|
-
}
|
|
4110
|
-
if (!(method === "GET" || method === "HEAD")) {
|
|
4111
|
-
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
|
4112
|
-
init.body = new ReadableStream({
|
|
4113
|
-
start(controller) {
|
|
4114
|
-
controller.enqueue(incoming.rawBody);
|
|
4115
|
-
controller.close();
|
|
4116
|
-
}
|
|
4117
|
-
});
|
|
4118
|
-
} else if (incoming[wrapBodyStream]) {
|
|
4119
|
-
let reader;
|
|
4120
|
-
init.body = new ReadableStream({
|
|
4121
|
-
async pull(controller) {
|
|
4122
|
-
try {
|
|
4123
|
-
reader ||= require$$3.Readable.toWeb(incoming).getReader();
|
|
4124
|
-
const { done, value } = await reader.read();
|
|
4125
|
-
if (done) {
|
|
4126
|
-
controller.close();
|
|
4127
|
-
} else {
|
|
4128
|
-
controller.enqueue(value);
|
|
4129
|
-
}
|
|
4130
|
-
} catch (error) {
|
|
4131
|
-
controller.error(error);
|
|
4132
|
-
}
|
|
4133
|
-
}
|
|
4134
|
-
});
|
|
4135
|
-
} else {
|
|
4136
|
-
init.body = require$$3.Readable.toWeb(incoming);
|
|
4137
|
-
}
|
|
4138
|
-
}
|
|
4139
|
-
return new Request$1(url, init);
|
|
4140
|
-
};
|
|
4141
|
-
var getRequestCache = Symbol("getRequestCache");
|
|
4142
|
-
var requestCache = Symbol("requestCache");
|
|
4143
|
-
var incomingKey = Symbol("incomingKey");
|
|
4144
|
-
var urlKey = Symbol("urlKey");
|
|
4145
|
-
var headersKey = Symbol("headersKey");
|
|
4146
|
-
var abortControllerKey = Symbol("abortControllerKey");
|
|
4147
|
-
var getAbortController = Symbol("getAbortController");
|
|
4148
|
-
var requestPrototype = {
|
|
4149
|
-
get method() {
|
|
4150
|
-
return this[incomingKey].method || "GET";
|
|
4151
|
-
},
|
|
4152
|
-
get url() {
|
|
4153
|
-
return this[urlKey];
|
|
4154
|
-
},
|
|
4155
|
-
get headers() {
|
|
4156
|
-
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
4157
|
-
},
|
|
4158
|
-
[getAbortController]() {
|
|
4159
|
-
this[getRequestCache]();
|
|
4160
|
-
return this[abortControllerKey];
|
|
4161
|
-
},
|
|
4162
|
-
[getRequestCache]() {
|
|
4163
|
-
this[abortControllerKey] ||= new AbortController();
|
|
4164
|
-
return this[requestCache] ||= newRequestFromIncoming(
|
|
4165
|
-
this.method,
|
|
4166
|
-
this[urlKey],
|
|
4167
|
-
this.headers,
|
|
4168
|
-
this[incomingKey],
|
|
4169
|
-
this[abortControllerKey]
|
|
4170
|
-
);
|
|
4171
|
-
}
|
|
4172
|
-
};
|
|
4173
|
-
[
|
|
4174
|
-
"body",
|
|
4175
|
-
"bodyUsed",
|
|
4176
|
-
"cache",
|
|
4177
|
-
"credentials",
|
|
4178
|
-
"destination",
|
|
4179
|
-
"integrity",
|
|
4180
|
-
"mode",
|
|
4181
|
-
"redirect",
|
|
4182
|
-
"referrer",
|
|
4183
|
-
"referrerPolicy",
|
|
4184
|
-
"signal",
|
|
4185
|
-
"keepalive"
|
|
4186
|
-
].forEach((k) => {
|
|
4187
|
-
Object.defineProperty(requestPrototype, k, {
|
|
4188
|
-
get() {
|
|
4189
|
-
return this[getRequestCache]()[k];
|
|
4190
|
-
}
|
|
4191
|
-
});
|
|
4192
|
-
});
|
|
4193
|
-
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
4194
|
-
Object.defineProperty(requestPrototype, k, {
|
|
4195
|
-
value: function() {
|
|
4196
|
-
return this[getRequestCache]()[k]();
|
|
4197
|
-
}
|
|
4198
|
-
});
|
|
4199
|
-
});
|
|
4200
|
-
Object.setPrototypeOf(requestPrototype, Request$1.prototype);
|
|
4201
|
-
var newRequest = (incoming, defaultHostname) => {
|
|
4202
|
-
const req = Object.create(requestPrototype);
|
|
4203
|
-
req[incomingKey] = incoming;
|
|
4204
|
-
const incomingUrl = incoming.url || "";
|
|
4205
|
-
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
|
4206
|
-
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
4207
|
-
if (incoming instanceof http2.Http2ServerRequest) {
|
|
4208
|
-
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
4209
|
-
}
|
|
4210
|
-
try {
|
|
4211
|
-
const url2 = new URL(incomingUrl);
|
|
4212
|
-
req[urlKey] = url2.href;
|
|
4213
|
-
} catch (e) {
|
|
4214
|
-
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
4215
|
-
}
|
|
4216
|
-
return req;
|
|
4217
|
-
}
|
|
4218
|
-
const host = (incoming instanceof http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
|
4219
|
-
if (!host) {
|
|
4220
|
-
throw new RequestError("Missing host header");
|
|
4221
|
-
}
|
|
4222
|
-
let scheme;
|
|
4223
|
-
if (incoming instanceof http2.Http2ServerRequest) {
|
|
4224
|
-
scheme = incoming.scheme;
|
|
4225
|
-
if (!(scheme === "http" || scheme === "https")) {
|
|
4226
|
-
throw new RequestError("Unsupported scheme");
|
|
4227
|
-
}
|
|
4228
|
-
} else {
|
|
4229
|
-
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
4230
|
-
}
|
|
4231
|
-
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
|
4232
|
-
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
|
4233
|
-
throw new RequestError("Invalid host header");
|
|
4234
|
-
}
|
|
4235
|
-
req[urlKey] = url.href;
|
|
4236
|
-
return req;
|
|
4237
|
-
};
|
|
4238
|
-
|
|
4239
|
-
// src/response.ts
|
|
4240
|
-
var responseCache = Symbol("responseCache");
|
|
4241
|
-
var getResponseCache = Symbol("getResponseCache");
|
|
4242
|
-
var cacheKey = Symbol("cache");
|
|
4243
|
-
var GlobalResponse = global.Response;
|
|
4244
|
-
var Response2 = class _Response {
|
|
4245
|
-
#body;
|
|
4246
|
-
#init;
|
|
4247
|
-
[getResponseCache]() {
|
|
4248
|
-
delete this[cacheKey];
|
|
4249
|
-
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
|
4250
|
-
}
|
|
4251
|
-
constructor(body, init) {
|
|
4252
|
-
let headers;
|
|
4253
|
-
this.#body = body;
|
|
4254
|
-
if (init instanceof _Response) {
|
|
4255
|
-
const cachedGlobalResponse = init[responseCache];
|
|
4256
|
-
if (cachedGlobalResponse) {
|
|
4257
|
-
this.#init = cachedGlobalResponse;
|
|
4258
|
-
this[getResponseCache]();
|
|
4259
|
-
return;
|
|
4260
|
-
} else {
|
|
4261
|
-
this.#init = init.#init;
|
|
4262
|
-
headers = new Headers(init.#init.headers);
|
|
4263
|
-
}
|
|
4264
|
-
} else {
|
|
4265
|
-
this.#init = init;
|
|
4266
|
-
}
|
|
4267
|
-
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
|
4268
|
-
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
|
4269
|
-
this[cacheKey] = [init?.status || 200, body, headers];
|
|
4270
|
-
}
|
|
4271
|
-
}
|
|
4272
|
-
get headers() {
|
|
4273
|
-
const cache = this[cacheKey];
|
|
4274
|
-
if (cache) {
|
|
4275
|
-
if (!(cache[2] instanceof Headers)) {
|
|
4276
|
-
cache[2] = new Headers(cache[2]);
|
|
4277
|
-
}
|
|
4278
|
-
return cache[2];
|
|
4279
|
-
}
|
|
4280
|
-
return this[getResponseCache]().headers;
|
|
4281
|
-
}
|
|
4282
|
-
get status() {
|
|
4283
|
-
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
|
4284
|
-
}
|
|
4285
|
-
get ok() {
|
|
4286
|
-
const status = this.status;
|
|
4287
|
-
return status >= 200 && status < 300;
|
|
4288
|
-
}
|
|
4289
|
-
};
|
|
4290
|
-
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
|
4291
|
-
Object.defineProperty(Response2.prototype, k, {
|
|
4292
|
-
get() {
|
|
4293
|
-
return this[getResponseCache]()[k];
|
|
4294
|
-
}
|
|
4295
|
-
});
|
|
4296
|
-
});
|
|
4297
|
-
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
4298
|
-
Object.defineProperty(Response2.prototype, k, {
|
|
4299
|
-
value: function() {
|
|
4300
|
-
return this[getResponseCache]()[k]();
|
|
4301
|
-
}
|
|
4302
|
-
});
|
|
4303
|
-
});
|
|
4304
|
-
Object.setPrototypeOf(Response2, GlobalResponse);
|
|
4305
|
-
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
|
4306
|
-
|
|
4307
|
-
// src/utils.ts
|
|
4308
|
-
async function readWithoutBlocking(readPromise) {
|
|
4309
|
-
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
|
4310
|
-
}
|
|
4311
|
-
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
|
4312
|
-
const cancel = (error) => {
|
|
4313
|
-
reader.cancel(error).catch(() => {
|
|
4314
|
-
});
|
|
4315
|
-
};
|
|
4316
|
-
writable.on("close", cancel);
|
|
4317
|
-
writable.on("error", cancel);
|
|
4318
|
-
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
|
4319
|
-
return reader.closed.finally(() => {
|
|
4320
|
-
writable.off("close", cancel);
|
|
4321
|
-
writable.off("error", cancel);
|
|
4322
|
-
});
|
|
4323
|
-
function handleStreamError(error) {
|
|
4324
|
-
if (error) {
|
|
4325
|
-
writable.destroy(error);
|
|
4326
|
-
}
|
|
4327
|
-
}
|
|
4328
|
-
function onDrain() {
|
|
4329
|
-
reader.read().then(flow, handleStreamError);
|
|
4330
|
-
}
|
|
4331
|
-
function flow({ done, value }) {
|
|
4332
|
-
try {
|
|
4333
|
-
if (done) {
|
|
4334
|
-
writable.end();
|
|
4335
|
-
} else if (!writable.write(value)) {
|
|
4336
|
-
writable.once("drain", onDrain);
|
|
4337
|
-
} else {
|
|
4338
|
-
return reader.read().then(flow, handleStreamError);
|
|
4339
|
-
}
|
|
4340
|
-
} catch (e) {
|
|
4341
|
-
handleStreamError(e);
|
|
4342
|
-
}
|
|
4343
|
-
}
|
|
4344
|
-
}
|
|
4345
|
-
function writeFromReadableStream(stream, writable) {
|
|
4346
|
-
if (stream.locked) {
|
|
4347
|
-
throw new TypeError("ReadableStream is locked.");
|
|
4348
|
-
} else if (writable.destroyed) {
|
|
4349
|
-
return;
|
|
4350
|
-
}
|
|
4351
|
-
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
4352
|
-
}
|
|
4353
|
-
var buildOutgoingHttpHeaders = (headers) => {
|
|
4354
|
-
const res = {};
|
|
4355
|
-
if (!(headers instanceof Headers)) {
|
|
4356
|
-
headers = new Headers(headers ?? void 0);
|
|
4357
|
-
}
|
|
4358
|
-
const cookies = [];
|
|
4359
|
-
for (const [k, v] of headers) {
|
|
4360
|
-
if (k === "set-cookie") {
|
|
4361
|
-
cookies.push(v);
|
|
4362
|
-
} else {
|
|
4363
|
-
res[k] = v;
|
|
4364
|
-
}
|
|
4365
|
-
}
|
|
4366
|
-
if (cookies.length > 0) {
|
|
4367
|
-
res["set-cookie"] = cookies;
|
|
4368
|
-
}
|
|
4369
|
-
res["content-type"] ??= "text/plain; charset=UTF-8";
|
|
4370
|
-
return res;
|
|
4371
|
-
};
|
|
4372
|
-
|
|
4373
|
-
// src/utils/response/constants.ts
|
|
4374
|
-
var X_ALREADY_SENT = "x-hono-already-sent";
|
|
4375
|
-
var webFetch = global.fetch;
|
|
4376
|
-
if (typeof global.crypto === "undefined") {
|
|
4377
|
-
global.crypto = crypto$1;
|
|
4378
|
-
}
|
|
4379
|
-
global.fetch = (info, init) => {
|
|
4380
|
-
init = {
|
|
4381
|
-
// Disable compression handling so people can return the result of a fetch
|
|
4382
|
-
// directly in the loader without messing with the Content-Encoding header.
|
|
4383
|
-
compress: false,
|
|
4384
|
-
...init
|
|
4385
|
-
};
|
|
4386
|
-
return webFetch(info, init);
|
|
4387
|
-
};
|
|
4388
|
-
|
|
4389
|
-
// src/listener.ts
|
|
4390
|
-
var outgoingEnded = Symbol("outgoingEnded");
|
|
4391
|
-
var handleRequestError = () => new Response(null, {
|
|
4392
|
-
status: 400
|
|
4393
|
-
});
|
|
4394
|
-
var handleFetchError = (e) => new Response(null, {
|
|
4395
|
-
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
|
4396
|
-
});
|
|
4397
|
-
var handleResponseError = (e, outgoing) => {
|
|
4398
|
-
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
|
4399
|
-
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
|
4400
|
-
console.info("The user aborted a request.");
|
|
4401
|
-
} else {
|
|
4402
|
-
console.error(e);
|
|
4403
|
-
if (!outgoing.headersSent) {
|
|
4404
|
-
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
|
4405
|
-
}
|
|
4406
|
-
outgoing.end(`Error: ${err.message}`);
|
|
4407
|
-
outgoing.destroy(err);
|
|
4408
|
-
}
|
|
4409
|
-
};
|
|
4410
|
-
var flushHeaders = (outgoing) => {
|
|
4411
|
-
if ("flushHeaders" in outgoing && outgoing.writable) {
|
|
4412
|
-
outgoing.flushHeaders();
|
|
4413
|
-
}
|
|
4414
|
-
};
|
|
4415
|
-
var responseViaCache = async (res, outgoing) => {
|
|
4416
|
-
let [status, body, header] = res[cacheKey];
|
|
4417
|
-
if (header instanceof Headers) {
|
|
4418
|
-
header = buildOutgoingHttpHeaders(header);
|
|
4419
|
-
}
|
|
4420
|
-
if (typeof body === "string") {
|
|
4421
|
-
header["Content-Length"] = Buffer.byteLength(body);
|
|
4422
|
-
} else if (body instanceof Uint8Array) {
|
|
4423
|
-
header["Content-Length"] = body.byteLength;
|
|
4424
|
-
} else if (body instanceof Blob) {
|
|
4425
|
-
header["Content-Length"] = body.size;
|
|
4426
|
-
}
|
|
4427
|
-
outgoing.writeHead(status, header);
|
|
4428
|
-
if (typeof body === "string" || body instanceof Uint8Array) {
|
|
4429
|
-
outgoing.end(body);
|
|
4430
|
-
} else if (body instanceof Blob) {
|
|
4431
|
-
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
4432
|
-
} else {
|
|
4433
|
-
flushHeaders(outgoing);
|
|
4434
|
-
await writeFromReadableStream(body, outgoing)?.catch(
|
|
4435
|
-
(e) => handleResponseError(e, outgoing)
|
|
4436
|
-
);
|
|
4437
|
-
}
|
|
4438
|
-
outgoing[outgoingEnded]?.();
|
|
4439
|
-
};
|
|
4440
|
-
var isPromise = (res) => typeof res.then === "function";
|
|
4441
|
-
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
4442
|
-
if (isPromise(res)) {
|
|
4443
|
-
if (options.errorHandler) {
|
|
4444
|
-
try {
|
|
4445
|
-
res = await res;
|
|
4446
|
-
} catch (err) {
|
|
4447
|
-
const errRes = await options.errorHandler(err);
|
|
4448
|
-
if (!errRes) {
|
|
4449
|
-
return;
|
|
4450
|
-
}
|
|
4451
|
-
res = errRes;
|
|
4452
|
-
}
|
|
4453
|
-
} else {
|
|
4454
|
-
res = await res.catch(handleFetchError);
|
|
4455
|
-
}
|
|
4456
|
-
}
|
|
4457
|
-
if (cacheKey in res) {
|
|
4458
|
-
return responseViaCache(res, outgoing);
|
|
4459
|
-
}
|
|
4460
|
-
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
|
4461
|
-
if (res.body) {
|
|
4462
|
-
const reader = res.body.getReader();
|
|
4463
|
-
const values = [];
|
|
4464
|
-
let done = false;
|
|
4465
|
-
let currentReadPromise = void 0;
|
|
4466
|
-
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
4467
|
-
let maxReadCount = 2;
|
|
4468
|
-
for (let i = 0; i < maxReadCount; i++) {
|
|
4469
|
-
currentReadPromise ||= reader.read();
|
|
4470
|
-
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
4471
|
-
console.error(e);
|
|
4472
|
-
done = true;
|
|
4473
|
-
});
|
|
4474
|
-
if (!chunk) {
|
|
4475
|
-
if (i === 1) {
|
|
4476
|
-
await new Promise((resolve) => setTimeout(resolve));
|
|
4477
|
-
maxReadCount = 3;
|
|
4478
|
-
continue;
|
|
4479
|
-
}
|
|
4480
|
-
break;
|
|
4481
|
-
}
|
|
4482
|
-
currentReadPromise = void 0;
|
|
4483
|
-
if (chunk.value) {
|
|
4484
|
-
values.push(chunk.value);
|
|
4485
|
-
}
|
|
4486
|
-
if (chunk.done) {
|
|
4487
|
-
done = true;
|
|
4488
|
-
break;
|
|
4489
|
-
}
|
|
4490
|
-
}
|
|
4491
|
-
if (done && !("content-length" in resHeaderRecord)) {
|
|
4492
|
-
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
4493
|
-
}
|
|
4494
|
-
}
|
|
4495
|
-
outgoing.writeHead(res.status, resHeaderRecord);
|
|
4496
|
-
values.forEach((value) => {
|
|
4497
|
-
outgoing.write(value);
|
|
4498
|
-
});
|
|
4499
|
-
if (done) {
|
|
4500
|
-
outgoing.end();
|
|
4501
|
-
} else {
|
|
4502
|
-
if (values.length === 0) {
|
|
4503
|
-
flushHeaders(outgoing);
|
|
4504
|
-
}
|
|
4505
|
-
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
|
4506
|
-
}
|
|
4507
|
-
} else if (resHeaderRecord[X_ALREADY_SENT]) ; else {
|
|
4508
|
-
outgoing.writeHead(res.status, resHeaderRecord);
|
|
4509
|
-
outgoing.end();
|
|
4510
|
-
}
|
|
4511
|
-
outgoing[outgoingEnded]?.();
|
|
4512
|
-
};
|
|
4513
|
-
var getRequestListener = (fetchCallback, options = {}) => {
|
|
4514
|
-
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
|
4515
|
-
if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
|
|
4516
|
-
Object.defineProperty(global, "Request", {
|
|
4517
|
-
value: Request$1
|
|
4518
|
-
});
|
|
4519
|
-
Object.defineProperty(global, "Response", {
|
|
4520
|
-
value: Response2
|
|
4521
|
-
});
|
|
4522
|
-
}
|
|
4523
|
-
return async (incoming, outgoing) => {
|
|
4524
|
-
let res, req;
|
|
4525
|
-
try {
|
|
4526
|
-
req = newRequest(incoming, options.hostname);
|
|
4527
|
-
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
|
4528
|
-
if (!incomingEnded) {
|
|
4529
|
-
;
|
|
4530
|
-
incoming[wrapBodyStream] = true;
|
|
4531
|
-
incoming.on("end", () => {
|
|
4532
|
-
incomingEnded = true;
|
|
4533
|
-
});
|
|
4534
|
-
if (incoming instanceof http2.Http2ServerRequest) {
|
|
4535
|
-
;
|
|
4536
|
-
outgoing[outgoingEnded] = () => {
|
|
4537
|
-
if (!incomingEnded) {
|
|
4538
|
-
setTimeout(() => {
|
|
4539
|
-
if (!incomingEnded) {
|
|
4540
|
-
setTimeout(() => {
|
|
4541
|
-
incoming.destroy();
|
|
4542
|
-
outgoing.destroy();
|
|
4543
|
-
});
|
|
4544
|
-
}
|
|
4545
|
-
});
|
|
4546
|
-
}
|
|
4547
|
-
};
|
|
4548
|
-
}
|
|
4549
|
-
}
|
|
4550
|
-
outgoing.on("close", () => {
|
|
4551
|
-
const abortController = req[abortControllerKey];
|
|
4552
|
-
if (abortController) {
|
|
4553
|
-
if (incoming.errored) {
|
|
4554
|
-
req[abortControllerKey].abort(incoming.errored.toString());
|
|
4555
|
-
} else if (!outgoing.writableFinished) {
|
|
4556
|
-
req[abortControllerKey].abort("Client connection prematurely closed.");
|
|
4557
|
-
}
|
|
4558
|
-
}
|
|
4559
|
-
if (!incomingEnded) {
|
|
4560
|
-
setTimeout(() => {
|
|
4561
|
-
if (!incomingEnded) {
|
|
4562
|
-
setTimeout(() => {
|
|
4563
|
-
incoming.destroy();
|
|
4564
|
-
});
|
|
4565
|
-
}
|
|
4566
|
-
});
|
|
4567
|
-
}
|
|
4568
|
-
});
|
|
4569
|
-
res = fetchCallback(req, { incoming, outgoing });
|
|
4570
|
-
if (cacheKey in res) {
|
|
4571
|
-
return responseViaCache(res, outgoing);
|
|
4572
|
-
}
|
|
4573
|
-
} catch (e) {
|
|
4574
|
-
if (!res) {
|
|
4575
|
-
if (options.errorHandler) {
|
|
4576
|
-
res = await options.errorHandler(req ? e : toRequestError(e));
|
|
4577
|
-
if (!res) {
|
|
4578
|
-
return;
|
|
4579
|
-
}
|
|
4580
|
-
} else if (!req) {
|
|
4581
|
-
res = handleRequestError();
|
|
4582
|
-
} else {
|
|
4583
|
-
res = handleFetchError(e);
|
|
4584
|
-
}
|
|
4585
|
-
} else {
|
|
4586
|
-
return handleResponseError(e, outgoing);
|
|
4587
|
-
}
|
|
4588
|
-
}
|
|
4589
|
-
try {
|
|
4590
|
-
return await responseViaResponseObject(res, outgoing, options);
|
|
4591
|
-
} catch (e) {
|
|
4592
|
-
return handleResponseError(e, outgoing);
|
|
4593
|
-
}
|
|
4594
|
-
};
|
|
4595
|
-
};
|
|
4596
|
-
|
|
4597
|
-
// src/server.ts
|
|
4598
|
-
var createAdaptorServer = (options) => {
|
|
4599
|
-
const fetchCallback = options.fetch;
|
|
4600
|
-
const requestListener = getRequestListener(fetchCallback, {
|
|
4601
|
-
hostname: options.hostname,
|
|
4602
|
-
overrideGlobalObjects: options.overrideGlobalObjects,
|
|
4603
|
-
autoCleanupIncoming: options.autoCleanupIncoming
|
|
4604
|
-
});
|
|
4605
|
-
const createServer = options.createServer || http.createServer;
|
|
4606
|
-
const server = createServer(options.serverOptions || {}, requestListener);
|
|
4607
|
-
return server;
|
|
4608
|
-
};
|
|
4609
|
-
var serve = (options, listeningListener) => {
|
|
4610
|
-
const server = createAdaptorServer(options);
|
|
4611
|
-
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
|
4612
|
-
const serverInfo = server.address();
|
|
4613
|
-
listeningListener && listeningListener(serverInfo);
|
|
4614
|
-
});
|
|
4615
|
-
return server;
|
|
4616
|
-
};
|
|
4617
|
-
|
|
4618
|
-
// src/helper/html/index.ts
|
|
4619
|
-
var html = (strings, ...values) => {
|
|
4620
|
-
const buffer = [""];
|
|
4621
|
-
for (let i = 0, len = strings.length - 1; i < len; i++) {
|
|
4622
|
-
buffer[0] += strings[i];
|
|
4623
|
-
const children = Array.isArray(values[i]) ? values[i].flat(Infinity) : [values[i]];
|
|
4624
|
-
for (let i2 = 0, len2 = children.length; i2 < len2; i2++) {
|
|
4625
|
-
const child = children[i2];
|
|
4626
|
-
if (typeof child === "string") {
|
|
4627
|
-
escapeToBuffer(child, buffer);
|
|
4628
|
-
} else if (typeof child === "number") {
|
|
4629
|
-
buffer[0] += child;
|
|
4630
|
-
} else if (typeof child === "boolean" || child === null || child === void 0) {
|
|
4631
|
-
continue;
|
|
4632
|
-
} else if (typeof child === "object" && child.isEscaped) {
|
|
4633
|
-
if (child.callbacks) {
|
|
4634
|
-
buffer.unshift("", child);
|
|
4635
|
-
} else {
|
|
4636
|
-
const tmp = child.toString();
|
|
4637
|
-
if (tmp instanceof Promise) {
|
|
4638
|
-
buffer.unshift("", tmp);
|
|
4639
|
-
} else {
|
|
4640
|
-
buffer[0] += tmp;
|
|
4641
|
-
}
|
|
4642
|
-
}
|
|
4643
|
-
} else if (child instanceof Promise) {
|
|
4644
|
-
buffer.unshift("", child);
|
|
4645
|
-
} else {
|
|
4646
|
-
escapeToBuffer(child.toString(), buffer);
|
|
4647
|
-
}
|
|
4648
|
-
}
|
|
4649
|
-
}
|
|
4650
|
-
buffer[0] += strings.at(-1);
|
|
4651
|
-
return buffer.length === 1 ? "callbacks" in buffer ? raw(resolveCallbackSync(raw(buffer[0], buffer.callbacks))) : raw(buffer[0]) : stringBufferToString(buffer, buffer.callbacks);
|
|
4652
|
-
};
|
|
4653
|
-
|
|
4654
|
-
// src/index.ts
|
|
4655
|
-
|
|
4656
|
-
// src/swagger/renderer.ts
|
|
4657
|
-
var RENDER_TYPE = {
|
|
4658
|
-
STRING_ARRAY: "string_array",
|
|
4659
|
-
STRING: "string",
|
|
4660
|
-
JSON_STRING: "json_string",
|
|
4661
|
-
RAW: "raw"
|
|
4662
|
-
};
|
|
4663
|
-
var RENDER_TYPE_MAP = {
|
|
4664
|
-
configUrl: RENDER_TYPE.STRING,
|
|
4665
|
-
deepLinking: RENDER_TYPE.RAW,
|
|
4666
|
-
presets: RENDER_TYPE.STRING_ARRAY,
|
|
4667
|
-
plugins: RENDER_TYPE.STRING_ARRAY,
|
|
4668
|
-
spec: RENDER_TYPE.JSON_STRING,
|
|
4669
|
-
url: RENDER_TYPE.STRING,
|
|
4670
|
-
urls: RENDER_TYPE.JSON_STRING,
|
|
4671
|
-
layout: RENDER_TYPE.STRING,
|
|
4672
|
-
docExpansion: RENDER_TYPE.STRING,
|
|
4673
|
-
maxDisplayedTags: RENDER_TYPE.RAW,
|
|
4674
|
-
operationsSorter: RENDER_TYPE.RAW,
|
|
4675
|
-
requestInterceptor: RENDER_TYPE.RAW,
|
|
4676
|
-
responseInterceptor: RENDER_TYPE.RAW,
|
|
4677
|
-
persistAuthorization: RENDER_TYPE.RAW,
|
|
4678
|
-
defaultModelsExpandDepth: RENDER_TYPE.RAW,
|
|
4679
|
-
defaultModelExpandDepth: RENDER_TYPE.RAW,
|
|
4680
|
-
defaultModelRendering: RENDER_TYPE.STRING,
|
|
4681
|
-
displayRequestDuration: RENDER_TYPE.RAW,
|
|
4682
|
-
filter: RENDER_TYPE.RAW,
|
|
4683
|
-
showExtensions: RENDER_TYPE.RAW,
|
|
4684
|
-
showCommonExtensions: RENDER_TYPE.RAW,
|
|
4685
|
-
queryConfigEnabled: RENDER_TYPE.RAW,
|
|
4686
|
-
displayOperationId: RENDER_TYPE.RAW,
|
|
4687
|
-
tagsSorter: RENDER_TYPE.RAW,
|
|
4688
|
-
onComplete: RENDER_TYPE.RAW,
|
|
4689
|
-
syntaxHighlight: RENDER_TYPE.JSON_STRING,
|
|
4690
|
-
tryItOutEnabled: RENDER_TYPE.RAW,
|
|
4691
|
-
requestSnippetsEnabled: RENDER_TYPE.RAW,
|
|
4692
|
-
requestSnippets: RENDER_TYPE.JSON_STRING,
|
|
4693
|
-
oauth2RedirectUrl: RENDER_TYPE.STRING,
|
|
4694
|
-
showMutabledRequest: RENDER_TYPE.RAW,
|
|
4695
|
-
request: RENDER_TYPE.JSON_STRING,
|
|
4696
|
-
supportedSubmitMethods: RENDER_TYPE.JSON_STRING,
|
|
4697
|
-
validatorUrl: RENDER_TYPE.STRING,
|
|
4698
|
-
withCredentials: RENDER_TYPE.RAW,
|
|
4699
|
-
modelPropertyMacro: RENDER_TYPE.RAW,
|
|
4700
|
-
parameterMacro: RENDER_TYPE.RAW
|
|
4701
|
-
};
|
|
4702
|
-
var renderSwaggerUIOptions = (options) => {
|
|
4703
|
-
const optionsStrings = Object.entries(options).map(([k, v]) => {
|
|
4704
|
-
const key = k;
|
|
4705
|
-
if (!RENDER_TYPE_MAP[key] || v === void 0) {
|
|
4706
|
-
return "";
|
|
4707
|
-
}
|
|
4708
|
-
switch (RENDER_TYPE_MAP[key]) {
|
|
4709
|
-
case RENDER_TYPE.STRING:
|
|
4710
|
-
return `${key}: '${v}'`;
|
|
4711
|
-
case RENDER_TYPE.STRING_ARRAY:
|
|
4712
|
-
if (!Array.isArray(v)) {
|
|
4713
|
-
return "";
|
|
4714
|
-
}
|
|
4715
|
-
return `${key}: [${v.map((ve) => `${ve}`).join(",")}]`;
|
|
4716
|
-
case RENDER_TYPE.JSON_STRING:
|
|
4717
|
-
return `${key}: ${JSON.stringify(v)}`;
|
|
4718
|
-
case RENDER_TYPE.RAW:
|
|
4719
|
-
return `${key}: ${v}`;
|
|
4720
|
-
default:
|
|
4721
|
-
return "";
|
|
4722
|
-
}
|
|
4723
|
-
}).filter((item) => item !== "").join(",");
|
|
4724
|
-
return optionsStrings;
|
|
4725
|
-
};
|
|
4726
|
-
|
|
4727
|
-
// src/swagger/resource.ts
|
|
4728
|
-
var remoteAssets = ({ version }) => {
|
|
4729
|
-
const url = `https://cdn.jsdelivr.net/npm/swagger-ui-dist${version !== void 0 ? `@${version}` : ""}`;
|
|
4730
|
-
return {
|
|
4731
|
-
css: [`${url}/swagger-ui.css`],
|
|
4732
|
-
js: [`${url}/swagger-ui-bundle.js`]
|
|
4733
|
-
};
|
|
4734
|
-
};
|
|
4735
|
-
|
|
4736
|
-
// src/index.ts
|
|
4737
|
-
var SwaggerUI = (options) => {
|
|
4738
|
-
const asset = remoteAssets({ version: options?.version });
|
|
4739
|
-
delete options.version;
|
|
4740
|
-
if (options.manuallySwaggerUIHtml) {
|
|
4741
|
-
return options.manuallySwaggerUIHtml(asset);
|
|
4742
|
-
}
|
|
4743
|
-
const optionsStrings = renderSwaggerUIOptions(options);
|
|
4744
|
-
return `
|
|
4745
|
-
<div>
|
|
4746
|
-
<div id="swagger-ui"></div>
|
|
4747
|
-
${asset.css.map((url) => html`<link rel="stylesheet" href="${url}" />`)}
|
|
4748
|
-
${asset.js.map((url) => html`<script src="${url}" crossorigin="anonymous"></script>`)}
|
|
4749
|
-
<script>
|
|
4750
|
-
window.onload = () => {
|
|
4751
|
-
window.ui = SwaggerUIBundle({
|
|
4752
|
-
dom_id: '#swagger-ui',${optionsStrings},
|
|
4753
|
-
})
|
|
4754
|
-
}
|
|
4755
|
-
</script>
|
|
4756
|
-
</div>
|
|
4757
|
-
`;
|
|
4758
|
-
};
|
|
4759
|
-
var middleware = (options) => async (c) => {
|
|
4760
|
-
const title = options?.title ?? "SwaggerUI";
|
|
4761
|
-
return c.html(
|
|
4762
|
-
/* html */
|
|
4763
|
-
`
|
|
4764
|
-
<html lang="en">
|
|
4765
|
-
<head>
|
|
4766
|
-
<meta charset="utf-8" />
|
|
4767
|
-
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
4768
|
-
<meta name="description" content="SwaggerUI" />
|
|
4769
|
-
<title>${title}</title>
|
|
4770
|
-
</head>
|
|
4771
|
-
<body>
|
|
4772
|
-
${SwaggerUI(options)}
|
|
4773
|
-
</body>
|
|
4774
|
-
</html>
|
|
4775
|
-
`
|
|
4776
|
-
);
|
|
4777
|
-
};
|
|
4778
|
-
|
|
4779
2480
|
function success(data, options = {}) {
|
|
4780
2481
|
const { status = 200, meta = {} } = options;
|
|
4781
2482
|
return {
|
|
@@ -4943,7 +2644,7 @@ function asyncHandler(fn) {
|
|
|
4943
2644
|
}
|
|
4944
2645
|
|
|
4945
2646
|
function createResourceRoutes(resource, version, config = {}) {
|
|
4946
|
-
const app = new Hono();
|
|
2647
|
+
const app = new hono.Hono();
|
|
4947
2648
|
const {
|
|
4948
2649
|
methods = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
|
|
4949
2650
|
customMiddleware = [],
|
|
@@ -6253,7 +3954,7 @@ class ApiServer {
|
|
|
6253
3954
|
description: options.apiDescription || "Auto-generated REST API for s3db.js resources"
|
|
6254
3955
|
}
|
|
6255
3956
|
};
|
|
6256
|
-
this.app = new Hono();
|
|
3957
|
+
this.app = new hono.Hono();
|
|
6257
3958
|
this.server = null;
|
|
6258
3959
|
this.isRunning = false;
|
|
6259
3960
|
this.openAPISpec = null;
|
|
@@ -6340,7 +4041,7 @@ class ApiServer {
|
|
|
6340
4041
|
return c.json(this.openAPISpec);
|
|
6341
4042
|
});
|
|
6342
4043
|
if (this.options.docsUI === "swagger") {
|
|
6343
|
-
this.app.get("/docs",
|
|
4044
|
+
this.app.get("/docs", swaggerUi.swaggerUI({
|
|
6344
4045
|
url: "/openapi.json"
|
|
6345
4046
|
}));
|
|
6346
4047
|
} else {
|
|
@@ -6419,7 +4120,7 @@ class ApiServer {
|
|
|
6419
4120
|
const { port, host } = this.options;
|
|
6420
4121
|
return new Promise((resolve, reject) => {
|
|
6421
4122
|
try {
|
|
6422
|
-
this.server = serve({
|
|
4123
|
+
this.server = nodeServer.serve({
|
|
6423
4124
|
fetch: this.app.fetch,
|
|
6424
4125
|
port,
|
|
6425
4126
|
hostname: host
|
|
@@ -15659,6 +13360,9 @@ class RelationPlugin extends Plugin {
|
|
|
15659
13360
|
this.batchSize = config.batchSize || 100;
|
|
15660
13361
|
this.preventN1 = config.preventN1 !== void 0 ? config.preventN1 : true;
|
|
15661
13362
|
this.verbose = config.verbose || false;
|
|
13363
|
+
this.fallbackLimit = config.fallbackLimit !== void 0 ? config.fallbackLimit : null;
|
|
13364
|
+
this.cascadeBatchSize = config.cascadeBatchSize || 10;
|
|
13365
|
+
this.cascadeTransactions = config.cascadeTransactions !== void 0 ? config.cascadeTransactions : false;
|
|
15662
13366
|
this._loaderCache = /* @__PURE__ */ new Map();
|
|
15663
13367
|
this._partitionCache = /* @__PURE__ */ new Map();
|
|
15664
13368
|
this.stats = {
|
|
@@ -15667,7 +13371,8 @@ class RelationPlugin extends Plugin {
|
|
|
15667
13371
|
batchLoads: 0,
|
|
15668
13372
|
cascadeOperations: 0,
|
|
15669
13373
|
partitionCacheHits: 0,
|
|
15670
|
-
deduplicatedQueries: 0
|
|
13374
|
+
deduplicatedQueries: 0,
|
|
13375
|
+
fallbackLimitWarnings: 0
|
|
15671
13376
|
};
|
|
15672
13377
|
}
|
|
15673
13378
|
/**
|
|
@@ -15932,13 +13637,7 @@ class RelationPlugin extends Plugin {
|
|
|
15932
13637
|
localKeys
|
|
15933
13638
|
);
|
|
15934
13639
|
} else {
|
|
15935
|
-
|
|
15936
|
-
console.log(
|
|
15937
|
-
`[RelationPlugin] No partition found for ${relatedResource.name}.${config.foreignKey}, using full scan`
|
|
15938
|
-
);
|
|
15939
|
-
}
|
|
15940
|
-
const allRelated = await relatedResource.list({ limit: 1e4 });
|
|
15941
|
-
relatedRecords = allRelated.filter((r) => localKeys.includes(r[config.foreignKey]));
|
|
13640
|
+
relatedRecords = await this._fallbackLoad(relatedResource, config.foreignKey, localKeys);
|
|
15942
13641
|
}
|
|
15943
13642
|
const relatedMap = /* @__PURE__ */ new Map();
|
|
15944
13643
|
relatedRecords.forEach((related) => {
|
|
@@ -15977,13 +13676,7 @@ class RelationPlugin extends Plugin {
|
|
|
15977
13676
|
localKeys
|
|
15978
13677
|
);
|
|
15979
13678
|
} else {
|
|
15980
|
-
|
|
15981
|
-
console.log(
|
|
15982
|
-
`[RelationPlugin] No partition found for ${relatedResource.name}.${config.foreignKey}, using full scan`
|
|
15983
|
-
);
|
|
15984
|
-
}
|
|
15985
|
-
const allRelated = await relatedResource.list({ limit: 1e4 });
|
|
15986
|
-
relatedRecords = allRelated.filter((r) => localKeys.includes(r[config.foreignKey]));
|
|
13679
|
+
relatedRecords = await this._fallbackLoad(relatedResource, config.foreignKey, localKeys);
|
|
15987
13680
|
}
|
|
15988
13681
|
const relatedMap = /* @__PURE__ */ new Map();
|
|
15989
13682
|
relatedRecords.forEach((related) => {
|
|
@@ -16029,13 +13722,7 @@ class RelationPlugin extends Plugin {
|
|
|
16029
13722
|
foreignKeys
|
|
16030
13723
|
);
|
|
16031
13724
|
} else {
|
|
16032
|
-
|
|
16033
|
-
console.log(
|
|
16034
|
-
`[RelationPlugin] No partition found for ${relatedResource.name}.${config.localKey}, using full scan`
|
|
16035
|
-
);
|
|
16036
|
-
}
|
|
16037
|
-
const allRelated = await relatedResource.list({ limit: 1e4 });
|
|
16038
|
-
return allRelated.filter((r) => foreignKeys.includes(r[config.localKey]));
|
|
13725
|
+
return await this._fallbackLoad(relatedResource, config.localKey, foreignKeys);
|
|
16039
13726
|
}
|
|
16040
13727
|
});
|
|
16041
13728
|
if (!ok) {
|
|
@@ -16092,13 +13779,7 @@ class RelationPlugin extends Plugin {
|
|
|
16092
13779
|
localKeys
|
|
16093
13780
|
);
|
|
16094
13781
|
} else {
|
|
16095
|
-
|
|
16096
|
-
console.log(
|
|
16097
|
-
`[RelationPlugin] No partition found for ${junctionResource.name}.${config.foreignKey}, using full scan`
|
|
16098
|
-
);
|
|
16099
|
-
}
|
|
16100
|
-
const allJunction = await junctionResource.list({ limit: 1e4 });
|
|
16101
|
-
junctionRecords = allJunction.filter((j) => localKeys.includes(j[config.foreignKey]));
|
|
13782
|
+
junctionRecords = await this._fallbackLoad(junctionResource, config.foreignKey, localKeys);
|
|
16102
13783
|
}
|
|
16103
13784
|
if (junctionRecords.length === 0) {
|
|
16104
13785
|
records.forEach((r) => r[relationName] = []);
|
|
@@ -16115,13 +13796,7 @@ class RelationPlugin extends Plugin {
|
|
|
16115
13796
|
otherKeys
|
|
16116
13797
|
);
|
|
16117
13798
|
} else {
|
|
16118
|
-
|
|
16119
|
-
console.log(
|
|
16120
|
-
`[RelationPlugin] No partition found for ${relatedResource.name}.${config.localKey}, using full scan`
|
|
16121
|
-
);
|
|
16122
|
-
}
|
|
16123
|
-
const allRelated = await relatedResource.list({ limit: 1e4 });
|
|
16124
|
-
relatedRecords = allRelated.filter((r) => otherKeys.includes(r[config.localKey]));
|
|
13799
|
+
relatedRecords = await this._fallbackLoad(relatedResource, config.localKey, otherKeys);
|
|
16125
13800
|
}
|
|
16126
13801
|
const relatedMap = /* @__PURE__ */ new Map();
|
|
16127
13802
|
relatedRecords.forEach((related) => {
|
|
@@ -16145,6 +13820,47 @@ class RelationPlugin extends Plugin {
|
|
|
16145
13820
|
}
|
|
16146
13821
|
return records;
|
|
16147
13822
|
}
|
|
13823
|
+
/**
|
|
13824
|
+
* Batch process operations with controlled parallelism
|
|
13825
|
+
* @private
|
|
13826
|
+
*/
|
|
13827
|
+
async _batchProcess(items, operation, batchSize = null) {
|
|
13828
|
+
if (items.length === 0) return [];
|
|
13829
|
+
const actualBatchSize = batchSize || this.cascadeBatchSize;
|
|
13830
|
+
const results = [];
|
|
13831
|
+
for (let i = 0; i < items.length; i += actualBatchSize) {
|
|
13832
|
+
const chunk = items.slice(i, i + actualBatchSize);
|
|
13833
|
+
const chunkPromises = chunk.map((item) => operation(item));
|
|
13834
|
+
const chunkResults = await Promise.all(chunkPromises);
|
|
13835
|
+
results.push(...chunkResults);
|
|
13836
|
+
}
|
|
13837
|
+
return results;
|
|
13838
|
+
}
|
|
13839
|
+
/**
|
|
13840
|
+
* Load records using fallback (full scan) when no partition is available
|
|
13841
|
+
* Issues warnings when limit is reached to prevent silent data loss
|
|
13842
|
+
* @private
|
|
13843
|
+
*/
|
|
13844
|
+
async _fallbackLoad(resource, fieldName, filterValues) {
|
|
13845
|
+
const options = this.fallbackLimit !== null ? { limit: this.fallbackLimit } : {};
|
|
13846
|
+
if (this.verbose) {
|
|
13847
|
+
console.log(
|
|
13848
|
+
`[RelationPlugin] No partition found for ${resource.name}.${fieldName}, using full scan` + (this.fallbackLimit ? ` (limited to ${this.fallbackLimit} records)` : " (no limit)")
|
|
13849
|
+
);
|
|
13850
|
+
}
|
|
13851
|
+
const allRecords = await resource.list(options);
|
|
13852
|
+
const filteredRecords = allRecords.filter((r) => filterValues.includes(r[fieldName]));
|
|
13853
|
+
if (this.fallbackLimit && allRecords.length >= this.fallbackLimit) {
|
|
13854
|
+
this.stats.fallbackLimitWarnings++;
|
|
13855
|
+
console.warn(
|
|
13856
|
+
`[RelationPlugin] WARNING: Fallback query for ${resource.name}.${fieldName} hit the limit of ${this.fallbackLimit} records. Some related records may be missing! Consider:
|
|
13857
|
+
1. Adding a partition on field "${fieldName}" for better performance
|
|
13858
|
+
2. Increasing fallbackLimit in plugin config (or set to null for no limit)
|
|
13859
|
+
Partition example: partitions: { by${fieldName.charAt(0).toUpperCase() + fieldName.slice(1)}: { fields: { ${fieldName}: 'string' } } }`
|
|
13860
|
+
);
|
|
13861
|
+
}
|
|
13862
|
+
return filteredRecords;
|
|
13863
|
+
}
|
|
16148
13864
|
/**
|
|
16149
13865
|
* Find partition by field name (for efficient relation loading)
|
|
16150
13866
|
* Uses cache to avoid repeated lookups
|
|
@@ -16220,6 +13936,7 @@ class RelationPlugin extends Plugin {
|
|
|
16220
13936
|
/**
|
|
16221
13937
|
* Cascade delete operation
|
|
16222
13938
|
* Uses partitions when available for efficient cascade
|
|
13939
|
+
* Supports transaction/rollback when enabled
|
|
16223
13940
|
* @private
|
|
16224
13941
|
*/
|
|
16225
13942
|
async _cascadeDelete(record, resource, relationName, config) {
|
|
@@ -16231,6 +13948,8 @@ class RelationPlugin extends Plugin {
|
|
|
16231
13948
|
relation: relationName
|
|
16232
13949
|
});
|
|
16233
13950
|
}
|
|
13951
|
+
const deletedRecords = [];
|
|
13952
|
+
config.type === "belongsToMany" ? this.database.resource(config.through) : null;
|
|
16234
13953
|
try {
|
|
16235
13954
|
if (config.type === "hasMany") {
|
|
16236
13955
|
let relatedRecords;
|
|
@@ -16250,12 +13969,15 @@ class RelationPlugin extends Plugin {
|
|
|
16250
13969
|
[config.foreignKey]: record[config.localKey]
|
|
16251
13970
|
});
|
|
16252
13971
|
}
|
|
16253
|
-
|
|
16254
|
-
|
|
13972
|
+
if (this.cascadeTransactions) {
|
|
13973
|
+
deletedRecords.push(...relatedRecords.map((r) => ({ type: "delete", resource: relatedResource, record: r })));
|
|
16255
13974
|
}
|
|
13975
|
+
await this._batchProcess(relatedRecords, async (related) => {
|
|
13976
|
+
return await relatedResource.delete(related.id);
|
|
13977
|
+
});
|
|
16256
13978
|
if (this.verbose) {
|
|
16257
13979
|
console.log(
|
|
16258
|
-
`[RelationPlugin] Cascade deleted ${relatedRecords.length} ${config.resource} for ${resource.name}:${record.id}`
|
|
13980
|
+
`[RelationPlugin] Cascade deleted ${relatedRecords.length} ${config.resource} for ${resource.name}:${record.id} (batched in ${Math.ceil(relatedRecords.length / this.cascadeBatchSize)} chunks)`
|
|
16259
13981
|
);
|
|
16260
13982
|
}
|
|
16261
13983
|
} else if (config.type === "hasOne") {
|
|
@@ -16272,15 +13994,18 @@ class RelationPlugin extends Plugin {
|
|
|
16272
13994
|
});
|
|
16273
13995
|
}
|
|
16274
13996
|
if (relatedRecords.length > 0) {
|
|
13997
|
+
if (this.cascadeTransactions) {
|
|
13998
|
+
deletedRecords.push({ type: "delete", resource: relatedResource, record: relatedRecords[0] });
|
|
13999
|
+
}
|
|
16275
14000
|
await relatedResource.delete(relatedRecords[0].id);
|
|
16276
14001
|
}
|
|
16277
14002
|
} else if (config.type === "belongsToMany") {
|
|
16278
|
-
const
|
|
16279
|
-
if (
|
|
14003
|
+
const junctionResource2 = this.database.resource(config.through);
|
|
14004
|
+
if (junctionResource2) {
|
|
16280
14005
|
let junctionRecords;
|
|
16281
|
-
const partitionName = this._findPartitionByField(
|
|
14006
|
+
const partitionName = this._findPartitionByField(junctionResource2, config.foreignKey);
|
|
16282
14007
|
if (partitionName) {
|
|
16283
|
-
junctionRecords = await
|
|
14008
|
+
junctionRecords = await junctionResource2.list({
|
|
16284
14009
|
partition: partitionName,
|
|
16285
14010
|
partitionValues: { [config.foreignKey]: record[config.localKey] }
|
|
16286
14011
|
});
|
|
@@ -16290,21 +14015,45 @@ class RelationPlugin extends Plugin {
|
|
|
16290
14015
|
);
|
|
16291
14016
|
}
|
|
16292
14017
|
} else {
|
|
16293
|
-
junctionRecords = await
|
|
14018
|
+
junctionRecords = await junctionResource2.query({
|
|
16294
14019
|
[config.foreignKey]: record[config.localKey]
|
|
16295
14020
|
});
|
|
16296
14021
|
}
|
|
16297
|
-
|
|
16298
|
-
|
|
14022
|
+
if (this.cascadeTransactions) {
|
|
14023
|
+
deletedRecords.push(...junctionRecords.map((j) => ({ type: "delete", resource: junctionResource2, record: j })));
|
|
16299
14024
|
}
|
|
14025
|
+
await this._batchProcess(junctionRecords, async (junction) => {
|
|
14026
|
+
return await junctionResource2.delete(junction.id);
|
|
14027
|
+
});
|
|
16300
14028
|
if (this.verbose) {
|
|
16301
14029
|
console.log(
|
|
16302
|
-
`[RelationPlugin] Cascade deleted ${junctionRecords.length} junction records from ${config.through}`
|
|
14030
|
+
`[RelationPlugin] Cascade deleted ${junctionRecords.length} junction records from ${config.through} (batched in ${Math.ceil(junctionRecords.length / this.cascadeBatchSize)} chunks)`
|
|
16303
14031
|
);
|
|
16304
14032
|
}
|
|
16305
14033
|
}
|
|
16306
14034
|
}
|
|
16307
14035
|
} catch (error) {
|
|
14036
|
+
if (this.cascadeTransactions && deletedRecords.length > 0) {
|
|
14037
|
+
console.error(
|
|
14038
|
+
`[RelationPlugin] Cascade delete failed, attempting rollback of ${deletedRecords.length} records...`
|
|
14039
|
+
);
|
|
14040
|
+
const rollbackErrors = [];
|
|
14041
|
+
for (const { resource: res, record: rec } of deletedRecords.reverse()) {
|
|
14042
|
+
try {
|
|
14043
|
+
await res.insert(rec);
|
|
14044
|
+
} catch (rollbackError) {
|
|
14045
|
+
rollbackErrors.push({ record: rec.id, error: rollbackError.message });
|
|
14046
|
+
}
|
|
14047
|
+
}
|
|
14048
|
+
if (rollbackErrors.length > 0) {
|
|
14049
|
+
console.error(
|
|
14050
|
+
`[RelationPlugin] Rollback partially failed for ${rollbackErrors.length} records:`,
|
|
14051
|
+
rollbackErrors
|
|
14052
|
+
);
|
|
14053
|
+
} else if (this.verbose) {
|
|
14054
|
+
console.log(`[RelationPlugin] Rollback successful, restored ${deletedRecords.length} records`);
|
|
14055
|
+
}
|
|
14056
|
+
}
|
|
16308
14057
|
throw new CascadeError("delete", resource.name, record.id, error, {
|
|
16309
14058
|
relation: relationName,
|
|
16310
14059
|
relatedResource: config.resource
|
|
@@ -16314,6 +14063,7 @@ class RelationPlugin extends Plugin {
|
|
|
16314
14063
|
/**
|
|
16315
14064
|
* Cascade update operation (update foreign keys when local key changes)
|
|
16316
14065
|
* Uses partitions when available for efficient cascade
|
|
14066
|
+
* Supports transaction/rollback when enabled
|
|
16317
14067
|
* @private
|
|
16318
14068
|
*/
|
|
16319
14069
|
async _cascadeUpdate(record, changes, resource, relationName, config) {
|
|
@@ -16322,6 +14072,7 @@ class RelationPlugin extends Plugin {
|
|
|
16322
14072
|
if (!relatedResource) {
|
|
16323
14073
|
return;
|
|
16324
14074
|
}
|
|
14075
|
+
const updatedRecords = [];
|
|
16325
14076
|
try {
|
|
16326
14077
|
const oldLocalKeyValue = record[config.localKey];
|
|
16327
14078
|
const newLocalKeyValue = changes[config.localKey];
|
|
@@ -16345,17 +14096,48 @@ class RelationPlugin extends Plugin {
|
|
|
16345
14096
|
[config.foreignKey]: oldLocalKeyValue
|
|
16346
14097
|
});
|
|
16347
14098
|
}
|
|
16348
|
-
|
|
16349
|
-
|
|
14099
|
+
if (this.cascadeTransactions) {
|
|
14100
|
+
updatedRecords.push(...relatedRecords.map((r) => ({
|
|
14101
|
+
type: "update",
|
|
14102
|
+
resource: relatedResource,
|
|
14103
|
+
id: r.id,
|
|
14104
|
+
oldValue: r[config.foreignKey],
|
|
14105
|
+
newValue: newLocalKeyValue,
|
|
14106
|
+
field: config.foreignKey
|
|
14107
|
+
})));
|
|
14108
|
+
}
|
|
14109
|
+
await this._batchProcess(relatedRecords, async (related) => {
|
|
14110
|
+
return await relatedResource.update(related.id, {
|
|
16350
14111
|
[config.foreignKey]: newLocalKeyValue
|
|
16351
14112
|
}, { skipCascade: true });
|
|
16352
|
-
}
|
|
14113
|
+
});
|
|
16353
14114
|
if (this.verbose) {
|
|
16354
14115
|
console.log(
|
|
16355
|
-
`[RelationPlugin] Cascade updated ${relatedRecords.length} ${config.resource} records`
|
|
14116
|
+
`[RelationPlugin] Cascade updated ${relatedRecords.length} ${config.resource} records (batched in ${Math.ceil(relatedRecords.length / this.cascadeBatchSize)} chunks)`
|
|
16356
14117
|
);
|
|
16357
14118
|
}
|
|
16358
14119
|
} catch (error) {
|
|
14120
|
+
if (this.cascadeTransactions && updatedRecords.length > 0) {
|
|
14121
|
+
console.error(
|
|
14122
|
+
`[RelationPlugin] Cascade update failed, attempting rollback of ${updatedRecords.length} records...`
|
|
14123
|
+
);
|
|
14124
|
+
const rollbackErrors = [];
|
|
14125
|
+
for (const { resource: res, id, field, oldValue } of updatedRecords.reverse()) {
|
|
14126
|
+
try {
|
|
14127
|
+
await res.update(id, { [field]: oldValue }, { skipCascade: true });
|
|
14128
|
+
} catch (rollbackError) {
|
|
14129
|
+
rollbackErrors.push({ id, error: rollbackError.message });
|
|
14130
|
+
}
|
|
14131
|
+
}
|
|
14132
|
+
if (rollbackErrors.length > 0) {
|
|
14133
|
+
console.error(
|
|
14134
|
+
`[RelationPlugin] Rollback partially failed for ${rollbackErrors.length} records:`,
|
|
14135
|
+
rollbackErrors
|
|
14136
|
+
);
|
|
14137
|
+
} else if (this.verbose) {
|
|
14138
|
+
console.log(`[RelationPlugin] Rollback successful, restored ${updatedRecords.length} records`);
|
|
14139
|
+
}
|
|
14140
|
+
}
|
|
16359
14141
|
throw new CascadeError("update", resource.name, record.id, error, {
|
|
16360
14142
|
relation: relationName,
|
|
16361
14143
|
relatedResource: config.resource
|
|
@@ -20866,7 +18648,7 @@ class ResourceReader extends EventEmitter {
|
|
|
20866
18648
|
this.batchSize = batchSize;
|
|
20867
18649
|
this.concurrency = concurrency;
|
|
20868
18650
|
this.input = new ResourceIdsPageReader({ resource: this.resource });
|
|
20869
|
-
this.transform = new
|
|
18651
|
+
this.transform = new stream$1.Transform({
|
|
20870
18652
|
objectMode: true,
|
|
20871
18653
|
transform: this._transform.bind(this)
|
|
20872
18654
|
});
|
|
@@ -20918,7 +18700,7 @@ class ResourceWriter extends EventEmitter {
|
|
|
20918
18700
|
this.concurrency = concurrency;
|
|
20919
18701
|
this.buffer = [];
|
|
20920
18702
|
this.writing = false;
|
|
20921
|
-
this.writable = new
|
|
18703
|
+
this.writable = new stream$1.Writable({
|
|
20922
18704
|
objectMode: true,
|
|
20923
18705
|
write: this._write.bind(this)
|
|
20924
18706
|
});
|
|
@@ -24205,7 +21987,7 @@ class Database extends EventEmitter {
|
|
|
24205
21987
|
this.id = idGenerator(7);
|
|
24206
21988
|
this.version = "1";
|
|
24207
21989
|
this.s3dbVersion = (() => {
|
|
24208
|
-
const [ok, err, version] = tryFn(() => true ? "12.0
|
|
21990
|
+
const [ok, err, version] = tryFn(() => true ? "12.1.0" : "latest");
|
|
24209
21991
|
return ok ? version : "latest";
|
|
24210
21992
|
})();
|
|
24211
21993
|
this.resources = {};
|
|
@@ -38346,7 +36128,7 @@ class TfStatePlugin extends Plugin {
|
|
|
38346
36128
|
console.log(`[TfStatePlugin] Setting up cron monitoring: ${this.monitorCron}`);
|
|
38347
36129
|
}
|
|
38348
36130
|
await requirePluginDependency("tfstate-plugin");
|
|
38349
|
-
const [ok, err, cronModule] = await tryFn(() =>
|
|
36131
|
+
const [ok, err, cronModule] = await tryFn(() => import('node-cron'));
|
|
38350
36132
|
if (!ok) {
|
|
38351
36133
|
throw new TfStateError(`Failed to import node-cron: ${err.message}`);
|
|
38352
36134
|
}
|
|
@@ -40043,1418 +37825,6 @@ var prometheusFormatter = /*#__PURE__*/Object.freeze({
|
|
|
40043
37825
|
formatPrometheusMetrics: formatPrometheusMetrics
|
|
40044
37826
|
});
|
|
40045
37827
|
|
|
40046
|
-
function getDefaultExportFromCjs (x) {
|
|
40047
|
-
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
40048
|
-
}
|
|
40049
|
-
|
|
40050
|
-
var nodeCron$2 = {};
|
|
40051
|
-
|
|
40052
|
-
var inlineScheduledTask = {};
|
|
40053
|
-
|
|
40054
|
-
var runner = {};
|
|
40055
|
-
|
|
40056
|
-
var createId = {};
|
|
40057
|
-
|
|
40058
|
-
const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('s3db.cjs.js', document.baseURI).href)));
|
|
40059
|
-
function __require() { return require$1("node:crypto"); }
|
|
40060
|
-
|
|
40061
|
-
var hasRequiredCreateId;
|
|
40062
|
-
|
|
40063
|
-
function requireCreateId () {
|
|
40064
|
-
if (hasRequiredCreateId) return createId;
|
|
40065
|
-
hasRequiredCreateId = 1;
|
|
40066
|
-
var __importDefault = (createId && createId.__importDefault) || function (mod) {
|
|
40067
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
40068
|
-
};
|
|
40069
|
-
Object.defineProperty(createId, "__esModule", { value: true });
|
|
40070
|
-
createId.createID = createID;
|
|
40071
|
-
const node_crypto_1 = __importDefault(__require());
|
|
40072
|
-
function createID(prefix = '', length = 16) {
|
|
40073
|
-
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
40074
|
-
const values = node_crypto_1.default.randomBytes(length);
|
|
40075
|
-
const id = Array.from(values, v => charset[v % charset.length]).join('');
|
|
40076
|
-
return prefix ? `${prefix}-${id}` : id;
|
|
40077
|
-
}
|
|
40078
|
-
|
|
40079
|
-
return createId;
|
|
40080
|
-
}
|
|
40081
|
-
|
|
40082
|
-
var logger = {};
|
|
40083
|
-
|
|
40084
|
-
var hasRequiredLogger;
|
|
40085
|
-
|
|
40086
|
-
function requireLogger () {
|
|
40087
|
-
if (hasRequiredLogger) return logger;
|
|
40088
|
-
hasRequiredLogger = 1;
|
|
40089
|
-
Object.defineProperty(logger, "__esModule", { value: true });
|
|
40090
|
-
const levelColors = {
|
|
40091
|
-
INFO: '\x1b[36m',
|
|
40092
|
-
WARN: '\x1b[33m',
|
|
40093
|
-
ERROR: '\x1b[31m',
|
|
40094
|
-
DEBUG: '\x1b[35m',
|
|
40095
|
-
};
|
|
40096
|
-
const GREEN = '\x1b[32m';
|
|
40097
|
-
const RESET = '\x1b[0m';
|
|
40098
|
-
function log(level, message, extra) {
|
|
40099
|
-
const timestamp = new Date().toISOString();
|
|
40100
|
-
const color = levelColors[level] ?? '';
|
|
40101
|
-
const prefix = `[${timestamp}] [PID: ${process.pid}] ${GREEN}[NODE-CRON]${GREEN} ${color}[${level}]${RESET}`;
|
|
40102
|
-
const output = `${prefix} ${message}`;
|
|
40103
|
-
switch (level) {
|
|
40104
|
-
case 'ERROR':
|
|
40105
|
-
console.error(output, extra ?? '');
|
|
40106
|
-
break;
|
|
40107
|
-
case 'DEBUG':
|
|
40108
|
-
console.debug(output, extra ?? '');
|
|
40109
|
-
break;
|
|
40110
|
-
case 'WARN':
|
|
40111
|
-
console.warn(output);
|
|
40112
|
-
break;
|
|
40113
|
-
case 'INFO':
|
|
40114
|
-
default:
|
|
40115
|
-
console.info(output);
|
|
40116
|
-
break;
|
|
40117
|
-
}
|
|
40118
|
-
}
|
|
40119
|
-
const logger$1 = {
|
|
40120
|
-
info(message) {
|
|
40121
|
-
log('INFO', message);
|
|
40122
|
-
},
|
|
40123
|
-
warn(message) {
|
|
40124
|
-
log('WARN', message);
|
|
40125
|
-
},
|
|
40126
|
-
error(message, err) {
|
|
40127
|
-
if (message instanceof Error) {
|
|
40128
|
-
log('ERROR', message.message, message);
|
|
40129
|
-
}
|
|
40130
|
-
else {
|
|
40131
|
-
log('ERROR', message, err);
|
|
40132
|
-
}
|
|
40133
|
-
},
|
|
40134
|
-
debug(message, err) {
|
|
40135
|
-
if (message instanceof Error) {
|
|
40136
|
-
log('DEBUG', message.message, message);
|
|
40137
|
-
}
|
|
40138
|
-
else {
|
|
40139
|
-
log('DEBUG', message, err);
|
|
40140
|
-
}
|
|
40141
|
-
},
|
|
40142
|
-
};
|
|
40143
|
-
logger.default = logger$1;
|
|
40144
|
-
|
|
40145
|
-
return logger;
|
|
40146
|
-
}
|
|
40147
|
-
|
|
40148
|
-
var trackedPromise = {};
|
|
40149
|
-
|
|
40150
|
-
var hasRequiredTrackedPromise;
|
|
40151
|
-
|
|
40152
|
-
function requireTrackedPromise () {
|
|
40153
|
-
if (hasRequiredTrackedPromise) return trackedPromise;
|
|
40154
|
-
hasRequiredTrackedPromise = 1;
|
|
40155
|
-
Object.defineProperty(trackedPromise, "__esModule", { value: true });
|
|
40156
|
-
trackedPromise.TrackedPromise = void 0;
|
|
40157
|
-
class TrackedPromise {
|
|
40158
|
-
promise;
|
|
40159
|
-
error;
|
|
40160
|
-
state;
|
|
40161
|
-
value;
|
|
40162
|
-
constructor(executor) {
|
|
40163
|
-
this.state = 'pending';
|
|
40164
|
-
this.promise = new Promise((resolve, reject) => {
|
|
40165
|
-
executor((value) => {
|
|
40166
|
-
this.state = 'fulfilled';
|
|
40167
|
-
this.value = value;
|
|
40168
|
-
resolve(value);
|
|
40169
|
-
}, (error) => {
|
|
40170
|
-
this.state = 'rejected';
|
|
40171
|
-
this.error = error;
|
|
40172
|
-
reject(error);
|
|
40173
|
-
});
|
|
40174
|
-
});
|
|
40175
|
-
}
|
|
40176
|
-
getPromise() {
|
|
40177
|
-
return this.promise;
|
|
40178
|
-
}
|
|
40179
|
-
getState() {
|
|
40180
|
-
return this.state;
|
|
40181
|
-
}
|
|
40182
|
-
isPending() {
|
|
40183
|
-
return this.state === 'pending';
|
|
40184
|
-
}
|
|
40185
|
-
isFulfilled() {
|
|
40186
|
-
return this.state === 'fulfilled';
|
|
40187
|
-
}
|
|
40188
|
-
isRejected() {
|
|
40189
|
-
return this.state === 'rejected';
|
|
40190
|
-
}
|
|
40191
|
-
getValue() {
|
|
40192
|
-
return this.value;
|
|
40193
|
-
}
|
|
40194
|
-
getError() {
|
|
40195
|
-
return this.error;
|
|
40196
|
-
}
|
|
40197
|
-
then(onfulfilled, onrejected) {
|
|
40198
|
-
return this.promise.then(onfulfilled, onrejected);
|
|
40199
|
-
}
|
|
40200
|
-
catch(onrejected) {
|
|
40201
|
-
return this.promise.catch(onrejected);
|
|
40202
|
-
}
|
|
40203
|
-
finally(onfinally) {
|
|
40204
|
-
return this.promise.finally(onfinally);
|
|
40205
|
-
}
|
|
40206
|
-
}
|
|
40207
|
-
trackedPromise.TrackedPromise = TrackedPromise;
|
|
40208
|
-
|
|
40209
|
-
return trackedPromise;
|
|
40210
|
-
}
|
|
40211
|
-
|
|
40212
|
-
var hasRequiredRunner;
|
|
40213
|
-
|
|
40214
|
-
function requireRunner () {
|
|
40215
|
-
if (hasRequiredRunner) return runner;
|
|
40216
|
-
hasRequiredRunner = 1;
|
|
40217
|
-
var __importDefault = (runner && runner.__importDefault) || function (mod) {
|
|
40218
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
40219
|
-
};
|
|
40220
|
-
Object.defineProperty(runner, "__esModule", { value: true });
|
|
40221
|
-
runner.Runner = void 0;
|
|
40222
|
-
const create_id_1 = requireCreateId();
|
|
40223
|
-
const logger_1 = __importDefault(requireLogger());
|
|
40224
|
-
const tracked_promise_1 = requireTrackedPromise();
|
|
40225
|
-
function emptyOnFn() { }
|
|
40226
|
-
function emptyHookFn() { return true; }
|
|
40227
|
-
function defaultOnError(date, error) {
|
|
40228
|
-
logger_1.default.error('Task failed with error!', error);
|
|
40229
|
-
}
|
|
40230
|
-
class Runner {
|
|
40231
|
-
timeMatcher;
|
|
40232
|
-
onMatch;
|
|
40233
|
-
noOverlap;
|
|
40234
|
-
maxExecutions;
|
|
40235
|
-
maxRandomDelay;
|
|
40236
|
-
runCount;
|
|
40237
|
-
running;
|
|
40238
|
-
heartBeatTimeout;
|
|
40239
|
-
onMissedExecution;
|
|
40240
|
-
onOverlap;
|
|
40241
|
-
onError;
|
|
40242
|
-
beforeRun;
|
|
40243
|
-
onFinished;
|
|
40244
|
-
onMaxExecutions;
|
|
40245
|
-
constructor(timeMatcher, onMatch, options) {
|
|
40246
|
-
this.timeMatcher = timeMatcher;
|
|
40247
|
-
this.onMatch = onMatch;
|
|
40248
|
-
this.noOverlap = options == undefined || options.noOverlap === undefined ? false : options.noOverlap;
|
|
40249
|
-
this.maxExecutions = options?.maxExecutions;
|
|
40250
|
-
this.maxRandomDelay = options?.maxRandomDelay || 0;
|
|
40251
|
-
this.onMissedExecution = options?.onMissedExecution || emptyOnFn;
|
|
40252
|
-
this.onOverlap = options?.onOverlap || emptyOnFn;
|
|
40253
|
-
this.onError = options?.onError || defaultOnError;
|
|
40254
|
-
this.onFinished = options?.onFinished || emptyHookFn;
|
|
40255
|
-
this.beforeRun = options?.beforeRun || emptyHookFn;
|
|
40256
|
-
this.onMaxExecutions = options?.onMaxExecutions || emptyOnFn;
|
|
40257
|
-
this.runCount = 0;
|
|
40258
|
-
this.running = false;
|
|
40259
|
-
}
|
|
40260
|
-
start() {
|
|
40261
|
-
this.running = true;
|
|
40262
|
-
let lastExecution;
|
|
40263
|
-
let expectedNextExecution;
|
|
40264
|
-
const scheduleNextHeartBeat = (currentDate) => {
|
|
40265
|
-
if (this.running) {
|
|
40266
|
-
clearTimeout(this.heartBeatTimeout);
|
|
40267
|
-
this.heartBeatTimeout = setTimeout(heartBeat, getDelay(this.timeMatcher, currentDate));
|
|
40268
|
-
}
|
|
40269
|
-
};
|
|
40270
|
-
const runTask = (date) => {
|
|
40271
|
-
return new Promise(async (resolve) => {
|
|
40272
|
-
const execution = {
|
|
40273
|
-
id: (0, create_id_1.createID)('exec'),
|
|
40274
|
-
reason: 'scheduled'
|
|
40275
|
-
};
|
|
40276
|
-
const shouldExecute = await this.beforeRun(date, execution);
|
|
40277
|
-
const randomDelay = Math.floor(Math.random() * this.maxRandomDelay);
|
|
40278
|
-
if (shouldExecute) {
|
|
40279
|
-
setTimeout(async () => {
|
|
40280
|
-
try {
|
|
40281
|
-
this.runCount++;
|
|
40282
|
-
execution.startedAt = new Date();
|
|
40283
|
-
const result = await this.onMatch(date, execution);
|
|
40284
|
-
execution.finishedAt = new Date();
|
|
40285
|
-
execution.result = result;
|
|
40286
|
-
this.onFinished(date, execution);
|
|
40287
|
-
if (this.maxExecutions && this.runCount >= this.maxExecutions) {
|
|
40288
|
-
this.onMaxExecutions(date);
|
|
40289
|
-
this.stop();
|
|
40290
|
-
}
|
|
40291
|
-
}
|
|
40292
|
-
catch (error) {
|
|
40293
|
-
execution.finishedAt = new Date();
|
|
40294
|
-
execution.error = error;
|
|
40295
|
-
this.onError(date, error, execution);
|
|
40296
|
-
}
|
|
40297
|
-
resolve(true);
|
|
40298
|
-
}, randomDelay);
|
|
40299
|
-
}
|
|
40300
|
-
});
|
|
40301
|
-
};
|
|
40302
|
-
const checkAndRun = (date) => {
|
|
40303
|
-
return new tracked_promise_1.TrackedPromise(async (resolve, reject) => {
|
|
40304
|
-
try {
|
|
40305
|
-
if (this.timeMatcher.match(date)) {
|
|
40306
|
-
await runTask(date);
|
|
40307
|
-
}
|
|
40308
|
-
resolve(true);
|
|
40309
|
-
}
|
|
40310
|
-
catch (err) {
|
|
40311
|
-
reject(err);
|
|
40312
|
-
}
|
|
40313
|
-
});
|
|
40314
|
-
};
|
|
40315
|
-
const heartBeat = async () => {
|
|
40316
|
-
const currentDate = nowWithoutMs();
|
|
40317
|
-
if (expectedNextExecution && expectedNextExecution.getTime() < currentDate.getTime()) {
|
|
40318
|
-
while (expectedNextExecution.getTime() < currentDate.getTime()) {
|
|
40319
|
-
logger_1.default.warn(`missed execution at ${expectedNextExecution}! Possible blocking IO or high CPU user at the same process used by node-cron.`);
|
|
40320
|
-
expectedNextExecution = this.timeMatcher.getNextMatch(expectedNextExecution);
|
|
40321
|
-
runAsync(this.onMissedExecution, expectedNextExecution, defaultOnError);
|
|
40322
|
-
}
|
|
40323
|
-
}
|
|
40324
|
-
if (lastExecution && lastExecution.getState() === 'pending') {
|
|
40325
|
-
runAsync(this.onOverlap, currentDate, defaultOnError);
|
|
40326
|
-
if (this.noOverlap) {
|
|
40327
|
-
logger_1.default.warn('task still running, new execution blocked by overlap prevention!');
|
|
40328
|
-
expectedNextExecution = this.timeMatcher.getNextMatch(currentDate);
|
|
40329
|
-
scheduleNextHeartBeat(currentDate);
|
|
40330
|
-
return;
|
|
40331
|
-
}
|
|
40332
|
-
}
|
|
40333
|
-
lastExecution = checkAndRun(currentDate);
|
|
40334
|
-
expectedNextExecution = this.timeMatcher.getNextMatch(currentDate);
|
|
40335
|
-
scheduleNextHeartBeat(currentDate);
|
|
40336
|
-
};
|
|
40337
|
-
this.heartBeatTimeout = setTimeout(() => {
|
|
40338
|
-
heartBeat();
|
|
40339
|
-
}, getDelay(this.timeMatcher, nowWithoutMs()));
|
|
40340
|
-
}
|
|
40341
|
-
nextRun() {
|
|
40342
|
-
return this.timeMatcher.getNextMatch(new Date());
|
|
40343
|
-
}
|
|
40344
|
-
stop() {
|
|
40345
|
-
this.running = false;
|
|
40346
|
-
if (this.heartBeatTimeout) {
|
|
40347
|
-
clearTimeout(this.heartBeatTimeout);
|
|
40348
|
-
this.heartBeatTimeout = undefined;
|
|
40349
|
-
}
|
|
40350
|
-
}
|
|
40351
|
-
isStarted() {
|
|
40352
|
-
return !!this.heartBeatTimeout && this.running;
|
|
40353
|
-
}
|
|
40354
|
-
isStopped() {
|
|
40355
|
-
return !this.isStarted();
|
|
40356
|
-
}
|
|
40357
|
-
async execute() {
|
|
40358
|
-
const date = new Date();
|
|
40359
|
-
const execution = {
|
|
40360
|
-
id: (0, create_id_1.createID)('exec'),
|
|
40361
|
-
reason: 'invoked'
|
|
40362
|
-
};
|
|
40363
|
-
try {
|
|
40364
|
-
const shouldExecute = await this.beforeRun(date, execution);
|
|
40365
|
-
if (shouldExecute) {
|
|
40366
|
-
this.runCount++;
|
|
40367
|
-
execution.startedAt = new Date();
|
|
40368
|
-
const result = await this.onMatch(date, execution);
|
|
40369
|
-
execution.finishedAt = new Date();
|
|
40370
|
-
execution.result = result;
|
|
40371
|
-
this.onFinished(date, execution);
|
|
40372
|
-
}
|
|
40373
|
-
}
|
|
40374
|
-
catch (error) {
|
|
40375
|
-
execution.finishedAt = new Date();
|
|
40376
|
-
execution.error = error;
|
|
40377
|
-
this.onError(date, error, execution);
|
|
40378
|
-
}
|
|
40379
|
-
}
|
|
40380
|
-
}
|
|
40381
|
-
runner.Runner = Runner;
|
|
40382
|
-
async function runAsync(fn, date, onError) {
|
|
40383
|
-
try {
|
|
40384
|
-
await fn(date);
|
|
40385
|
-
}
|
|
40386
|
-
catch (error) {
|
|
40387
|
-
onError(date, error);
|
|
40388
|
-
}
|
|
40389
|
-
}
|
|
40390
|
-
function getDelay(timeMatcher, currentDate) {
|
|
40391
|
-
const maxDelay = 86400000;
|
|
40392
|
-
const nextRun = timeMatcher.getNextMatch(currentDate);
|
|
40393
|
-
const now = new Date();
|
|
40394
|
-
const delay = nextRun.getTime() - now.getTime();
|
|
40395
|
-
if (delay > maxDelay) {
|
|
40396
|
-
return maxDelay;
|
|
40397
|
-
}
|
|
40398
|
-
return Math.max(0, delay);
|
|
40399
|
-
}
|
|
40400
|
-
function nowWithoutMs() {
|
|
40401
|
-
const date = new Date();
|
|
40402
|
-
date.setMilliseconds(0);
|
|
40403
|
-
return date;
|
|
40404
|
-
}
|
|
40405
|
-
|
|
40406
|
-
return runner;
|
|
40407
|
-
}
|
|
40408
|
-
|
|
40409
|
-
var timeMatcher = {};
|
|
40410
|
-
|
|
40411
|
-
var convertion = {};
|
|
40412
|
-
|
|
40413
|
-
var monthNamesConversion = {};
|
|
40414
|
-
|
|
40415
|
-
var hasRequiredMonthNamesConversion;
|
|
40416
|
-
|
|
40417
|
-
function requireMonthNamesConversion () {
|
|
40418
|
-
if (hasRequiredMonthNamesConversion) return monthNamesConversion;
|
|
40419
|
-
hasRequiredMonthNamesConversion = 1;
|
|
40420
|
-
Object.defineProperty(monthNamesConversion, "__esModule", { value: true });
|
|
40421
|
-
monthNamesConversion.default = (() => {
|
|
40422
|
-
const months = ['january', 'february', 'march', 'april', 'may', 'june', 'july',
|
|
40423
|
-
'august', 'september', 'october', 'november', 'december'];
|
|
40424
|
-
const shortMonths = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
|
|
40425
|
-
'sep', 'oct', 'nov', 'dec'];
|
|
40426
|
-
function convertMonthName(expression, items) {
|
|
40427
|
-
for (let i = 0; i < items.length; i++) {
|
|
40428
|
-
expression = expression.replace(new RegExp(items[i], 'gi'), i + 1);
|
|
40429
|
-
}
|
|
40430
|
-
return expression;
|
|
40431
|
-
}
|
|
40432
|
-
function interprete(monthExpression) {
|
|
40433
|
-
monthExpression = convertMonthName(monthExpression, months);
|
|
40434
|
-
monthExpression = convertMonthName(monthExpression, shortMonths);
|
|
40435
|
-
return monthExpression;
|
|
40436
|
-
}
|
|
40437
|
-
return interprete;
|
|
40438
|
-
})();
|
|
40439
|
-
|
|
40440
|
-
return monthNamesConversion;
|
|
40441
|
-
}
|
|
40442
|
-
|
|
40443
|
-
var weekDayNamesConversion = {};
|
|
40444
|
-
|
|
40445
|
-
var hasRequiredWeekDayNamesConversion;
|
|
40446
|
-
|
|
40447
|
-
function requireWeekDayNamesConversion () {
|
|
40448
|
-
if (hasRequiredWeekDayNamesConversion) return weekDayNamesConversion;
|
|
40449
|
-
hasRequiredWeekDayNamesConversion = 1;
|
|
40450
|
-
Object.defineProperty(weekDayNamesConversion, "__esModule", { value: true });
|
|
40451
|
-
weekDayNamesConversion.default = (() => {
|
|
40452
|
-
const weekDays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
|
|
40453
|
-
'friday', 'saturday'];
|
|
40454
|
-
const shortWeekDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
|
|
40455
|
-
function convertWeekDayName(expression, items) {
|
|
40456
|
-
for (let i = 0; i < items.length; i++) {
|
|
40457
|
-
expression = expression.replace(new RegExp(items[i], 'gi'), i);
|
|
40458
|
-
}
|
|
40459
|
-
return expression;
|
|
40460
|
-
}
|
|
40461
|
-
function convertWeekDays(expression) {
|
|
40462
|
-
expression = expression.replace('7', '0');
|
|
40463
|
-
expression = convertWeekDayName(expression, weekDays);
|
|
40464
|
-
return convertWeekDayName(expression, shortWeekDays);
|
|
40465
|
-
}
|
|
40466
|
-
return convertWeekDays;
|
|
40467
|
-
})();
|
|
40468
|
-
|
|
40469
|
-
return weekDayNamesConversion;
|
|
40470
|
-
}
|
|
40471
|
-
|
|
40472
|
-
var asteriskToRangeConversion = {};
|
|
40473
|
-
|
|
40474
|
-
var hasRequiredAsteriskToRangeConversion;
|
|
40475
|
-
|
|
40476
|
-
function requireAsteriskToRangeConversion () {
|
|
40477
|
-
if (hasRequiredAsteriskToRangeConversion) return asteriskToRangeConversion;
|
|
40478
|
-
hasRequiredAsteriskToRangeConversion = 1;
|
|
40479
|
-
Object.defineProperty(asteriskToRangeConversion, "__esModule", { value: true });
|
|
40480
|
-
asteriskToRangeConversion.default = (() => {
|
|
40481
|
-
function convertAsterisk(expression, replecement) {
|
|
40482
|
-
if (expression.indexOf('*') !== -1) {
|
|
40483
|
-
return expression.replace('*', replecement);
|
|
40484
|
-
}
|
|
40485
|
-
return expression;
|
|
40486
|
-
}
|
|
40487
|
-
function convertAsterisksToRanges(expressions) {
|
|
40488
|
-
expressions[0] = convertAsterisk(expressions[0], '0-59');
|
|
40489
|
-
expressions[1] = convertAsterisk(expressions[1], '0-59');
|
|
40490
|
-
expressions[2] = convertAsterisk(expressions[2], '0-23');
|
|
40491
|
-
expressions[3] = convertAsterisk(expressions[3], '1-31');
|
|
40492
|
-
expressions[4] = convertAsterisk(expressions[4], '1-12');
|
|
40493
|
-
expressions[5] = convertAsterisk(expressions[5], '0-6');
|
|
40494
|
-
return expressions;
|
|
40495
|
-
}
|
|
40496
|
-
return convertAsterisksToRanges;
|
|
40497
|
-
})();
|
|
40498
|
-
|
|
40499
|
-
return asteriskToRangeConversion;
|
|
40500
|
-
}
|
|
40501
|
-
|
|
40502
|
-
var rangeConversion = {};
|
|
40503
|
-
|
|
40504
|
-
var hasRequiredRangeConversion;
|
|
40505
|
-
|
|
40506
|
-
function requireRangeConversion () {
|
|
40507
|
-
if (hasRequiredRangeConversion) return rangeConversion;
|
|
40508
|
-
hasRequiredRangeConversion = 1;
|
|
40509
|
-
Object.defineProperty(rangeConversion, "__esModule", { value: true });
|
|
40510
|
-
rangeConversion.default = (() => {
|
|
40511
|
-
function replaceWithRange(expression, text, init, end, stepTxt) {
|
|
40512
|
-
const step = parseInt(stepTxt);
|
|
40513
|
-
const numbers = [];
|
|
40514
|
-
let last = parseInt(end);
|
|
40515
|
-
let first = parseInt(init);
|
|
40516
|
-
if (first > last) {
|
|
40517
|
-
last = parseInt(init);
|
|
40518
|
-
first = parseInt(end);
|
|
40519
|
-
}
|
|
40520
|
-
for (let i = first; i <= last; i += step) {
|
|
40521
|
-
numbers.push(i);
|
|
40522
|
-
}
|
|
40523
|
-
return expression.replace(new RegExp(text, 'i'), numbers.join());
|
|
40524
|
-
}
|
|
40525
|
-
function convertRange(expression) {
|
|
40526
|
-
const rangeRegEx = /(\d+)-(\d+)(\/(\d+)|)/;
|
|
40527
|
-
let match = rangeRegEx.exec(expression);
|
|
40528
|
-
while (match !== null && match.length > 0) {
|
|
40529
|
-
expression = replaceWithRange(expression, match[0], match[1], match[2], match[4] || '1');
|
|
40530
|
-
match = rangeRegEx.exec(expression);
|
|
40531
|
-
}
|
|
40532
|
-
return expression;
|
|
40533
|
-
}
|
|
40534
|
-
function convertAllRanges(expressions) {
|
|
40535
|
-
for (let i = 0; i < expressions.length; i++) {
|
|
40536
|
-
expressions[i] = convertRange(expressions[i]);
|
|
40537
|
-
}
|
|
40538
|
-
return expressions;
|
|
40539
|
-
}
|
|
40540
|
-
return convertAllRanges;
|
|
40541
|
-
})();
|
|
40542
|
-
|
|
40543
|
-
return rangeConversion;
|
|
40544
|
-
}
|
|
40545
|
-
|
|
40546
|
-
var hasRequiredConvertion;
|
|
40547
|
-
|
|
40548
|
-
function requireConvertion () {
|
|
40549
|
-
if (hasRequiredConvertion) return convertion;
|
|
40550
|
-
hasRequiredConvertion = 1;
|
|
40551
|
-
var __importDefault = (convertion && convertion.__importDefault) || function (mod) {
|
|
40552
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
40553
|
-
};
|
|
40554
|
-
Object.defineProperty(convertion, "__esModule", { value: true });
|
|
40555
|
-
const month_names_conversion_1 = __importDefault(requireMonthNamesConversion());
|
|
40556
|
-
const week_day_names_conversion_1 = __importDefault(requireWeekDayNamesConversion());
|
|
40557
|
-
const asterisk_to_range_conversion_1 = __importDefault(requireAsteriskToRangeConversion());
|
|
40558
|
-
const range_conversion_1 = __importDefault(requireRangeConversion());
|
|
40559
|
-
convertion.default = (() => {
|
|
40560
|
-
function appendSeccondExpression(expressions) {
|
|
40561
|
-
if (expressions.length === 5) {
|
|
40562
|
-
return ['0'].concat(expressions);
|
|
40563
|
-
}
|
|
40564
|
-
return expressions;
|
|
40565
|
-
}
|
|
40566
|
-
function removeSpaces(str) {
|
|
40567
|
-
return str.replace(/\s{2,}/g, ' ').trim();
|
|
40568
|
-
}
|
|
40569
|
-
function normalizeIntegers(expressions) {
|
|
40570
|
-
for (let i = 0; i < expressions.length; i++) {
|
|
40571
|
-
const numbers = expressions[i].split(',');
|
|
40572
|
-
for (let j = 0; j < numbers.length; j++) {
|
|
40573
|
-
numbers[j] = parseInt(numbers[j]);
|
|
40574
|
-
}
|
|
40575
|
-
expressions[i] = numbers;
|
|
40576
|
-
}
|
|
40577
|
-
return expressions;
|
|
40578
|
-
}
|
|
40579
|
-
function interprete(expression) {
|
|
40580
|
-
let expressions = removeSpaces(`${expression}`).split(' ');
|
|
40581
|
-
expressions = appendSeccondExpression(expressions);
|
|
40582
|
-
expressions[4] = (0, month_names_conversion_1.default)(expressions[4]);
|
|
40583
|
-
expressions[5] = (0, week_day_names_conversion_1.default)(expressions[5]);
|
|
40584
|
-
expressions = (0, asterisk_to_range_conversion_1.default)(expressions);
|
|
40585
|
-
expressions = (0, range_conversion_1.default)(expressions);
|
|
40586
|
-
expressions = normalizeIntegers(expressions);
|
|
40587
|
-
return expressions;
|
|
40588
|
-
}
|
|
40589
|
-
return interprete;
|
|
40590
|
-
})();
|
|
40591
|
-
|
|
40592
|
-
return convertion;
|
|
40593
|
-
}
|
|
40594
|
-
|
|
40595
|
-
var localizedTime = {};
|
|
40596
|
-
|
|
40597
|
-
var hasRequiredLocalizedTime;
|
|
40598
|
-
|
|
40599
|
-
function requireLocalizedTime () {
|
|
40600
|
-
if (hasRequiredLocalizedTime) return localizedTime;
|
|
40601
|
-
hasRequiredLocalizedTime = 1;
|
|
40602
|
-
Object.defineProperty(localizedTime, "__esModule", { value: true });
|
|
40603
|
-
localizedTime.LocalizedTime = void 0;
|
|
40604
|
-
class LocalizedTime {
|
|
40605
|
-
timestamp;
|
|
40606
|
-
parts;
|
|
40607
|
-
timezone;
|
|
40608
|
-
constructor(date, timezone) {
|
|
40609
|
-
this.timestamp = date.getTime();
|
|
40610
|
-
this.timezone = timezone;
|
|
40611
|
-
this.parts = buildDateParts(date, timezone);
|
|
40612
|
-
}
|
|
40613
|
-
toDate() {
|
|
40614
|
-
return new Date(this.timestamp);
|
|
40615
|
-
}
|
|
40616
|
-
toISO() {
|
|
40617
|
-
const gmt = this.parts.gmt.replace(/^GMT/, '');
|
|
40618
|
-
const offset = gmt ? gmt : 'Z';
|
|
40619
|
-
const pad = (n) => String(n).padStart(2, '0');
|
|
40620
|
-
return `${this.parts.year}-${pad(this.parts.month)}-${pad(this.parts.day)}`
|
|
40621
|
-
+ `T${pad(this.parts.hour)}:${pad(this.parts.minute)}:${pad(this.parts.second)}`
|
|
40622
|
-
+ `.${String(this.parts.milisecond).padStart(3, '0')}`
|
|
40623
|
-
+ offset;
|
|
40624
|
-
}
|
|
40625
|
-
getParts() {
|
|
40626
|
-
return this.parts;
|
|
40627
|
-
}
|
|
40628
|
-
set(field, value) {
|
|
40629
|
-
this.parts[field] = value;
|
|
40630
|
-
const newDate = new Date(this.toISO());
|
|
40631
|
-
this.timestamp = newDate.getTime();
|
|
40632
|
-
this.parts = buildDateParts(newDate, this.timezone);
|
|
40633
|
-
}
|
|
40634
|
-
}
|
|
40635
|
-
localizedTime.LocalizedTime = LocalizedTime;
|
|
40636
|
-
function buildDateParts(date, timezone) {
|
|
40637
|
-
const dftOptions = {
|
|
40638
|
-
year: 'numeric',
|
|
40639
|
-
month: '2-digit',
|
|
40640
|
-
day: '2-digit',
|
|
40641
|
-
hour: '2-digit',
|
|
40642
|
-
minute: '2-digit',
|
|
40643
|
-
second: '2-digit',
|
|
40644
|
-
weekday: 'short',
|
|
40645
|
-
hour12: false
|
|
40646
|
-
};
|
|
40647
|
-
if (timezone) {
|
|
40648
|
-
dftOptions.timeZone = timezone;
|
|
40649
|
-
}
|
|
40650
|
-
const dateFormat = new Intl.DateTimeFormat('en-US', dftOptions);
|
|
40651
|
-
const parts = dateFormat.formatToParts(date).filter(part => {
|
|
40652
|
-
return part.type !== 'literal';
|
|
40653
|
-
}).reduce((acc, part) => {
|
|
40654
|
-
acc[part.type] = part.value;
|
|
40655
|
-
return acc;
|
|
40656
|
-
}, {});
|
|
40657
|
-
return {
|
|
40658
|
-
day: parseInt(parts.day),
|
|
40659
|
-
month: parseInt(parts.month),
|
|
40660
|
-
year: parseInt(parts.year),
|
|
40661
|
-
hour: parts.hour === '24' ? 0 : parseInt(parts.hour),
|
|
40662
|
-
minute: parseInt(parts.minute),
|
|
40663
|
-
second: parseInt(parts.second),
|
|
40664
|
-
milisecond: date.getMilliseconds(),
|
|
40665
|
-
weekday: parts.weekday,
|
|
40666
|
-
gmt: getTimezoneGMT(date, timezone)
|
|
40667
|
-
};
|
|
40668
|
-
}
|
|
40669
|
-
function getTimezoneGMT(date, timezone) {
|
|
40670
|
-
const utcDate = new Date(date.toLocaleString('en-US', { timeZone: 'UTC' }));
|
|
40671
|
-
const tzDate = new Date(date.toLocaleString('en-US', { timeZone: timezone }));
|
|
40672
|
-
let offsetInMinutes = (utcDate.getTime() - tzDate.getTime()) / 60000;
|
|
40673
|
-
const sign = offsetInMinutes <= 0 ? '+' : '-';
|
|
40674
|
-
offsetInMinutes = Math.abs(offsetInMinutes);
|
|
40675
|
-
if (offsetInMinutes === 0)
|
|
40676
|
-
return 'Z';
|
|
40677
|
-
const hours = Math.floor(offsetInMinutes / 60).toString().padStart(2, '0');
|
|
40678
|
-
const minutes = Math.floor(offsetInMinutes % 60).toString().padStart(2, '0');
|
|
40679
|
-
return `GMT${sign}${hours}:${minutes}`;
|
|
40680
|
-
}
|
|
40681
|
-
|
|
40682
|
-
return localizedTime;
|
|
40683
|
-
}
|
|
40684
|
-
|
|
40685
|
-
var matcherWalker = {};
|
|
40686
|
-
|
|
40687
|
-
var hasRequiredMatcherWalker;
|
|
40688
|
-
|
|
40689
|
-
function requireMatcherWalker () {
|
|
40690
|
-
if (hasRequiredMatcherWalker) return matcherWalker;
|
|
40691
|
-
hasRequiredMatcherWalker = 1;
|
|
40692
|
-
var __importDefault = (matcherWalker && matcherWalker.__importDefault) || function (mod) {
|
|
40693
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
40694
|
-
};
|
|
40695
|
-
Object.defineProperty(matcherWalker, "__esModule", { value: true });
|
|
40696
|
-
matcherWalker.MatcherWalker = void 0;
|
|
40697
|
-
const convertion_1 = __importDefault(requireConvertion());
|
|
40698
|
-
const localized_time_1 = requireLocalizedTime();
|
|
40699
|
-
const time_matcher_1 = requireTimeMatcher();
|
|
40700
|
-
const week_day_names_conversion_1 = __importDefault(requireWeekDayNamesConversion());
|
|
40701
|
-
class MatcherWalker {
|
|
40702
|
-
cronExpression;
|
|
40703
|
-
baseDate;
|
|
40704
|
-
pattern;
|
|
40705
|
-
expressions;
|
|
40706
|
-
timeMatcher;
|
|
40707
|
-
timezone;
|
|
40708
|
-
constructor(cronExpression, baseDate, timezone) {
|
|
40709
|
-
this.cronExpression = cronExpression;
|
|
40710
|
-
this.baseDate = baseDate;
|
|
40711
|
-
this.timeMatcher = new time_matcher_1.TimeMatcher(cronExpression, timezone);
|
|
40712
|
-
this.timezone = timezone;
|
|
40713
|
-
this.expressions = (0, convertion_1.default)(cronExpression);
|
|
40714
|
-
}
|
|
40715
|
-
isMatching() {
|
|
40716
|
-
return this.timeMatcher.match(this.baseDate);
|
|
40717
|
-
}
|
|
40718
|
-
matchNext() {
|
|
40719
|
-
const findNextDateIgnoringWeekday = () => {
|
|
40720
|
-
const baseDate = new Date(this.baseDate.getTime());
|
|
40721
|
-
baseDate.setMilliseconds(0);
|
|
40722
|
-
const localTime = new localized_time_1.LocalizedTime(baseDate, this.timezone);
|
|
40723
|
-
const dateParts = localTime.getParts();
|
|
40724
|
-
const date = new localized_time_1.LocalizedTime(localTime.toDate(), this.timezone);
|
|
40725
|
-
const seconds = this.expressions[0];
|
|
40726
|
-
const nextSecond = availableValue(seconds, dateParts.second);
|
|
40727
|
-
if (nextSecond) {
|
|
40728
|
-
date.set('second', nextSecond);
|
|
40729
|
-
if (this.timeMatcher.match(date.toDate())) {
|
|
40730
|
-
return date;
|
|
40731
|
-
}
|
|
40732
|
-
}
|
|
40733
|
-
date.set('second', seconds[0]);
|
|
40734
|
-
const minutes = this.expressions[1];
|
|
40735
|
-
const nextMinute = availableValue(minutes, dateParts.minute);
|
|
40736
|
-
if (nextMinute) {
|
|
40737
|
-
date.set('minute', nextMinute);
|
|
40738
|
-
if (this.timeMatcher.match(date.toDate())) {
|
|
40739
|
-
return date;
|
|
40740
|
-
}
|
|
40741
|
-
}
|
|
40742
|
-
date.set('minute', minutes[0]);
|
|
40743
|
-
const hours = this.expressions[2];
|
|
40744
|
-
const nextHour = availableValue(hours, dateParts.hour);
|
|
40745
|
-
if (nextHour) {
|
|
40746
|
-
date.set('hour', nextHour);
|
|
40747
|
-
if (this.timeMatcher.match(date.toDate())) {
|
|
40748
|
-
return date;
|
|
40749
|
-
}
|
|
40750
|
-
}
|
|
40751
|
-
date.set('hour', hours[0]);
|
|
40752
|
-
const days = this.expressions[3];
|
|
40753
|
-
const nextDay = availableValue(days, dateParts.day);
|
|
40754
|
-
if (nextDay) {
|
|
40755
|
-
date.set('day', nextDay);
|
|
40756
|
-
if (this.timeMatcher.match(date.toDate())) {
|
|
40757
|
-
return date;
|
|
40758
|
-
}
|
|
40759
|
-
}
|
|
40760
|
-
date.set('day', days[0]);
|
|
40761
|
-
const months = this.expressions[4];
|
|
40762
|
-
const nextMonth = availableValue(months, dateParts.month);
|
|
40763
|
-
if (nextMonth) {
|
|
40764
|
-
date.set('month', nextMonth);
|
|
40765
|
-
if (this.timeMatcher.match(date.toDate())) {
|
|
40766
|
-
return date;
|
|
40767
|
-
}
|
|
40768
|
-
}
|
|
40769
|
-
date.set('year', date.getParts().year + 1);
|
|
40770
|
-
date.set('month', months[0]);
|
|
40771
|
-
return date;
|
|
40772
|
-
};
|
|
40773
|
-
const date = findNextDateIgnoringWeekday();
|
|
40774
|
-
const weekdays = this.expressions[5];
|
|
40775
|
-
let currentWeekday = parseInt((0, week_day_names_conversion_1.default)(date.getParts().weekday));
|
|
40776
|
-
while (!(weekdays.indexOf(currentWeekday) > -1)) {
|
|
40777
|
-
date.set('year', date.getParts().year + 1);
|
|
40778
|
-
currentWeekday = parseInt((0, week_day_names_conversion_1.default)(date.getParts().weekday));
|
|
40779
|
-
}
|
|
40780
|
-
return date;
|
|
40781
|
-
}
|
|
40782
|
-
}
|
|
40783
|
-
matcherWalker.MatcherWalker = MatcherWalker;
|
|
40784
|
-
function availableValue(values, currentValue) {
|
|
40785
|
-
const availableValues = values.sort((a, b) => a - b).filter(s => s > currentValue);
|
|
40786
|
-
if (availableValues.length > 0)
|
|
40787
|
-
return availableValues[0];
|
|
40788
|
-
return false;
|
|
40789
|
-
}
|
|
40790
|
-
|
|
40791
|
-
return matcherWalker;
|
|
40792
|
-
}
|
|
40793
|
-
|
|
40794
|
-
var hasRequiredTimeMatcher;
|
|
40795
|
-
|
|
40796
|
-
function requireTimeMatcher () {
|
|
40797
|
-
if (hasRequiredTimeMatcher) return timeMatcher;
|
|
40798
|
-
hasRequiredTimeMatcher = 1;
|
|
40799
|
-
var __importDefault = (timeMatcher && timeMatcher.__importDefault) || function (mod) {
|
|
40800
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
40801
|
-
};
|
|
40802
|
-
Object.defineProperty(timeMatcher, "__esModule", { value: true });
|
|
40803
|
-
timeMatcher.TimeMatcher = void 0;
|
|
40804
|
-
const index_1 = __importDefault(requireConvertion());
|
|
40805
|
-
const week_day_names_conversion_1 = __importDefault(requireWeekDayNamesConversion());
|
|
40806
|
-
const localized_time_1 = requireLocalizedTime();
|
|
40807
|
-
const matcher_walker_1 = requireMatcherWalker();
|
|
40808
|
-
function matchValue(allowedValues, value) {
|
|
40809
|
-
return allowedValues.indexOf(value) !== -1;
|
|
40810
|
-
}
|
|
40811
|
-
class TimeMatcher {
|
|
40812
|
-
timezone;
|
|
40813
|
-
pattern;
|
|
40814
|
-
expressions;
|
|
40815
|
-
constructor(pattern, timezone) {
|
|
40816
|
-
this.timezone = timezone;
|
|
40817
|
-
this.pattern = pattern;
|
|
40818
|
-
this.expressions = (0, index_1.default)(pattern);
|
|
40819
|
-
}
|
|
40820
|
-
match(date) {
|
|
40821
|
-
const localizedTime = new localized_time_1.LocalizedTime(date, this.timezone);
|
|
40822
|
-
const parts = localizedTime.getParts();
|
|
40823
|
-
const runOnSecond = matchValue(this.expressions[0], parts.second);
|
|
40824
|
-
const runOnMinute = matchValue(this.expressions[1], parts.minute);
|
|
40825
|
-
const runOnHour = matchValue(this.expressions[2], parts.hour);
|
|
40826
|
-
const runOnDay = matchValue(this.expressions[3], parts.day);
|
|
40827
|
-
const runOnMonth = matchValue(this.expressions[4], parts.month);
|
|
40828
|
-
const runOnWeekDay = matchValue(this.expressions[5], parseInt((0, week_day_names_conversion_1.default)(parts.weekday)));
|
|
40829
|
-
return runOnSecond && runOnMinute && runOnHour && runOnDay && runOnMonth && runOnWeekDay;
|
|
40830
|
-
}
|
|
40831
|
-
getNextMatch(date) {
|
|
40832
|
-
const walker = new matcher_walker_1.MatcherWalker(this.pattern, date, this.timezone);
|
|
40833
|
-
const next = walker.matchNext();
|
|
40834
|
-
return next.toDate();
|
|
40835
|
-
}
|
|
40836
|
-
}
|
|
40837
|
-
timeMatcher.TimeMatcher = TimeMatcher;
|
|
40838
|
-
|
|
40839
|
-
return timeMatcher;
|
|
40840
|
-
}
|
|
40841
|
-
|
|
40842
|
-
var stateMachine = {};
|
|
40843
|
-
|
|
40844
|
-
var hasRequiredStateMachine;
|
|
40845
|
-
|
|
40846
|
-
function requireStateMachine () {
|
|
40847
|
-
if (hasRequiredStateMachine) return stateMachine;
|
|
40848
|
-
hasRequiredStateMachine = 1;
|
|
40849
|
-
Object.defineProperty(stateMachine, "__esModule", { value: true });
|
|
40850
|
-
stateMachine.StateMachine = void 0;
|
|
40851
|
-
const allowedTransitions = {
|
|
40852
|
-
'stopped': ['stopped', 'idle', 'destroyed'],
|
|
40853
|
-
'idle': ['idle', 'running', 'stopped', 'destroyed'],
|
|
40854
|
-
'running': ['running', 'idle', 'stopped', 'destroyed'],
|
|
40855
|
-
'destroyed': ['destroyed']
|
|
40856
|
-
};
|
|
40857
|
-
class StateMachine {
|
|
40858
|
-
state;
|
|
40859
|
-
constructor(initial = 'stopped') {
|
|
40860
|
-
this.state = initial;
|
|
40861
|
-
}
|
|
40862
|
-
changeState(state) {
|
|
40863
|
-
if (allowedTransitions[this.state].includes(state)) {
|
|
40864
|
-
this.state = state;
|
|
40865
|
-
}
|
|
40866
|
-
else {
|
|
40867
|
-
throw new Error(`invalid transition from ${this.state} to ${state}`);
|
|
40868
|
-
}
|
|
40869
|
-
}
|
|
40870
|
-
}
|
|
40871
|
-
stateMachine.StateMachine = StateMachine;
|
|
40872
|
-
|
|
40873
|
-
return stateMachine;
|
|
40874
|
-
}
|
|
40875
|
-
|
|
40876
|
-
var hasRequiredInlineScheduledTask;
|
|
40877
|
-
|
|
40878
|
-
function requireInlineScheduledTask () {
|
|
40879
|
-
if (hasRequiredInlineScheduledTask) return inlineScheduledTask;
|
|
40880
|
-
hasRequiredInlineScheduledTask = 1;
|
|
40881
|
-
var __importDefault = (inlineScheduledTask && inlineScheduledTask.__importDefault) || function (mod) {
|
|
40882
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
40883
|
-
};
|
|
40884
|
-
Object.defineProperty(inlineScheduledTask, "__esModule", { value: true });
|
|
40885
|
-
inlineScheduledTask.InlineScheduledTask = void 0;
|
|
40886
|
-
const events_1 = __importDefault(EventEmitter);
|
|
40887
|
-
const runner_1 = requireRunner();
|
|
40888
|
-
const time_matcher_1 = requireTimeMatcher();
|
|
40889
|
-
const create_id_1 = requireCreateId();
|
|
40890
|
-
const state_machine_1 = requireStateMachine();
|
|
40891
|
-
const logger_1 = __importDefault(requireLogger());
|
|
40892
|
-
const localized_time_1 = requireLocalizedTime();
|
|
40893
|
-
class TaskEmitter extends events_1.default {
|
|
40894
|
-
}
|
|
40895
|
-
class InlineScheduledTask {
|
|
40896
|
-
emitter;
|
|
40897
|
-
cronExpression;
|
|
40898
|
-
timeMatcher;
|
|
40899
|
-
runner;
|
|
40900
|
-
id;
|
|
40901
|
-
name;
|
|
40902
|
-
stateMachine;
|
|
40903
|
-
timezone;
|
|
40904
|
-
constructor(cronExpression, taskFn, options) {
|
|
40905
|
-
this.emitter = new TaskEmitter();
|
|
40906
|
-
this.cronExpression = cronExpression;
|
|
40907
|
-
this.id = (0, create_id_1.createID)('task', 12);
|
|
40908
|
-
this.name = options?.name || this.id;
|
|
40909
|
-
this.timezone = options?.timezone;
|
|
40910
|
-
this.timeMatcher = new time_matcher_1.TimeMatcher(cronExpression, options?.timezone);
|
|
40911
|
-
this.stateMachine = new state_machine_1.StateMachine();
|
|
40912
|
-
const runnerOptions = {
|
|
40913
|
-
timezone: options?.timezone,
|
|
40914
|
-
noOverlap: options?.noOverlap,
|
|
40915
|
-
maxExecutions: options?.maxExecutions,
|
|
40916
|
-
maxRandomDelay: options?.maxRandomDelay,
|
|
40917
|
-
beforeRun: (date, execution) => {
|
|
40918
|
-
if (execution.reason === 'scheduled') {
|
|
40919
|
-
this.changeState('running');
|
|
40920
|
-
}
|
|
40921
|
-
this.emitter.emit('execution:started', this.createContext(date, execution));
|
|
40922
|
-
return true;
|
|
40923
|
-
},
|
|
40924
|
-
onFinished: (date, execution) => {
|
|
40925
|
-
if (execution.reason === 'scheduled') {
|
|
40926
|
-
this.changeState('idle');
|
|
40927
|
-
}
|
|
40928
|
-
this.emitter.emit('execution:finished', this.createContext(date, execution));
|
|
40929
|
-
return true;
|
|
40930
|
-
},
|
|
40931
|
-
onError: (date, error, execution) => {
|
|
40932
|
-
logger_1.default.error(error);
|
|
40933
|
-
this.emitter.emit('execution:failed', this.createContext(date, execution));
|
|
40934
|
-
this.changeState('idle');
|
|
40935
|
-
},
|
|
40936
|
-
onOverlap: (date) => {
|
|
40937
|
-
this.emitter.emit('execution:overlap', this.createContext(date));
|
|
40938
|
-
},
|
|
40939
|
-
onMissedExecution: (date) => {
|
|
40940
|
-
this.emitter.emit('execution:missed', this.createContext(date));
|
|
40941
|
-
},
|
|
40942
|
-
onMaxExecutions: (date) => {
|
|
40943
|
-
this.emitter.emit('execution:maxReached', this.createContext(date));
|
|
40944
|
-
this.destroy();
|
|
40945
|
-
}
|
|
40946
|
-
};
|
|
40947
|
-
this.runner = new runner_1.Runner(this.timeMatcher, (date, execution) => {
|
|
40948
|
-
return taskFn(this.createContext(date, execution));
|
|
40949
|
-
}, runnerOptions);
|
|
40950
|
-
}
|
|
40951
|
-
getNextRun() {
|
|
40952
|
-
if (this.stateMachine.state !== 'stopped') {
|
|
40953
|
-
return this.runner.nextRun();
|
|
40954
|
-
}
|
|
40955
|
-
return null;
|
|
40956
|
-
}
|
|
40957
|
-
changeState(state) {
|
|
40958
|
-
if (this.runner.isStarted()) {
|
|
40959
|
-
this.stateMachine.changeState(state);
|
|
40960
|
-
}
|
|
40961
|
-
}
|
|
40962
|
-
start() {
|
|
40963
|
-
if (this.runner.isStopped()) {
|
|
40964
|
-
this.runner.start();
|
|
40965
|
-
this.stateMachine.changeState('idle');
|
|
40966
|
-
this.emitter.emit('task:started', this.createContext(new Date()));
|
|
40967
|
-
}
|
|
40968
|
-
}
|
|
40969
|
-
stop() {
|
|
40970
|
-
if (this.runner.isStarted()) {
|
|
40971
|
-
this.runner.stop();
|
|
40972
|
-
this.stateMachine.changeState('stopped');
|
|
40973
|
-
this.emitter.emit('task:stopped', this.createContext(new Date()));
|
|
40974
|
-
}
|
|
40975
|
-
}
|
|
40976
|
-
getStatus() {
|
|
40977
|
-
return this.stateMachine.state;
|
|
40978
|
-
}
|
|
40979
|
-
destroy() {
|
|
40980
|
-
if (this.stateMachine.state === 'destroyed')
|
|
40981
|
-
return;
|
|
40982
|
-
this.stop();
|
|
40983
|
-
this.stateMachine.changeState('destroyed');
|
|
40984
|
-
this.emitter.emit('task:destroyed', this.createContext(new Date()));
|
|
40985
|
-
}
|
|
40986
|
-
execute() {
|
|
40987
|
-
return new Promise((resolve, reject) => {
|
|
40988
|
-
const onFail = (context) => {
|
|
40989
|
-
this.off('execution:finished', onFail);
|
|
40990
|
-
reject(context.execution?.error);
|
|
40991
|
-
};
|
|
40992
|
-
const onFinished = (context) => {
|
|
40993
|
-
this.off('execution:failed', onFail);
|
|
40994
|
-
resolve(context.execution?.result);
|
|
40995
|
-
};
|
|
40996
|
-
this.once('execution:finished', onFinished);
|
|
40997
|
-
this.once('execution:failed', onFail);
|
|
40998
|
-
this.runner.execute();
|
|
40999
|
-
});
|
|
41000
|
-
}
|
|
41001
|
-
on(event, fun) {
|
|
41002
|
-
this.emitter.on(event, fun);
|
|
41003
|
-
}
|
|
41004
|
-
off(event, fun) {
|
|
41005
|
-
this.emitter.off(event, fun);
|
|
41006
|
-
}
|
|
41007
|
-
once(event, fun) {
|
|
41008
|
-
this.emitter.once(event, fun);
|
|
41009
|
-
}
|
|
41010
|
-
createContext(executionDate, execution) {
|
|
41011
|
-
const localTime = new localized_time_1.LocalizedTime(executionDate, this.timezone);
|
|
41012
|
-
const ctx = {
|
|
41013
|
-
date: localTime.toDate(),
|
|
41014
|
-
dateLocalIso: localTime.toISO(),
|
|
41015
|
-
triggeredAt: new Date(),
|
|
41016
|
-
task: this,
|
|
41017
|
-
execution: execution
|
|
41018
|
-
};
|
|
41019
|
-
return ctx;
|
|
41020
|
-
}
|
|
41021
|
-
}
|
|
41022
|
-
inlineScheduledTask.InlineScheduledTask = InlineScheduledTask;
|
|
41023
|
-
|
|
41024
|
-
return inlineScheduledTask;
|
|
41025
|
-
}
|
|
41026
|
-
|
|
41027
|
-
var taskRegistry = {};
|
|
41028
|
-
|
|
41029
|
-
var hasRequiredTaskRegistry;
|
|
41030
|
-
|
|
41031
|
-
function requireTaskRegistry () {
|
|
41032
|
-
if (hasRequiredTaskRegistry) return taskRegistry;
|
|
41033
|
-
hasRequiredTaskRegistry = 1;
|
|
41034
|
-
Object.defineProperty(taskRegistry, "__esModule", { value: true });
|
|
41035
|
-
taskRegistry.TaskRegistry = void 0;
|
|
41036
|
-
const tasks = new Map();
|
|
41037
|
-
class TaskRegistry {
|
|
41038
|
-
add(task) {
|
|
41039
|
-
if (this.has(task.id)) {
|
|
41040
|
-
throw Error(`task ${task.id} already registred!`);
|
|
41041
|
-
}
|
|
41042
|
-
tasks.set(task.id, task);
|
|
41043
|
-
task.on('task:destroyed', () => {
|
|
41044
|
-
this.remove(task);
|
|
41045
|
-
});
|
|
41046
|
-
}
|
|
41047
|
-
get(taskId) {
|
|
41048
|
-
return tasks.get(taskId);
|
|
41049
|
-
}
|
|
41050
|
-
remove(task) {
|
|
41051
|
-
if (this.has(task.id)) {
|
|
41052
|
-
task?.destroy();
|
|
41053
|
-
tasks.delete(task.id);
|
|
41054
|
-
}
|
|
41055
|
-
}
|
|
41056
|
-
all() {
|
|
41057
|
-
return tasks;
|
|
41058
|
-
}
|
|
41059
|
-
has(taskId) {
|
|
41060
|
-
return tasks.has(taskId);
|
|
41061
|
-
}
|
|
41062
|
-
killAll() {
|
|
41063
|
-
tasks.forEach(id => this.remove(id));
|
|
41064
|
-
}
|
|
41065
|
-
}
|
|
41066
|
-
taskRegistry.TaskRegistry = TaskRegistry;
|
|
41067
|
-
|
|
41068
|
-
return taskRegistry;
|
|
41069
|
-
}
|
|
41070
|
-
|
|
41071
|
-
var patternValidation = {};
|
|
41072
|
-
|
|
41073
|
-
var hasRequiredPatternValidation;
|
|
41074
|
-
|
|
41075
|
-
function requirePatternValidation () {
|
|
41076
|
-
if (hasRequiredPatternValidation) return patternValidation;
|
|
41077
|
-
hasRequiredPatternValidation = 1;
|
|
41078
|
-
var __importDefault = (patternValidation && patternValidation.__importDefault) || function (mod) {
|
|
41079
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
41080
|
-
};
|
|
41081
|
-
Object.defineProperty(patternValidation, "__esModule", { value: true });
|
|
41082
|
-
const index_1 = __importDefault(requireConvertion());
|
|
41083
|
-
const validationRegex = /^(?:\d+|\*|\*\/\d+)$/;
|
|
41084
|
-
function isValidExpression(expression, min, max) {
|
|
41085
|
-
const options = expression;
|
|
41086
|
-
for (const option of options) {
|
|
41087
|
-
const optionAsInt = parseInt(option, 10);
|
|
41088
|
-
if ((!Number.isNaN(optionAsInt) &&
|
|
41089
|
-
(optionAsInt < min || optionAsInt > max)) ||
|
|
41090
|
-
!validationRegex.test(option))
|
|
41091
|
-
return false;
|
|
41092
|
-
}
|
|
41093
|
-
return true;
|
|
41094
|
-
}
|
|
41095
|
-
function isInvalidSecond(expression) {
|
|
41096
|
-
return !isValidExpression(expression, 0, 59);
|
|
41097
|
-
}
|
|
41098
|
-
function isInvalidMinute(expression) {
|
|
41099
|
-
return !isValidExpression(expression, 0, 59);
|
|
41100
|
-
}
|
|
41101
|
-
function isInvalidHour(expression) {
|
|
41102
|
-
return !isValidExpression(expression, 0, 23);
|
|
41103
|
-
}
|
|
41104
|
-
function isInvalidDayOfMonth(expression) {
|
|
41105
|
-
return !isValidExpression(expression, 1, 31);
|
|
41106
|
-
}
|
|
41107
|
-
function isInvalidMonth(expression) {
|
|
41108
|
-
return !isValidExpression(expression, 1, 12);
|
|
41109
|
-
}
|
|
41110
|
-
function isInvalidWeekDay(expression) {
|
|
41111
|
-
return !isValidExpression(expression, 0, 7);
|
|
41112
|
-
}
|
|
41113
|
-
function validateFields(patterns, executablePatterns) {
|
|
41114
|
-
if (isInvalidSecond(executablePatterns[0]))
|
|
41115
|
-
throw new Error(`${patterns[0]} is a invalid expression for second`);
|
|
41116
|
-
if (isInvalidMinute(executablePatterns[1]))
|
|
41117
|
-
throw new Error(`${patterns[1]} is a invalid expression for minute`);
|
|
41118
|
-
if (isInvalidHour(executablePatterns[2]))
|
|
41119
|
-
throw new Error(`${patterns[2]} is a invalid expression for hour`);
|
|
41120
|
-
if (isInvalidDayOfMonth(executablePatterns[3]))
|
|
41121
|
-
throw new Error(`${patterns[3]} is a invalid expression for day of month`);
|
|
41122
|
-
if (isInvalidMonth(executablePatterns[4]))
|
|
41123
|
-
throw new Error(`${patterns[4]} is a invalid expression for month`);
|
|
41124
|
-
if (isInvalidWeekDay(executablePatterns[5]))
|
|
41125
|
-
throw new Error(`${patterns[5]} is a invalid expression for week day`);
|
|
41126
|
-
}
|
|
41127
|
-
function validate(pattern) {
|
|
41128
|
-
if (typeof pattern !== 'string')
|
|
41129
|
-
throw new TypeError('pattern must be a string!');
|
|
41130
|
-
const patterns = pattern.split(' ');
|
|
41131
|
-
const executablePatterns = (0, index_1.default)(pattern);
|
|
41132
|
-
if (patterns.length === 5)
|
|
41133
|
-
patterns.unshift('0');
|
|
41134
|
-
validateFields(patterns, executablePatterns);
|
|
41135
|
-
}
|
|
41136
|
-
patternValidation.default = validate;
|
|
41137
|
-
|
|
41138
|
-
return patternValidation;
|
|
41139
|
-
}
|
|
41140
|
-
|
|
41141
|
-
var backgroundScheduledTask = {};
|
|
41142
|
-
|
|
41143
|
-
var hasRequiredBackgroundScheduledTask;
|
|
41144
|
-
|
|
41145
|
-
function requireBackgroundScheduledTask () {
|
|
41146
|
-
if (hasRequiredBackgroundScheduledTask) return backgroundScheduledTask;
|
|
41147
|
-
hasRequiredBackgroundScheduledTask = 1;
|
|
41148
|
-
var __importDefault = (backgroundScheduledTask && backgroundScheduledTask.__importDefault) || function (mod) {
|
|
41149
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
41150
|
-
};
|
|
41151
|
-
Object.defineProperty(backgroundScheduledTask, "__esModule", { value: true });
|
|
41152
|
-
const path_1 = path$1;
|
|
41153
|
-
const child_process_1 = require$$1;
|
|
41154
|
-
const create_id_1 = requireCreateId();
|
|
41155
|
-
const stream_1 = require$$3;
|
|
41156
|
-
const state_machine_1 = requireStateMachine();
|
|
41157
|
-
const localized_time_1 = requireLocalizedTime();
|
|
41158
|
-
const logger_1 = __importDefault(requireLogger());
|
|
41159
|
-
const time_matcher_1 = requireTimeMatcher();
|
|
41160
|
-
const daemonPath = (0, path_1.resolve)(__dirname, 'daemon.js');
|
|
41161
|
-
class TaskEmitter extends stream_1.EventEmitter {
|
|
41162
|
-
}
|
|
41163
|
-
class BackgroundScheduledTask {
|
|
41164
|
-
emitter;
|
|
41165
|
-
id;
|
|
41166
|
-
name;
|
|
41167
|
-
cronExpression;
|
|
41168
|
-
taskPath;
|
|
41169
|
-
options;
|
|
41170
|
-
forkProcess;
|
|
41171
|
-
stateMachine;
|
|
41172
|
-
constructor(cronExpression, taskPath, options) {
|
|
41173
|
-
this.cronExpression = cronExpression;
|
|
41174
|
-
this.taskPath = taskPath;
|
|
41175
|
-
this.options = options;
|
|
41176
|
-
this.id = (0, create_id_1.createID)('task');
|
|
41177
|
-
this.name = options?.name || this.id;
|
|
41178
|
-
this.emitter = new TaskEmitter();
|
|
41179
|
-
this.stateMachine = new state_machine_1.StateMachine('stopped');
|
|
41180
|
-
this.on('task:stopped', () => {
|
|
41181
|
-
this.forkProcess?.kill();
|
|
41182
|
-
this.forkProcess = undefined;
|
|
41183
|
-
this.stateMachine.changeState('stopped');
|
|
41184
|
-
});
|
|
41185
|
-
this.on('task:destroyed', () => {
|
|
41186
|
-
this.forkProcess?.kill();
|
|
41187
|
-
this.forkProcess = undefined;
|
|
41188
|
-
this.stateMachine.changeState('destroyed');
|
|
41189
|
-
});
|
|
41190
|
-
}
|
|
41191
|
-
getNextRun() {
|
|
41192
|
-
if (this.stateMachine.state !== 'stopped') {
|
|
41193
|
-
const timeMatcher = new time_matcher_1.TimeMatcher(this.cronExpression, this.options?.timezone);
|
|
41194
|
-
return timeMatcher.getNextMatch(new Date());
|
|
41195
|
-
}
|
|
41196
|
-
return null;
|
|
41197
|
-
}
|
|
41198
|
-
start() {
|
|
41199
|
-
return new Promise((resolve, reject) => {
|
|
41200
|
-
if (this.forkProcess) {
|
|
41201
|
-
return resolve(undefined);
|
|
41202
|
-
}
|
|
41203
|
-
const timeout = setTimeout(() => {
|
|
41204
|
-
reject(new Error('Start operation timed out'));
|
|
41205
|
-
}, 5000);
|
|
41206
|
-
try {
|
|
41207
|
-
this.forkProcess = (0, child_process_1.fork)(daemonPath);
|
|
41208
|
-
this.forkProcess.on('error', (err) => {
|
|
41209
|
-
clearTimeout(timeout);
|
|
41210
|
-
reject(new Error(`Error on daemon: ${err.message}`));
|
|
41211
|
-
});
|
|
41212
|
-
this.forkProcess.on('exit', (code, signal) => {
|
|
41213
|
-
if (code !== 0 && signal !== 'SIGTERM') {
|
|
41214
|
-
const erro = new Error(`node-cron daemon exited with code ${code || signal}`);
|
|
41215
|
-
logger_1.default.error(erro);
|
|
41216
|
-
clearTimeout(timeout);
|
|
41217
|
-
reject(erro);
|
|
41218
|
-
}
|
|
41219
|
-
});
|
|
41220
|
-
this.forkProcess.on('message', (message) => {
|
|
41221
|
-
if (message.jsonError) {
|
|
41222
|
-
if (message.context?.execution) {
|
|
41223
|
-
message.context.execution.error = deserializeError(message.jsonError);
|
|
41224
|
-
delete message.jsonError;
|
|
41225
|
-
}
|
|
41226
|
-
}
|
|
41227
|
-
if (message.context?.task?.state) {
|
|
41228
|
-
this.stateMachine.changeState(message.context?.task?.state);
|
|
41229
|
-
}
|
|
41230
|
-
if (message.context) {
|
|
41231
|
-
const execution = message.context?.execution;
|
|
41232
|
-
delete execution?.hasError;
|
|
41233
|
-
const context = this.createContext(new Date(message.context.date), execution);
|
|
41234
|
-
this.emitter.emit(message.event, context);
|
|
41235
|
-
}
|
|
41236
|
-
});
|
|
41237
|
-
this.once('task:started', () => {
|
|
41238
|
-
this.stateMachine.changeState('idle');
|
|
41239
|
-
clearTimeout(timeout);
|
|
41240
|
-
resolve(undefined);
|
|
41241
|
-
});
|
|
41242
|
-
this.forkProcess.send({
|
|
41243
|
-
command: 'task:start',
|
|
41244
|
-
path: this.taskPath,
|
|
41245
|
-
cron: this.cronExpression,
|
|
41246
|
-
options: this.options
|
|
41247
|
-
});
|
|
41248
|
-
}
|
|
41249
|
-
catch (error) {
|
|
41250
|
-
reject(error);
|
|
41251
|
-
}
|
|
41252
|
-
});
|
|
41253
|
-
}
|
|
41254
|
-
stop() {
|
|
41255
|
-
return new Promise((resolve, reject) => {
|
|
41256
|
-
if (!this.forkProcess) {
|
|
41257
|
-
return resolve(undefined);
|
|
41258
|
-
}
|
|
41259
|
-
const timeoutId = setTimeout(() => {
|
|
41260
|
-
clearTimeout(timeoutId);
|
|
41261
|
-
reject(new Error('Stop operation timed out'));
|
|
41262
|
-
}, 5000);
|
|
41263
|
-
const cleanupAndResolve = () => {
|
|
41264
|
-
clearTimeout(timeoutId);
|
|
41265
|
-
this.off('task:stopped', onStopped);
|
|
41266
|
-
this.forkProcess = undefined;
|
|
41267
|
-
resolve(undefined);
|
|
41268
|
-
};
|
|
41269
|
-
const onStopped = () => {
|
|
41270
|
-
cleanupAndResolve();
|
|
41271
|
-
};
|
|
41272
|
-
this.once('task:stopped', onStopped);
|
|
41273
|
-
this.forkProcess.send({
|
|
41274
|
-
command: 'task:stop'
|
|
41275
|
-
});
|
|
41276
|
-
});
|
|
41277
|
-
}
|
|
41278
|
-
getStatus() {
|
|
41279
|
-
return this.stateMachine.state;
|
|
41280
|
-
}
|
|
41281
|
-
destroy() {
|
|
41282
|
-
return new Promise((resolve, reject) => {
|
|
41283
|
-
if (!this.forkProcess) {
|
|
41284
|
-
return resolve(undefined);
|
|
41285
|
-
}
|
|
41286
|
-
const timeoutId = setTimeout(() => {
|
|
41287
|
-
clearTimeout(timeoutId);
|
|
41288
|
-
reject(new Error('Destroy operation timed out'));
|
|
41289
|
-
}, 5000);
|
|
41290
|
-
const onDestroy = () => {
|
|
41291
|
-
clearTimeout(timeoutId);
|
|
41292
|
-
this.off('task:destroyed', onDestroy);
|
|
41293
|
-
resolve(undefined);
|
|
41294
|
-
};
|
|
41295
|
-
this.once('task:destroyed', onDestroy);
|
|
41296
|
-
this.forkProcess.send({
|
|
41297
|
-
command: 'task:destroy'
|
|
41298
|
-
});
|
|
41299
|
-
});
|
|
41300
|
-
}
|
|
41301
|
-
execute() {
|
|
41302
|
-
return new Promise((resolve, reject) => {
|
|
41303
|
-
if (!this.forkProcess) {
|
|
41304
|
-
return reject(new Error('Cannot execute background task because it hasn\'t been started yet. Please initialize the task using the start() method before attempting to execute it.'));
|
|
41305
|
-
}
|
|
41306
|
-
const timeoutId = setTimeout(() => {
|
|
41307
|
-
cleanupListeners();
|
|
41308
|
-
reject(new Error('Execution timeout exceeded'));
|
|
41309
|
-
}, 5000);
|
|
41310
|
-
const cleanupListeners = () => {
|
|
41311
|
-
clearTimeout(timeoutId);
|
|
41312
|
-
this.off('execution:finished', onFinished);
|
|
41313
|
-
this.off('execution:failed', onFail);
|
|
41314
|
-
};
|
|
41315
|
-
const onFinished = (context) => {
|
|
41316
|
-
cleanupListeners();
|
|
41317
|
-
resolve(context.execution?.result);
|
|
41318
|
-
};
|
|
41319
|
-
const onFail = (context) => {
|
|
41320
|
-
cleanupListeners();
|
|
41321
|
-
reject(context.execution?.error || new Error('Execution failed without specific error'));
|
|
41322
|
-
};
|
|
41323
|
-
this.once('execution:finished', onFinished);
|
|
41324
|
-
this.once('execution:failed', onFail);
|
|
41325
|
-
this.forkProcess.send({
|
|
41326
|
-
command: 'task:execute'
|
|
41327
|
-
});
|
|
41328
|
-
});
|
|
41329
|
-
}
|
|
41330
|
-
on(event, fun) {
|
|
41331
|
-
this.emitter.on(event, fun);
|
|
41332
|
-
}
|
|
41333
|
-
off(event, fun) {
|
|
41334
|
-
this.emitter.off(event, fun);
|
|
41335
|
-
}
|
|
41336
|
-
once(event, fun) {
|
|
41337
|
-
this.emitter.once(event, fun);
|
|
41338
|
-
}
|
|
41339
|
-
createContext(executionDate, execution) {
|
|
41340
|
-
const localTime = new localized_time_1.LocalizedTime(executionDate, this.options?.timezone);
|
|
41341
|
-
const ctx = {
|
|
41342
|
-
date: localTime.toDate(),
|
|
41343
|
-
dateLocalIso: localTime.toISO(),
|
|
41344
|
-
triggeredAt: new Date(),
|
|
41345
|
-
task: this,
|
|
41346
|
-
execution: execution
|
|
41347
|
-
};
|
|
41348
|
-
return ctx;
|
|
41349
|
-
}
|
|
41350
|
-
}
|
|
41351
|
-
function deserializeError(str) {
|
|
41352
|
-
const data = JSON.parse(str);
|
|
41353
|
-
const Err = globalThis[data.name] || Error;
|
|
41354
|
-
const err = new Err(data.message);
|
|
41355
|
-
if (data.stack) {
|
|
41356
|
-
err.stack = data.stack;
|
|
41357
|
-
}
|
|
41358
|
-
Object.keys(data).forEach(key => {
|
|
41359
|
-
if (!['name', 'message', 'stack'].includes(key)) {
|
|
41360
|
-
err[key] = data[key];
|
|
41361
|
-
}
|
|
41362
|
-
});
|
|
41363
|
-
return err;
|
|
41364
|
-
}
|
|
41365
|
-
backgroundScheduledTask.default = BackgroundScheduledTask;
|
|
41366
|
-
|
|
41367
|
-
return backgroundScheduledTask;
|
|
41368
|
-
}
|
|
41369
|
-
|
|
41370
|
-
var hasRequiredNodeCron;
|
|
41371
|
-
|
|
41372
|
-
function requireNodeCron () {
|
|
41373
|
-
if (hasRequiredNodeCron) return nodeCron$2;
|
|
41374
|
-
hasRequiredNodeCron = 1;
|
|
41375
|
-
(function (exports) {
|
|
41376
|
-
var __importDefault = (nodeCron$2 && nodeCron$2.__importDefault) || function (mod) {
|
|
41377
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
41378
|
-
};
|
|
41379
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
41380
|
-
exports.nodeCron = exports.getTask = exports.getTasks = void 0;
|
|
41381
|
-
exports.schedule = schedule;
|
|
41382
|
-
exports.createTask = createTask;
|
|
41383
|
-
exports.solvePath = solvePath;
|
|
41384
|
-
exports.validate = validate;
|
|
41385
|
-
const inline_scheduled_task_1 = requireInlineScheduledTask();
|
|
41386
|
-
const task_registry_1 = requireTaskRegistry();
|
|
41387
|
-
const pattern_validation_1 = __importDefault(requirePatternValidation());
|
|
41388
|
-
const background_scheduled_task_1 = __importDefault(requireBackgroundScheduledTask());
|
|
41389
|
-
const path_1 = __importDefault(path$1);
|
|
41390
|
-
const url_1 = require$$5;
|
|
41391
|
-
const registry = new task_registry_1.TaskRegistry();
|
|
41392
|
-
function schedule(expression, func, options) {
|
|
41393
|
-
const task = createTask(expression, func, options);
|
|
41394
|
-
task.start();
|
|
41395
|
-
return task;
|
|
41396
|
-
}
|
|
41397
|
-
function createTask(expression, func, options) {
|
|
41398
|
-
let task;
|
|
41399
|
-
if (func instanceof Function) {
|
|
41400
|
-
task = new inline_scheduled_task_1.InlineScheduledTask(expression, func, options);
|
|
41401
|
-
}
|
|
41402
|
-
else {
|
|
41403
|
-
const taskPath = solvePath(func);
|
|
41404
|
-
task = new background_scheduled_task_1.default(expression, taskPath, options);
|
|
41405
|
-
}
|
|
41406
|
-
registry.add(task);
|
|
41407
|
-
return task;
|
|
41408
|
-
}
|
|
41409
|
-
function solvePath(filePath) {
|
|
41410
|
-
if (path_1.default.isAbsolute(filePath))
|
|
41411
|
-
return (0, url_1.pathToFileURL)(filePath).href;
|
|
41412
|
-
if (filePath.startsWith('file://'))
|
|
41413
|
-
return filePath;
|
|
41414
|
-
const stackLines = new Error().stack?.split('\n');
|
|
41415
|
-
if (stackLines) {
|
|
41416
|
-
stackLines?.shift();
|
|
41417
|
-
const callerLine = stackLines?.find((line) => { return line.indexOf(__filename) === -1; });
|
|
41418
|
-
const match = callerLine?.match(/(file:\/\/)?(((\/?)(\w:))?([/\\].+)):\d+:\d+/);
|
|
41419
|
-
if (match) {
|
|
41420
|
-
const dir = `${match[5] ?? ""}${path_1.default.dirname(match[6])}`;
|
|
41421
|
-
return (0, url_1.pathToFileURL)(path_1.default.resolve(dir, filePath)).href;
|
|
41422
|
-
}
|
|
41423
|
-
}
|
|
41424
|
-
throw new Error(`Could not locate task file ${filePath}`);
|
|
41425
|
-
}
|
|
41426
|
-
function validate(expression) {
|
|
41427
|
-
try {
|
|
41428
|
-
(0, pattern_validation_1.default)(expression);
|
|
41429
|
-
return true;
|
|
41430
|
-
}
|
|
41431
|
-
catch (e) {
|
|
41432
|
-
return false;
|
|
41433
|
-
}
|
|
41434
|
-
}
|
|
41435
|
-
exports.getTasks = registry.all;
|
|
41436
|
-
exports.getTask = registry.get;
|
|
41437
|
-
exports.nodeCron = {
|
|
41438
|
-
schedule,
|
|
41439
|
-
createTask,
|
|
41440
|
-
validate,
|
|
41441
|
-
getTasks: exports.getTasks,
|
|
41442
|
-
getTask: exports.getTask,
|
|
41443
|
-
};
|
|
41444
|
-
exports.default = exports.nodeCron;
|
|
41445
|
-
|
|
41446
|
-
} (nodeCron$2));
|
|
41447
|
-
return nodeCron$2;
|
|
41448
|
-
}
|
|
41449
|
-
|
|
41450
|
-
var nodeCronExports = requireNodeCron();
|
|
41451
|
-
var nodeCron = /*@__PURE__*/getDefaultExportFromCjs(nodeCronExports);
|
|
41452
|
-
|
|
41453
|
-
var nodeCron$1 = /*#__PURE__*/_mergeNamespaces({
|
|
41454
|
-
__proto__: null,
|
|
41455
|
-
default: nodeCron
|
|
41456
|
-
}, [nodeCronExports]);
|
|
41457
|
-
|
|
41458
37828
|
function silhouetteScore(vectors, assignments, centroids, distanceFn = euclideanDistance) {
|
|
41459
37829
|
const k = centroids.length;
|
|
41460
37830
|
const n = vectors.length;
|