s3db.js 12.0.0 → 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 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 http = require('http');
9
- var http2 = require('http2');
10
- var require$$3 = require('stream');
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,9 +33,6 @@ 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 require$$0 = require('node:crypto');
35
- var require$$1 = require('child_process');
36
- var require$$5 = require('url');
37
36
 
38
37
  function _interopNamespaceDefault(e) {
39
38
  var n = Object.create(null);
@@ -52,21 +51,6 @@ function _interopNamespaceDefault(e) {
52
51
  return Object.freeze(n);
53
52
  }
54
53
 
55
- function _mergeNamespaces(n, m) {
56
- m.forEach(function (e) {
57
- e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
58
- if (k !== 'default' && !(k in n)) {
59
- var d = Object.getOwnPropertyDescriptor(e, k);
60
- Object.defineProperty(n, k, d.get ? d : {
61
- enumerable: true,
62
- get: function () { return e[k]; }
63
- });
64
- }
65
- });
66
- });
67
- return Object.freeze(n);
68
- }
69
-
70
54
  var actualFS__namespace = /*#__PURE__*/_interopNamespaceDefault(actualFS);
71
55
 
72
56
  const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
@@ -1986,44 +1970,31 @@ class PluginStorage {
1986
1970
  * @returns {Promise<boolean>} True if extended, false if not found or no TTL
1987
1971
  */
1988
1972
  async touch(key, additionalSeconds) {
1989
- const [ok, err, response] = await tryFn(() => this.client.getObject(key));
1973
+ const [ok, err, response] = await tryFn(() => this.client.headObject(key));
1990
1974
  if (!ok) {
1991
1975
  return false;
1992
1976
  }
1993
1977
  const metadata = response.Metadata || {};
1994
1978
  const parsedMetadata = this._parseMetadataValues(metadata);
1995
- let data = parsedMetadata;
1996
- if (response.Body) {
1997
- const [ok2, err2, result] = await tryFn(async () => {
1998
- const bodyContent = await response.Body.transformToString();
1999
- if (bodyContent && bodyContent.trim()) {
2000
- const body = JSON.parse(bodyContent);
2001
- return { ...parsedMetadata, ...body };
2002
- }
2003
- return parsedMetadata;
2004
- });
2005
- if (!ok2) {
2006
- return false;
2007
- }
2008
- data = result;
2009
- }
2010
- const expiresAt = data._expiresat || data._expiresAt;
1979
+ const expiresAt = parsedMetadata._expiresat || parsedMetadata._expiresAt;
2011
1980
  if (!expiresAt) {
2012
1981
  return false;
2013
1982
  }
2014
- data._expiresAt = expiresAt + additionalSeconds * 1e3;
2015
- delete data._expiresat;
2016
- const { metadata: newMetadata, body: newBody } = this._applyBehavior(data, "body-overflow");
2017
- const putParams = {
2018
- key,
2019
- metadata: newMetadata,
2020
- contentType: "application/json"
2021
- };
2022
- if (newBody !== null) {
2023
- putParams.body = JSON.stringify(newBody);
2024
- }
2025
- const [putOk] = await tryFn(() => this.client.putObject(putParams));
2026
- return putOk;
1983
+ parsedMetadata._expiresAt = expiresAt + additionalSeconds * 1e3;
1984
+ delete parsedMetadata._expiresat;
1985
+ const encodedMetadata = {};
1986
+ for (const [metaKey, metaValue] of Object.entries(parsedMetadata)) {
1987
+ const { encoded } = metadataEncode(metaValue);
1988
+ encodedMetadata[metaKey] = encoded;
1989
+ }
1990
+ const [copyOk] = await tryFn(() => this.client.copyObject({
1991
+ from: key,
1992
+ to: key,
1993
+ metadata: encodedMetadata,
1994
+ metadataDirective: "REPLACE",
1995
+ contentType: response.ContentType || "application/json"
1996
+ }));
1997
+ return copyOk;
2027
1998
  }
2028
1999
  /**
2029
2000
  * Delete a single object
@@ -2158,12 +2129,41 @@ class PluginStorage {
2158
2129
  /**
2159
2130
  * Increment a counter value
2160
2131
  *
2132
+ * Optimization: Uses HEAD + COPY for existing counters to avoid body transfer.
2133
+ * Falls back to GET + PUT for non-existent counters or those with additional data.
2134
+ *
2161
2135
  * @param {string} key - S3 key
2162
2136
  * @param {number} amount - Amount to increment (default: 1)
2163
2137
  * @param {Object} options - Options (e.g., ttl)
2164
2138
  * @returns {Promise<number>} New value
2165
2139
  */
2166
2140
  async increment(key, amount = 1, options = {}) {
2141
+ const [headOk, headErr, headResponse] = await tryFn(() => this.client.headObject(key));
2142
+ if (headOk && headResponse.Metadata) {
2143
+ const metadata = headResponse.Metadata || {};
2144
+ const parsedMetadata = this._parseMetadataValues(metadata);
2145
+ const currentValue = parsedMetadata.value || 0;
2146
+ const newValue = currentValue + amount;
2147
+ parsedMetadata.value = newValue;
2148
+ if (options.ttl) {
2149
+ parsedMetadata._expiresAt = Date.now() + options.ttl * 1e3;
2150
+ }
2151
+ const encodedMetadata = {};
2152
+ for (const [metaKey, metaValue] of Object.entries(parsedMetadata)) {
2153
+ const { encoded } = metadataEncode(metaValue);
2154
+ encodedMetadata[metaKey] = encoded;
2155
+ }
2156
+ const [copyOk] = await tryFn(() => this.client.copyObject({
2157
+ from: key,
2158
+ to: key,
2159
+ metadata: encodedMetadata,
2160
+ metadataDirective: "REPLACE",
2161
+ contentType: headResponse.ContentType || "application/json"
2162
+ }));
2163
+ if (copyOk) {
2164
+ return newValue;
2165
+ }
2166
+ }
2167
2167
  const data = await this.get(key);
2168
2168
  const value = (data?.value || 0) + amount;
2169
2169
  await this.set(key, { value }, options);
@@ -2383,6 +2383,9 @@ class Plugin extends EventEmitter {
2383
2383
  * - Pode modificar argumentos/resultados.
2384
2384
  */
2385
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
+ }
2386
2389
  if (!resource._pluginMiddlewares) {
2387
2390
  resource._pluginMiddlewares = {};
2388
2391
  }
@@ -2474,2291 +2477,6 @@ const PluginObject = {
2474
2477
  }
2475
2478
  };
2476
2479
 
2477
- // src/compose.ts
2478
- var compose = (middleware, onError, onNotFound) => {
2479
- return (context, next) => {
2480
- let index = -1;
2481
- return dispatch(0);
2482
- async function dispatch(i) {
2483
- if (i <= index) {
2484
- throw new Error("next() called multiple times");
2485
- }
2486
- index = i;
2487
- let res;
2488
- let isError = false;
2489
- let handler;
2490
- if (middleware[i]) {
2491
- handler = middleware[i][0][0];
2492
- context.req.routeIndex = i;
2493
- } else {
2494
- handler = i === middleware.length && next || void 0;
2495
- }
2496
- if (handler) {
2497
- try {
2498
- res = await handler(context, () => dispatch(i + 1));
2499
- } catch (err) {
2500
- if (err instanceof Error && onError) {
2501
- context.error = err;
2502
- res = await onError(err, context);
2503
- isError = true;
2504
- } else {
2505
- throw err;
2506
- }
2507
- }
2508
- } else {
2509
- if (context.finalized === false && onNotFound) {
2510
- res = await onNotFound(context);
2511
- }
2512
- }
2513
- if (res && (context.finalized === false || isError)) {
2514
- context.res = res;
2515
- }
2516
- return context;
2517
- }
2518
- };
2519
- };
2520
-
2521
- // src/request/constants.ts
2522
- var GET_MATCH_RESULT = Symbol();
2523
-
2524
- // src/utils/body.ts
2525
- var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
2526
- const { all = false, dot = false } = options;
2527
- const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
2528
- const contentType = headers.get("Content-Type");
2529
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
2530
- return parseFormData(request, { all, dot });
2531
- }
2532
- return {};
2533
- };
2534
- async function parseFormData(request, options) {
2535
- const formData = await request.formData();
2536
- if (formData) {
2537
- return convertFormDataToBodyData(formData, options);
2538
- }
2539
- return {};
2540
- }
2541
- function convertFormDataToBodyData(formData, options) {
2542
- const form = /* @__PURE__ */ Object.create(null);
2543
- formData.forEach((value, key) => {
2544
- const shouldParseAllValues = options.all || key.endsWith("[]");
2545
- if (!shouldParseAllValues) {
2546
- form[key] = value;
2547
- } else {
2548
- handleParsingAllValues(form, key, value);
2549
- }
2550
- });
2551
- if (options.dot) {
2552
- Object.entries(form).forEach(([key, value]) => {
2553
- const shouldParseDotValues = key.includes(".");
2554
- if (shouldParseDotValues) {
2555
- handleParsingNestedValues(form, key, value);
2556
- delete form[key];
2557
- }
2558
- });
2559
- }
2560
- return form;
2561
- }
2562
- var handleParsingAllValues = (form, key, value) => {
2563
- if (form[key] !== void 0) {
2564
- if (Array.isArray(form[key])) {
2565
- form[key].push(value);
2566
- } else {
2567
- form[key] = [form[key], value];
2568
- }
2569
- } else {
2570
- if (!key.endsWith("[]")) {
2571
- form[key] = value;
2572
- } else {
2573
- form[key] = [value];
2574
- }
2575
- }
2576
- };
2577
- var handleParsingNestedValues = (form, key, value) => {
2578
- let nestedForm = form;
2579
- const keys = key.split(".");
2580
- keys.forEach((key2, index) => {
2581
- if (index === keys.length - 1) {
2582
- nestedForm[key2] = value;
2583
- } else {
2584
- if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
2585
- nestedForm[key2] = /* @__PURE__ */ Object.create(null);
2586
- }
2587
- nestedForm = nestedForm[key2];
2588
- }
2589
- });
2590
- };
2591
-
2592
- // src/utils/url.ts
2593
- var splitPath = (path) => {
2594
- const paths = path.split("/");
2595
- if (paths[0] === "") {
2596
- paths.shift();
2597
- }
2598
- return paths;
2599
- };
2600
- var splitRoutingPath = (routePath) => {
2601
- const { groups, path } = extractGroupsFromPath(routePath);
2602
- const paths = splitPath(path);
2603
- return replaceGroupMarks(paths, groups);
2604
- };
2605
- var extractGroupsFromPath = (path) => {
2606
- const groups = [];
2607
- path = path.replace(/\{[^}]+\}/g, (match, index) => {
2608
- const mark = `@${index}`;
2609
- groups.push([mark, match]);
2610
- return mark;
2611
- });
2612
- return { groups, path };
2613
- };
2614
- var replaceGroupMarks = (paths, groups) => {
2615
- for (let i = groups.length - 1; i >= 0; i--) {
2616
- const [mark] = groups[i];
2617
- for (let j = paths.length - 1; j >= 0; j--) {
2618
- if (paths[j].includes(mark)) {
2619
- paths[j] = paths[j].replace(mark, groups[i][1]);
2620
- break;
2621
- }
2622
- }
2623
- }
2624
- return paths;
2625
- };
2626
- var patternCache = {};
2627
- var getPattern = (label, next) => {
2628
- if (label === "*") {
2629
- return "*";
2630
- }
2631
- const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2632
- if (match) {
2633
- const cacheKey = `${label}#${next}`;
2634
- if (!patternCache[cacheKey]) {
2635
- if (match[2]) {
2636
- patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
2637
- } else {
2638
- patternCache[cacheKey] = [label, match[1], true];
2639
- }
2640
- }
2641
- return patternCache[cacheKey];
2642
- }
2643
- return null;
2644
- };
2645
- var tryDecode = (str, decoder) => {
2646
- try {
2647
- return decoder(str);
2648
- } catch {
2649
- return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
2650
- try {
2651
- return decoder(match);
2652
- } catch {
2653
- return match;
2654
- }
2655
- });
2656
- }
2657
- };
2658
- var tryDecodeURI = (str) => tryDecode(str, decodeURI);
2659
- var getPath = (request) => {
2660
- const url = request.url;
2661
- const start = url.indexOf("/", url.indexOf(":") + 4);
2662
- let i = start;
2663
- for (; i < url.length; i++) {
2664
- const charCode = url.charCodeAt(i);
2665
- if (charCode === 37) {
2666
- const queryIndex = url.indexOf("?", i);
2667
- const path = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
2668
- return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
2669
- } else if (charCode === 63) {
2670
- break;
2671
- }
2672
- }
2673
- return url.slice(start, i);
2674
- };
2675
- var getPathNoStrict = (request) => {
2676
- const result = getPath(request);
2677
- return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
2678
- };
2679
- var mergePath = (base, sub, ...rest) => {
2680
- if (rest.length) {
2681
- sub = mergePath(sub, ...rest);
2682
- }
2683
- return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
2684
- };
2685
- var checkOptionalParameter = (path) => {
2686
- if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
2687
- return null;
2688
- }
2689
- const segments = path.split("/");
2690
- const results = [];
2691
- let basePath = "";
2692
- segments.forEach((segment) => {
2693
- if (segment !== "" && !/\:/.test(segment)) {
2694
- basePath += "/" + segment;
2695
- } else if (/\:/.test(segment)) {
2696
- if (/\?/.test(segment)) {
2697
- if (results.length === 0 && basePath === "") {
2698
- results.push("/");
2699
- } else {
2700
- results.push(basePath);
2701
- }
2702
- const optionalSegment = segment.replace("?", "");
2703
- basePath += "/" + optionalSegment;
2704
- results.push(basePath);
2705
- } else {
2706
- basePath += "/" + segment;
2707
- }
2708
- }
2709
- });
2710
- return results.filter((v, i, a) => a.indexOf(v) === i);
2711
- };
2712
- var _decodeURI = (value) => {
2713
- if (!/[%+]/.test(value)) {
2714
- return value;
2715
- }
2716
- if (value.indexOf("+") !== -1) {
2717
- value = value.replace(/\+/g, " ");
2718
- }
2719
- return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
2720
- };
2721
- var _getQueryParam = (url, key, multiple) => {
2722
- let encoded;
2723
- if (!multiple && key && !/[%+]/.test(key)) {
2724
- let keyIndex2 = url.indexOf(`?${key}`, 8);
2725
- if (keyIndex2 === -1) {
2726
- keyIndex2 = url.indexOf(`&${key}`, 8);
2727
- }
2728
- while (keyIndex2 !== -1) {
2729
- const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
2730
- if (trailingKeyCode === 61) {
2731
- const valueIndex = keyIndex2 + key.length + 2;
2732
- const endIndex = url.indexOf("&", valueIndex);
2733
- return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
2734
- } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
2735
- return "";
2736
- }
2737
- keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
2738
- }
2739
- encoded = /[%+]/.test(url);
2740
- if (!encoded) {
2741
- return void 0;
2742
- }
2743
- }
2744
- const results = {};
2745
- encoded ??= /[%+]/.test(url);
2746
- let keyIndex = url.indexOf("?", 8);
2747
- while (keyIndex !== -1) {
2748
- const nextKeyIndex = url.indexOf("&", keyIndex + 1);
2749
- let valueIndex = url.indexOf("=", keyIndex);
2750
- if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
2751
- valueIndex = -1;
2752
- }
2753
- let name = url.slice(
2754
- keyIndex + 1,
2755
- valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
2756
- );
2757
- if (encoded) {
2758
- name = _decodeURI(name);
2759
- }
2760
- keyIndex = nextKeyIndex;
2761
- if (name === "") {
2762
- continue;
2763
- }
2764
- let value;
2765
- if (valueIndex === -1) {
2766
- value = "";
2767
- } else {
2768
- value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
2769
- if (encoded) {
2770
- value = _decodeURI(value);
2771
- }
2772
- }
2773
- if (multiple) {
2774
- if (!(results[name] && Array.isArray(results[name]))) {
2775
- results[name] = [];
2776
- }
2777
- results[name].push(value);
2778
- } else {
2779
- results[name] ??= value;
2780
- }
2781
- }
2782
- return key ? results[key] : results;
2783
- };
2784
- var getQueryParam = _getQueryParam;
2785
- var getQueryParams = (url, key) => {
2786
- return _getQueryParam(url, key, true);
2787
- };
2788
- var decodeURIComponent_ = decodeURIComponent;
2789
-
2790
- // src/request.ts
2791
- var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
2792
- var HonoRequest = class {
2793
- raw;
2794
- #validatedData;
2795
- #matchResult;
2796
- routeIndex = 0;
2797
- path;
2798
- bodyCache = {};
2799
- constructor(request, path = "/", matchResult = [[]]) {
2800
- this.raw = request;
2801
- this.path = path;
2802
- this.#matchResult = matchResult;
2803
- this.#validatedData = {};
2804
- }
2805
- param(key) {
2806
- return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
2807
- }
2808
- #getDecodedParam(key) {
2809
- const paramKey = this.#matchResult[0][this.routeIndex][1][key];
2810
- const param = this.#getParamValue(paramKey);
2811
- return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
2812
- }
2813
- #getAllDecodedParams() {
2814
- const decoded = {};
2815
- const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
2816
- for (const key of keys) {
2817
- const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
2818
- if (value !== void 0) {
2819
- decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
2820
- }
2821
- }
2822
- return decoded;
2823
- }
2824
- #getParamValue(paramKey) {
2825
- return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
2826
- }
2827
- query(key) {
2828
- return getQueryParam(this.url, key);
2829
- }
2830
- queries(key) {
2831
- return getQueryParams(this.url, key);
2832
- }
2833
- header(name) {
2834
- if (name) {
2835
- return this.raw.headers.get(name) ?? void 0;
2836
- }
2837
- const headerData = {};
2838
- this.raw.headers.forEach((value, key) => {
2839
- headerData[key] = value;
2840
- });
2841
- return headerData;
2842
- }
2843
- async parseBody(options) {
2844
- return this.bodyCache.parsedBody ??= await parseBody(this, options);
2845
- }
2846
- #cachedBody = (key) => {
2847
- const { bodyCache, raw } = this;
2848
- const cachedBody = bodyCache[key];
2849
- if (cachedBody) {
2850
- return cachedBody;
2851
- }
2852
- const anyCachedKey = Object.keys(bodyCache)[0];
2853
- if (anyCachedKey) {
2854
- return bodyCache[anyCachedKey].then((body) => {
2855
- if (anyCachedKey === "json") {
2856
- body = JSON.stringify(body);
2857
- }
2858
- return new Response(body)[key]();
2859
- });
2860
- }
2861
- return bodyCache[key] = raw[key]();
2862
- };
2863
- json() {
2864
- return this.#cachedBody("text").then((text) => JSON.parse(text));
2865
- }
2866
- text() {
2867
- return this.#cachedBody("text");
2868
- }
2869
- arrayBuffer() {
2870
- return this.#cachedBody("arrayBuffer");
2871
- }
2872
- blob() {
2873
- return this.#cachedBody("blob");
2874
- }
2875
- formData() {
2876
- return this.#cachedBody("formData");
2877
- }
2878
- addValidatedData(target, data) {
2879
- this.#validatedData[target] = data;
2880
- }
2881
- valid(target) {
2882
- return this.#validatedData[target];
2883
- }
2884
- get url() {
2885
- return this.raw.url;
2886
- }
2887
- get method() {
2888
- return this.raw.method;
2889
- }
2890
- get [GET_MATCH_RESULT]() {
2891
- return this.#matchResult;
2892
- }
2893
- get matchedRoutes() {
2894
- return this.#matchResult[0].map(([[, route]]) => route);
2895
- }
2896
- get routePath() {
2897
- return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
2898
- }
2899
- };
2900
-
2901
- // src/utils/html.ts
2902
- var HtmlEscapedCallbackPhase = {
2903
- Stringify: 1};
2904
- var raw = (value, callbacks) => {
2905
- const escapedString = new String(value);
2906
- escapedString.isEscaped = true;
2907
- escapedString.callbacks = callbacks;
2908
- return escapedString;
2909
- };
2910
- var escapeRe = /[&<>'"]/;
2911
- var stringBufferToString = async (buffer, callbacks) => {
2912
- let str = "";
2913
- callbacks ||= [];
2914
- const resolvedBuffer = await Promise.all(buffer);
2915
- for (let i = resolvedBuffer.length - 1; ; i--) {
2916
- str += resolvedBuffer[i];
2917
- i--;
2918
- if (i < 0) {
2919
- break;
2920
- }
2921
- let r = resolvedBuffer[i];
2922
- if (typeof r === "object") {
2923
- callbacks.push(...r.callbacks || []);
2924
- }
2925
- const isEscaped = r.isEscaped;
2926
- r = await (typeof r === "object" ? r.toString() : r);
2927
- if (typeof r === "object") {
2928
- callbacks.push(...r.callbacks || []);
2929
- }
2930
- if (r.isEscaped ?? isEscaped) {
2931
- str += r;
2932
- } else {
2933
- const buf = [str];
2934
- escapeToBuffer(r, buf);
2935
- str = buf[0];
2936
- }
2937
- }
2938
- return raw(str, callbacks);
2939
- };
2940
- var escapeToBuffer = (str, buffer) => {
2941
- const match = str.search(escapeRe);
2942
- if (match === -1) {
2943
- buffer[0] += str;
2944
- return;
2945
- }
2946
- let escape;
2947
- let index;
2948
- let lastIndex = 0;
2949
- for (index = match; index < str.length; index++) {
2950
- switch (str.charCodeAt(index)) {
2951
- case 34:
2952
- escape = "&quot;";
2953
- break;
2954
- case 39:
2955
- escape = "&#39;";
2956
- break;
2957
- case 38:
2958
- escape = "&amp;";
2959
- break;
2960
- case 60:
2961
- escape = "&lt;";
2962
- break;
2963
- case 62:
2964
- escape = "&gt;";
2965
- break;
2966
- default:
2967
- continue;
2968
- }
2969
- buffer[0] += str.substring(lastIndex, index) + escape;
2970
- lastIndex = index + 1;
2971
- }
2972
- buffer[0] += str.substring(lastIndex, index);
2973
- };
2974
- var resolveCallbackSync = (str) => {
2975
- const callbacks = str.callbacks;
2976
- if (!callbacks?.length) {
2977
- return str;
2978
- }
2979
- const buffer = [str];
2980
- const context = {};
2981
- callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));
2982
- return buffer[0];
2983
- };
2984
- var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
2985
- if (typeof str === "object" && !(str instanceof String)) {
2986
- if (!(str instanceof Promise)) {
2987
- str = str.toString();
2988
- }
2989
- if (str instanceof Promise) {
2990
- str = await str;
2991
- }
2992
- }
2993
- const callbacks = str.callbacks;
2994
- if (!callbacks?.length) {
2995
- return Promise.resolve(str);
2996
- }
2997
- if (buffer) {
2998
- buffer[0] += str;
2999
- } else {
3000
- buffer = [str];
3001
- }
3002
- const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
3003
- (res) => Promise.all(
3004
- res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
3005
- ).then(() => buffer[0])
3006
- );
3007
- {
3008
- return resStr;
3009
- }
3010
- };
3011
-
3012
- // src/context.ts
3013
- var TEXT_PLAIN = "text/plain; charset=UTF-8";
3014
- var setDefaultContentType = (contentType, headers) => {
3015
- return {
3016
- "Content-Type": contentType,
3017
- ...headers
3018
- };
3019
- };
3020
- var Context = class {
3021
- #rawRequest;
3022
- #req;
3023
- env = {};
3024
- #var;
3025
- finalized = false;
3026
- error;
3027
- #status;
3028
- #executionCtx;
3029
- #res;
3030
- #layout;
3031
- #renderer;
3032
- #notFoundHandler;
3033
- #preparedHeaders;
3034
- #matchResult;
3035
- #path;
3036
- constructor(req, options) {
3037
- this.#rawRequest = req;
3038
- if (options) {
3039
- this.#executionCtx = options.executionCtx;
3040
- this.env = options.env;
3041
- this.#notFoundHandler = options.notFoundHandler;
3042
- this.#path = options.path;
3043
- this.#matchResult = options.matchResult;
3044
- }
3045
- }
3046
- get req() {
3047
- this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
3048
- return this.#req;
3049
- }
3050
- get event() {
3051
- if (this.#executionCtx && "respondWith" in this.#executionCtx) {
3052
- return this.#executionCtx;
3053
- } else {
3054
- throw Error("This context has no FetchEvent");
3055
- }
3056
- }
3057
- get executionCtx() {
3058
- if (this.#executionCtx) {
3059
- return this.#executionCtx;
3060
- } else {
3061
- throw Error("This context has no ExecutionContext");
3062
- }
3063
- }
3064
- get res() {
3065
- return this.#res ||= new Response(null, {
3066
- headers: this.#preparedHeaders ??= new Headers()
3067
- });
3068
- }
3069
- set res(_res) {
3070
- if (this.#res && _res) {
3071
- _res = new Response(_res.body, _res);
3072
- for (const [k, v] of this.#res.headers.entries()) {
3073
- if (k === "content-type") {
3074
- continue;
3075
- }
3076
- if (k === "set-cookie") {
3077
- const cookies = this.#res.headers.getSetCookie();
3078
- _res.headers.delete("set-cookie");
3079
- for (const cookie of cookies) {
3080
- _res.headers.append("set-cookie", cookie);
3081
- }
3082
- } else {
3083
- _res.headers.set(k, v);
3084
- }
3085
- }
3086
- }
3087
- this.#res = _res;
3088
- this.finalized = true;
3089
- }
3090
- render = (...args) => {
3091
- this.#renderer ??= (content) => this.html(content);
3092
- return this.#renderer(...args);
3093
- };
3094
- setLayout = (layout) => this.#layout = layout;
3095
- getLayout = () => this.#layout;
3096
- setRenderer = (renderer) => {
3097
- this.#renderer = renderer;
3098
- };
3099
- header = (name, value, options) => {
3100
- if (this.finalized) {
3101
- this.#res = new Response(this.#res.body, this.#res);
3102
- }
3103
- const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
3104
- if (value === void 0) {
3105
- headers.delete(name);
3106
- } else if (options?.append) {
3107
- headers.append(name, value);
3108
- } else {
3109
- headers.set(name, value);
3110
- }
3111
- };
3112
- status = (status) => {
3113
- this.#status = status;
3114
- };
3115
- set = (key, value) => {
3116
- this.#var ??= /* @__PURE__ */ new Map();
3117
- this.#var.set(key, value);
3118
- };
3119
- get = (key) => {
3120
- return this.#var ? this.#var.get(key) : void 0;
3121
- };
3122
- get var() {
3123
- if (!this.#var) {
3124
- return {};
3125
- }
3126
- return Object.fromEntries(this.#var);
3127
- }
3128
- #newResponse(data, arg, headers) {
3129
- const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
3130
- if (typeof arg === "object" && "headers" in arg) {
3131
- const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
3132
- for (const [key, value] of argHeaders) {
3133
- if (key.toLowerCase() === "set-cookie") {
3134
- responseHeaders.append(key, value);
3135
- } else {
3136
- responseHeaders.set(key, value);
3137
- }
3138
- }
3139
- }
3140
- if (headers) {
3141
- for (const [k, v] of Object.entries(headers)) {
3142
- if (typeof v === "string") {
3143
- responseHeaders.set(k, v);
3144
- } else {
3145
- responseHeaders.delete(k);
3146
- for (const v2 of v) {
3147
- responseHeaders.append(k, v2);
3148
- }
3149
- }
3150
- }
3151
- }
3152
- const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
3153
- return new Response(data, { status, headers: responseHeaders });
3154
- }
3155
- newResponse = (...args) => this.#newResponse(...args);
3156
- body = (data, arg, headers) => this.#newResponse(data, arg, headers);
3157
- text = (text, arg, headers) => {
3158
- return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
3159
- text,
3160
- arg,
3161
- setDefaultContentType(TEXT_PLAIN, headers)
3162
- );
3163
- };
3164
- json = (object, arg, headers) => {
3165
- return this.#newResponse(
3166
- JSON.stringify(object),
3167
- arg,
3168
- setDefaultContentType("application/json", headers)
3169
- );
3170
- };
3171
- html = (html, arg, headers) => {
3172
- const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
3173
- return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
3174
- };
3175
- redirect = (location, status) => {
3176
- const locationString = String(location);
3177
- this.header(
3178
- "Location",
3179
- !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
3180
- );
3181
- return this.newResponse(null, status ?? 302);
3182
- };
3183
- notFound = () => {
3184
- this.#notFoundHandler ??= () => new Response();
3185
- return this.#notFoundHandler(this);
3186
- };
3187
- };
3188
-
3189
- // src/router.ts
3190
- var METHOD_NAME_ALL = "ALL";
3191
- var METHOD_NAME_ALL_LOWERCASE = "all";
3192
- var METHODS = ["get", "post", "put", "delete", "options", "patch"];
3193
- var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
3194
- var UnsupportedPathError = class extends Error {
3195
- };
3196
-
3197
- // src/utils/constants.ts
3198
- var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
3199
-
3200
- // src/hono-base.ts
3201
- var notFoundHandler = (c) => {
3202
- return c.text("404 Not Found", 404);
3203
- };
3204
- var errorHandler$1 = (err, c) => {
3205
- if ("getResponse" in err) {
3206
- const res = err.getResponse();
3207
- return c.newResponse(res.body, res);
3208
- }
3209
- console.error(err);
3210
- return c.text("Internal Server Error", 500);
3211
- };
3212
- var Hono$1 = class Hono {
3213
- get;
3214
- post;
3215
- put;
3216
- delete;
3217
- options;
3218
- patch;
3219
- all;
3220
- on;
3221
- use;
3222
- router;
3223
- getPath;
3224
- _basePath = "/";
3225
- #path = "/";
3226
- routes = [];
3227
- constructor(options = {}) {
3228
- const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
3229
- allMethods.forEach((method) => {
3230
- this[method] = (args1, ...args) => {
3231
- if (typeof args1 === "string") {
3232
- this.#path = args1;
3233
- } else {
3234
- this.#addRoute(method, this.#path, args1);
3235
- }
3236
- args.forEach((handler) => {
3237
- this.#addRoute(method, this.#path, handler);
3238
- });
3239
- return this;
3240
- };
3241
- });
3242
- this.on = (method, path, ...handlers) => {
3243
- for (const p of [path].flat()) {
3244
- this.#path = p;
3245
- for (const m of [method].flat()) {
3246
- handlers.map((handler) => {
3247
- this.#addRoute(m.toUpperCase(), this.#path, handler);
3248
- });
3249
- }
3250
- }
3251
- return this;
3252
- };
3253
- this.use = (arg1, ...handlers) => {
3254
- if (typeof arg1 === "string") {
3255
- this.#path = arg1;
3256
- } else {
3257
- this.#path = "*";
3258
- handlers.unshift(arg1);
3259
- }
3260
- handlers.forEach((handler) => {
3261
- this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
3262
- });
3263
- return this;
3264
- };
3265
- const { strict, ...optionsWithoutStrict } = options;
3266
- Object.assign(this, optionsWithoutStrict);
3267
- this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
3268
- }
3269
- #clone() {
3270
- const clone = new Hono$1({
3271
- router: this.router,
3272
- getPath: this.getPath
3273
- });
3274
- clone.errorHandler = this.errorHandler;
3275
- clone.#notFoundHandler = this.#notFoundHandler;
3276
- clone.routes = this.routes;
3277
- return clone;
3278
- }
3279
- #notFoundHandler = notFoundHandler;
3280
- errorHandler = errorHandler$1;
3281
- route(path, app) {
3282
- const subApp = this.basePath(path);
3283
- app.routes.map((r) => {
3284
- let handler;
3285
- if (app.errorHandler === errorHandler$1) {
3286
- handler = r.handler;
3287
- } else {
3288
- handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
3289
- handler[COMPOSED_HANDLER] = r.handler;
3290
- }
3291
- subApp.#addRoute(r.method, r.path, handler);
3292
- });
3293
- return this;
3294
- }
3295
- basePath(path) {
3296
- const subApp = this.#clone();
3297
- subApp._basePath = mergePath(this._basePath, path);
3298
- return subApp;
3299
- }
3300
- onError = (handler) => {
3301
- this.errorHandler = handler;
3302
- return this;
3303
- };
3304
- notFound = (handler) => {
3305
- this.#notFoundHandler = handler;
3306
- return this;
3307
- };
3308
- mount(path, applicationHandler, options) {
3309
- let replaceRequest;
3310
- let optionHandler;
3311
- if (options) {
3312
- if (typeof options === "function") {
3313
- optionHandler = options;
3314
- } else {
3315
- optionHandler = options.optionHandler;
3316
- if (options.replaceRequest === false) {
3317
- replaceRequest = (request) => request;
3318
- } else {
3319
- replaceRequest = options.replaceRequest;
3320
- }
3321
- }
3322
- }
3323
- const getOptions = optionHandler ? (c) => {
3324
- const options2 = optionHandler(c);
3325
- return Array.isArray(options2) ? options2 : [options2];
3326
- } : (c) => {
3327
- let executionContext = void 0;
3328
- try {
3329
- executionContext = c.executionCtx;
3330
- } catch {
3331
- }
3332
- return [c.env, executionContext];
3333
- };
3334
- replaceRequest ||= (() => {
3335
- const mergedPath = mergePath(this._basePath, path);
3336
- const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
3337
- return (request) => {
3338
- const url = new URL(request.url);
3339
- url.pathname = url.pathname.slice(pathPrefixLength) || "/";
3340
- return new Request(url, request);
3341
- };
3342
- })();
3343
- const handler = async (c, next) => {
3344
- const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
3345
- if (res) {
3346
- return res;
3347
- }
3348
- await next();
3349
- };
3350
- this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
3351
- return this;
3352
- }
3353
- #addRoute(method, path, handler) {
3354
- method = method.toUpperCase();
3355
- path = mergePath(this._basePath, path);
3356
- const r = { basePath: this._basePath, path, method, handler };
3357
- this.router.add(method, path, [handler, r]);
3358
- this.routes.push(r);
3359
- }
3360
- #handleError(err, c) {
3361
- if (err instanceof Error) {
3362
- return this.errorHandler(err, c);
3363
- }
3364
- throw err;
3365
- }
3366
- #dispatch(request, executionCtx, env, method) {
3367
- if (method === "HEAD") {
3368
- return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
3369
- }
3370
- const path = this.getPath(request, { env });
3371
- const matchResult = this.router.match(method, path);
3372
- const c = new Context(request, {
3373
- path,
3374
- matchResult,
3375
- env,
3376
- executionCtx,
3377
- notFoundHandler: this.#notFoundHandler
3378
- });
3379
- if (matchResult[0].length === 1) {
3380
- let res;
3381
- try {
3382
- res = matchResult[0][0][0][0](c, async () => {
3383
- c.res = await this.#notFoundHandler(c);
3384
- });
3385
- } catch (err) {
3386
- return this.#handleError(err, c);
3387
- }
3388
- return res instanceof Promise ? res.then(
3389
- (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
3390
- ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
3391
- }
3392
- const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
3393
- return (async () => {
3394
- try {
3395
- const context = await composed(c);
3396
- if (!context.finalized) {
3397
- throw new Error(
3398
- "Context is not finalized. Did you forget to return a Response object or `await next()`?"
3399
- );
3400
- }
3401
- return context.res;
3402
- } catch (err) {
3403
- return this.#handleError(err, c);
3404
- }
3405
- })();
3406
- }
3407
- fetch = (request, ...rest) => {
3408
- return this.#dispatch(request, rest[1], rest[0], request.method);
3409
- };
3410
- request = (input, requestInit, Env, executionCtx) => {
3411
- if (input instanceof Request) {
3412
- return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
3413
- }
3414
- input = input.toString();
3415
- return this.fetch(
3416
- new Request(
3417
- /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
3418
- requestInit
3419
- ),
3420
- Env,
3421
- executionCtx
3422
- );
3423
- };
3424
- fire = () => {
3425
- addEventListener("fetch", (event) => {
3426
- event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
3427
- });
3428
- };
3429
- };
3430
-
3431
- // src/router/reg-exp-router/matcher.ts
3432
- var emptyParam = [];
3433
- function match$1(method, path) {
3434
- const matchers = this.buildAllMatchers();
3435
- const match2 = (method2, path2) => {
3436
- const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
3437
- const staticMatch = matcher[2][path2];
3438
- if (staticMatch) {
3439
- return staticMatch;
3440
- }
3441
- const match3 = path2.match(matcher[0]);
3442
- if (!match3) {
3443
- return [[], emptyParam];
3444
- }
3445
- const index = match3.indexOf("", 1);
3446
- return [matcher[1][index], match3];
3447
- };
3448
- this.match = match2;
3449
- return match2(method, path);
3450
- }
3451
-
3452
- // src/router/reg-exp-router/node.ts
3453
- var LABEL_REG_EXP_STR = "[^/]+";
3454
- var ONLY_WILDCARD_REG_EXP_STR = ".*";
3455
- var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
3456
- var PATH_ERROR = Symbol();
3457
- var regExpMetaChars = new Set(".\\+*[^]$()");
3458
- function compareKey(a, b) {
3459
- if (a.length === 1) {
3460
- return b.length === 1 ? a < b ? -1 : 1 : -1;
3461
- }
3462
- if (b.length === 1) {
3463
- return 1;
3464
- }
3465
- if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
3466
- return 1;
3467
- } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
3468
- return -1;
3469
- }
3470
- if (a === LABEL_REG_EXP_STR) {
3471
- return 1;
3472
- } else if (b === LABEL_REG_EXP_STR) {
3473
- return -1;
3474
- }
3475
- return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
3476
- }
3477
- var Node$1 = class Node {
3478
- #index;
3479
- #varIndex;
3480
- #children = /* @__PURE__ */ Object.create(null);
3481
- insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
3482
- if (tokens.length === 0) {
3483
- if (this.#index !== void 0) {
3484
- throw PATH_ERROR;
3485
- }
3486
- if (pathErrorCheckOnly) {
3487
- return;
3488
- }
3489
- this.#index = index;
3490
- return;
3491
- }
3492
- const [token, ...restTokens] = tokens;
3493
- const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
3494
- let node;
3495
- if (pattern) {
3496
- const name = pattern[1];
3497
- let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
3498
- if (name && pattern[2]) {
3499
- if (regexpStr === ".*") {
3500
- throw PATH_ERROR;
3501
- }
3502
- regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
3503
- if (/\((?!\?:)/.test(regexpStr)) {
3504
- throw PATH_ERROR;
3505
- }
3506
- }
3507
- node = this.#children[regexpStr];
3508
- if (!node) {
3509
- if (Object.keys(this.#children).some(
3510
- (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
3511
- )) {
3512
- throw PATH_ERROR;
3513
- }
3514
- if (pathErrorCheckOnly) {
3515
- return;
3516
- }
3517
- node = this.#children[regexpStr] = new Node$1();
3518
- if (name !== "") {
3519
- node.#varIndex = context.varIndex++;
3520
- }
3521
- }
3522
- if (!pathErrorCheckOnly && name !== "") {
3523
- paramMap.push([name, node.#varIndex]);
3524
- }
3525
- } else {
3526
- node = this.#children[token];
3527
- if (!node) {
3528
- if (Object.keys(this.#children).some(
3529
- (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
3530
- )) {
3531
- throw PATH_ERROR;
3532
- }
3533
- if (pathErrorCheckOnly) {
3534
- return;
3535
- }
3536
- node = this.#children[token] = new Node$1();
3537
- }
3538
- }
3539
- node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
3540
- }
3541
- buildRegExpStr() {
3542
- const childKeys = Object.keys(this.#children).sort(compareKey);
3543
- const strList = childKeys.map((k) => {
3544
- const c = this.#children[k];
3545
- return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
3546
- });
3547
- if (typeof this.#index === "number") {
3548
- strList.unshift(`#${this.#index}`);
3549
- }
3550
- if (strList.length === 0) {
3551
- return "";
3552
- }
3553
- if (strList.length === 1) {
3554
- return strList[0];
3555
- }
3556
- return "(?:" + strList.join("|") + ")";
3557
- }
3558
- };
3559
-
3560
- // src/router/reg-exp-router/trie.ts
3561
- var Trie = class {
3562
- #context = { varIndex: 0 };
3563
- #root = new Node$1();
3564
- insert(path, index, pathErrorCheckOnly) {
3565
- const paramAssoc = [];
3566
- const groups = [];
3567
- for (let i = 0; ; ) {
3568
- let replaced = false;
3569
- path = path.replace(/\{[^}]+\}/g, (m) => {
3570
- const mark = `@\\${i}`;
3571
- groups[i] = [mark, m];
3572
- i++;
3573
- replaced = true;
3574
- return mark;
3575
- });
3576
- if (!replaced) {
3577
- break;
3578
- }
3579
- }
3580
- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
3581
- for (let i = groups.length - 1; i >= 0; i--) {
3582
- const [mark] = groups[i];
3583
- for (let j = tokens.length - 1; j >= 0; j--) {
3584
- if (tokens[j].indexOf(mark) !== -1) {
3585
- tokens[j] = tokens[j].replace(mark, groups[i][1]);
3586
- break;
3587
- }
3588
- }
3589
- }
3590
- this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
3591
- return paramAssoc;
3592
- }
3593
- buildRegExp() {
3594
- let regexp = this.#root.buildRegExpStr();
3595
- if (regexp === "") {
3596
- return [/^$/, [], []];
3597
- }
3598
- let captureIndex = 0;
3599
- const indexReplacementMap = [];
3600
- const paramReplacementMap = [];
3601
- regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
3602
- if (handlerIndex !== void 0) {
3603
- indexReplacementMap[++captureIndex] = Number(handlerIndex);
3604
- return "$()";
3605
- }
3606
- if (paramIndex !== void 0) {
3607
- paramReplacementMap[Number(paramIndex)] = ++captureIndex;
3608
- return "";
3609
- }
3610
- return "";
3611
- });
3612
- return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
3613
- }
3614
- };
3615
-
3616
- // src/router/reg-exp-router/router.ts
3617
- var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
3618
- var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
3619
- function buildWildcardRegExp(path) {
3620
- return wildcardRegExpCache[path] ??= new RegExp(
3621
- path === "*" ? "" : `^${path.replace(
3622
- /\/\*$|([.\\+*[^\]$()])/g,
3623
- (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
3624
- )}$`
3625
- );
3626
- }
3627
- function clearWildcardRegExpCache() {
3628
- wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
3629
- }
3630
- function buildMatcherFromPreprocessedRoutes(routes) {
3631
- const trie = new Trie();
3632
- const handlerData = [];
3633
- if (routes.length === 0) {
3634
- return nullMatcher;
3635
- }
3636
- const routesWithStaticPathFlag = routes.map(
3637
- (route) => [!/\*|\/:/.test(route[0]), ...route]
3638
- ).sort(
3639
- ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
3640
- );
3641
- const staticMap = /* @__PURE__ */ Object.create(null);
3642
- for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
3643
- const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
3644
- if (pathErrorCheckOnly) {
3645
- staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
3646
- } else {
3647
- j++;
3648
- }
3649
- let paramAssoc;
3650
- try {
3651
- paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
3652
- } catch (e) {
3653
- throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
3654
- }
3655
- if (pathErrorCheckOnly) {
3656
- continue;
3657
- }
3658
- handlerData[j] = handlers.map(([h, paramCount]) => {
3659
- const paramIndexMap = /* @__PURE__ */ Object.create(null);
3660
- paramCount -= 1;
3661
- for (; paramCount >= 0; paramCount--) {
3662
- const [key, value] = paramAssoc[paramCount];
3663
- paramIndexMap[key] = value;
3664
- }
3665
- return [h, paramIndexMap];
3666
- });
3667
- }
3668
- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
3669
- for (let i = 0, len = handlerData.length; i < len; i++) {
3670
- for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
3671
- const map = handlerData[i][j]?.[1];
3672
- if (!map) {
3673
- continue;
3674
- }
3675
- const keys = Object.keys(map);
3676
- for (let k = 0, len3 = keys.length; k < len3; k++) {
3677
- map[keys[k]] = paramReplacementMap[map[keys[k]]];
3678
- }
3679
- }
3680
- }
3681
- const handlerMap = [];
3682
- for (const i in indexReplacementMap) {
3683
- handlerMap[i] = handlerData[indexReplacementMap[i]];
3684
- }
3685
- return [regexp, handlerMap, staticMap];
3686
- }
3687
- function findMiddleware(middleware, path) {
3688
- if (!middleware) {
3689
- return void 0;
3690
- }
3691
- for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
3692
- if (buildWildcardRegExp(k).test(path)) {
3693
- return [...middleware[k]];
3694
- }
3695
- }
3696
- return void 0;
3697
- }
3698
- var RegExpRouter = class {
3699
- name = "RegExpRouter";
3700
- #middleware;
3701
- #routes;
3702
- constructor() {
3703
- this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
3704
- this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
3705
- }
3706
- add(method, path, handler) {
3707
- const middleware = this.#middleware;
3708
- const routes = this.#routes;
3709
- if (!middleware || !routes) {
3710
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
3711
- }
3712
- if (!middleware[method]) {
3713
- [middleware, routes].forEach((handlerMap) => {
3714
- handlerMap[method] = /* @__PURE__ */ Object.create(null);
3715
- Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
3716
- handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
3717
- });
3718
- });
3719
- }
3720
- if (path === "/*") {
3721
- path = "*";
3722
- }
3723
- const paramCount = (path.match(/\/:/g) || []).length;
3724
- if (/\*$/.test(path)) {
3725
- const re = buildWildcardRegExp(path);
3726
- if (method === METHOD_NAME_ALL) {
3727
- Object.keys(middleware).forEach((m) => {
3728
- middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
3729
- });
3730
- } else {
3731
- middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
3732
- }
3733
- Object.keys(middleware).forEach((m) => {
3734
- if (method === METHOD_NAME_ALL || method === m) {
3735
- Object.keys(middleware[m]).forEach((p) => {
3736
- re.test(p) && middleware[m][p].push([handler, paramCount]);
3737
- });
3738
- }
3739
- });
3740
- Object.keys(routes).forEach((m) => {
3741
- if (method === METHOD_NAME_ALL || method === m) {
3742
- Object.keys(routes[m]).forEach(
3743
- (p) => re.test(p) && routes[m][p].push([handler, paramCount])
3744
- );
3745
- }
3746
- });
3747
- return;
3748
- }
3749
- const paths = checkOptionalParameter(path) || [path];
3750
- for (let i = 0, len = paths.length; i < len; i++) {
3751
- const path2 = paths[i];
3752
- Object.keys(routes).forEach((m) => {
3753
- if (method === METHOD_NAME_ALL || method === m) {
3754
- routes[m][path2] ||= [
3755
- ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
3756
- ];
3757
- routes[m][path2].push([handler, paramCount - len + i + 1]);
3758
- }
3759
- });
3760
- }
3761
- }
3762
- match = match$1;
3763
- buildAllMatchers() {
3764
- const matchers = /* @__PURE__ */ Object.create(null);
3765
- Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
3766
- matchers[method] ||= this.#buildMatcher(method);
3767
- });
3768
- this.#middleware = this.#routes = void 0;
3769
- clearWildcardRegExpCache();
3770
- return matchers;
3771
- }
3772
- #buildMatcher(method) {
3773
- const routes = [];
3774
- let hasOwnRoute = method === METHOD_NAME_ALL;
3775
- [this.#middleware, this.#routes].forEach((r) => {
3776
- const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
3777
- if (ownRoute.length !== 0) {
3778
- hasOwnRoute ||= true;
3779
- routes.push(...ownRoute);
3780
- } else if (method !== METHOD_NAME_ALL) {
3781
- routes.push(
3782
- ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
3783
- );
3784
- }
3785
- });
3786
- if (!hasOwnRoute) {
3787
- return null;
3788
- } else {
3789
- return buildMatcherFromPreprocessedRoutes(routes);
3790
- }
3791
- }
3792
- };
3793
-
3794
- // src/router/smart-router/router.ts
3795
- var SmartRouter = class {
3796
- name = "SmartRouter";
3797
- #routers = [];
3798
- #routes = [];
3799
- constructor(init) {
3800
- this.#routers = init.routers;
3801
- }
3802
- add(method, path, handler) {
3803
- if (!this.#routes) {
3804
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
3805
- }
3806
- this.#routes.push([method, path, handler]);
3807
- }
3808
- match(method, path) {
3809
- if (!this.#routes) {
3810
- throw new Error("Fatal error");
3811
- }
3812
- const routers = this.#routers;
3813
- const routes = this.#routes;
3814
- const len = routers.length;
3815
- let i = 0;
3816
- let res;
3817
- for (; i < len; i++) {
3818
- const router = routers[i];
3819
- try {
3820
- for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
3821
- router.add(...routes[i2]);
3822
- }
3823
- res = router.match(method, path);
3824
- } catch (e) {
3825
- if (e instanceof UnsupportedPathError) {
3826
- continue;
3827
- }
3828
- throw e;
3829
- }
3830
- this.match = router.match.bind(router);
3831
- this.#routers = [router];
3832
- this.#routes = void 0;
3833
- break;
3834
- }
3835
- if (i === len) {
3836
- throw new Error("Fatal error");
3837
- }
3838
- this.name = `SmartRouter + ${this.activeRouter.name}`;
3839
- return res;
3840
- }
3841
- get activeRouter() {
3842
- if (this.#routes || this.#routers.length !== 1) {
3843
- throw new Error("No active router has been determined yet.");
3844
- }
3845
- return this.#routers[0];
3846
- }
3847
- };
3848
-
3849
- // src/router/trie-router/node.ts
3850
- var emptyParams = /* @__PURE__ */ Object.create(null);
3851
- var Node = class {
3852
- #methods;
3853
- #children;
3854
- #patterns;
3855
- #order = 0;
3856
- #params = emptyParams;
3857
- constructor(method, handler, children) {
3858
- this.#children = children || /* @__PURE__ */ Object.create(null);
3859
- this.#methods = [];
3860
- if (method && handler) {
3861
- const m = /* @__PURE__ */ Object.create(null);
3862
- m[method] = { handler, possibleKeys: [], score: 0 };
3863
- this.#methods = [m];
3864
- }
3865
- this.#patterns = [];
3866
- }
3867
- insert(method, path, handler) {
3868
- this.#order = ++this.#order;
3869
- let curNode = this;
3870
- const parts = splitRoutingPath(path);
3871
- const possibleKeys = [];
3872
- for (let i = 0, len = parts.length; i < len; i++) {
3873
- const p = parts[i];
3874
- const nextP = parts[i + 1];
3875
- const pattern = getPattern(p, nextP);
3876
- const key = Array.isArray(pattern) ? pattern[0] : p;
3877
- if (key in curNode.#children) {
3878
- curNode = curNode.#children[key];
3879
- if (pattern) {
3880
- possibleKeys.push(pattern[1]);
3881
- }
3882
- continue;
3883
- }
3884
- curNode.#children[key] = new Node();
3885
- if (pattern) {
3886
- curNode.#patterns.push(pattern);
3887
- possibleKeys.push(pattern[1]);
3888
- }
3889
- curNode = curNode.#children[key];
3890
- }
3891
- curNode.#methods.push({
3892
- [method]: {
3893
- handler,
3894
- possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
3895
- score: this.#order
3896
- }
3897
- });
3898
- return curNode;
3899
- }
3900
- #getHandlerSets(node, method, nodeParams, params) {
3901
- const handlerSets = [];
3902
- for (let i = 0, len = node.#methods.length; i < len; i++) {
3903
- const m = node.#methods[i];
3904
- const handlerSet = m[method] || m[METHOD_NAME_ALL];
3905
- const processedSet = {};
3906
- if (handlerSet !== void 0) {
3907
- handlerSet.params = /* @__PURE__ */ Object.create(null);
3908
- handlerSets.push(handlerSet);
3909
- if (nodeParams !== emptyParams || params && params !== emptyParams) {
3910
- for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
3911
- const key = handlerSet.possibleKeys[i2];
3912
- const processed = processedSet[handlerSet.score];
3913
- handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
3914
- processedSet[handlerSet.score] = true;
3915
- }
3916
- }
3917
- }
3918
- }
3919
- return handlerSets;
3920
- }
3921
- search(method, path) {
3922
- const handlerSets = [];
3923
- this.#params = emptyParams;
3924
- const curNode = this;
3925
- let curNodes = [curNode];
3926
- const parts = splitPath(path);
3927
- const curNodesQueue = [];
3928
- for (let i = 0, len = parts.length; i < len; i++) {
3929
- const part = parts[i];
3930
- const isLast = i === len - 1;
3931
- const tempNodes = [];
3932
- for (let j = 0, len2 = curNodes.length; j < len2; j++) {
3933
- const node = curNodes[j];
3934
- const nextNode = node.#children[part];
3935
- if (nextNode) {
3936
- nextNode.#params = node.#params;
3937
- if (isLast) {
3938
- if (nextNode.#children["*"]) {
3939
- handlerSets.push(
3940
- ...this.#getHandlerSets(nextNode.#children["*"], method, node.#params)
3941
- );
3942
- }
3943
- handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
3944
- } else {
3945
- tempNodes.push(nextNode);
3946
- }
3947
- }
3948
- for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
3949
- const pattern = node.#patterns[k];
3950
- const params = node.#params === emptyParams ? {} : { ...node.#params };
3951
- if (pattern === "*") {
3952
- const astNode = node.#children["*"];
3953
- if (astNode) {
3954
- handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
3955
- astNode.#params = params;
3956
- tempNodes.push(astNode);
3957
- }
3958
- continue;
3959
- }
3960
- const [key, name, matcher] = pattern;
3961
- if (!part && !(matcher instanceof RegExp)) {
3962
- continue;
3963
- }
3964
- const child = node.#children[key];
3965
- const restPathString = parts.slice(i).join("/");
3966
- if (matcher instanceof RegExp) {
3967
- const m = matcher.exec(restPathString);
3968
- if (m) {
3969
- params[name] = m[0];
3970
- handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
3971
- if (Object.keys(child.#children).length) {
3972
- child.#params = params;
3973
- const componentCount = m[0].match(/\//)?.length ?? 0;
3974
- const targetCurNodes = curNodesQueue[componentCount] ||= [];
3975
- targetCurNodes.push(child);
3976
- }
3977
- continue;
3978
- }
3979
- }
3980
- if (matcher === true || matcher.test(part)) {
3981
- params[name] = part;
3982
- if (isLast) {
3983
- handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
3984
- if (child.#children["*"]) {
3985
- handlerSets.push(
3986
- ...this.#getHandlerSets(child.#children["*"], method, params, node.#params)
3987
- );
3988
- }
3989
- } else {
3990
- child.#params = params;
3991
- tempNodes.push(child);
3992
- }
3993
- }
3994
- }
3995
- }
3996
- curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
3997
- }
3998
- if (handlerSets.length > 1) {
3999
- handlerSets.sort((a, b) => {
4000
- return a.score - b.score;
4001
- });
4002
- }
4003
- return [handlerSets.map(({ handler, params }) => [handler, params])];
4004
- }
4005
- };
4006
-
4007
- // src/router/trie-router/router.ts
4008
- var TrieRouter = class {
4009
- name = "TrieRouter";
4010
- #node;
4011
- constructor() {
4012
- this.#node = new Node();
4013
- }
4014
- add(method, path, handler) {
4015
- const results = checkOptionalParameter(path);
4016
- if (results) {
4017
- for (let i = 0, len = results.length; i < len; i++) {
4018
- this.#node.insert(method, results[i], handler);
4019
- }
4020
- return;
4021
- }
4022
- this.#node.insert(method, path, handler);
4023
- }
4024
- match(method, path) {
4025
- return this.#node.search(method, path);
4026
- }
4027
- };
4028
-
4029
- // src/hono.ts
4030
- var Hono = class extends Hono$1 {
4031
- constructor(options = {}) {
4032
- super(options);
4033
- this.router = options.router ?? new SmartRouter({
4034
- routers: [new RegExpRouter(), new TrieRouter()]
4035
- });
4036
- }
4037
- };
4038
-
4039
- // src/server.ts
4040
- var RequestError = class extends Error {
4041
- constructor(message, options) {
4042
- super(message, options);
4043
- this.name = "RequestError";
4044
- }
4045
- };
4046
- var toRequestError = (e) => {
4047
- if (e instanceof RequestError) {
4048
- return e;
4049
- }
4050
- return new RequestError(e.message, { cause: e });
4051
- };
4052
- var GlobalRequest = global.Request;
4053
- var Request$1 = class Request extends GlobalRequest {
4054
- constructor(input, options) {
4055
- if (typeof input === "object" && getRequestCache in input) {
4056
- input = input[getRequestCache]();
4057
- }
4058
- if (typeof options?.body?.getReader !== "undefined") {
4059
- options.duplex ??= "half";
4060
- }
4061
- super(input, options);
4062
- }
4063
- };
4064
- var newHeadersFromIncoming = (incoming) => {
4065
- const headerRecord = [];
4066
- const rawHeaders = incoming.rawHeaders;
4067
- for (let i = 0; i < rawHeaders.length; i += 2) {
4068
- const { [i]: key, [i + 1]: value } = rawHeaders;
4069
- if (key.charCodeAt(0) !== /*:*/
4070
- 58) {
4071
- headerRecord.push([key, value]);
4072
- }
4073
- }
4074
- return new Headers(headerRecord);
4075
- };
4076
- var wrapBodyStream = Symbol("wrapBodyStream");
4077
- var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
4078
- const init = {
4079
- method,
4080
- headers,
4081
- signal: abortController.signal
4082
- };
4083
- if (method === "TRACE") {
4084
- init.method = "GET";
4085
- const req = new Request$1(url, init);
4086
- Object.defineProperty(req, "method", {
4087
- get() {
4088
- return "TRACE";
4089
- }
4090
- });
4091
- return req;
4092
- }
4093
- if (!(method === "GET" || method === "HEAD")) {
4094
- if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
4095
- init.body = new ReadableStream({
4096
- start(controller) {
4097
- controller.enqueue(incoming.rawBody);
4098
- controller.close();
4099
- }
4100
- });
4101
- } else if (incoming[wrapBodyStream]) {
4102
- let reader;
4103
- init.body = new ReadableStream({
4104
- async pull(controller) {
4105
- try {
4106
- reader ||= require$$3.Readable.toWeb(incoming).getReader();
4107
- const { done, value } = await reader.read();
4108
- if (done) {
4109
- controller.close();
4110
- } else {
4111
- controller.enqueue(value);
4112
- }
4113
- } catch (error) {
4114
- controller.error(error);
4115
- }
4116
- }
4117
- });
4118
- } else {
4119
- init.body = require$$3.Readable.toWeb(incoming);
4120
- }
4121
- }
4122
- return new Request$1(url, init);
4123
- };
4124
- var getRequestCache = Symbol("getRequestCache");
4125
- var requestCache = Symbol("requestCache");
4126
- var incomingKey = Symbol("incomingKey");
4127
- var urlKey = Symbol("urlKey");
4128
- var headersKey = Symbol("headersKey");
4129
- var abortControllerKey = Symbol("abortControllerKey");
4130
- var getAbortController = Symbol("getAbortController");
4131
- var requestPrototype = {
4132
- get method() {
4133
- return this[incomingKey].method || "GET";
4134
- },
4135
- get url() {
4136
- return this[urlKey];
4137
- },
4138
- get headers() {
4139
- return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
4140
- },
4141
- [getAbortController]() {
4142
- this[getRequestCache]();
4143
- return this[abortControllerKey];
4144
- },
4145
- [getRequestCache]() {
4146
- this[abortControllerKey] ||= new AbortController();
4147
- return this[requestCache] ||= newRequestFromIncoming(
4148
- this.method,
4149
- this[urlKey],
4150
- this.headers,
4151
- this[incomingKey],
4152
- this[abortControllerKey]
4153
- );
4154
- }
4155
- };
4156
- [
4157
- "body",
4158
- "bodyUsed",
4159
- "cache",
4160
- "credentials",
4161
- "destination",
4162
- "integrity",
4163
- "mode",
4164
- "redirect",
4165
- "referrer",
4166
- "referrerPolicy",
4167
- "signal",
4168
- "keepalive"
4169
- ].forEach((k) => {
4170
- Object.defineProperty(requestPrototype, k, {
4171
- get() {
4172
- return this[getRequestCache]()[k];
4173
- }
4174
- });
4175
- });
4176
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
4177
- Object.defineProperty(requestPrototype, k, {
4178
- value: function() {
4179
- return this[getRequestCache]()[k]();
4180
- }
4181
- });
4182
- });
4183
- Object.setPrototypeOf(requestPrototype, Request$1.prototype);
4184
- var newRequest = (incoming, defaultHostname) => {
4185
- const req = Object.create(requestPrototype);
4186
- req[incomingKey] = incoming;
4187
- const incomingUrl = incoming.url || "";
4188
- if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
4189
- (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
4190
- if (incoming instanceof http2.Http2ServerRequest) {
4191
- throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
4192
- }
4193
- try {
4194
- const url2 = new URL(incomingUrl);
4195
- req[urlKey] = url2.href;
4196
- } catch (e) {
4197
- throw new RequestError("Invalid absolute URL", { cause: e });
4198
- }
4199
- return req;
4200
- }
4201
- const host = (incoming instanceof http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
4202
- if (!host) {
4203
- throw new RequestError("Missing host header");
4204
- }
4205
- let scheme;
4206
- if (incoming instanceof http2.Http2ServerRequest) {
4207
- scheme = incoming.scheme;
4208
- if (!(scheme === "http" || scheme === "https")) {
4209
- throw new RequestError("Unsupported scheme");
4210
- }
4211
- } else {
4212
- scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
4213
- }
4214
- const url = new URL(`${scheme}://${host}${incomingUrl}`);
4215
- if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
4216
- throw new RequestError("Invalid host header");
4217
- }
4218
- req[urlKey] = url.href;
4219
- return req;
4220
- };
4221
-
4222
- // src/response.ts
4223
- var responseCache = Symbol("responseCache");
4224
- var getResponseCache = Symbol("getResponseCache");
4225
- var cacheKey = Symbol("cache");
4226
- var GlobalResponse = global.Response;
4227
- var Response2 = class _Response {
4228
- #body;
4229
- #init;
4230
- [getResponseCache]() {
4231
- delete this[cacheKey];
4232
- return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
4233
- }
4234
- constructor(body, init) {
4235
- let headers;
4236
- this.#body = body;
4237
- if (init instanceof _Response) {
4238
- const cachedGlobalResponse = init[responseCache];
4239
- if (cachedGlobalResponse) {
4240
- this.#init = cachedGlobalResponse;
4241
- this[getResponseCache]();
4242
- return;
4243
- } else {
4244
- this.#init = init.#init;
4245
- headers = new Headers(init.#init.headers);
4246
- }
4247
- } else {
4248
- this.#init = init;
4249
- }
4250
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
4251
- headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
4252
- this[cacheKey] = [init?.status || 200, body, headers];
4253
- }
4254
- }
4255
- get headers() {
4256
- const cache = this[cacheKey];
4257
- if (cache) {
4258
- if (!(cache[2] instanceof Headers)) {
4259
- cache[2] = new Headers(cache[2]);
4260
- }
4261
- return cache[2];
4262
- }
4263
- return this[getResponseCache]().headers;
4264
- }
4265
- get status() {
4266
- return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
4267
- }
4268
- get ok() {
4269
- const status = this.status;
4270
- return status >= 200 && status < 300;
4271
- }
4272
- };
4273
- ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
4274
- Object.defineProperty(Response2.prototype, k, {
4275
- get() {
4276
- return this[getResponseCache]()[k];
4277
- }
4278
- });
4279
- });
4280
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
4281
- Object.defineProperty(Response2.prototype, k, {
4282
- value: function() {
4283
- return this[getResponseCache]()[k]();
4284
- }
4285
- });
4286
- });
4287
- Object.setPrototypeOf(Response2, GlobalResponse);
4288
- Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
4289
-
4290
- // src/utils.ts
4291
- async function readWithoutBlocking(readPromise) {
4292
- return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
4293
- }
4294
- function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
4295
- const cancel = (error) => {
4296
- reader.cancel(error).catch(() => {
4297
- });
4298
- };
4299
- writable.on("close", cancel);
4300
- writable.on("error", cancel);
4301
- (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
4302
- return reader.closed.finally(() => {
4303
- writable.off("close", cancel);
4304
- writable.off("error", cancel);
4305
- });
4306
- function handleStreamError(error) {
4307
- if (error) {
4308
- writable.destroy(error);
4309
- }
4310
- }
4311
- function onDrain() {
4312
- reader.read().then(flow, handleStreamError);
4313
- }
4314
- function flow({ done, value }) {
4315
- try {
4316
- if (done) {
4317
- writable.end();
4318
- } else if (!writable.write(value)) {
4319
- writable.once("drain", onDrain);
4320
- } else {
4321
- return reader.read().then(flow, handleStreamError);
4322
- }
4323
- } catch (e) {
4324
- handleStreamError(e);
4325
- }
4326
- }
4327
- }
4328
- function writeFromReadableStream(stream, writable) {
4329
- if (stream.locked) {
4330
- throw new TypeError("ReadableStream is locked.");
4331
- } else if (writable.destroyed) {
4332
- return;
4333
- }
4334
- return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
4335
- }
4336
- var buildOutgoingHttpHeaders = (headers) => {
4337
- const res = {};
4338
- if (!(headers instanceof Headers)) {
4339
- headers = new Headers(headers ?? void 0);
4340
- }
4341
- const cookies = [];
4342
- for (const [k, v] of headers) {
4343
- if (k === "set-cookie") {
4344
- cookies.push(v);
4345
- } else {
4346
- res[k] = v;
4347
- }
4348
- }
4349
- if (cookies.length > 0) {
4350
- res["set-cookie"] = cookies;
4351
- }
4352
- res["content-type"] ??= "text/plain; charset=UTF-8";
4353
- return res;
4354
- };
4355
-
4356
- // src/utils/response/constants.ts
4357
- var X_ALREADY_SENT = "x-hono-already-sent";
4358
- var webFetch = global.fetch;
4359
- if (typeof global.crypto === "undefined") {
4360
- global.crypto = crypto$1;
4361
- }
4362
- global.fetch = (info, init) => {
4363
- init = {
4364
- // Disable compression handling so people can return the result of a fetch
4365
- // directly in the loader without messing with the Content-Encoding header.
4366
- compress: false,
4367
- ...init
4368
- };
4369
- return webFetch(info, init);
4370
- };
4371
-
4372
- // src/listener.ts
4373
- var outgoingEnded = Symbol("outgoingEnded");
4374
- var handleRequestError = () => new Response(null, {
4375
- status: 400
4376
- });
4377
- var handleFetchError = (e) => new Response(null, {
4378
- status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
4379
- });
4380
- var handleResponseError = (e, outgoing) => {
4381
- const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
4382
- if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
4383
- console.info("The user aborted a request.");
4384
- } else {
4385
- console.error(e);
4386
- if (!outgoing.headersSent) {
4387
- outgoing.writeHead(500, { "Content-Type": "text/plain" });
4388
- }
4389
- outgoing.end(`Error: ${err.message}`);
4390
- outgoing.destroy(err);
4391
- }
4392
- };
4393
- var flushHeaders = (outgoing) => {
4394
- if ("flushHeaders" in outgoing && outgoing.writable) {
4395
- outgoing.flushHeaders();
4396
- }
4397
- };
4398
- var responseViaCache = async (res, outgoing) => {
4399
- let [status, body, header] = res[cacheKey];
4400
- if (header instanceof Headers) {
4401
- header = buildOutgoingHttpHeaders(header);
4402
- }
4403
- if (typeof body === "string") {
4404
- header["Content-Length"] = Buffer.byteLength(body);
4405
- } else if (body instanceof Uint8Array) {
4406
- header["Content-Length"] = body.byteLength;
4407
- } else if (body instanceof Blob) {
4408
- header["Content-Length"] = body.size;
4409
- }
4410
- outgoing.writeHead(status, header);
4411
- if (typeof body === "string" || body instanceof Uint8Array) {
4412
- outgoing.end(body);
4413
- } else if (body instanceof Blob) {
4414
- outgoing.end(new Uint8Array(await body.arrayBuffer()));
4415
- } else {
4416
- flushHeaders(outgoing);
4417
- await writeFromReadableStream(body, outgoing)?.catch(
4418
- (e) => handleResponseError(e, outgoing)
4419
- );
4420
- }
4421
- outgoing[outgoingEnded]?.();
4422
- };
4423
- var isPromise = (res) => typeof res.then === "function";
4424
- var responseViaResponseObject = async (res, outgoing, options = {}) => {
4425
- if (isPromise(res)) {
4426
- if (options.errorHandler) {
4427
- try {
4428
- res = await res;
4429
- } catch (err) {
4430
- const errRes = await options.errorHandler(err);
4431
- if (!errRes) {
4432
- return;
4433
- }
4434
- res = errRes;
4435
- }
4436
- } else {
4437
- res = await res.catch(handleFetchError);
4438
- }
4439
- }
4440
- if (cacheKey in res) {
4441
- return responseViaCache(res, outgoing);
4442
- }
4443
- const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
4444
- if (res.body) {
4445
- const reader = res.body.getReader();
4446
- const values = [];
4447
- let done = false;
4448
- let currentReadPromise = void 0;
4449
- if (resHeaderRecord["transfer-encoding"] !== "chunked") {
4450
- let maxReadCount = 2;
4451
- for (let i = 0; i < maxReadCount; i++) {
4452
- currentReadPromise ||= reader.read();
4453
- const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
4454
- console.error(e);
4455
- done = true;
4456
- });
4457
- if (!chunk) {
4458
- if (i === 1) {
4459
- await new Promise((resolve) => setTimeout(resolve));
4460
- maxReadCount = 3;
4461
- continue;
4462
- }
4463
- break;
4464
- }
4465
- currentReadPromise = void 0;
4466
- if (chunk.value) {
4467
- values.push(chunk.value);
4468
- }
4469
- if (chunk.done) {
4470
- done = true;
4471
- break;
4472
- }
4473
- }
4474
- if (done && !("content-length" in resHeaderRecord)) {
4475
- resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
4476
- }
4477
- }
4478
- outgoing.writeHead(res.status, resHeaderRecord);
4479
- values.forEach((value) => {
4480
- outgoing.write(value);
4481
- });
4482
- if (done) {
4483
- outgoing.end();
4484
- } else {
4485
- if (values.length === 0) {
4486
- flushHeaders(outgoing);
4487
- }
4488
- await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
4489
- }
4490
- } else if (resHeaderRecord[X_ALREADY_SENT]) ; else {
4491
- outgoing.writeHead(res.status, resHeaderRecord);
4492
- outgoing.end();
4493
- }
4494
- outgoing[outgoingEnded]?.();
4495
- };
4496
- var getRequestListener = (fetchCallback, options = {}) => {
4497
- const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
4498
- if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
4499
- Object.defineProperty(global, "Request", {
4500
- value: Request$1
4501
- });
4502
- Object.defineProperty(global, "Response", {
4503
- value: Response2
4504
- });
4505
- }
4506
- return async (incoming, outgoing) => {
4507
- let res, req;
4508
- try {
4509
- req = newRequest(incoming, options.hostname);
4510
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
4511
- if (!incomingEnded) {
4512
- ;
4513
- incoming[wrapBodyStream] = true;
4514
- incoming.on("end", () => {
4515
- incomingEnded = true;
4516
- });
4517
- if (incoming instanceof http2.Http2ServerRequest) {
4518
- ;
4519
- outgoing[outgoingEnded] = () => {
4520
- if (!incomingEnded) {
4521
- setTimeout(() => {
4522
- if (!incomingEnded) {
4523
- setTimeout(() => {
4524
- incoming.destroy();
4525
- outgoing.destroy();
4526
- });
4527
- }
4528
- });
4529
- }
4530
- };
4531
- }
4532
- }
4533
- outgoing.on("close", () => {
4534
- const abortController = req[abortControllerKey];
4535
- if (abortController) {
4536
- if (incoming.errored) {
4537
- req[abortControllerKey].abort(incoming.errored.toString());
4538
- } else if (!outgoing.writableFinished) {
4539
- req[abortControllerKey].abort("Client connection prematurely closed.");
4540
- }
4541
- }
4542
- if (!incomingEnded) {
4543
- setTimeout(() => {
4544
- if (!incomingEnded) {
4545
- setTimeout(() => {
4546
- incoming.destroy();
4547
- });
4548
- }
4549
- });
4550
- }
4551
- });
4552
- res = fetchCallback(req, { incoming, outgoing });
4553
- if (cacheKey in res) {
4554
- return responseViaCache(res, outgoing);
4555
- }
4556
- } catch (e) {
4557
- if (!res) {
4558
- if (options.errorHandler) {
4559
- res = await options.errorHandler(req ? e : toRequestError(e));
4560
- if (!res) {
4561
- return;
4562
- }
4563
- } else if (!req) {
4564
- res = handleRequestError();
4565
- } else {
4566
- res = handleFetchError(e);
4567
- }
4568
- } else {
4569
- return handleResponseError(e, outgoing);
4570
- }
4571
- }
4572
- try {
4573
- return await responseViaResponseObject(res, outgoing, options);
4574
- } catch (e) {
4575
- return handleResponseError(e, outgoing);
4576
- }
4577
- };
4578
- };
4579
-
4580
- // src/server.ts
4581
- var createAdaptorServer = (options) => {
4582
- const fetchCallback = options.fetch;
4583
- const requestListener = getRequestListener(fetchCallback, {
4584
- hostname: options.hostname,
4585
- overrideGlobalObjects: options.overrideGlobalObjects,
4586
- autoCleanupIncoming: options.autoCleanupIncoming
4587
- });
4588
- const createServer = options.createServer || http.createServer;
4589
- const server = createServer(options.serverOptions || {}, requestListener);
4590
- return server;
4591
- };
4592
- var serve = (options, listeningListener) => {
4593
- const server = createAdaptorServer(options);
4594
- server.listen(options?.port ?? 3e3, options.hostname, () => {
4595
- const serverInfo = server.address();
4596
- listeningListener && listeningListener(serverInfo);
4597
- });
4598
- return server;
4599
- };
4600
-
4601
- // src/helper/html/index.ts
4602
- var html = (strings, ...values) => {
4603
- const buffer = [""];
4604
- for (let i = 0, len = strings.length - 1; i < len; i++) {
4605
- buffer[0] += strings[i];
4606
- const children = Array.isArray(values[i]) ? values[i].flat(Infinity) : [values[i]];
4607
- for (let i2 = 0, len2 = children.length; i2 < len2; i2++) {
4608
- const child = children[i2];
4609
- if (typeof child === "string") {
4610
- escapeToBuffer(child, buffer);
4611
- } else if (typeof child === "number") {
4612
- buffer[0] += child;
4613
- } else if (typeof child === "boolean" || child === null || child === void 0) {
4614
- continue;
4615
- } else if (typeof child === "object" && child.isEscaped) {
4616
- if (child.callbacks) {
4617
- buffer.unshift("", child);
4618
- } else {
4619
- const tmp = child.toString();
4620
- if (tmp instanceof Promise) {
4621
- buffer.unshift("", tmp);
4622
- } else {
4623
- buffer[0] += tmp;
4624
- }
4625
- }
4626
- } else if (child instanceof Promise) {
4627
- buffer.unshift("", child);
4628
- } else {
4629
- escapeToBuffer(child.toString(), buffer);
4630
- }
4631
- }
4632
- }
4633
- buffer[0] += strings.at(-1);
4634
- return buffer.length === 1 ? "callbacks" in buffer ? raw(resolveCallbackSync(raw(buffer[0], buffer.callbacks))) : raw(buffer[0]) : stringBufferToString(buffer, buffer.callbacks);
4635
- };
4636
-
4637
- // src/index.ts
4638
-
4639
- // src/swagger/renderer.ts
4640
- var RENDER_TYPE = {
4641
- STRING_ARRAY: "string_array",
4642
- STRING: "string",
4643
- JSON_STRING: "json_string",
4644
- RAW: "raw"
4645
- };
4646
- var RENDER_TYPE_MAP = {
4647
- configUrl: RENDER_TYPE.STRING,
4648
- deepLinking: RENDER_TYPE.RAW,
4649
- presets: RENDER_TYPE.STRING_ARRAY,
4650
- plugins: RENDER_TYPE.STRING_ARRAY,
4651
- spec: RENDER_TYPE.JSON_STRING,
4652
- url: RENDER_TYPE.STRING,
4653
- urls: RENDER_TYPE.JSON_STRING,
4654
- layout: RENDER_TYPE.STRING,
4655
- docExpansion: RENDER_TYPE.STRING,
4656
- maxDisplayedTags: RENDER_TYPE.RAW,
4657
- operationsSorter: RENDER_TYPE.RAW,
4658
- requestInterceptor: RENDER_TYPE.RAW,
4659
- responseInterceptor: RENDER_TYPE.RAW,
4660
- persistAuthorization: RENDER_TYPE.RAW,
4661
- defaultModelsExpandDepth: RENDER_TYPE.RAW,
4662
- defaultModelExpandDepth: RENDER_TYPE.RAW,
4663
- defaultModelRendering: RENDER_TYPE.STRING,
4664
- displayRequestDuration: RENDER_TYPE.RAW,
4665
- filter: RENDER_TYPE.RAW,
4666
- showExtensions: RENDER_TYPE.RAW,
4667
- showCommonExtensions: RENDER_TYPE.RAW,
4668
- queryConfigEnabled: RENDER_TYPE.RAW,
4669
- displayOperationId: RENDER_TYPE.RAW,
4670
- tagsSorter: RENDER_TYPE.RAW,
4671
- onComplete: RENDER_TYPE.RAW,
4672
- syntaxHighlight: RENDER_TYPE.JSON_STRING,
4673
- tryItOutEnabled: RENDER_TYPE.RAW,
4674
- requestSnippetsEnabled: RENDER_TYPE.RAW,
4675
- requestSnippets: RENDER_TYPE.JSON_STRING,
4676
- oauth2RedirectUrl: RENDER_TYPE.STRING,
4677
- showMutabledRequest: RENDER_TYPE.RAW,
4678
- request: RENDER_TYPE.JSON_STRING,
4679
- supportedSubmitMethods: RENDER_TYPE.JSON_STRING,
4680
- validatorUrl: RENDER_TYPE.STRING,
4681
- withCredentials: RENDER_TYPE.RAW,
4682
- modelPropertyMacro: RENDER_TYPE.RAW,
4683
- parameterMacro: RENDER_TYPE.RAW
4684
- };
4685
- var renderSwaggerUIOptions = (options) => {
4686
- const optionsStrings = Object.entries(options).map(([k, v]) => {
4687
- const key = k;
4688
- if (!RENDER_TYPE_MAP[key] || v === void 0) {
4689
- return "";
4690
- }
4691
- switch (RENDER_TYPE_MAP[key]) {
4692
- case RENDER_TYPE.STRING:
4693
- return `${key}: '${v}'`;
4694
- case RENDER_TYPE.STRING_ARRAY:
4695
- if (!Array.isArray(v)) {
4696
- return "";
4697
- }
4698
- return `${key}: [${v.map((ve) => `${ve}`).join(",")}]`;
4699
- case RENDER_TYPE.JSON_STRING:
4700
- return `${key}: ${JSON.stringify(v)}`;
4701
- case RENDER_TYPE.RAW:
4702
- return `${key}: ${v}`;
4703
- default:
4704
- return "";
4705
- }
4706
- }).filter((item) => item !== "").join(",");
4707
- return optionsStrings;
4708
- };
4709
-
4710
- // src/swagger/resource.ts
4711
- var remoteAssets = ({ version }) => {
4712
- const url = `https://cdn.jsdelivr.net/npm/swagger-ui-dist${version !== void 0 ? `@${version}` : ""}`;
4713
- return {
4714
- css: [`${url}/swagger-ui.css`],
4715
- js: [`${url}/swagger-ui-bundle.js`]
4716
- };
4717
- };
4718
-
4719
- // src/index.ts
4720
- var SwaggerUI = (options) => {
4721
- const asset = remoteAssets({ version: options?.version });
4722
- delete options.version;
4723
- if (options.manuallySwaggerUIHtml) {
4724
- return options.manuallySwaggerUIHtml(asset);
4725
- }
4726
- const optionsStrings = renderSwaggerUIOptions(options);
4727
- return `
4728
- <div>
4729
- <div id="swagger-ui"></div>
4730
- ${asset.css.map((url) => html`<link rel="stylesheet" href="${url}" />`)}
4731
- ${asset.js.map((url) => html`<script src="${url}" crossorigin="anonymous"></script>`)}
4732
- <script>
4733
- window.onload = () => {
4734
- window.ui = SwaggerUIBundle({
4735
- dom_id: '#swagger-ui',${optionsStrings},
4736
- })
4737
- }
4738
- </script>
4739
- </div>
4740
- `;
4741
- };
4742
- var middleware = (options) => async (c) => {
4743
- const title = options?.title ?? "SwaggerUI";
4744
- return c.html(
4745
- /* html */
4746
- `
4747
- <html lang="en">
4748
- <head>
4749
- <meta charset="utf-8" />
4750
- <meta name="viewport" content="width=device-width, initial-scale=1" />
4751
- <meta name="description" content="SwaggerUI" />
4752
- <title>${title}</title>
4753
- </head>
4754
- <body>
4755
- ${SwaggerUI(options)}
4756
- </body>
4757
- </html>
4758
- `
4759
- );
4760
- };
4761
-
4762
2480
  function success(data, options = {}) {
4763
2481
  const { status = 200, meta = {} } = options;
4764
2482
  return {
@@ -4926,7 +2644,7 @@ function asyncHandler(fn) {
4926
2644
  }
4927
2645
 
4928
2646
  function createResourceRoutes(resource, version, config = {}) {
4929
- const app = new Hono();
2647
+ const app = new hono.Hono();
4930
2648
  const {
4931
2649
  methods = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
4932
2650
  customMiddleware = [],
@@ -6236,7 +3954,7 @@ class ApiServer {
6236
3954
  description: options.apiDescription || "Auto-generated REST API for s3db.js resources"
6237
3955
  }
6238
3956
  };
6239
- this.app = new Hono();
3957
+ this.app = new hono.Hono();
6240
3958
  this.server = null;
6241
3959
  this.isRunning = false;
6242
3960
  this.openAPISpec = null;
@@ -6323,7 +4041,7 @@ class ApiServer {
6323
4041
  return c.json(this.openAPISpec);
6324
4042
  });
6325
4043
  if (this.options.docsUI === "swagger") {
6326
- this.app.get("/docs", middleware({
4044
+ this.app.get("/docs", swaggerUi.swaggerUI({
6327
4045
  url: "/openapi.json"
6328
4046
  }));
6329
4047
  } else {
@@ -6402,7 +4120,7 @@ class ApiServer {
6402
4120
  const { port, host } = this.options;
6403
4121
  return new Promise((resolve, reject) => {
6404
4122
  try {
6405
- this.server = serve({
4123
+ this.server = nodeServer.serve({
6406
4124
  fetch: this.app.fetch,
6407
4125
  port,
6408
4126
  hostname: host
@@ -15642,6 +13360,9 @@ class RelationPlugin extends Plugin {
15642
13360
  this.batchSize = config.batchSize || 100;
15643
13361
  this.preventN1 = config.preventN1 !== void 0 ? config.preventN1 : true;
15644
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;
15645
13366
  this._loaderCache = /* @__PURE__ */ new Map();
15646
13367
  this._partitionCache = /* @__PURE__ */ new Map();
15647
13368
  this.stats = {
@@ -15650,7 +13371,8 @@ class RelationPlugin extends Plugin {
15650
13371
  batchLoads: 0,
15651
13372
  cascadeOperations: 0,
15652
13373
  partitionCacheHits: 0,
15653
- deduplicatedQueries: 0
13374
+ deduplicatedQueries: 0,
13375
+ fallbackLimitWarnings: 0
15654
13376
  };
15655
13377
  }
15656
13378
  /**
@@ -15915,13 +13637,7 @@ class RelationPlugin extends Plugin {
15915
13637
  localKeys
15916
13638
  );
15917
13639
  } else {
15918
- if (this.verbose) {
15919
- console.log(
15920
- `[RelationPlugin] No partition found for ${relatedResource.name}.${config.foreignKey}, using full scan`
15921
- );
15922
- }
15923
- const allRelated = await relatedResource.list({ limit: 1e4 });
15924
- relatedRecords = allRelated.filter((r) => localKeys.includes(r[config.foreignKey]));
13640
+ relatedRecords = await this._fallbackLoad(relatedResource, config.foreignKey, localKeys);
15925
13641
  }
15926
13642
  const relatedMap = /* @__PURE__ */ new Map();
15927
13643
  relatedRecords.forEach((related) => {
@@ -15960,13 +13676,7 @@ class RelationPlugin extends Plugin {
15960
13676
  localKeys
15961
13677
  );
15962
13678
  } else {
15963
- if (this.verbose) {
15964
- console.log(
15965
- `[RelationPlugin] No partition found for ${relatedResource.name}.${config.foreignKey}, using full scan`
15966
- );
15967
- }
15968
- const allRelated = await relatedResource.list({ limit: 1e4 });
15969
- relatedRecords = allRelated.filter((r) => localKeys.includes(r[config.foreignKey]));
13679
+ relatedRecords = await this._fallbackLoad(relatedResource, config.foreignKey, localKeys);
15970
13680
  }
15971
13681
  const relatedMap = /* @__PURE__ */ new Map();
15972
13682
  relatedRecords.forEach((related) => {
@@ -16012,13 +13722,7 @@ class RelationPlugin extends Plugin {
16012
13722
  foreignKeys
16013
13723
  );
16014
13724
  } else {
16015
- if (this.verbose) {
16016
- console.log(
16017
- `[RelationPlugin] No partition found for ${relatedResource.name}.${config.localKey}, using full scan`
16018
- );
16019
- }
16020
- const allRelated = await relatedResource.list({ limit: 1e4 });
16021
- return allRelated.filter((r) => foreignKeys.includes(r[config.localKey]));
13725
+ return await this._fallbackLoad(relatedResource, config.localKey, foreignKeys);
16022
13726
  }
16023
13727
  });
16024
13728
  if (!ok) {
@@ -16075,13 +13779,7 @@ class RelationPlugin extends Plugin {
16075
13779
  localKeys
16076
13780
  );
16077
13781
  } else {
16078
- if (this.verbose) {
16079
- console.log(
16080
- `[RelationPlugin] No partition found for ${junctionResource.name}.${config.foreignKey}, using full scan`
16081
- );
16082
- }
16083
- const allJunction = await junctionResource.list({ limit: 1e4 });
16084
- junctionRecords = allJunction.filter((j) => localKeys.includes(j[config.foreignKey]));
13782
+ junctionRecords = await this._fallbackLoad(junctionResource, config.foreignKey, localKeys);
16085
13783
  }
16086
13784
  if (junctionRecords.length === 0) {
16087
13785
  records.forEach((r) => r[relationName] = []);
@@ -16098,13 +13796,7 @@ class RelationPlugin extends Plugin {
16098
13796
  otherKeys
16099
13797
  );
16100
13798
  } else {
16101
- if (this.verbose) {
16102
- console.log(
16103
- `[RelationPlugin] No partition found for ${relatedResource.name}.${config.localKey}, using full scan`
16104
- );
16105
- }
16106
- const allRelated = await relatedResource.list({ limit: 1e4 });
16107
- relatedRecords = allRelated.filter((r) => otherKeys.includes(r[config.localKey]));
13799
+ relatedRecords = await this._fallbackLoad(relatedResource, config.localKey, otherKeys);
16108
13800
  }
16109
13801
  const relatedMap = /* @__PURE__ */ new Map();
16110
13802
  relatedRecords.forEach((related) => {
@@ -16128,6 +13820,47 @@ class RelationPlugin extends Plugin {
16128
13820
  }
16129
13821
  return records;
16130
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
+ }
16131
13864
  /**
16132
13865
  * Find partition by field name (for efficient relation loading)
16133
13866
  * Uses cache to avoid repeated lookups
@@ -16203,6 +13936,7 @@ class RelationPlugin extends Plugin {
16203
13936
  /**
16204
13937
  * Cascade delete operation
16205
13938
  * Uses partitions when available for efficient cascade
13939
+ * Supports transaction/rollback when enabled
16206
13940
  * @private
16207
13941
  */
16208
13942
  async _cascadeDelete(record, resource, relationName, config) {
@@ -16214,6 +13948,8 @@ class RelationPlugin extends Plugin {
16214
13948
  relation: relationName
16215
13949
  });
16216
13950
  }
13951
+ const deletedRecords = [];
13952
+ config.type === "belongsToMany" ? this.database.resource(config.through) : null;
16217
13953
  try {
16218
13954
  if (config.type === "hasMany") {
16219
13955
  let relatedRecords;
@@ -16233,12 +13969,15 @@ class RelationPlugin extends Plugin {
16233
13969
  [config.foreignKey]: record[config.localKey]
16234
13970
  });
16235
13971
  }
16236
- for (const related of relatedRecords) {
16237
- await relatedResource.delete(related.id);
13972
+ if (this.cascadeTransactions) {
13973
+ deletedRecords.push(...relatedRecords.map((r) => ({ type: "delete", resource: relatedResource, record: r })));
16238
13974
  }
13975
+ await this._batchProcess(relatedRecords, async (related) => {
13976
+ return await relatedResource.delete(related.id);
13977
+ });
16239
13978
  if (this.verbose) {
16240
13979
  console.log(
16241
- `[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)`
16242
13981
  );
16243
13982
  }
16244
13983
  } else if (config.type === "hasOne") {
@@ -16255,15 +13994,18 @@ class RelationPlugin extends Plugin {
16255
13994
  });
16256
13995
  }
16257
13996
  if (relatedRecords.length > 0) {
13997
+ if (this.cascadeTransactions) {
13998
+ deletedRecords.push({ type: "delete", resource: relatedResource, record: relatedRecords[0] });
13999
+ }
16258
14000
  await relatedResource.delete(relatedRecords[0].id);
16259
14001
  }
16260
14002
  } else if (config.type === "belongsToMany") {
16261
- const junctionResource = this.database.resource(config.through);
16262
- if (junctionResource) {
14003
+ const junctionResource2 = this.database.resource(config.through);
14004
+ if (junctionResource2) {
16263
14005
  let junctionRecords;
16264
- const partitionName = this._findPartitionByField(junctionResource, config.foreignKey);
14006
+ const partitionName = this._findPartitionByField(junctionResource2, config.foreignKey);
16265
14007
  if (partitionName) {
16266
- junctionRecords = await junctionResource.list({
14008
+ junctionRecords = await junctionResource2.list({
16267
14009
  partition: partitionName,
16268
14010
  partitionValues: { [config.foreignKey]: record[config.localKey] }
16269
14011
  });
@@ -16273,21 +14015,45 @@ class RelationPlugin extends Plugin {
16273
14015
  );
16274
14016
  }
16275
14017
  } else {
16276
- junctionRecords = await junctionResource.query({
14018
+ junctionRecords = await junctionResource2.query({
16277
14019
  [config.foreignKey]: record[config.localKey]
16278
14020
  });
16279
14021
  }
16280
- for (const junction of junctionRecords) {
16281
- await junctionResource.delete(junction.id);
14022
+ if (this.cascadeTransactions) {
14023
+ deletedRecords.push(...junctionRecords.map((j) => ({ type: "delete", resource: junctionResource2, record: j })));
16282
14024
  }
14025
+ await this._batchProcess(junctionRecords, async (junction) => {
14026
+ return await junctionResource2.delete(junction.id);
14027
+ });
16283
14028
  if (this.verbose) {
16284
14029
  console.log(
16285
- `[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)`
16286
14031
  );
16287
14032
  }
16288
14033
  }
16289
14034
  }
16290
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
+ }
16291
14057
  throw new CascadeError("delete", resource.name, record.id, error, {
16292
14058
  relation: relationName,
16293
14059
  relatedResource: config.resource
@@ -16297,6 +14063,7 @@ class RelationPlugin extends Plugin {
16297
14063
  /**
16298
14064
  * Cascade update operation (update foreign keys when local key changes)
16299
14065
  * Uses partitions when available for efficient cascade
14066
+ * Supports transaction/rollback when enabled
16300
14067
  * @private
16301
14068
  */
16302
14069
  async _cascadeUpdate(record, changes, resource, relationName, config) {
@@ -16305,6 +14072,7 @@ class RelationPlugin extends Plugin {
16305
14072
  if (!relatedResource) {
16306
14073
  return;
16307
14074
  }
14075
+ const updatedRecords = [];
16308
14076
  try {
16309
14077
  const oldLocalKeyValue = record[config.localKey];
16310
14078
  const newLocalKeyValue = changes[config.localKey];
@@ -16328,17 +14096,48 @@ class RelationPlugin extends Plugin {
16328
14096
  [config.foreignKey]: oldLocalKeyValue
16329
14097
  });
16330
14098
  }
16331
- for (const related of relatedRecords) {
16332
- await relatedResource.update(related.id, {
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, {
16333
14111
  [config.foreignKey]: newLocalKeyValue
16334
14112
  }, { skipCascade: true });
16335
- }
14113
+ });
16336
14114
  if (this.verbose) {
16337
14115
  console.log(
16338
- `[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)`
16339
14117
  );
16340
14118
  }
16341
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
+ }
16342
14141
  throw new CascadeError("update", resource.name, record.id, error, {
16343
14142
  relation: relationName,
16344
14143
  relatedResource: config.resource
@@ -19163,7 +16962,17 @@ class Client extends EventEmitter {
19163
16962
  Bucket: this.config.bucket,
19164
16963
  Key: keyPrefix ? path$1.join(keyPrefix, key) : key
19165
16964
  };
19166
- const [ok, err, response] = await tryFn(() => this.sendCommand(new clientS3.HeadObjectCommand(options)));
16965
+ const [ok, err, response] = await tryFn(async () => {
16966
+ const res = await this.sendCommand(new clientS3.HeadObjectCommand(options));
16967
+ if (res.Metadata) {
16968
+ const decodedMetadata = {};
16969
+ for (const [key2, value] of Object.entries(res.Metadata)) {
16970
+ decodedMetadata[key2] = metadataDecode(value);
16971
+ }
16972
+ res.Metadata = decodedMetadata;
16973
+ }
16974
+ return res;
16975
+ });
19167
16976
  this.emit("headObject", err || response, { key });
19168
16977
  if (!ok) {
19169
16978
  throw mapAwsError(err, {
@@ -19175,14 +16984,29 @@ class Client extends EventEmitter {
19175
16984
  }
19176
16985
  return response;
19177
16986
  }
19178
- async copyObject({ from, to }) {
16987
+ async copyObject({ from, to, metadata, metadataDirective, contentType }) {
16988
+ const keyPrefix = typeof this.config.keyPrefix === "string" ? this.config.keyPrefix : "";
19179
16989
  const options = {
19180
16990
  Bucket: this.config.bucket,
19181
- Key: this.config.keyPrefix ? path$1.join(this.config.keyPrefix, to) : to,
19182
- CopySource: path$1.join(this.config.bucket, this.config.keyPrefix ? path$1.join(this.config.keyPrefix, from) : from)
16991
+ Key: keyPrefix ? path$1.join(keyPrefix, to) : to,
16992
+ CopySource: path$1.join(this.config.bucket, keyPrefix ? path$1.join(keyPrefix, from) : from)
19183
16993
  };
16994
+ if (metadataDirective) {
16995
+ options.MetadataDirective = metadataDirective;
16996
+ }
16997
+ if (metadata && typeof metadata === "object") {
16998
+ const encodedMetadata = {};
16999
+ for (const [key, value] of Object.entries(metadata)) {
17000
+ const { encoded } = metadataEncode(value);
17001
+ encodedMetadata[key] = encoded;
17002
+ }
17003
+ options.Metadata = encodedMetadata;
17004
+ }
17005
+ if (contentType) {
17006
+ options.ContentType = contentType;
17007
+ }
19184
17008
  const [ok, err, response] = await tryFn(() => this.sendCommand(new clientS3.CopyObjectCommand(options)));
19185
- this.emit("copyObject", err || response, { from, to });
17009
+ this.emit("copyObject", err || response, { from, to, metadataDirective });
19186
17010
  if (!ok) {
19187
17011
  throw mapAwsError(err, {
19188
17012
  bucket: this.config.bucket,
@@ -20824,7 +18648,7 @@ class ResourceReader extends EventEmitter {
20824
18648
  this.batchSize = batchSize;
20825
18649
  this.concurrency = concurrency;
20826
18650
  this.input = new ResourceIdsPageReader({ resource: this.resource });
20827
- this.transform = new require$$3.Transform({
18651
+ this.transform = new stream$1.Transform({
20828
18652
  objectMode: true,
20829
18653
  transform: this._transform.bind(this)
20830
18654
  });
@@ -20876,7 +18700,7 @@ class ResourceWriter extends EventEmitter {
20876
18700
  this.concurrency = concurrency;
20877
18701
  this.buffer = [];
20878
18702
  this.writing = false;
20879
- this.writable = new require$$3.Writable({
18703
+ this.writable = new stream$1.Writable({
20880
18704
  objectMode: true,
20881
18705
  write: this._write.bind(this)
20882
18706
  });
@@ -22385,6 +20209,235 @@ ${errorDetails}`,
22385
20209
  return finalResult;
22386
20210
  }
22387
20211
  }
20212
+ /**
20213
+ * Patch resource (partial update optimized for metadata-only behaviors)
20214
+ *
20215
+ * This method provides an optimized update path for resources using metadata-only behaviors
20216
+ * (enforce-limits, truncate-data). It uses HeadObject + CopyObject for atomic updates without
20217
+ * body transfer, eliminating race conditions and reducing latency by ~50%.
20218
+ *
20219
+ * For behaviors that store data in body (body-overflow, body-only), it automatically falls
20220
+ * back to the standard update() method.
20221
+ *
20222
+ * @param {string} id - Resource ID
20223
+ * @param {Object} fields - Fields to update (partial data)
20224
+ * @param {Object} options - Update options
20225
+ * @param {string} options.partition - Partition name (if using partitions)
20226
+ * @param {Object} options.partitionValues - Partition values (if using partitions)
20227
+ * @returns {Promise<Object>} Updated resource data
20228
+ *
20229
+ * @example
20230
+ * // Fast atomic update (enforce-limits behavior)
20231
+ * await resource.patch('user-123', { status: 'active', loginCount: 42 });
20232
+ *
20233
+ * @example
20234
+ * // With partitions
20235
+ * await resource.patch('order-456', { status: 'shipped' }, {
20236
+ * partition: 'byRegion',
20237
+ * partitionValues: { region: 'US' }
20238
+ * });
20239
+ */
20240
+ async patch(id, fields, options = {}) {
20241
+ if (lodashEs.isEmpty(id)) {
20242
+ throw new Error("id cannot be empty");
20243
+ }
20244
+ if (!fields || typeof fields !== "object") {
20245
+ throw new Error("fields must be a non-empty object");
20246
+ }
20247
+ const behavior = this.behavior;
20248
+ const hasNestedFields = Object.keys(fields).some((key) => key.includes("."));
20249
+ if ((behavior === "enforce-limits" || behavior === "truncate-data") && !hasNestedFields) {
20250
+ return await this._patchViaCopyObject(id, fields, options);
20251
+ }
20252
+ return await this.update(id, fields, options);
20253
+ }
20254
+ /**
20255
+ * Internal helper: Optimized patch using HeadObject + CopyObject
20256
+ * Only works for metadata-only behaviors (enforce-limits, truncate-data)
20257
+ * Only for simple field updates (no nested fields with dot notation)
20258
+ * @private
20259
+ */
20260
+ async _patchViaCopyObject(id, fields, options = {}) {
20261
+ const { partition, partitionValues } = options;
20262
+ const key = this.getResourceKey(id);
20263
+ const headResponse = await this.client.headObject(key);
20264
+ const currentMetadata = headResponse.Metadata || {};
20265
+ let currentData = await this.schema.unmapper(currentMetadata);
20266
+ if (!currentData.id) {
20267
+ currentData.id = id;
20268
+ }
20269
+ const fieldsClone = lodashEs.cloneDeep(fields);
20270
+ let mergedData = lodashEs.cloneDeep(currentData);
20271
+ for (const [key2, value] of Object.entries(fieldsClone)) {
20272
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
20273
+ mergedData[key2] = lodashEs.merge({}, mergedData[key2], value);
20274
+ } else {
20275
+ mergedData[key2] = lodashEs.cloneDeep(value);
20276
+ }
20277
+ }
20278
+ if (this.config.timestamps) {
20279
+ mergedData.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
20280
+ }
20281
+ const validationResult = await this.schema.validate(mergedData);
20282
+ if (validationResult !== true) {
20283
+ throw new ValidationError("Validation failed during patch", validationResult);
20284
+ }
20285
+ const newMetadata = await this.schema.mapper(mergedData);
20286
+ newMetadata._v = String(this.version);
20287
+ await this.client.copyObject({
20288
+ from: key,
20289
+ to: key,
20290
+ metadataDirective: "REPLACE",
20291
+ metadata: newMetadata
20292
+ });
20293
+ if (this.config.partitions && Object.keys(this.config.partitions).length > 0) {
20294
+ const oldData = { ...currentData, id };
20295
+ const newData = { ...mergedData, id };
20296
+ if (this.config.asyncPartitions) {
20297
+ setImmediate(() => {
20298
+ this.handlePartitionReferenceUpdates(oldData, newData).catch((err) => {
20299
+ this.emit("partitionIndexError", {
20300
+ operation: "patch",
20301
+ id,
20302
+ error: err
20303
+ });
20304
+ });
20305
+ });
20306
+ } else {
20307
+ await this.handlePartitionReferenceUpdates(oldData, newData);
20308
+ }
20309
+ }
20310
+ return mergedData;
20311
+ }
20312
+ /**
20313
+ * Replace resource (full object replacement without GET)
20314
+ *
20315
+ * This method performs a direct PUT operation without fetching the current object.
20316
+ * Use this when you already have the complete object and want to replace it entirely,
20317
+ * saving 1 S3 request (GET).
20318
+ *
20319
+ * ⚠️ Warning: You must provide ALL required fields. Missing fields will NOT be preserved
20320
+ * from the current object. This method does not merge with existing data.
20321
+ *
20322
+ * @param {string} id - Resource ID
20323
+ * @param {Object} fullData - Complete object data (all required fields)
20324
+ * @param {Object} options - Update options
20325
+ * @param {string} options.partition - Partition name (if using partitions)
20326
+ * @param {Object} options.partitionValues - Partition values (if using partitions)
20327
+ * @returns {Promise<Object>} Replaced resource data
20328
+ *
20329
+ * @example
20330
+ * // Replace entire object (must include ALL required fields)
20331
+ * await resource.replace('user-123', {
20332
+ * name: 'John Doe',
20333
+ * email: 'john@example.com',
20334
+ * status: 'active',
20335
+ * loginCount: 42
20336
+ * });
20337
+ *
20338
+ * @example
20339
+ * // With partitions
20340
+ * await resource.replace('order-456', fullOrderData, {
20341
+ * partition: 'byRegion',
20342
+ * partitionValues: { region: 'US' }
20343
+ * });
20344
+ */
20345
+ async replace(id, fullData, options = {}) {
20346
+ if (lodashEs.isEmpty(id)) {
20347
+ throw new Error("id cannot be empty");
20348
+ }
20349
+ if (!fullData || typeof fullData !== "object") {
20350
+ throw new Error("fullData must be a non-empty object");
20351
+ }
20352
+ const { partition, partitionValues } = options;
20353
+ const dataClone = lodashEs.cloneDeep(fullData);
20354
+ const attributesWithDefaults = this.applyDefaults(dataClone);
20355
+ if (this.config.timestamps) {
20356
+ if (!attributesWithDefaults.createdAt) {
20357
+ attributesWithDefaults.createdAt = (/* @__PURE__ */ new Date()).toISOString();
20358
+ }
20359
+ attributesWithDefaults.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
20360
+ }
20361
+ const completeData = { id, ...attributesWithDefaults };
20362
+ const {
20363
+ errors,
20364
+ isValid,
20365
+ data: validated
20366
+ } = await this.validate(completeData);
20367
+ if (!isValid) {
20368
+ const errorMsg = errors && errors.length && errors[0].message ? errors[0].message : "Replace failed";
20369
+ throw new InvalidResourceItem({
20370
+ bucket: this.client.config.bucket,
20371
+ resourceName: this.name,
20372
+ attributes: completeData,
20373
+ validation: errors,
20374
+ message: errorMsg
20375
+ });
20376
+ }
20377
+ const { id: validatedId, ...validatedAttributes } = validated;
20378
+ const mappedMetadata = await this.schema.mapper(validatedAttributes);
20379
+ mappedMetadata._v = String(this.version);
20380
+ const behaviorImpl = getBehavior(this.behavior);
20381
+ const { mappedData: finalMetadata, body } = await behaviorImpl.handleInsert({
20382
+ resource: this,
20383
+ data: validatedAttributes,
20384
+ mappedData: mappedMetadata,
20385
+ originalData: completeData
20386
+ });
20387
+ const key = this.getResourceKey(id);
20388
+ let contentType = void 0;
20389
+ if (body && body !== "") {
20390
+ const [okParse] = await tryFn(() => Promise.resolve(JSON.parse(body)));
20391
+ if (okParse) contentType = "application/json";
20392
+ }
20393
+ if (this.behavior === "body-only" && (!body || body === "")) {
20394
+ throw new Error(`[Resource.replace] Attempt to save object without body! Data: id=${id}, resource=${this.name}`);
20395
+ }
20396
+ const [okPut, errPut] = await tryFn(() => this.client.putObject({
20397
+ key,
20398
+ body,
20399
+ contentType,
20400
+ metadata: finalMetadata
20401
+ }));
20402
+ if (!okPut) {
20403
+ const msg = errPut && errPut.message ? errPut.message : "";
20404
+ if (msg.includes("metadata headers exceed") || msg.includes("Replace failed")) {
20405
+ const totalSize = calculateTotalSize(finalMetadata);
20406
+ const effectiveLimit = calculateEffectiveLimit({
20407
+ s3Limit: 2047,
20408
+ systemConfig: {
20409
+ version: this.version,
20410
+ timestamps: this.config.timestamps,
20411
+ id
20412
+ }
20413
+ });
20414
+ const excess = totalSize - effectiveLimit;
20415
+ errPut.totalSize = totalSize;
20416
+ errPut.limit = 2047;
20417
+ errPut.effectiveLimit = effectiveLimit;
20418
+ errPut.excess = excess;
20419
+ throw new ResourceError("metadata headers exceed", { resourceName: this.name, operation: "replace", id, totalSize, effectiveLimit, excess, suggestion: "Reduce metadata size or number of fields." });
20420
+ }
20421
+ throw errPut;
20422
+ }
20423
+ const replacedObject = { id, ...validatedAttributes };
20424
+ if (this.config.partitions && Object.keys(this.config.partitions).length > 0) {
20425
+ if (this.config.asyncPartitions) {
20426
+ setImmediate(() => {
20427
+ this.handlePartitionReferenceUpdates({}, replacedObject).catch((err) => {
20428
+ this.emit("partitionIndexError", {
20429
+ operation: "replace",
20430
+ id,
20431
+ error: err
20432
+ });
20433
+ });
20434
+ });
20435
+ } else {
20436
+ await this.handlePartitionReferenceUpdates({}, replacedObject);
20437
+ }
20438
+ }
20439
+ return replacedObject;
20440
+ }
22388
20441
  /**
22389
20442
  * Update with conditional check (If-Match ETag)
22390
20443
  * @param {string} id - Resource ID
@@ -23733,29 +21786,6 @@ ${errorDetails}`,
23733
21786
  }
23734
21787
  return filtered;
23735
21788
  }
23736
- async replace(id, attributes) {
23737
- await this.delete(id);
23738
- await new Promise((r) => setTimeout(r, 100));
23739
- const maxWait = 5e3;
23740
- const interval = 50;
23741
- const start = Date.now();
23742
- while (Date.now() - start < maxWait) {
23743
- const exists = await this.exists(id);
23744
- if (!exists) {
23745
- break;
23746
- }
23747
- await new Promise((r) => setTimeout(r, interval));
23748
- }
23749
- const [ok, err, result] = await tryFn(() => this.insert({ ...attributes, id }));
23750
- if (!ok) {
23751
- if (err && err.message && err.message.includes("already exists")) {
23752
- const updateResult = await this.update(id, attributes);
23753
- return updateResult;
23754
- }
23755
- throw err;
23756
- }
23757
- return result;
23758
- }
23759
21789
  // --- MIDDLEWARE SYSTEM ---
23760
21790
  _initMiddleware() {
23761
21791
  this._middlewares = /* @__PURE__ */ new Map();
@@ -23957,7 +21987,7 @@ class Database extends EventEmitter {
23957
21987
  this.id = idGenerator(7);
23958
21988
  this.version = "1";
23959
21989
  this.s3dbVersion = (() => {
23960
- const [ok, err, version] = tryFn(() => true ? "12.0.0" : "latest");
21990
+ const [ok, err, version] = tryFn(() => true ? "12.1.0" : "latest");
23961
21991
  return ok ? version : "latest";
23962
21992
  })();
23963
21993
  this.resources = {};
@@ -26827,7 +24857,7 @@ class ReplicatorPlugin extends Plugin {
26827
24857
  async updateReplicatorLog(logId, updates) {
26828
24858
  if (!this.replicatorLog) return;
26829
24859
  const [ok, err] = await tryFn(async () => {
26830
- await this.replicatorLog.update(logId, {
24860
+ await this.replicatorLog.patch(logId, {
26831
24861
  ...updates,
26832
24862
  lastAttempt: (/* @__PURE__ */ new Date()).toISOString()
26833
24863
  });
@@ -38098,7 +36128,7 @@ class TfStatePlugin extends Plugin {
38098
36128
  console.log(`[TfStatePlugin] Setting up cron monitoring: ${this.monitorCron}`);
38099
36129
  }
38100
36130
  await requirePluginDependency("tfstate-plugin");
38101
- const [ok, err, cronModule] = await tryFn(() => Promise.resolve().then(function () { return nodeCron$1; }));
36131
+ const [ok, err, cronModule] = await tryFn(() => import('node-cron'));
38102
36132
  if (!ok) {
38103
36133
  throw new TfStateError(`Failed to import node-cron: ${err.message}`);
38104
36134
  }
@@ -39795,1415 +37825,6 @@ var prometheusFormatter = /*#__PURE__*/Object.freeze({
39795
37825
  formatPrometheusMetrics: formatPrometheusMetrics
39796
37826
  });
39797
37827
 
39798
- function getDefaultExportFromCjs (x) {
39799
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
39800
- }
39801
-
39802
- var nodeCron$2 = {};
39803
-
39804
- var inlineScheduledTask = {};
39805
-
39806
- var runner = {};
39807
-
39808
- var createId = {};
39809
-
39810
- var hasRequiredCreateId;
39811
-
39812
- function requireCreateId () {
39813
- if (hasRequiredCreateId) return createId;
39814
- hasRequiredCreateId = 1;
39815
- var __importDefault = (createId && createId.__importDefault) || function (mod) {
39816
- return (mod && mod.__esModule) ? mod : { "default": mod };
39817
- };
39818
- Object.defineProperty(createId, "__esModule", { value: true });
39819
- createId.createID = createID;
39820
- const node_crypto_1 = __importDefault(require$$0);
39821
- function createID(prefix = '', length = 16) {
39822
- const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
39823
- const values = node_crypto_1.default.randomBytes(length);
39824
- const id = Array.from(values, v => charset[v % charset.length]).join('');
39825
- return prefix ? `${prefix}-${id}` : id;
39826
- }
39827
-
39828
- return createId;
39829
- }
39830
-
39831
- var logger = {};
39832
-
39833
- var hasRequiredLogger;
39834
-
39835
- function requireLogger () {
39836
- if (hasRequiredLogger) return logger;
39837
- hasRequiredLogger = 1;
39838
- Object.defineProperty(logger, "__esModule", { value: true });
39839
- const levelColors = {
39840
- INFO: '\x1b[36m',
39841
- WARN: '\x1b[33m',
39842
- ERROR: '\x1b[31m',
39843
- DEBUG: '\x1b[35m',
39844
- };
39845
- const GREEN = '\x1b[32m';
39846
- const RESET = '\x1b[0m';
39847
- function log(level, message, extra) {
39848
- const timestamp = new Date().toISOString();
39849
- const color = levelColors[level] ?? '';
39850
- const prefix = `[${timestamp}] [PID: ${process.pid}] ${GREEN}[NODE-CRON]${GREEN} ${color}[${level}]${RESET}`;
39851
- const output = `${prefix} ${message}`;
39852
- switch (level) {
39853
- case 'ERROR':
39854
- console.error(output, extra ?? '');
39855
- break;
39856
- case 'DEBUG':
39857
- console.debug(output, extra ?? '');
39858
- break;
39859
- case 'WARN':
39860
- console.warn(output);
39861
- break;
39862
- case 'INFO':
39863
- default:
39864
- console.info(output);
39865
- break;
39866
- }
39867
- }
39868
- const logger$1 = {
39869
- info(message) {
39870
- log('INFO', message);
39871
- },
39872
- warn(message) {
39873
- log('WARN', message);
39874
- },
39875
- error(message, err) {
39876
- if (message instanceof Error) {
39877
- log('ERROR', message.message, message);
39878
- }
39879
- else {
39880
- log('ERROR', message, err);
39881
- }
39882
- },
39883
- debug(message, err) {
39884
- if (message instanceof Error) {
39885
- log('DEBUG', message.message, message);
39886
- }
39887
- else {
39888
- log('DEBUG', message, err);
39889
- }
39890
- },
39891
- };
39892
- logger.default = logger$1;
39893
-
39894
- return logger;
39895
- }
39896
-
39897
- var trackedPromise = {};
39898
-
39899
- var hasRequiredTrackedPromise;
39900
-
39901
- function requireTrackedPromise () {
39902
- if (hasRequiredTrackedPromise) return trackedPromise;
39903
- hasRequiredTrackedPromise = 1;
39904
- Object.defineProperty(trackedPromise, "__esModule", { value: true });
39905
- trackedPromise.TrackedPromise = void 0;
39906
- class TrackedPromise {
39907
- promise;
39908
- error;
39909
- state;
39910
- value;
39911
- constructor(executor) {
39912
- this.state = 'pending';
39913
- this.promise = new Promise((resolve, reject) => {
39914
- executor((value) => {
39915
- this.state = 'fulfilled';
39916
- this.value = value;
39917
- resolve(value);
39918
- }, (error) => {
39919
- this.state = 'rejected';
39920
- this.error = error;
39921
- reject(error);
39922
- });
39923
- });
39924
- }
39925
- getPromise() {
39926
- return this.promise;
39927
- }
39928
- getState() {
39929
- return this.state;
39930
- }
39931
- isPending() {
39932
- return this.state === 'pending';
39933
- }
39934
- isFulfilled() {
39935
- return this.state === 'fulfilled';
39936
- }
39937
- isRejected() {
39938
- return this.state === 'rejected';
39939
- }
39940
- getValue() {
39941
- return this.value;
39942
- }
39943
- getError() {
39944
- return this.error;
39945
- }
39946
- then(onfulfilled, onrejected) {
39947
- return this.promise.then(onfulfilled, onrejected);
39948
- }
39949
- catch(onrejected) {
39950
- return this.promise.catch(onrejected);
39951
- }
39952
- finally(onfinally) {
39953
- return this.promise.finally(onfinally);
39954
- }
39955
- }
39956
- trackedPromise.TrackedPromise = TrackedPromise;
39957
-
39958
- return trackedPromise;
39959
- }
39960
-
39961
- var hasRequiredRunner;
39962
-
39963
- function requireRunner () {
39964
- if (hasRequiredRunner) return runner;
39965
- hasRequiredRunner = 1;
39966
- var __importDefault = (runner && runner.__importDefault) || function (mod) {
39967
- return (mod && mod.__esModule) ? mod : { "default": mod };
39968
- };
39969
- Object.defineProperty(runner, "__esModule", { value: true });
39970
- runner.Runner = void 0;
39971
- const create_id_1 = requireCreateId();
39972
- const logger_1 = __importDefault(requireLogger());
39973
- const tracked_promise_1 = requireTrackedPromise();
39974
- function emptyOnFn() { }
39975
- function emptyHookFn() { return true; }
39976
- function defaultOnError(date, error) {
39977
- logger_1.default.error('Task failed with error!', error);
39978
- }
39979
- class Runner {
39980
- timeMatcher;
39981
- onMatch;
39982
- noOverlap;
39983
- maxExecutions;
39984
- maxRandomDelay;
39985
- runCount;
39986
- running;
39987
- heartBeatTimeout;
39988
- onMissedExecution;
39989
- onOverlap;
39990
- onError;
39991
- beforeRun;
39992
- onFinished;
39993
- onMaxExecutions;
39994
- constructor(timeMatcher, onMatch, options) {
39995
- this.timeMatcher = timeMatcher;
39996
- this.onMatch = onMatch;
39997
- this.noOverlap = options == undefined || options.noOverlap === undefined ? false : options.noOverlap;
39998
- this.maxExecutions = options?.maxExecutions;
39999
- this.maxRandomDelay = options?.maxRandomDelay || 0;
40000
- this.onMissedExecution = options?.onMissedExecution || emptyOnFn;
40001
- this.onOverlap = options?.onOverlap || emptyOnFn;
40002
- this.onError = options?.onError || defaultOnError;
40003
- this.onFinished = options?.onFinished || emptyHookFn;
40004
- this.beforeRun = options?.beforeRun || emptyHookFn;
40005
- this.onMaxExecutions = options?.onMaxExecutions || emptyOnFn;
40006
- this.runCount = 0;
40007
- this.running = false;
40008
- }
40009
- start() {
40010
- this.running = true;
40011
- let lastExecution;
40012
- let expectedNextExecution;
40013
- const scheduleNextHeartBeat = (currentDate) => {
40014
- if (this.running) {
40015
- clearTimeout(this.heartBeatTimeout);
40016
- this.heartBeatTimeout = setTimeout(heartBeat, getDelay(this.timeMatcher, currentDate));
40017
- }
40018
- };
40019
- const runTask = (date) => {
40020
- return new Promise(async (resolve) => {
40021
- const execution = {
40022
- id: (0, create_id_1.createID)('exec'),
40023
- reason: 'scheduled'
40024
- };
40025
- const shouldExecute = await this.beforeRun(date, execution);
40026
- const randomDelay = Math.floor(Math.random() * this.maxRandomDelay);
40027
- if (shouldExecute) {
40028
- setTimeout(async () => {
40029
- try {
40030
- this.runCount++;
40031
- execution.startedAt = new Date();
40032
- const result = await this.onMatch(date, execution);
40033
- execution.finishedAt = new Date();
40034
- execution.result = result;
40035
- this.onFinished(date, execution);
40036
- if (this.maxExecutions && this.runCount >= this.maxExecutions) {
40037
- this.onMaxExecutions(date);
40038
- this.stop();
40039
- }
40040
- }
40041
- catch (error) {
40042
- execution.finishedAt = new Date();
40043
- execution.error = error;
40044
- this.onError(date, error, execution);
40045
- }
40046
- resolve(true);
40047
- }, randomDelay);
40048
- }
40049
- });
40050
- };
40051
- const checkAndRun = (date) => {
40052
- return new tracked_promise_1.TrackedPromise(async (resolve, reject) => {
40053
- try {
40054
- if (this.timeMatcher.match(date)) {
40055
- await runTask(date);
40056
- }
40057
- resolve(true);
40058
- }
40059
- catch (err) {
40060
- reject(err);
40061
- }
40062
- });
40063
- };
40064
- const heartBeat = async () => {
40065
- const currentDate = nowWithoutMs();
40066
- if (expectedNextExecution && expectedNextExecution.getTime() < currentDate.getTime()) {
40067
- while (expectedNextExecution.getTime() < currentDate.getTime()) {
40068
- logger_1.default.warn(`missed execution at ${expectedNextExecution}! Possible blocking IO or high CPU user at the same process used by node-cron.`);
40069
- expectedNextExecution = this.timeMatcher.getNextMatch(expectedNextExecution);
40070
- runAsync(this.onMissedExecution, expectedNextExecution, defaultOnError);
40071
- }
40072
- }
40073
- if (lastExecution && lastExecution.getState() === 'pending') {
40074
- runAsync(this.onOverlap, currentDate, defaultOnError);
40075
- if (this.noOverlap) {
40076
- logger_1.default.warn('task still running, new execution blocked by overlap prevention!');
40077
- expectedNextExecution = this.timeMatcher.getNextMatch(currentDate);
40078
- scheduleNextHeartBeat(currentDate);
40079
- return;
40080
- }
40081
- }
40082
- lastExecution = checkAndRun(currentDate);
40083
- expectedNextExecution = this.timeMatcher.getNextMatch(currentDate);
40084
- scheduleNextHeartBeat(currentDate);
40085
- };
40086
- this.heartBeatTimeout = setTimeout(() => {
40087
- heartBeat();
40088
- }, getDelay(this.timeMatcher, nowWithoutMs()));
40089
- }
40090
- nextRun() {
40091
- return this.timeMatcher.getNextMatch(new Date());
40092
- }
40093
- stop() {
40094
- this.running = false;
40095
- if (this.heartBeatTimeout) {
40096
- clearTimeout(this.heartBeatTimeout);
40097
- this.heartBeatTimeout = undefined;
40098
- }
40099
- }
40100
- isStarted() {
40101
- return !!this.heartBeatTimeout && this.running;
40102
- }
40103
- isStopped() {
40104
- return !this.isStarted();
40105
- }
40106
- async execute() {
40107
- const date = new Date();
40108
- const execution = {
40109
- id: (0, create_id_1.createID)('exec'),
40110
- reason: 'invoked'
40111
- };
40112
- try {
40113
- const shouldExecute = await this.beforeRun(date, execution);
40114
- if (shouldExecute) {
40115
- this.runCount++;
40116
- execution.startedAt = new Date();
40117
- const result = await this.onMatch(date, execution);
40118
- execution.finishedAt = new Date();
40119
- execution.result = result;
40120
- this.onFinished(date, execution);
40121
- }
40122
- }
40123
- catch (error) {
40124
- execution.finishedAt = new Date();
40125
- execution.error = error;
40126
- this.onError(date, error, execution);
40127
- }
40128
- }
40129
- }
40130
- runner.Runner = Runner;
40131
- async function runAsync(fn, date, onError) {
40132
- try {
40133
- await fn(date);
40134
- }
40135
- catch (error) {
40136
- onError(date, error);
40137
- }
40138
- }
40139
- function getDelay(timeMatcher, currentDate) {
40140
- const maxDelay = 86400000;
40141
- const nextRun = timeMatcher.getNextMatch(currentDate);
40142
- const now = new Date();
40143
- const delay = nextRun.getTime() - now.getTime();
40144
- if (delay > maxDelay) {
40145
- return maxDelay;
40146
- }
40147
- return Math.max(0, delay);
40148
- }
40149
- function nowWithoutMs() {
40150
- const date = new Date();
40151
- date.setMilliseconds(0);
40152
- return date;
40153
- }
40154
-
40155
- return runner;
40156
- }
40157
-
40158
- var timeMatcher = {};
40159
-
40160
- var convertion = {};
40161
-
40162
- var monthNamesConversion = {};
40163
-
40164
- var hasRequiredMonthNamesConversion;
40165
-
40166
- function requireMonthNamesConversion () {
40167
- if (hasRequiredMonthNamesConversion) return monthNamesConversion;
40168
- hasRequiredMonthNamesConversion = 1;
40169
- Object.defineProperty(monthNamesConversion, "__esModule", { value: true });
40170
- monthNamesConversion.default = (() => {
40171
- const months = ['january', 'february', 'march', 'april', 'may', 'june', 'july',
40172
- 'august', 'september', 'october', 'november', 'december'];
40173
- const shortMonths = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
40174
- 'sep', 'oct', 'nov', 'dec'];
40175
- function convertMonthName(expression, items) {
40176
- for (let i = 0; i < items.length; i++) {
40177
- expression = expression.replace(new RegExp(items[i], 'gi'), i + 1);
40178
- }
40179
- return expression;
40180
- }
40181
- function interprete(monthExpression) {
40182
- monthExpression = convertMonthName(monthExpression, months);
40183
- monthExpression = convertMonthName(monthExpression, shortMonths);
40184
- return monthExpression;
40185
- }
40186
- return interprete;
40187
- })();
40188
-
40189
- return monthNamesConversion;
40190
- }
40191
-
40192
- var weekDayNamesConversion = {};
40193
-
40194
- var hasRequiredWeekDayNamesConversion;
40195
-
40196
- function requireWeekDayNamesConversion () {
40197
- if (hasRequiredWeekDayNamesConversion) return weekDayNamesConversion;
40198
- hasRequiredWeekDayNamesConversion = 1;
40199
- Object.defineProperty(weekDayNamesConversion, "__esModule", { value: true });
40200
- weekDayNamesConversion.default = (() => {
40201
- const weekDays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
40202
- 'friday', 'saturday'];
40203
- const shortWeekDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
40204
- function convertWeekDayName(expression, items) {
40205
- for (let i = 0; i < items.length; i++) {
40206
- expression = expression.replace(new RegExp(items[i], 'gi'), i);
40207
- }
40208
- return expression;
40209
- }
40210
- function convertWeekDays(expression) {
40211
- expression = expression.replace('7', '0');
40212
- expression = convertWeekDayName(expression, weekDays);
40213
- return convertWeekDayName(expression, shortWeekDays);
40214
- }
40215
- return convertWeekDays;
40216
- })();
40217
-
40218
- return weekDayNamesConversion;
40219
- }
40220
-
40221
- var asteriskToRangeConversion = {};
40222
-
40223
- var hasRequiredAsteriskToRangeConversion;
40224
-
40225
- function requireAsteriskToRangeConversion () {
40226
- if (hasRequiredAsteriskToRangeConversion) return asteriskToRangeConversion;
40227
- hasRequiredAsteriskToRangeConversion = 1;
40228
- Object.defineProperty(asteriskToRangeConversion, "__esModule", { value: true });
40229
- asteriskToRangeConversion.default = (() => {
40230
- function convertAsterisk(expression, replecement) {
40231
- if (expression.indexOf('*') !== -1) {
40232
- return expression.replace('*', replecement);
40233
- }
40234
- return expression;
40235
- }
40236
- function convertAsterisksToRanges(expressions) {
40237
- expressions[0] = convertAsterisk(expressions[0], '0-59');
40238
- expressions[1] = convertAsterisk(expressions[1], '0-59');
40239
- expressions[2] = convertAsterisk(expressions[2], '0-23');
40240
- expressions[3] = convertAsterisk(expressions[3], '1-31');
40241
- expressions[4] = convertAsterisk(expressions[4], '1-12');
40242
- expressions[5] = convertAsterisk(expressions[5], '0-6');
40243
- return expressions;
40244
- }
40245
- return convertAsterisksToRanges;
40246
- })();
40247
-
40248
- return asteriskToRangeConversion;
40249
- }
40250
-
40251
- var rangeConversion = {};
40252
-
40253
- var hasRequiredRangeConversion;
40254
-
40255
- function requireRangeConversion () {
40256
- if (hasRequiredRangeConversion) return rangeConversion;
40257
- hasRequiredRangeConversion = 1;
40258
- Object.defineProperty(rangeConversion, "__esModule", { value: true });
40259
- rangeConversion.default = (() => {
40260
- function replaceWithRange(expression, text, init, end, stepTxt) {
40261
- const step = parseInt(stepTxt);
40262
- const numbers = [];
40263
- let last = parseInt(end);
40264
- let first = parseInt(init);
40265
- if (first > last) {
40266
- last = parseInt(init);
40267
- first = parseInt(end);
40268
- }
40269
- for (let i = first; i <= last; i += step) {
40270
- numbers.push(i);
40271
- }
40272
- return expression.replace(new RegExp(text, 'i'), numbers.join());
40273
- }
40274
- function convertRange(expression) {
40275
- const rangeRegEx = /(\d+)-(\d+)(\/(\d+)|)/;
40276
- let match = rangeRegEx.exec(expression);
40277
- while (match !== null && match.length > 0) {
40278
- expression = replaceWithRange(expression, match[0], match[1], match[2], match[4] || '1');
40279
- match = rangeRegEx.exec(expression);
40280
- }
40281
- return expression;
40282
- }
40283
- function convertAllRanges(expressions) {
40284
- for (let i = 0; i < expressions.length; i++) {
40285
- expressions[i] = convertRange(expressions[i]);
40286
- }
40287
- return expressions;
40288
- }
40289
- return convertAllRanges;
40290
- })();
40291
-
40292
- return rangeConversion;
40293
- }
40294
-
40295
- var hasRequiredConvertion;
40296
-
40297
- function requireConvertion () {
40298
- if (hasRequiredConvertion) return convertion;
40299
- hasRequiredConvertion = 1;
40300
- var __importDefault = (convertion && convertion.__importDefault) || function (mod) {
40301
- return (mod && mod.__esModule) ? mod : { "default": mod };
40302
- };
40303
- Object.defineProperty(convertion, "__esModule", { value: true });
40304
- const month_names_conversion_1 = __importDefault(requireMonthNamesConversion());
40305
- const week_day_names_conversion_1 = __importDefault(requireWeekDayNamesConversion());
40306
- const asterisk_to_range_conversion_1 = __importDefault(requireAsteriskToRangeConversion());
40307
- const range_conversion_1 = __importDefault(requireRangeConversion());
40308
- convertion.default = (() => {
40309
- function appendSeccondExpression(expressions) {
40310
- if (expressions.length === 5) {
40311
- return ['0'].concat(expressions);
40312
- }
40313
- return expressions;
40314
- }
40315
- function removeSpaces(str) {
40316
- return str.replace(/\s{2,}/g, ' ').trim();
40317
- }
40318
- function normalizeIntegers(expressions) {
40319
- for (let i = 0; i < expressions.length; i++) {
40320
- const numbers = expressions[i].split(',');
40321
- for (let j = 0; j < numbers.length; j++) {
40322
- numbers[j] = parseInt(numbers[j]);
40323
- }
40324
- expressions[i] = numbers;
40325
- }
40326
- return expressions;
40327
- }
40328
- function interprete(expression) {
40329
- let expressions = removeSpaces(`${expression}`).split(' ');
40330
- expressions = appendSeccondExpression(expressions);
40331
- expressions[4] = (0, month_names_conversion_1.default)(expressions[4]);
40332
- expressions[5] = (0, week_day_names_conversion_1.default)(expressions[5]);
40333
- expressions = (0, asterisk_to_range_conversion_1.default)(expressions);
40334
- expressions = (0, range_conversion_1.default)(expressions);
40335
- expressions = normalizeIntegers(expressions);
40336
- return expressions;
40337
- }
40338
- return interprete;
40339
- })();
40340
-
40341
- return convertion;
40342
- }
40343
-
40344
- var localizedTime = {};
40345
-
40346
- var hasRequiredLocalizedTime;
40347
-
40348
- function requireLocalizedTime () {
40349
- if (hasRequiredLocalizedTime) return localizedTime;
40350
- hasRequiredLocalizedTime = 1;
40351
- Object.defineProperty(localizedTime, "__esModule", { value: true });
40352
- localizedTime.LocalizedTime = void 0;
40353
- class LocalizedTime {
40354
- timestamp;
40355
- parts;
40356
- timezone;
40357
- constructor(date, timezone) {
40358
- this.timestamp = date.getTime();
40359
- this.timezone = timezone;
40360
- this.parts = buildDateParts(date, timezone);
40361
- }
40362
- toDate() {
40363
- return new Date(this.timestamp);
40364
- }
40365
- toISO() {
40366
- const gmt = this.parts.gmt.replace(/^GMT/, '');
40367
- const offset = gmt ? gmt : 'Z';
40368
- const pad = (n) => String(n).padStart(2, '0');
40369
- return `${this.parts.year}-${pad(this.parts.month)}-${pad(this.parts.day)}`
40370
- + `T${pad(this.parts.hour)}:${pad(this.parts.minute)}:${pad(this.parts.second)}`
40371
- + `.${String(this.parts.milisecond).padStart(3, '0')}`
40372
- + offset;
40373
- }
40374
- getParts() {
40375
- return this.parts;
40376
- }
40377
- set(field, value) {
40378
- this.parts[field] = value;
40379
- const newDate = new Date(this.toISO());
40380
- this.timestamp = newDate.getTime();
40381
- this.parts = buildDateParts(newDate, this.timezone);
40382
- }
40383
- }
40384
- localizedTime.LocalizedTime = LocalizedTime;
40385
- function buildDateParts(date, timezone) {
40386
- const dftOptions = {
40387
- year: 'numeric',
40388
- month: '2-digit',
40389
- day: '2-digit',
40390
- hour: '2-digit',
40391
- minute: '2-digit',
40392
- second: '2-digit',
40393
- weekday: 'short',
40394
- hour12: false
40395
- };
40396
- if (timezone) {
40397
- dftOptions.timeZone = timezone;
40398
- }
40399
- const dateFormat = new Intl.DateTimeFormat('en-US', dftOptions);
40400
- const parts = dateFormat.formatToParts(date).filter(part => {
40401
- return part.type !== 'literal';
40402
- }).reduce((acc, part) => {
40403
- acc[part.type] = part.value;
40404
- return acc;
40405
- }, {});
40406
- return {
40407
- day: parseInt(parts.day),
40408
- month: parseInt(parts.month),
40409
- year: parseInt(parts.year),
40410
- hour: parts.hour === '24' ? 0 : parseInt(parts.hour),
40411
- minute: parseInt(parts.minute),
40412
- second: parseInt(parts.second),
40413
- milisecond: date.getMilliseconds(),
40414
- weekday: parts.weekday,
40415
- gmt: getTimezoneGMT(date, timezone)
40416
- };
40417
- }
40418
- function getTimezoneGMT(date, timezone) {
40419
- const utcDate = new Date(date.toLocaleString('en-US', { timeZone: 'UTC' }));
40420
- const tzDate = new Date(date.toLocaleString('en-US', { timeZone: timezone }));
40421
- let offsetInMinutes = (utcDate.getTime() - tzDate.getTime()) / 60000;
40422
- const sign = offsetInMinutes <= 0 ? '+' : '-';
40423
- offsetInMinutes = Math.abs(offsetInMinutes);
40424
- if (offsetInMinutes === 0)
40425
- return 'Z';
40426
- const hours = Math.floor(offsetInMinutes / 60).toString().padStart(2, '0');
40427
- const minutes = Math.floor(offsetInMinutes % 60).toString().padStart(2, '0');
40428
- return `GMT${sign}${hours}:${minutes}`;
40429
- }
40430
-
40431
- return localizedTime;
40432
- }
40433
-
40434
- var matcherWalker = {};
40435
-
40436
- var hasRequiredMatcherWalker;
40437
-
40438
- function requireMatcherWalker () {
40439
- if (hasRequiredMatcherWalker) return matcherWalker;
40440
- hasRequiredMatcherWalker = 1;
40441
- var __importDefault = (matcherWalker && matcherWalker.__importDefault) || function (mod) {
40442
- return (mod && mod.__esModule) ? mod : { "default": mod };
40443
- };
40444
- Object.defineProperty(matcherWalker, "__esModule", { value: true });
40445
- matcherWalker.MatcherWalker = void 0;
40446
- const convertion_1 = __importDefault(requireConvertion());
40447
- const localized_time_1 = requireLocalizedTime();
40448
- const time_matcher_1 = requireTimeMatcher();
40449
- const week_day_names_conversion_1 = __importDefault(requireWeekDayNamesConversion());
40450
- class MatcherWalker {
40451
- cronExpression;
40452
- baseDate;
40453
- pattern;
40454
- expressions;
40455
- timeMatcher;
40456
- timezone;
40457
- constructor(cronExpression, baseDate, timezone) {
40458
- this.cronExpression = cronExpression;
40459
- this.baseDate = baseDate;
40460
- this.timeMatcher = new time_matcher_1.TimeMatcher(cronExpression, timezone);
40461
- this.timezone = timezone;
40462
- this.expressions = (0, convertion_1.default)(cronExpression);
40463
- }
40464
- isMatching() {
40465
- return this.timeMatcher.match(this.baseDate);
40466
- }
40467
- matchNext() {
40468
- const findNextDateIgnoringWeekday = () => {
40469
- const baseDate = new Date(this.baseDate.getTime());
40470
- baseDate.setMilliseconds(0);
40471
- const localTime = new localized_time_1.LocalizedTime(baseDate, this.timezone);
40472
- const dateParts = localTime.getParts();
40473
- const date = new localized_time_1.LocalizedTime(localTime.toDate(), this.timezone);
40474
- const seconds = this.expressions[0];
40475
- const nextSecond = availableValue(seconds, dateParts.second);
40476
- if (nextSecond) {
40477
- date.set('second', nextSecond);
40478
- if (this.timeMatcher.match(date.toDate())) {
40479
- return date;
40480
- }
40481
- }
40482
- date.set('second', seconds[0]);
40483
- const minutes = this.expressions[1];
40484
- const nextMinute = availableValue(minutes, dateParts.minute);
40485
- if (nextMinute) {
40486
- date.set('minute', nextMinute);
40487
- if (this.timeMatcher.match(date.toDate())) {
40488
- return date;
40489
- }
40490
- }
40491
- date.set('minute', minutes[0]);
40492
- const hours = this.expressions[2];
40493
- const nextHour = availableValue(hours, dateParts.hour);
40494
- if (nextHour) {
40495
- date.set('hour', nextHour);
40496
- if (this.timeMatcher.match(date.toDate())) {
40497
- return date;
40498
- }
40499
- }
40500
- date.set('hour', hours[0]);
40501
- const days = this.expressions[3];
40502
- const nextDay = availableValue(days, dateParts.day);
40503
- if (nextDay) {
40504
- date.set('day', nextDay);
40505
- if (this.timeMatcher.match(date.toDate())) {
40506
- return date;
40507
- }
40508
- }
40509
- date.set('day', days[0]);
40510
- const months = this.expressions[4];
40511
- const nextMonth = availableValue(months, dateParts.month);
40512
- if (nextMonth) {
40513
- date.set('month', nextMonth);
40514
- if (this.timeMatcher.match(date.toDate())) {
40515
- return date;
40516
- }
40517
- }
40518
- date.set('year', date.getParts().year + 1);
40519
- date.set('month', months[0]);
40520
- return date;
40521
- };
40522
- const date = findNextDateIgnoringWeekday();
40523
- const weekdays = this.expressions[5];
40524
- let currentWeekday = parseInt((0, week_day_names_conversion_1.default)(date.getParts().weekday));
40525
- while (!(weekdays.indexOf(currentWeekday) > -1)) {
40526
- date.set('year', date.getParts().year + 1);
40527
- currentWeekday = parseInt((0, week_day_names_conversion_1.default)(date.getParts().weekday));
40528
- }
40529
- return date;
40530
- }
40531
- }
40532
- matcherWalker.MatcherWalker = MatcherWalker;
40533
- function availableValue(values, currentValue) {
40534
- const availableValues = values.sort((a, b) => a - b).filter(s => s > currentValue);
40535
- if (availableValues.length > 0)
40536
- return availableValues[0];
40537
- return false;
40538
- }
40539
-
40540
- return matcherWalker;
40541
- }
40542
-
40543
- var hasRequiredTimeMatcher;
40544
-
40545
- function requireTimeMatcher () {
40546
- if (hasRequiredTimeMatcher) return timeMatcher;
40547
- hasRequiredTimeMatcher = 1;
40548
- var __importDefault = (timeMatcher && timeMatcher.__importDefault) || function (mod) {
40549
- return (mod && mod.__esModule) ? mod : { "default": mod };
40550
- };
40551
- Object.defineProperty(timeMatcher, "__esModule", { value: true });
40552
- timeMatcher.TimeMatcher = void 0;
40553
- const index_1 = __importDefault(requireConvertion());
40554
- const week_day_names_conversion_1 = __importDefault(requireWeekDayNamesConversion());
40555
- const localized_time_1 = requireLocalizedTime();
40556
- const matcher_walker_1 = requireMatcherWalker();
40557
- function matchValue(allowedValues, value) {
40558
- return allowedValues.indexOf(value) !== -1;
40559
- }
40560
- class TimeMatcher {
40561
- timezone;
40562
- pattern;
40563
- expressions;
40564
- constructor(pattern, timezone) {
40565
- this.timezone = timezone;
40566
- this.pattern = pattern;
40567
- this.expressions = (0, index_1.default)(pattern);
40568
- }
40569
- match(date) {
40570
- const localizedTime = new localized_time_1.LocalizedTime(date, this.timezone);
40571
- const parts = localizedTime.getParts();
40572
- const runOnSecond = matchValue(this.expressions[0], parts.second);
40573
- const runOnMinute = matchValue(this.expressions[1], parts.minute);
40574
- const runOnHour = matchValue(this.expressions[2], parts.hour);
40575
- const runOnDay = matchValue(this.expressions[3], parts.day);
40576
- const runOnMonth = matchValue(this.expressions[4], parts.month);
40577
- const runOnWeekDay = matchValue(this.expressions[5], parseInt((0, week_day_names_conversion_1.default)(parts.weekday)));
40578
- return runOnSecond && runOnMinute && runOnHour && runOnDay && runOnMonth && runOnWeekDay;
40579
- }
40580
- getNextMatch(date) {
40581
- const walker = new matcher_walker_1.MatcherWalker(this.pattern, date, this.timezone);
40582
- const next = walker.matchNext();
40583
- return next.toDate();
40584
- }
40585
- }
40586
- timeMatcher.TimeMatcher = TimeMatcher;
40587
-
40588
- return timeMatcher;
40589
- }
40590
-
40591
- var stateMachine = {};
40592
-
40593
- var hasRequiredStateMachine;
40594
-
40595
- function requireStateMachine () {
40596
- if (hasRequiredStateMachine) return stateMachine;
40597
- hasRequiredStateMachine = 1;
40598
- Object.defineProperty(stateMachine, "__esModule", { value: true });
40599
- stateMachine.StateMachine = void 0;
40600
- const allowedTransitions = {
40601
- 'stopped': ['stopped', 'idle', 'destroyed'],
40602
- 'idle': ['idle', 'running', 'stopped', 'destroyed'],
40603
- 'running': ['running', 'idle', 'stopped', 'destroyed'],
40604
- 'destroyed': ['destroyed']
40605
- };
40606
- class StateMachine {
40607
- state;
40608
- constructor(initial = 'stopped') {
40609
- this.state = initial;
40610
- }
40611
- changeState(state) {
40612
- if (allowedTransitions[this.state].includes(state)) {
40613
- this.state = state;
40614
- }
40615
- else {
40616
- throw new Error(`invalid transition from ${this.state} to ${state}`);
40617
- }
40618
- }
40619
- }
40620
- stateMachine.StateMachine = StateMachine;
40621
-
40622
- return stateMachine;
40623
- }
40624
-
40625
- var hasRequiredInlineScheduledTask;
40626
-
40627
- function requireInlineScheduledTask () {
40628
- if (hasRequiredInlineScheduledTask) return inlineScheduledTask;
40629
- hasRequiredInlineScheduledTask = 1;
40630
- var __importDefault = (inlineScheduledTask && inlineScheduledTask.__importDefault) || function (mod) {
40631
- return (mod && mod.__esModule) ? mod : { "default": mod };
40632
- };
40633
- Object.defineProperty(inlineScheduledTask, "__esModule", { value: true });
40634
- inlineScheduledTask.InlineScheduledTask = void 0;
40635
- const events_1 = __importDefault(EventEmitter);
40636
- const runner_1 = requireRunner();
40637
- const time_matcher_1 = requireTimeMatcher();
40638
- const create_id_1 = requireCreateId();
40639
- const state_machine_1 = requireStateMachine();
40640
- const logger_1 = __importDefault(requireLogger());
40641
- const localized_time_1 = requireLocalizedTime();
40642
- class TaskEmitter extends events_1.default {
40643
- }
40644
- class InlineScheduledTask {
40645
- emitter;
40646
- cronExpression;
40647
- timeMatcher;
40648
- runner;
40649
- id;
40650
- name;
40651
- stateMachine;
40652
- timezone;
40653
- constructor(cronExpression, taskFn, options) {
40654
- this.emitter = new TaskEmitter();
40655
- this.cronExpression = cronExpression;
40656
- this.id = (0, create_id_1.createID)('task', 12);
40657
- this.name = options?.name || this.id;
40658
- this.timezone = options?.timezone;
40659
- this.timeMatcher = new time_matcher_1.TimeMatcher(cronExpression, options?.timezone);
40660
- this.stateMachine = new state_machine_1.StateMachine();
40661
- const runnerOptions = {
40662
- timezone: options?.timezone,
40663
- noOverlap: options?.noOverlap,
40664
- maxExecutions: options?.maxExecutions,
40665
- maxRandomDelay: options?.maxRandomDelay,
40666
- beforeRun: (date, execution) => {
40667
- if (execution.reason === 'scheduled') {
40668
- this.changeState('running');
40669
- }
40670
- this.emitter.emit('execution:started', this.createContext(date, execution));
40671
- return true;
40672
- },
40673
- onFinished: (date, execution) => {
40674
- if (execution.reason === 'scheduled') {
40675
- this.changeState('idle');
40676
- }
40677
- this.emitter.emit('execution:finished', this.createContext(date, execution));
40678
- return true;
40679
- },
40680
- onError: (date, error, execution) => {
40681
- logger_1.default.error(error);
40682
- this.emitter.emit('execution:failed', this.createContext(date, execution));
40683
- this.changeState('idle');
40684
- },
40685
- onOverlap: (date) => {
40686
- this.emitter.emit('execution:overlap', this.createContext(date));
40687
- },
40688
- onMissedExecution: (date) => {
40689
- this.emitter.emit('execution:missed', this.createContext(date));
40690
- },
40691
- onMaxExecutions: (date) => {
40692
- this.emitter.emit('execution:maxReached', this.createContext(date));
40693
- this.destroy();
40694
- }
40695
- };
40696
- this.runner = new runner_1.Runner(this.timeMatcher, (date, execution) => {
40697
- return taskFn(this.createContext(date, execution));
40698
- }, runnerOptions);
40699
- }
40700
- getNextRun() {
40701
- if (this.stateMachine.state !== 'stopped') {
40702
- return this.runner.nextRun();
40703
- }
40704
- return null;
40705
- }
40706
- changeState(state) {
40707
- if (this.runner.isStarted()) {
40708
- this.stateMachine.changeState(state);
40709
- }
40710
- }
40711
- start() {
40712
- if (this.runner.isStopped()) {
40713
- this.runner.start();
40714
- this.stateMachine.changeState('idle');
40715
- this.emitter.emit('task:started', this.createContext(new Date()));
40716
- }
40717
- }
40718
- stop() {
40719
- if (this.runner.isStarted()) {
40720
- this.runner.stop();
40721
- this.stateMachine.changeState('stopped');
40722
- this.emitter.emit('task:stopped', this.createContext(new Date()));
40723
- }
40724
- }
40725
- getStatus() {
40726
- return this.stateMachine.state;
40727
- }
40728
- destroy() {
40729
- if (this.stateMachine.state === 'destroyed')
40730
- return;
40731
- this.stop();
40732
- this.stateMachine.changeState('destroyed');
40733
- this.emitter.emit('task:destroyed', this.createContext(new Date()));
40734
- }
40735
- execute() {
40736
- return new Promise((resolve, reject) => {
40737
- const onFail = (context) => {
40738
- this.off('execution:finished', onFail);
40739
- reject(context.execution?.error);
40740
- };
40741
- const onFinished = (context) => {
40742
- this.off('execution:failed', onFail);
40743
- resolve(context.execution?.result);
40744
- };
40745
- this.once('execution:finished', onFinished);
40746
- this.once('execution:failed', onFail);
40747
- this.runner.execute();
40748
- });
40749
- }
40750
- on(event, fun) {
40751
- this.emitter.on(event, fun);
40752
- }
40753
- off(event, fun) {
40754
- this.emitter.off(event, fun);
40755
- }
40756
- once(event, fun) {
40757
- this.emitter.once(event, fun);
40758
- }
40759
- createContext(executionDate, execution) {
40760
- const localTime = new localized_time_1.LocalizedTime(executionDate, this.timezone);
40761
- const ctx = {
40762
- date: localTime.toDate(),
40763
- dateLocalIso: localTime.toISO(),
40764
- triggeredAt: new Date(),
40765
- task: this,
40766
- execution: execution
40767
- };
40768
- return ctx;
40769
- }
40770
- }
40771
- inlineScheduledTask.InlineScheduledTask = InlineScheduledTask;
40772
-
40773
- return inlineScheduledTask;
40774
- }
40775
-
40776
- var taskRegistry = {};
40777
-
40778
- var hasRequiredTaskRegistry;
40779
-
40780
- function requireTaskRegistry () {
40781
- if (hasRequiredTaskRegistry) return taskRegistry;
40782
- hasRequiredTaskRegistry = 1;
40783
- Object.defineProperty(taskRegistry, "__esModule", { value: true });
40784
- taskRegistry.TaskRegistry = void 0;
40785
- const tasks = new Map();
40786
- class TaskRegistry {
40787
- add(task) {
40788
- if (this.has(task.id)) {
40789
- throw Error(`task ${task.id} already registred!`);
40790
- }
40791
- tasks.set(task.id, task);
40792
- task.on('task:destroyed', () => {
40793
- this.remove(task);
40794
- });
40795
- }
40796
- get(taskId) {
40797
- return tasks.get(taskId);
40798
- }
40799
- remove(task) {
40800
- if (this.has(task.id)) {
40801
- task?.destroy();
40802
- tasks.delete(task.id);
40803
- }
40804
- }
40805
- all() {
40806
- return tasks;
40807
- }
40808
- has(taskId) {
40809
- return tasks.has(taskId);
40810
- }
40811
- killAll() {
40812
- tasks.forEach(id => this.remove(id));
40813
- }
40814
- }
40815
- taskRegistry.TaskRegistry = TaskRegistry;
40816
-
40817
- return taskRegistry;
40818
- }
40819
-
40820
- var patternValidation = {};
40821
-
40822
- var hasRequiredPatternValidation;
40823
-
40824
- function requirePatternValidation () {
40825
- if (hasRequiredPatternValidation) return patternValidation;
40826
- hasRequiredPatternValidation = 1;
40827
- var __importDefault = (patternValidation && patternValidation.__importDefault) || function (mod) {
40828
- return (mod && mod.__esModule) ? mod : { "default": mod };
40829
- };
40830
- Object.defineProperty(patternValidation, "__esModule", { value: true });
40831
- const index_1 = __importDefault(requireConvertion());
40832
- const validationRegex = /^(?:\d+|\*|\*\/\d+)$/;
40833
- function isValidExpression(expression, min, max) {
40834
- const options = expression;
40835
- for (const option of options) {
40836
- const optionAsInt = parseInt(option, 10);
40837
- if ((!Number.isNaN(optionAsInt) &&
40838
- (optionAsInt < min || optionAsInt > max)) ||
40839
- !validationRegex.test(option))
40840
- return false;
40841
- }
40842
- return true;
40843
- }
40844
- function isInvalidSecond(expression) {
40845
- return !isValidExpression(expression, 0, 59);
40846
- }
40847
- function isInvalidMinute(expression) {
40848
- return !isValidExpression(expression, 0, 59);
40849
- }
40850
- function isInvalidHour(expression) {
40851
- return !isValidExpression(expression, 0, 23);
40852
- }
40853
- function isInvalidDayOfMonth(expression) {
40854
- return !isValidExpression(expression, 1, 31);
40855
- }
40856
- function isInvalidMonth(expression) {
40857
- return !isValidExpression(expression, 1, 12);
40858
- }
40859
- function isInvalidWeekDay(expression) {
40860
- return !isValidExpression(expression, 0, 7);
40861
- }
40862
- function validateFields(patterns, executablePatterns) {
40863
- if (isInvalidSecond(executablePatterns[0]))
40864
- throw new Error(`${patterns[0]} is a invalid expression for second`);
40865
- if (isInvalidMinute(executablePatterns[1]))
40866
- throw new Error(`${patterns[1]} is a invalid expression for minute`);
40867
- if (isInvalidHour(executablePatterns[2]))
40868
- throw new Error(`${patterns[2]} is a invalid expression for hour`);
40869
- if (isInvalidDayOfMonth(executablePatterns[3]))
40870
- throw new Error(`${patterns[3]} is a invalid expression for day of month`);
40871
- if (isInvalidMonth(executablePatterns[4]))
40872
- throw new Error(`${patterns[4]} is a invalid expression for month`);
40873
- if (isInvalidWeekDay(executablePatterns[5]))
40874
- throw new Error(`${patterns[5]} is a invalid expression for week day`);
40875
- }
40876
- function validate(pattern) {
40877
- if (typeof pattern !== 'string')
40878
- throw new TypeError('pattern must be a string!');
40879
- const patterns = pattern.split(' ');
40880
- const executablePatterns = (0, index_1.default)(pattern);
40881
- if (patterns.length === 5)
40882
- patterns.unshift('0');
40883
- validateFields(patterns, executablePatterns);
40884
- }
40885
- patternValidation.default = validate;
40886
-
40887
- return patternValidation;
40888
- }
40889
-
40890
- var backgroundScheduledTask = {};
40891
-
40892
- var hasRequiredBackgroundScheduledTask;
40893
-
40894
- function requireBackgroundScheduledTask () {
40895
- if (hasRequiredBackgroundScheduledTask) return backgroundScheduledTask;
40896
- hasRequiredBackgroundScheduledTask = 1;
40897
- var __importDefault = (backgroundScheduledTask && backgroundScheduledTask.__importDefault) || function (mod) {
40898
- return (mod && mod.__esModule) ? mod : { "default": mod };
40899
- };
40900
- Object.defineProperty(backgroundScheduledTask, "__esModule", { value: true });
40901
- const path_1 = path$1;
40902
- const child_process_1 = require$$1;
40903
- const create_id_1 = requireCreateId();
40904
- const stream_1 = require$$3;
40905
- const state_machine_1 = requireStateMachine();
40906
- const localized_time_1 = requireLocalizedTime();
40907
- const logger_1 = __importDefault(requireLogger());
40908
- const time_matcher_1 = requireTimeMatcher();
40909
- const daemonPath = (0, path_1.resolve)(__dirname, 'daemon.js');
40910
- class TaskEmitter extends stream_1.EventEmitter {
40911
- }
40912
- class BackgroundScheduledTask {
40913
- emitter;
40914
- id;
40915
- name;
40916
- cronExpression;
40917
- taskPath;
40918
- options;
40919
- forkProcess;
40920
- stateMachine;
40921
- constructor(cronExpression, taskPath, options) {
40922
- this.cronExpression = cronExpression;
40923
- this.taskPath = taskPath;
40924
- this.options = options;
40925
- this.id = (0, create_id_1.createID)('task');
40926
- this.name = options?.name || this.id;
40927
- this.emitter = new TaskEmitter();
40928
- this.stateMachine = new state_machine_1.StateMachine('stopped');
40929
- this.on('task:stopped', () => {
40930
- this.forkProcess?.kill();
40931
- this.forkProcess = undefined;
40932
- this.stateMachine.changeState('stopped');
40933
- });
40934
- this.on('task:destroyed', () => {
40935
- this.forkProcess?.kill();
40936
- this.forkProcess = undefined;
40937
- this.stateMachine.changeState('destroyed');
40938
- });
40939
- }
40940
- getNextRun() {
40941
- if (this.stateMachine.state !== 'stopped') {
40942
- const timeMatcher = new time_matcher_1.TimeMatcher(this.cronExpression, this.options?.timezone);
40943
- return timeMatcher.getNextMatch(new Date());
40944
- }
40945
- return null;
40946
- }
40947
- start() {
40948
- return new Promise((resolve, reject) => {
40949
- if (this.forkProcess) {
40950
- return resolve(undefined);
40951
- }
40952
- const timeout = setTimeout(() => {
40953
- reject(new Error('Start operation timed out'));
40954
- }, 5000);
40955
- try {
40956
- this.forkProcess = (0, child_process_1.fork)(daemonPath);
40957
- this.forkProcess.on('error', (err) => {
40958
- clearTimeout(timeout);
40959
- reject(new Error(`Error on daemon: ${err.message}`));
40960
- });
40961
- this.forkProcess.on('exit', (code, signal) => {
40962
- if (code !== 0 && signal !== 'SIGTERM') {
40963
- const erro = new Error(`node-cron daemon exited with code ${code || signal}`);
40964
- logger_1.default.error(erro);
40965
- clearTimeout(timeout);
40966
- reject(erro);
40967
- }
40968
- });
40969
- this.forkProcess.on('message', (message) => {
40970
- if (message.jsonError) {
40971
- if (message.context?.execution) {
40972
- message.context.execution.error = deserializeError(message.jsonError);
40973
- delete message.jsonError;
40974
- }
40975
- }
40976
- if (message.context?.task?.state) {
40977
- this.stateMachine.changeState(message.context?.task?.state);
40978
- }
40979
- if (message.context) {
40980
- const execution = message.context?.execution;
40981
- delete execution?.hasError;
40982
- const context = this.createContext(new Date(message.context.date), execution);
40983
- this.emitter.emit(message.event, context);
40984
- }
40985
- });
40986
- this.once('task:started', () => {
40987
- this.stateMachine.changeState('idle');
40988
- clearTimeout(timeout);
40989
- resolve(undefined);
40990
- });
40991
- this.forkProcess.send({
40992
- command: 'task:start',
40993
- path: this.taskPath,
40994
- cron: this.cronExpression,
40995
- options: this.options
40996
- });
40997
- }
40998
- catch (error) {
40999
- reject(error);
41000
- }
41001
- });
41002
- }
41003
- stop() {
41004
- return new Promise((resolve, reject) => {
41005
- if (!this.forkProcess) {
41006
- return resolve(undefined);
41007
- }
41008
- const timeoutId = setTimeout(() => {
41009
- clearTimeout(timeoutId);
41010
- reject(new Error('Stop operation timed out'));
41011
- }, 5000);
41012
- const cleanupAndResolve = () => {
41013
- clearTimeout(timeoutId);
41014
- this.off('task:stopped', onStopped);
41015
- this.forkProcess = undefined;
41016
- resolve(undefined);
41017
- };
41018
- const onStopped = () => {
41019
- cleanupAndResolve();
41020
- };
41021
- this.once('task:stopped', onStopped);
41022
- this.forkProcess.send({
41023
- command: 'task:stop'
41024
- });
41025
- });
41026
- }
41027
- getStatus() {
41028
- return this.stateMachine.state;
41029
- }
41030
- destroy() {
41031
- return new Promise((resolve, reject) => {
41032
- if (!this.forkProcess) {
41033
- return resolve(undefined);
41034
- }
41035
- const timeoutId = setTimeout(() => {
41036
- clearTimeout(timeoutId);
41037
- reject(new Error('Destroy operation timed out'));
41038
- }, 5000);
41039
- const onDestroy = () => {
41040
- clearTimeout(timeoutId);
41041
- this.off('task:destroyed', onDestroy);
41042
- resolve(undefined);
41043
- };
41044
- this.once('task:destroyed', onDestroy);
41045
- this.forkProcess.send({
41046
- command: 'task:destroy'
41047
- });
41048
- });
41049
- }
41050
- execute() {
41051
- return new Promise((resolve, reject) => {
41052
- if (!this.forkProcess) {
41053
- 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.'));
41054
- }
41055
- const timeoutId = setTimeout(() => {
41056
- cleanupListeners();
41057
- reject(new Error('Execution timeout exceeded'));
41058
- }, 5000);
41059
- const cleanupListeners = () => {
41060
- clearTimeout(timeoutId);
41061
- this.off('execution:finished', onFinished);
41062
- this.off('execution:failed', onFail);
41063
- };
41064
- const onFinished = (context) => {
41065
- cleanupListeners();
41066
- resolve(context.execution?.result);
41067
- };
41068
- const onFail = (context) => {
41069
- cleanupListeners();
41070
- reject(context.execution?.error || new Error('Execution failed without specific error'));
41071
- };
41072
- this.once('execution:finished', onFinished);
41073
- this.once('execution:failed', onFail);
41074
- this.forkProcess.send({
41075
- command: 'task:execute'
41076
- });
41077
- });
41078
- }
41079
- on(event, fun) {
41080
- this.emitter.on(event, fun);
41081
- }
41082
- off(event, fun) {
41083
- this.emitter.off(event, fun);
41084
- }
41085
- once(event, fun) {
41086
- this.emitter.once(event, fun);
41087
- }
41088
- createContext(executionDate, execution) {
41089
- const localTime = new localized_time_1.LocalizedTime(executionDate, this.options?.timezone);
41090
- const ctx = {
41091
- date: localTime.toDate(),
41092
- dateLocalIso: localTime.toISO(),
41093
- triggeredAt: new Date(),
41094
- task: this,
41095
- execution: execution
41096
- };
41097
- return ctx;
41098
- }
41099
- }
41100
- function deserializeError(str) {
41101
- const data = JSON.parse(str);
41102
- const Err = globalThis[data.name] || Error;
41103
- const err = new Err(data.message);
41104
- if (data.stack) {
41105
- err.stack = data.stack;
41106
- }
41107
- Object.keys(data).forEach(key => {
41108
- if (!['name', 'message', 'stack'].includes(key)) {
41109
- err[key] = data[key];
41110
- }
41111
- });
41112
- return err;
41113
- }
41114
- backgroundScheduledTask.default = BackgroundScheduledTask;
41115
-
41116
- return backgroundScheduledTask;
41117
- }
41118
-
41119
- var hasRequiredNodeCron;
41120
-
41121
- function requireNodeCron () {
41122
- if (hasRequiredNodeCron) return nodeCron$2;
41123
- hasRequiredNodeCron = 1;
41124
- (function (exports) {
41125
- var __importDefault = (nodeCron$2 && nodeCron$2.__importDefault) || function (mod) {
41126
- return (mod && mod.__esModule) ? mod : { "default": mod };
41127
- };
41128
- Object.defineProperty(exports, "__esModule", { value: true });
41129
- exports.nodeCron = exports.getTask = exports.getTasks = void 0;
41130
- exports.schedule = schedule;
41131
- exports.createTask = createTask;
41132
- exports.solvePath = solvePath;
41133
- exports.validate = validate;
41134
- const inline_scheduled_task_1 = requireInlineScheduledTask();
41135
- const task_registry_1 = requireTaskRegistry();
41136
- const pattern_validation_1 = __importDefault(requirePatternValidation());
41137
- const background_scheduled_task_1 = __importDefault(requireBackgroundScheduledTask());
41138
- const path_1 = __importDefault(path$1);
41139
- const url_1 = require$$5;
41140
- const registry = new task_registry_1.TaskRegistry();
41141
- function schedule(expression, func, options) {
41142
- const task = createTask(expression, func, options);
41143
- task.start();
41144
- return task;
41145
- }
41146
- function createTask(expression, func, options) {
41147
- let task;
41148
- if (func instanceof Function) {
41149
- task = new inline_scheduled_task_1.InlineScheduledTask(expression, func, options);
41150
- }
41151
- else {
41152
- const taskPath = solvePath(func);
41153
- task = new background_scheduled_task_1.default(expression, taskPath, options);
41154
- }
41155
- registry.add(task);
41156
- return task;
41157
- }
41158
- function solvePath(filePath) {
41159
- if (path_1.default.isAbsolute(filePath))
41160
- return (0, url_1.pathToFileURL)(filePath).href;
41161
- if (filePath.startsWith('file://'))
41162
- return filePath;
41163
- const stackLines = new Error().stack?.split('\n');
41164
- if (stackLines) {
41165
- stackLines?.shift();
41166
- const callerLine = stackLines?.find((line) => { return line.indexOf(__filename) === -1; });
41167
- const match = callerLine?.match(/(file:\/\/)?(((\/?)(\w:))?([/\\].+)):\d+:\d+/);
41168
- if (match) {
41169
- const dir = `${match[5] ?? ""}${path_1.default.dirname(match[6])}`;
41170
- return (0, url_1.pathToFileURL)(path_1.default.resolve(dir, filePath)).href;
41171
- }
41172
- }
41173
- throw new Error(`Could not locate task file ${filePath}`);
41174
- }
41175
- function validate(expression) {
41176
- try {
41177
- (0, pattern_validation_1.default)(expression);
41178
- return true;
41179
- }
41180
- catch (e) {
41181
- return false;
41182
- }
41183
- }
41184
- exports.getTasks = registry.all;
41185
- exports.getTask = registry.get;
41186
- exports.nodeCron = {
41187
- schedule,
41188
- createTask,
41189
- validate,
41190
- getTasks: exports.getTasks,
41191
- getTask: exports.getTask,
41192
- };
41193
- exports.default = exports.nodeCron;
41194
-
41195
- } (nodeCron$2));
41196
- return nodeCron$2;
41197
- }
41198
-
41199
- var nodeCronExports = requireNodeCron();
41200
- var nodeCron = /*@__PURE__*/getDefaultExportFromCjs(nodeCronExports);
41201
-
41202
- var nodeCron$1 = /*#__PURE__*/_mergeNamespaces({
41203
- __proto__: null,
41204
- default: nodeCron
41205
- }, [nodeCronExports]);
41206
-
41207
37828
  function silhouetteScore(vectors, assignments, centroids, distanceFn = euclideanDistance) {
41208
37829
  const k = centroids.length;
41209
37830
  const n = vectors.length;