@ecosy/core 0.4.0 → 0.5.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.
Files changed (132) hide show
  1. package/CHANGELOG.md +163 -0
  2. package/dist/cache/disk.d.ts +32 -0
  3. package/dist/cache/disk.js +1 -0
  4. package/dist/cache/disk.mjs +1 -0
  5. package/dist/cache/index.d.ts +17 -0
  6. package/dist/cache/index.js +1 -0
  7. package/dist/cache/index.mjs +1 -0
  8. package/dist/cache/memory.d.ts +19 -0
  9. package/dist/cache/memory.js +1 -0
  10. package/dist/cache/memory.mjs +1 -0
  11. package/dist/cache/redis.d.ts +63 -0
  12. package/dist/cache/redis.js +1 -0
  13. package/dist/cache/redis.mjs +1 -0
  14. package/dist/cache/types.d.ts +35 -0
  15. package/dist/cache/types.js +1 -0
  16. package/dist/cache/types.mjs +1 -0
  17. package/dist/ecosy-core.umd.js +1 -1
  18. package/dist/ecosy-core.umd.js.map +1 -1
  19. package/dist/index.d.ts +0 -9
  20. package/dist/index.js +1 -1
  21. package/dist/index.mjs +1 -1
  22. package/dist/serialize/index.d.ts +62 -0
  23. package/dist/serialize/index.js +1 -0
  24. package/dist/serialize/index.mjs +1 -0
  25. package/dist/serialize/interpolate.d.ts +10 -0
  26. package/dist/serialize/interpolate.js +1 -0
  27. package/dist/serialize/interpolate.mjs +1 -0
  28. package/dist/serialize/json.d.ts +3 -0
  29. package/dist/serialize/json.js +1 -0
  30. package/dist/serialize/json.mjs +1 -0
  31. package/dist/serialize/primitive.d.ts +3 -0
  32. package/dist/serialize/primitive.js +1 -0
  33. package/dist/serialize/primitive.mjs +1 -0
  34. package/dist/serialize/query-string.d.ts +3 -0
  35. package/dist/serialize/query-string.js +1 -0
  36. package/dist/serialize/query-string.mjs +1 -0
  37. package/dist/serialize/types.d.ts +42 -0
  38. package/dist/serialize/url.d.ts +3 -0
  39. package/dist/serialize/url.js +1 -0
  40. package/dist/serialize/url.mjs +1 -0
  41. package/dist/syhemo/collectors.d.ts +25 -0
  42. package/dist/syhemo/collectors.js +1 -0
  43. package/dist/syhemo/collectors.mjs +1 -0
  44. package/dist/syhemo/exposition.d.ts +15 -0
  45. package/dist/syhemo/exposition.js +1 -0
  46. package/dist/syhemo/exposition.mjs +1 -0
  47. package/dist/syhemo/index.d.ts +50 -0
  48. package/dist/syhemo/index.js +1 -0
  49. package/dist/syhemo/index.mjs +1 -0
  50. package/dist/{logger.d.ts → syhemo/logger.d.ts} +23 -11
  51. package/dist/syhemo/logger.js +1 -0
  52. package/dist/{logger.mjs → syhemo/logger.mjs} +1 -1
  53. package/dist/syhemo/types.d.ts +114 -0
  54. package/dist/utilities/index.d.ts +2 -0
  55. package/dist/utilities/index.js +1 -1
  56. package/dist/utilities/index.mjs +1 -1
  57. package/dist/{searchify.d.ts → utilities/searchify.d.ts} +1 -1
  58. package/dist/utilities/searchify.js +1 -0
  59. package/dist/utilities/searchify.mjs +1 -0
  60. package/package.json +35 -37
  61. package/agents/skills/ecosy-core-fetcher/SKILL.md +0 -93
  62. package/dist/env.d.ts +0 -26
  63. package/dist/env.js +0 -1
  64. package/dist/env.mjs +0 -1
  65. package/dist/http/array.d.ts +0 -2
  66. package/dist/http/array.js +0 -1
  67. package/dist/http/array.mjs +0 -1
  68. package/dist/http/client.d.ts +0 -38
  69. package/dist/http/client.js +0 -1
  70. package/dist/http/client.mjs +0 -1
  71. package/dist/http/endpoint.d.ts +0 -8
  72. package/dist/http/endpoint.js +0 -1
  73. package/dist/http/endpoint.mjs +0 -1
  74. package/dist/http/fetcher.d.ts +0 -84
  75. package/dist/http/fetcher.js +0 -1
  76. package/dist/http/fetcher.mjs +0 -1
  77. package/dist/http/http-core.d.ts +0 -5
  78. package/dist/http/http-core.js +0 -1
  79. package/dist/http/http-core.mjs +0 -1
  80. package/dist/http/http-static.d.ts +0 -20
  81. package/dist/http/http-static.js +0 -1
  82. package/dist/http/http-static.mjs +0 -1
  83. package/dist/http/http.d.ts +0 -56
  84. package/dist/http/http.js +0 -1
  85. package/dist/http/http.mjs +0 -1
  86. package/dist/http/index.d.ts +0 -14
  87. package/dist/http/index.js +0 -1
  88. package/dist/http/index.mjs +0 -1
  89. package/dist/http/init.d.ts +0 -83
  90. package/dist/http/init.js +0 -1
  91. package/dist/http/init.mjs +0 -1
  92. package/dist/http/method.d.ts +0 -15
  93. package/dist/http/method.js +0 -1
  94. package/dist/http/method.mjs +0 -1
  95. package/dist/http/plugins/cache.d.ts +0 -13
  96. package/dist/http/plugins/cache.js +0 -1
  97. package/dist/http/plugins/cache.mjs +0 -1
  98. package/dist/http/plugins/dedupe.d.ts +0 -7
  99. package/dist/http/plugins/dedupe.js +0 -1
  100. package/dist/http/plugins/dedupe.mjs +0 -1
  101. package/dist/http/plugins/index.d.ts +0 -3
  102. package/dist/http/plugins/index.js +0 -1
  103. package/dist/http/plugins/index.mjs +0 -1
  104. package/dist/http/plugins/logger.d.ts +0 -24
  105. package/dist/http/plugins/logger.js +0 -1
  106. package/dist/http/plugins/logger.mjs +0 -1
  107. package/dist/http/request.d.ts +0 -26
  108. package/dist/http/response.d.ts +0 -9
  109. package/dist/http/utils.d.ts +0 -21
  110. package/dist/http/utils.js +0 -1
  111. package/dist/http/utils.mjs +0 -1
  112. package/dist/http/xml.d.ts +0 -24
  113. package/dist/http/xml.js +0 -1
  114. package/dist/http/xml.mjs +0 -1
  115. package/dist/logger.js +0 -1
  116. package/dist/node_modules/tslib/tslib.es6.js +0 -1
  117. package/dist/node_modules/tslib/tslib.es6.mjs +0 -1
  118. package/dist/searchify.js +0 -1
  119. package/dist/searchify.mjs +0 -1
  120. package/dist/serialize.d.ts +0 -80
  121. package/dist/serialize.js +0 -1
  122. package/dist/serialize.mjs +0 -1
  123. package/dist/syhemo.d.ts +0 -102
  124. package/dist/syhemo.js +0 -1
  125. package/dist/syhemo.mjs +0 -1
  126. /package/dist/{http/request.js → serialize/types.js} +0 -0
  127. /package/dist/{http/request.mjs → serialize/types.mjs} +0 -0
  128. /package/dist/{http/response.js → syhemo/types.js} +0 -0
  129. /package/dist/{http/response.mjs → syhemo/types.mjs} +0 -0
  130. /package/dist/{slugify.d.ts → utilities/slugify.d.ts} +0 -0
  131. /package/dist/{slugify.js → utilities/slugify.js} +0 -0
  132. /package/dist/{slugify.mjs → utilities/slugify.mjs} +0 -0
@@ -1,83 +0,0 @@
1
- import type { HttpMethod } from "./method";
2
- import type { MaybeArray } from "./array";
3
- import type { Promisable } from "../types";
4
- export type HttpCredentials = "same-origin" | "include" | "omit";
5
- export type HttpCache = "force-cache" | "no-store";
6
- export type HttpMode = "cors" | "no-cors" | "same-origin";
7
- export type HttpRedirect = "follow" | "manual" | "error";
8
- export type HttpPriority = "auto" | "high" | "low";
9
- export type HttpDuplex = "half" | "full";
10
- export type HttpImageFit = "scale-down" | "contain" | "cover" | "crop";
11
- export type HttpPolish = "lossless" | "lossy" | "off";
12
- export type HttpReferrerPolicy = "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
13
- export interface HttpInitNext {
14
- revalidate?: number;
15
- tags?: string[];
16
- }
17
- export interface HttpInitCf {
18
- cacheEverything?: boolean;
19
- cacheTtl?: number;
20
- cacheKey?: string;
21
- cacheTtlByStatus?: Record<string, number>;
22
- cacheTags?: string[];
23
- resolveOverride?: boolean;
24
- image?: {
25
- width?: number;
26
- height?: number;
27
- fit?: HttpImageFit;
28
- format?: string;
29
- quality?: number;
30
- };
31
- apps?: boolean;
32
- scrapeShield?: boolean;
33
- polish?: HttpPolish;
34
- minify?: {
35
- javascript?: boolean;
36
- html?: boolean;
37
- css?: boolean;
38
- };
39
- colo?: string;
40
- }
41
- /** Interceptor that can modify a request before it is sent. */
42
- export type HttpInterceptorRequest = (options: Omit<HttpInitSlice, "url">) => Promisable<Omit<HttpInitSlice, "url">>;
43
- /** Interceptor that can modify a `Response` after it is received. */
44
- export type HttpInterceptorResponse = (response: Response) => Promisable<Response>;
45
- /** Interceptor that transforms the parsed response data. */
46
- export type HttpInterceptorTransform = (data: Record<string, unknown>) => Promisable<any>;
47
- /** Interceptor that handles errors from requests. */
48
- export type HttpInterceptorError = (error: unknown) => Promisable<any>;
49
- /** Tuple type for registering interceptors by phase. */
50
- export type HttpInterceptorParameters = ["request", HttpInterceptorRequest] | ["response", HttpInterceptorResponse] | ["transform", HttpInterceptorTransform] | ["error", HttpInterceptorError];
51
- export interface HttpInitInterceptors {
52
- transform?: MaybeArray<HttpInterceptorTransform>;
53
- request?: MaybeArray<HttpInterceptorRequest>;
54
- response?: MaybeArray<HttpInterceptorResponse>;
55
- error?: MaybeArray<HttpInterceptorError>;
56
- }
57
- export interface HttpInit extends HttpInitNext, HttpInitCf, HttpInitInterceptors {
58
- url: string;
59
- method?: HttpMethod;
60
- query?: Record<string, string | number | boolean | null | undefined>;
61
- params?: Record<string, unknown>;
62
- headers?: Record<string, string>;
63
- body?: unknown;
64
- signal?: AbortSignal;
65
- credentials?: HttpCredentials;
66
- cache?: HttpCache;
67
- mode?: HttpMode;
68
- redirect?: HttpRedirect;
69
- referrer?: string;
70
- referrerPolicy?: HttpReferrerPolicy;
71
- integrity?: string;
72
- keepalive?: boolean;
73
- priority?: HttpPriority;
74
- duplex?: HttpDuplex;
75
- window?: null;
76
- dispatcher?: unknown;
77
- }
78
- export type HttpInitSlice = Omit<HttpInit, keyof HttpInitNext | keyof HttpInitCf | keyof HttpInitInterceptors> & {
79
- next?: HttpInitNext;
80
- cf?: HttpInitCf;
81
- interceptors?: HttpInitInterceptors;
82
- };
83
- export declare function getHttpInitSlice(init: Partial<HttpInit>): HttpInitSlice;
package/dist/http/init.js DELETED
@@ -1 +0,0 @@
1
- "use strict";const e={interceptors:["request","response","transform","error"],next:["revalidate","tags"],cf:["cacheEverything","cacheTtl","cacheKey","cacheTtlByStatus","cacheTags","resolveOverride","image","apps","scrapeShield","polish","minify","colo"]};exports.getHttpInitSlice=function(t){const c={},s={},r={},n={};return Object.entries(t).forEach(([t,i])=>{e.next.includes(t)?s[t]=i:e.interceptors.includes(t)?n[t]=i:e.cf.includes(t)?r[t]=i:c[t]=i}),Object.keys(s).length&&(c.next=s),Object.keys(r).length&&(c.cf=r),Object.keys(n)&&(c.interceptors=n),c};
@@ -1 +0,0 @@
1
- const e={interceptors:["request","response","transform","error"],next:["revalidate","tags"],cf:["cacheEverything","cacheTtl","cacheKey","cacheTtlByStatus","cacheTags","resolveOverride","image","apps","scrapeShield","polish","minify","colo"]};function t(t){const c={},r={},s={},n={};return Object.entries(t).forEach(([t,i])=>{e.next.includes(t)?r[t]=i:e.interceptors.includes(t)?n[t]=i:e.cf.includes(t)?s[t]=i:c[t]=i}),Object.keys(r).length&&(c.next=r),Object.keys(s).length&&(c.cf=s),Object.keys(n)&&(c.interceptors=n),c}export{t as getHttpInitSlice};
@@ -1,15 +0,0 @@
1
- export declare const Methods: {
2
- readonly GET: "GET";
3
- readonly POST: "POST";
4
- readonly PUT: "PUT";
5
- readonly DELETE: "DELETE";
6
- readonly PATCH: "PATCH";
7
- readonly HEAD: "HEAD";
8
- readonly OPTIONS: "OPTIONS";
9
- };
10
- export type HttpMethod = keyof typeof Methods;
11
- export declare const Uploads: {
12
- UPLOAD: string;
13
- RELATED: string;
14
- };
15
- export type HttpUpload = keyof typeof Uploads;
@@ -1 +0,0 @@
1
- "use strict";exports.Methods={GET:"GET",POST:"POST",PUT:"PUT",DELETE:"DELETE",PATCH:"PATCH",HEAD:"HEAD",OPTIONS:"OPTIONS"},exports.Uploads={UPLOAD:"UPLOAD",RELATED:"RELATED"};
@@ -1 +0,0 @@
1
- const E={GET:"GET",POST:"POST",PUT:"PUT",DELETE:"DELETE",PATCH:"PATCH",HEAD:"HEAD",OPTIONS:"OPTIONS"},T={UPLOAD:"UPLOAD",RELATED:"RELATED"};export{E as Methods,T as Uploads};
@@ -1,13 +0,0 @@
1
- import type { FetcherMiddleware } from "../fetcher";
2
- /**
3
- * Options for configuring the cache plugin.
4
- */
5
- export interface CachePluginOptions {
6
- /** Time-to-live for cached responses in milliseconds (default: 60000ms) */
7
- ttl?: number;
8
- }
9
- /**
10
- * Middleware plugin that provides lightweight in-memory caching.
11
- * Responses are cached based on the action key and arguments.
12
- */
13
- export declare function cachePlugin(options?: CachePluginOptions): FetcherMiddleware;
@@ -1 +0,0 @@
1
- "use strict";exports.cachePlugin=function(t={}){var e;const n=null!==(e=t.ttl)&&void 0!==e?e:6e4,a=new Map;return async(t,e,r)=>{const s=`${t.key}_${JSON.stringify(e)}`,i=a.get(s);if(i&&i.expiresAt>Date.now())return i.data;const c=await r();return a.set(s,{data:c,expiresAt:Date.now()+n}),c}};
@@ -1 +0,0 @@
1
- function t(t={}){var e;const n=null!==(e=t.ttl)&&void 0!==e?e:6e4,a=new Map;return async(t,e,r)=>{const i=`${t.key}_${JSON.stringify(e)}`,o=a.get(i);if(o&&o.expiresAt>Date.now())return o.data;const s=await r();return a.set(i,{data:s,expiresAt:Date.now()+n}),s}}export{t as cachePlugin};
@@ -1,7 +0,0 @@
1
- import type { FetcherMiddleware } from "../fetcher";
2
- /**
3
- * Middleware plugin that prevents the "Thundering Herd" problem.
4
- * It deduplicates identical concurrent requests and shares the same Promise
5
- * among all callers, ensuring only one network request is made.
6
- */
7
- export declare function dedupePlugin(): FetcherMiddleware;
@@ -1 +0,0 @@
1
- "use strict";exports.dedupePlugin=function(){const e=new Map;return async(t,n,s)=>{const r=`${t.key}_${JSON.stringify(n)}`;if(e.has(r))return e.get(r);const i=s().finally(()=>{e.delete(r)});return e.set(r,i),i}};
@@ -1 +0,0 @@
1
- function n(){const n=new Map;return async(t,e,r)=>{const s=`${t.key}_${JSON.stringify(e)}`;if(n.has(s))return n.get(s);const c=r().finally(()=>{n.delete(s)});return n.set(s,c),c}}export{n as dedupePlugin};
@@ -1,3 +0,0 @@
1
- export * from "./logger";
2
- export * from "./dedupe";
3
- export * from "./cache";
@@ -1 +0,0 @@
1
- "use strict";var e=require("./logger.js"),r=require("./dedupe.js"),u=require("./cache.js");exports.loggerPlugin=e.loggerPlugin,exports.dedupePlugin=r.dedupePlugin,exports.cachePlugin=u.cachePlugin;
@@ -1 +0,0 @@
1
- export{loggerPlugin}from"./logger.mjs";export{dedupePlugin}from"./dedupe.mjs";export{cachePlugin}from"./cache.mjs";
@@ -1,24 +0,0 @@
1
- import type { FetcherMiddleware } from "../fetcher";
2
- /**
3
- * Interface defining the logging methods required by the loggerPlugin.
4
- */
5
- export interface LoggerPluginOptions {
6
- /** The logger instance to use (e.g. console, winston, @ecosy/logger). Fallbacks to native console if available. */
7
- logger?: any;
8
- /** The method name to call on the logger for successful requests. Defaults to "info" or "log". */
9
- successLevel?: string;
10
- /** The method name to call on the logger for failed requests. Defaults to "error". */
11
- errorLevel?: string;
12
- /** Custom formatter for the request start log. Returns an array of arguments to be spread into the logger. */
13
- formatStart?: (key: string, args: any[]) => any[];
14
- /** Custom formatter for a successful response log. */
15
- formatSuccess?: (key: string, res: any, durationMs: number) => any[];
16
- /** Custom formatter for a failed response log. */
17
- formatError?: (key: string, err: any, durationMs: number) => any[];
18
- }
19
- /**
20
- * Middleware plugin that logs the lifecycle and execution time of requests.
21
- * Uses Dependency Inversion Principle (DIP) to allow passing any custom logger.
22
- * Supports custom log levels mapping and custom formatting.
23
- */
24
- export declare function loggerPlugin(options?: LoggerPluginOptions | any): FetcherMiddleware;
@@ -1 +0,0 @@
1
- "use strict";exports.loggerPlugin=function(o={}){var e,r,t;const n=o&&!o.info&&!o.log&&Object.getPrototypeOf(o)===Object.prototype?o:{logger:o},l="undefined"!=typeof console?console:void 0,c=n.logger||l,i=n.successLevel||"info",s=n.errorLevel||"error",d=(null===(e=null==c?void 0:c[i])||void 0===e?void 0:e.bind(c))||(null===(r=null==c?void 0:c.log)||void 0===r?void 0:r.bind(c))||(()=>{}),u=(null===(t=null==c?void 0:c[s])||void 0===t?void 0:t.bind(c))||(()=>{}),a=n.formatStart||((o,e)=>[`[Fetcher] 🚀 Start: ${o}`,e]),v=n.formatSuccess||((o,e,r)=>[`[Fetcher] ✅ Success: ${o} (${r}ms)`,e]),g=n.formatError||((o,e,r)=>[`[Fetcher] ❌ Error: ${o} (${r}ms)`,e]);return async(o,e,r)=>{const t=Date.now();d(...a(o.key,e));try{const e=await r();return d(...v(o.key,e,Date.now()-t)),e}catch(e){throw u(...g(o.key,e,Date.now()-t)),e}}};
@@ -1 +0,0 @@
1
- function o(o={}){var e,r,t;const n=o&&!o.info&&!o.log&&Object.getPrototypeOf(o)===Object.prototype?o:{logger:o},c="undefined"!=typeof console?console:void 0,l=n.logger||c,i=n.successLevel||"info",d=n.errorLevel||"error",s=(null===(e=null==l?void 0:l[i])||void 0===e?void 0:e.bind(l))||(null===(r=null==l?void 0:l.log)||void 0===r?void 0:r.bind(l))||(()=>{}),a=(null===(t=null==l?void 0:l[d])||void 0===t?void 0:t.bind(l))||(()=>{}),u=n.formatStart||((o,e)=>[`[Fetcher] 🚀 Start: ${o}`,e]),v=n.formatSuccess||((o,e,r)=>[`[Fetcher] ✅ Success: ${o} (${r}ms)`,e]),f=n.formatError||((o,e,r)=>[`[Fetcher] ❌ Error: ${o} (${r}ms)`,e]);return async(o,e,r)=>{const t=Date.now();s(...u(o.key,e));try{const e=await r();return s(...v(o.key,e,Date.now()-t)),e}catch(e){throw a(...f(o.key,e,Date.now()-t)),e}}}export{o as loggerPlugin};
@@ -1,26 +0,0 @@
1
- import type { HttpMethod } from "./method";
2
- /** Accepted query parameter formats for HTTP requests. */
3
- export type HttpQuery = string | Record<string, string | number | boolean | undefined> | Array<[string, string | number | boolean | undefined]> | URLSearchParams;
4
- /** Configuration object for an HTTP request. */
5
- export interface HttpRequest<Body = unknown, Params = Record<string, unknown>, Query = HttpQuery, Headers = Record<string, string>> {
6
- method: HttpMethod;
7
- url: string;
8
- headers?: Headers;
9
- body?: Body;
10
- query?: Query;
11
- params?: Params;
12
- signal?: AbortSignal;
13
- /**
14
- * Pass-through bag for `fetch`'s `RequestInit` options that the
15
- * library does not manage itself (`credentials`, `cache`, `mode`,
16
- * `redirect`, `referrer`, `referrerPolicy`, `integrity`, `keepalive`,
17
- * `priority`, `duplex`) plus framework extensions (`next` on Next.js,
18
- * `cf` on Cloudflare Workers, `dispatcher` on undici).
19
- *
20
- * Lib-level fields (`method`, `headers`, `body`, `signal`) cannot be
21
- * overridden here — they are applied after this bag is spread.
22
- * Unknown keys are silently dropped, so a compromised caller cannot
23
- * smuggle arbitrary fields into `fetch`.
24
- */
25
- configs?: Record<string, unknown>;
26
- }
@@ -1,9 +0,0 @@
1
- /** Normalized response returned by all `Http` methods. */
2
- export interface HttpResponse<T = unknown, E = unknown> {
3
- success: boolean;
4
- data: T;
5
- status: number;
6
- statusText: string;
7
- headers: Record<string, string>;
8
- error: E | null;
9
- }
@@ -1,21 +0,0 @@
1
- import type { HttpInit, HttpInitSlice } from "./init";
2
- import type { HttpQuery } from "./request";
3
- export declare class HttpUtils {
4
- static readonly AllowedOrigins: Set<unknown>;
5
- static defaultHeaders: Record<string, string>;
6
- static isAllowedOrigin(origin: string): boolean;
7
- static isValidQuery(query: unknown): query is HttpQuery;
8
- /** Strip prototype-pollution vectors from a plain object shallowly. */
9
- static stripUnsafeKeys<T extends Record<string, unknown>>(source: T): T;
10
- static normalizeQuery(options: HttpInit): string;
11
- static normalizeURL(options: HttpInitSlice): string;
12
- static normalizeHeaders(headers?: Record<string, string>, isFormData?: boolean): {
13
- [x: string]: string;
14
- };
15
- static removeURL(options: Omit<HttpInitSlice, "url">): HttpInitSlice;
16
- static extractFetchOptions(options: Omit<HttpInitSlice, "url">): RequestInit;
17
- static normalizeBody(options: Omit<HttpInitSlice, "url">): string | FormData | Uint8Array | ArrayBuffer | URLSearchParams | undefined;
18
- /** Parse a URL string into its origin, returning `null` if the input is relative or invalid. */
19
- static safeOrigin(url: string): string | null;
20
- static assertSameOriginResponse(requestURL: string, response: Response, sentHeaders: Record<string, string>): void;
21
- }
@@ -1 +0,0 @@
1
- "use strict";var e=require("../serialize.js"),t=require("../utilities/get.js"),r=require("./method.js"),i=require("../utilities/formdata.js");const s=new Set(["__proto__","constructor","prototype"]),o=new Set(["credentials","cache","mode","redirect","referrer","referrerPolicy","integrity","keepalive","priority","duplex","window","next","cf","dispatcher"]);class n{static isAllowedOrigin(e){return 0===this.AllowedOrigins.size||this.AllowedOrigins.has(e)}static isValidQuery(t){return"string"==typeof t||t instanceof URLSearchParams||(Array.isArray(t)?t.every(t=>Array.isArray(t)&&2===t.length&&"string"==typeof t[0]&&e.Serialize.Primitive.isPrimitive(t[1])):"object"==typeof t&&null!==t&&Object.values(t).every(t=>e.Serialize.Primitive.isPrimitive(t)))}static stripUnsafeKeys(e){const t=Object.create(null);for(const r of Object.keys(e))s.has(r)||(t[r]=e[r]);return t}static normalizeQuery(t){const{method:i,body:s,query:o}=t,a=i===r.Methods.GET&&n.isValidQuery(s)?s:o;if(!a||"object"!=typeof a)return"string"==typeof a?a:"";if(a instanceof URLSearchParams)return a.toString();const c=n.stripUnsafeKeys(a);return e.Serialize.queryString.stringify(c,{skipNull:!0,skipEmptyString:!0})}static normalizeURL(r){const{url:i="",params:s={}}=r,o=n.normalizeQuery(r);let a;if(i){if(i.startsWith("//"))throw new Error(`Http: protocol-relative URLs are not allowed: ${i}`);if(/^[a-z][a-z0-9+.-]*:/i.test(i)){let e;try{e=new URL(i)}catch(e){throw new Error(`Http: invalid absolute URL: ${i}`)}if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error(`Http: unsupported URL scheme: ${e.protocol}`);if(!n.isAllowedOrigin(e.origin))throw new Error(`Http: URL origin '${e.origin}' is not in allowedOrigins`);a=e.toString()}else{const e=(r.url||"/").replace(/\/+$/,""),t=i.replace(/^\/+/,"");a=e?`${e}/${t}`:`/${t}`}}else a=r.url||"/";if(o){const e=a.includes("?")?"&":"?";a+=`${e}${o}`}if(!a.includes("{")||!a.includes("}"))return a;const c=Array.isArray(s)?s:n.stripUnsafeKeys(s);return a.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(r,i)=>{const s=t.get(c,i);return null==s||"object"==typeof s?"":e.Serialize.URL.encode(String(s))})}static normalizeHeaders(e={},t){return t&&"Content-Type"in e?delete e["Content-Type"]:e["Content-Type"]=e["Content-Type"]||"application/json",Object.assign(Object.assign({},this.defaultHeaders),e)}static removeURL(e){return Object.entries(e).reduce((e,[t,r])=>("url"!==t&&(e[t]=r),e),{})}static extractFetchOptions(e){const t={};for(const r of Object.keys(e))o.has(r)&&(t[r]=e[r]);return t}static normalizeBody(e){const{method:t,body:s}=e;if(t!==r.Methods.GET&&t!==r.Methods.HEAD&&t!==r.Methods.OPTIONS)return t!==r.Methods.POST&&t!==r.Methods.PUT&&t!==r.Methods.PATCH&&t!==r.Methods.DELETE||!i.isFormData(s)?s instanceof URLSearchParams||s instanceof Uint8Array||s instanceof ArrayBuffer?s:void 0!==s?JSON.stringify(s):void 0:s}static safeOrigin(e){try{return new URL(e).origin}catch(e){return null}}static assertSameOriginResponse(e,t,r){const i=Object.keys(r).some(e=>"authorization"===e.toLowerCase()&&!!r[e]),s=Object.keys(r).some(e=>"cookie"===e.toLowerCase()&&!!r[e]);if(!i&&!s)return;const o=n.safeOrigin(e);if(!o)return;const a=t.url?n.safeOrigin(t.url):null;if(a&&a!==o&&!this.isAllowedOrigin(a))throw new Error(`Http: credentialed request was redirected from ${o} to untrusted origin ${a}`)}}n.AllowedOrigins=new Set,n.defaultHeaders={"Content-Type":"application/json"},exports.HttpUtils=n;
@@ -1 +0,0 @@
1
- import{Serialize as e}from"../serialize.mjs";import{get as t}from"../utilities/get.mjs";import{Methods as r}from"./method.mjs";import{isFormData as i}from"../utilities/formdata.mjs";const o=new Set(["__proto__","constructor","prototype"]),n=new Set(["credentials","cache","mode","redirect","referrer","referrerPolicy","integrity","keepalive","priority","duplex","window","next","cf","dispatcher"]);class s{static isAllowedOrigin(e){return 0===this.AllowedOrigins.size||this.AllowedOrigins.has(e)}static isValidQuery(t){return"string"==typeof t||t instanceof URLSearchParams||(Array.isArray(t)?t.every(t=>Array.isArray(t)&&2===t.length&&"string"==typeof t[0]&&e.Primitive.isPrimitive(t[1])):"object"==typeof t&&null!==t&&Object.values(t).every(t=>e.Primitive.isPrimitive(t)))}static stripUnsafeKeys(e){const t=Object.create(null);for(const r of Object.keys(e))o.has(r)||(t[r]=e[r]);return t}static normalizeQuery(t){const{method:i,body:o,query:n}=t,a=i===r.GET&&s.isValidQuery(o)?o:n;if(!a||"object"!=typeof a)return"string"==typeof a?a:"";if(a instanceof URLSearchParams)return a.toString();const c=s.stripUnsafeKeys(a);return e.queryString.stringify(c,{skipNull:!0,skipEmptyString:!0})}static normalizeURL(r){const{url:i="",params:o={}}=r,n=s.normalizeQuery(r);let a;if(i){if(i.startsWith("//"))throw new Error(`Http: protocol-relative URLs are not allowed: ${i}`);if(/^[a-z][a-z0-9+.-]*:/i.test(i)){let e;try{e=new URL(i)}catch(e){throw new Error(`Http: invalid absolute URL: ${i}`)}if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error(`Http: unsupported URL scheme: ${e.protocol}`);if(!s.isAllowedOrigin(e.origin))throw new Error(`Http: URL origin '${e.origin}' is not in allowedOrigins`);a=e.toString()}else{const e=(r.url||"/").replace(/\/+$/,""),t=i.replace(/^\/+/,"");a=e?`${e}/${t}`:`/${t}`}}else a=r.url||"/";if(n){const e=a.includes("?")?"&":"?";a+=`${e}${n}`}if(!a.includes("{")||!a.includes("}"))return a;const c=Array.isArray(o)?o:s.stripUnsafeKeys(o);return a.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(r,i)=>{const o=t(c,i);return null==o||"object"==typeof o?"":e.URL.encode(String(o))})}static normalizeHeaders(e={},t){return t&&"Content-Type"in e?delete e["Content-Type"]:e["Content-Type"]=e["Content-Type"]||"application/json",Object.assign(Object.assign({},this.defaultHeaders),e)}static removeURL(e){return Object.entries(e).reduce((e,[t,r])=>("url"!==t&&(e[t]=r),e),{})}static extractFetchOptions(e){const t={};for(const r of Object.keys(e))n.has(r)&&(t[r]=e[r]);return t}static normalizeBody(e){const{method:t,body:o}=e;if(t!==r.GET&&t!==r.HEAD&&t!==r.OPTIONS)return t!==r.POST&&t!==r.PUT&&t!==r.PATCH&&t!==r.DELETE||!i(o)?o instanceof URLSearchParams||o instanceof Uint8Array||o instanceof ArrayBuffer?o:void 0!==o?JSON.stringify(o):void 0:o}static safeOrigin(e){try{return new URL(e).origin}catch(e){return null}}static assertSameOriginResponse(e,t,r){const i=Object.keys(r).some(e=>"authorization"===e.toLowerCase()&&!!r[e]),o=Object.keys(r).some(e=>"cookie"===e.toLowerCase()&&!!r[e]);if(!i&&!o)return;const n=s.safeOrigin(e);if(!n)return;const a=t.url?s.safeOrigin(t.url):null;if(a&&a!==n&&!this.isAllowedOrigin(a))throw new Error(`Http: credentialed request was redirected from ${n} to untrusted origin ${a}`)}}s.AllowedOrigins=new Set,s.defaultHeaders={"Content-Type":"application/json"};export{s as HttpUtils};
@@ -1,24 +0,0 @@
1
- import { type FileListLike } from "../utilities/filelist";
2
- import type { HttpInit } from "./init";
3
- import type { HttpResponse } from "./response";
4
- import type { HttpRequest } from "./request";
5
- export interface HttpProgress {
6
- loaded: number;
7
- total: number;
8
- percentage: number;
9
- }
10
- export interface HttpUploadOptions extends Pick<HttpRequest, "headers" | "params" | "signal" | "query"> {
11
- onProgress?: (progress: HttpProgress) => void;
12
- name?: string;
13
- body?: Record<string, unknown>;
14
- }
15
- export interface HttpRelatedOptions extends Pick<HttpRequest, "headers" | "params" | "signal" | "query"> {
16
- metadata: Record<string, unknown>;
17
- metadataMimeType?: string;
18
- contentType: string;
19
- }
20
- import { HttpCore } from "./http-core";
21
- export declare abstract class HttpXML extends HttpCore {
22
- static upload<DataType = unknown, Err = unknown>(url: string, file: File | File[] | FileListLike, options?: HttpUploadOptions & Omit<HttpInit, "url" | "method" | "body">): Promise<HttpResponse<DataType, Err>>;
23
- static related<DataType = unknown, Err = unknown>(url: string, fileData: ArrayBuffer | Uint8Array, options: HttpRelatedOptions & Omit<HttpInit, "url" | "method" | "body">): Promise<HttpResponse<DataType, Err>>;
24
- }
package/dist/http/xml.js DELETED
@@ -1 +0,0 @@
1
- "use strict";var e=require("../node_modules/tslib/tslib.es6.js"),t=require("../utilities/formdata.js"),s=require("../utilities/flatten.js"),r=require("../utilities/filelist.js"),n=require("../utilities/sanitize-mime.js"),a=require("./array.js"),o=require("./init.js"),i=require("./method.js"),l=require("./utils.js"),d=require("./http-core.js");class u extends d.HttpCore{static upload(n,d,u){const c=(null==u?void 0:u.body)?t.objectToFormData(u.body):new FormData;let p=(null==u?void 0:u.name)||"file";if(Array.isArray(d)?(p.endsWith("[]")&&(p=p.slice(0,-2)),d.forEach((e,t)=>{c.append(`${p}[${t}]`,e,e.name)})):r.isFileList(d)?(p.endsWith("[]")&&(p=p.slice(0,-2)),Array.from(d).forEach((e,t)=>{c.append(`${p}[${t}]`,e,e.name)})):c.append(p,d,d.name),null==u?void 0:u.body){const e=s.flatten(u.body);Object.entries(e).forEach(([e,t])=>{null!=t&&c.append(e,String(t))})}return(null==u?void 0:u.onProgress)&&"undefined"!=typeof XMLHttpRequest?new Promise(async t=>{var s;try{const r=Object.assign(Object.assign({},u),{method:i.Methods.POST,url:n,body:c}),d=o.getHttpInitSlice(r),{interceptors:p}=d,h=e.__rest(d,["interceptors"]);let y=Object.assign({},h);const f=a.asArray(null!==(s=null==p?void 0:p.request)&&void 0!==s?s:[]);for(const e of f)y=await e(y);const m=l.HttpUtils.normalizeURL(y),T=l.HttpUtils.normalizeHeaders(y.headers||{},!0),b=new XMLHttpRequest;b.upload.addEventListener("progress",e=>{var t;if(e.lengthComputable){const s=Math.round(e.loaded/e.total*100);null===(t=u.onProgress)||void 0===t||t.call(u,{loaded:e.loaded,total:e.total,percentage:s})}}),b.addEventListener("load",async()=>{var e,s,r;try{const n=b.getResponseHeader("Content-Type")||"";let o=null;o=n.includes("application/json")?JSON.parse(b.responseText):b.responseText;const i=a.asArray(null!==(e=null==p?void 0:p.transform)&&void 0!==e?e:[]);let l=o;for(const e of i)l=await e(l);const d=a.asArray(null!==(s=null==p?void 0:p.response)&&void 0!==s?s:[]);let u=new Response(b.responseText,{status:b.status,statusText:b.statusText});for(const e of d)u=await e(u);const c={};u.headers.forEach((e,t)=>{c[t]=e});const h=u.ok||b.status>=200&&b.status<300;let y=null;if(!h){y=o.error||o;const e=a.asArray(null!==(r=null==p?void 0:p.error)&&void 0!==r?r:[]);for(const t of e)y=await t(y)}t({data:l,success:h,error:h?null:y,status:u.status,statusText:u.statusText,headers:c})}catch(e){t({data:null,success:!1,status:b.status,statusText:b.statusText,headers:{},error:e})}}),b.addEventListener("error",()=>{t({data:null,success:!1,status:b.status,statusText:b.statusText||"Network Error",headers:{},error:new Error("Network Error")})}),b.open(y.method||i.Methods.POST,m,!0),Object.entries(T).forEach(([e,t])=>{b.setRequestHeader(e,t)}),b.send(c)}catch(e){t({data:null,success:!1,status:0,statusText:"Error",headers:{},error:e})}}):this.request(Object.assign(Object.assign({},u),{method:i.Methods.POST,url:n,body:c}))}static related(e,t,s){const r=n.sanitizeMime(s.contentType),a=n.sanitizeMime(s.metadataMimeType||"application/json"),o=`----related-boundary-${Date.now()}-${Math.random().toString(36).slice(2)}`,l=JSON.stringify(s.metadata),d=new TextEncoder,u=d.encode(`--${o}\r\nContent-Type: ${a}; charset=UTF-8\r\n\r\n`+l+"\r\n"),c=d.encode(`--${o}\r\nContent-Type: ${r}\r\nContent-Transfer-Encoding: binary\r\n\r\n`),p=d.encode(`\r\n--${o}--`),h=t instanceof Uint8Array?t:new Uint8Array(t),y=new Uint8Array(u.length+c.length+h.length+p.length);return[u,c,h,p].reduce((e,t)=>(y.set(t,e),e+t.length),0),this.request(Object.assign(Object.assign({},s),{method:i.Methods.POST,url:e,body:y,headers:Object.assign(Object.assign({},s.headers||{}),{"Content-Type":`multipart/related; boundary=${o}`})}))}}exports.HttpXML=u;
package/dist/http/xml.mjs DELETED
@@ -1 +0,0 @@
1
- import{__rest as t}from"../node_modules/tslib/tslib.es6.mjs";import{objectToFormData as e}from"../utilities/formdata.mjs";import{flatten as s}from"../utilities/flatten.mjs";import{isFileList as r}from"../utilities/filelist.mjs";import{sanitizeMime as n}from"../utilities/sanitize-mime.mjs";import{asArray as o}from"./array.mjs";import{getHttpInitSlice as a}from"./init.mjs";import{Methods as i}from"./method.mjs";import{HttpUtils as l}from"./utils.mjs";import{HttpCore as d}from"./http-core.mjs";class u extends d{static upload(n,d,u){const c=(null==u?void 0:u.body)?e(u.body):new FormData;let m=(null==u?void 0:u.name)||"file";if(Array.isArray(d)?(m.endsWith("[]")&&(m=m.slice(0,-2)),d.forEach((t,e)=>{c.append(`${m}[${e}]`,t,t.name)})):r(d)?(m.endsWith("[]")&&(m=m.slice(0,-2)),Array.from(d).forEach((t,e)=>{c.append(`${m}[${e}]`,t,t.name)})):c.append(m,d,d.name),null==u?void 0:u.body){const t=s(u.body);Object.entries(t).forEach(([t,e])=>{null!=e&&c.append(t,String(e))})}return(null==u?void 0:u.onProgress)&&"undefined"!=typeof XMLHttpRequest?new Promise(async e=>{var s;try{const r=Object.assign(Object.assign({},u),{method:i.POST,url:n,body:c}),d=a(r),{interceptors:m}=d,p=t(d,["interceptors"]);let f=Object.assign({},p);const h=o(null!==(s=null==m?void 0:m.request)&&void 0!==s?s:[]);for(const t of h)f=await t(f);const y=l.normalizeURL(f),T=l.normalizeHeaders(f.headers||{},!0),b=new XMLHttpRequest;b.upload.addEventListener("progress",t=>{var e;if(t.lengthComputable){const s=Math.round(t.loaded/t.total*100);null===(e=u.onProgress)||void 0===e||e.call(u,{loaded:t.loaded,total:t.total,percentage:s})}}),b.addEventListener("load",async()=>{var t,s,r;try{const n=b.getResponseHeader("Content-Type")||"";let a=null;a=n.includes("application/json")?JSON.parse(b.responseText):b.responseText;const i=o(null!==(t=null==m?void 0:m.transform)&&void 0!==t?t:[]);let l=a;for(const t of i)l=await t(l);const d=o(null!==(s=null==m?void 0:m.response)&&void 0!==s?s:[]);let u=new Response(b.responseText,{status:b.status,statusText:b.statusText});for(const t of d)u=await t(u);const c={};u.headers.forEach((t,e)=>{c[e]=t});const p=u.ok||b.status>=200&&b.status<300;let f=null;if(!p){f=a.error||a;const t=o(null!==(r=null==m?void 0:m.error)&&void 0!==r?r:[]);for(const e of t)f=await e(f)}e({data:l,success:p,error:p?null:f,status:u.status,statusText:u.statusText,headers:c})}catch(t){e({data:null,success:!1,status:b.status,statusText:b.statusText,headers:{},error:t})}}),b.addEventListener("error",()=>{e({data:null,success:!1,status:b.status,statusText:b.statusText||"Network Error",headers:{},error:new Error("Network Error")})}),b.open(f.method||i.POST,y,!0),Object.entries(T).forEach(([t,e])=>{b.setRequestHeader(t,e)}),b.send(c)}catch(t){e({data:null,success:!1,status:0,statusText:"Error",headers:{},error:t})}}):this.request(Object.assign(Object.assign({},u),{method:i.POST,url:n,body:c}))}static related(t,e,s){const r=n(s.contentType),o=n(s.metadataMimeType||"application/json"),a=`----related-boundary-${Date.now()}-${Math.random().toString(36).slice(2)}`,l=JSON.stringify(s.metadata),d=new TextEncoder,u=d.encode(`--${a}\r\nContent-Type: ${o}; charset=UTF-8\r\n\r\n`+l+"\r\n"),c=d.encode(`--${a}\r\nContent-Type: ${r}\r\nContent-Transfer-Encoding: binary\r\n\r\n`),m=d.encode(`\r\n--${a}--`),p=e instanceof Uint8Array?e:new Uint8Array(e),f=new Uint8Array(u.length+c.length+p.length+m.length);return[u,c,p,m].reduce((t,e)=>(f.set(e,t),t+e.length),0),this.request(Object.assign(Object.assign({},s),{method:i.POST,url:t,body:f,headers:Object.assign(Object.assign({},s.headers||{}),{"Content-Type":`multipart/related; boundary=${a}`})}))}}export{u as HttpXML};
package/dist/logger.js DELETED
@@ -1 +0,0 @@
1
- "use strict";const o=()=>"undefined"==typeof window,t="",r="",e="",n="",s={LOG:"color:#22c55e;font-weight:bold",WARN:"color:#eab308;font-weight:bold",ERROR:"color:#ef4444;font-weight:bold",DEBUG:"color:#a855f7;font-weight:bold",VERBOSE:"color:#06b6d4;font-weight:bold"},c="color:inherit;font-weight:normal",a={LOG:"color:#22c55e",WARN:"color:#eab308",ERROR:"color:#ef4444",DEBUG:"color:#a855f7",VERBOSE:"color:#06b6d4"};function i(){return(new Date).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0})}const f={LOG:"",WARN:e,ERROR:"",DEBUG:"",VERBOSE:""},l=Symbol.for("@ecosy:logger"),m=globalThis;m[l]||(m[l]={buffer:[],errors:0,warns:0,total:0});const R=m[l];exports.Logger=class{constructor(o="@ecosy"){this.context=o}format(t,r,...e){const n="ERROR"===t?console.error:"WARN"===t?console.warn:console.log;R.buffer.push({timestamp:Date.now(),level:t,context:this.context,message:r}),R.buffer.length>200&&R.buffer.shift(),R.total++,"ERROR"===t&&R.errors++,"WARN"===t&&R.warns++,o()?this.formatServer(n,t,r,...e):this.formatBrowser(n,t,r,...e)}formatServer(s,c,a,...l){const m=f[c],R=`${n}${i()}${t}`;s(`${`${m}${r}${c.padEnd(7)}${t}`} ${`${e}${o()&&"undefined"!=typeof process?process.pid:0}${t}`} - ${R} ${`${e}[${this.context}]${t}`} ${`${m}${a}${t}`}`,...l)}formatBrowser(o,t,r,...e){o(`%c${t.padEnd(7)}%c - %c${i()}%c %c[${this.context}]%c %c${r}`,s[t],c,"color:#9ca3af;font-weight:normal",c,"color:#eab308;font-weight:normal",c,a[t],...e)}log(o,...t){this.format("LOG",o,...t)}warn(o,...t){this.format("WARN",o,...t)}error(o,...t){this.format("ERROR",o,...t)}debug(o,...t){this.format("DEBUG",o,...t)}verbose(o,...t){this.format("VERBOSE",o,...t)}static getLogs(){return[...R.buffer]}static drainCounts(){const o={errors:R.errors,warns:R.warns,total:R.total};return R.errors=0,R.warns=0,R.total=0,o}};
@@ -1 +0,0 @@
1
- "use strict";"function"==typeof SuppressedError&&SuppressedError,exports.__rest=function(r,e){var t={};for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&e.indexOf(o)<0&&(t[o]=r[o]);if(null!=r&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(r);n<o.length;n++)e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(r,o[n])&&(t[o[n]]=r[o[n]])}return t};
@@ -1 +0,0 @@
1
- function r(r,e){var t={};for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&e.indexOf(o)<0&&(t[o]=r[o]);if(null!=r&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(r);n<o.length;n++)e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(r,o[n])&&(t[o[n]]=r[o[n]])}return t}"function"==typeof SuppressedError&&SuppressedError;export{r as __rest};
package/dist/searchify.js DELETED
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./slugify.js");const t={separator:"",silent:!0,transformer:Object.assign({},e.DEFAULT_TRANSFORMER)};exports.default=function(i,s){const n=e.slugify(s,t),r=n.length,o={matches:[],positions:[]};if(!r)return o;const l=new Map,g=[...i.split("")].map((i,s)=>{let n=l.get(i);return void 0===n&&(n=e.slugify(i,t),l.set(i,n)),{originIndex:s,slugified:n,char:i}}).filter((e,t,i)=>0===t||(" "!==e.char||" "!==i[t-1].char));if(g.length<r)return o;for(let e=0;e<g.length;){const t=g[e];if(""===t.slugified){e++;continue}let s="",l=e,u=!0;for(;s.length<r&&l<g.length;){const e=g[l];if(""!==e.slugified&&(s+=e.slugified,!n.startsWith(s))){u=!1;break}l++}if(u&&s===n){const s=g[l-1],n=i.substring(t.originIndex,s.originIndex+1);o.matches.push(n),o.positions.push({start:t.originIndex,length:n.length}),e=l}else e++}return o};
@@ -1 +0,0 @@
1
- import{DEFAULT_TRANSFORMER as t,slugify as e}from"./slugify.mjs";const i={separator:"",silent:!0,transformer:Object.assign({},t)};function n(t,n){const s=e(n,i),r=s.length,o={matches:[],positions:[]};if(!r)return o;const l=new Map,g=[...t.split("")].map((t,n)=>{let s=l.get(t);return void 0===s&&(s=e(t,i),l.set(t,s)),{originIndex:n,slugified:s,char:t}}).filter((t,e,i)=>0===e||(" "!==t.char||" "!==i[e-1].char));if(g.length<r)return o;for(let e=0;e<g.length;){const i=g[e];if(""===i.slugified){e++;continue}let n="",l=e,f=!0;for(;n.length<r&&l<g.length;){const t=g[l];if(""!==t.slugified&&(n+=t.slugified,!s.startsWith(n))){f=!1;break}l++}if(f&&n===s){const n=g[l-1],s=t.substring(i.originIndex,n.originIndex+1);o.matches.push(s),o.positions.push({start:i.originIndex,length:s.length}),e=l}else e++}return o}export{n as default};
@@ -1,80 +0,0 @@
1
- import type { LiteralObject } from "./types/built-in";
2
- type Primitive = string | number | boolean | null | undefined | symbol | bigint;
3
- /** Options for {@link Serialize.queryString.stringify}. */
4
- export interface SerializeQueryOptions {
5
- /** Array serialization format. Defaults to `"none"`. */
6
- arrayFormat?: "bracket" | "index" | "comma" | "separator" | "none";
7
- /** Separator character when `arrayFormat` is `"separator"`. Defaults to `","`. */
8
- arrayFormatSeparator?: string;
9
- /** Skip keys whose value is `null` or `undefined`. */
10
- skipNull?: boolean;
11
- /** Skip keys whose value is an empty string. */
12
- skipEmptyString?: boolean;
13
- /** Whether to URL-encode keys and values, or a custom encoder function. Defaults to `true`. */
14
- encode?: boolean | ((value: string) => string);
15
- /** Reject keys with non-standard characters when `true`. Defaults to `true`. */
16
- strict?: boolean;
17
- /** Sort keys alphabetically, or provide a custom comparator. */
18
- sort?: boolean | ((a: string, b: string) => number);
19
- }
20
- /**
21
- * Centralized serialization engine and type-guard toolkit.
22
- * Addresses common pitfalls of `JSON.stringify`/`JSON.parse` — BigInt safety,
23
- * Date preservation, undefined stripping, and safe URL encoding/decoding.
24
- *
25
- * All methods are organized into frozen static getters:
26
- * - `Serialize.Primitive` — type guards and deep normalization
27
- * - `Serialize.JSON` — safe stringify/parse that never throws
28
- * - `Serialize.URL` — encode/decode/build with malformed-char recovery
29
- * - `Serialize.queryString` — parse and stringify query strings
30
- *
31
- * @example
32
- * ```ts
33
- * Serialize.JSON.stringify({ date: new Date(), big: 123n });
34
- * Serialize.JSON.parse<User>(jsonText);
35
- * Serialize.URL.encode("hello world");
36
- * Serialize.queryString.stringify({ page: 1, tags: ["a", "b"] });
37
- * ```
38
- */
39
- export declare class Serialize {
40
- /**
41
- * Interpolates `{key}` placeholders in a string using deep path resolution via {@link get}.
42
- * Objects are silently replaced with empty strings to avoid `[object Object]`.
43
- *
44
- * @param pattern - Template string with `{key}` or `{path.to.key}` placeholders.
45
- * @param params - Data object or array to resolve values from.
46
- * @returns The interpolated string.
47
- */
48
- static interpolate(pattern: string, params?: Record<string, unknown> | Array<unknown>): string;
49
- /** Type guards and deep normalization utilities. */
50
- private static _primitive;
51
- static get Primitive(): {
52
- readonly isString: (value: unknown) => value is string;
53
- readonly isNumber: (value: unknown) => value is number;
54
- readonly isBoolean: (value: unknown) => value is boolean;
55
- readonly isPrimitive: (value: unknown) => value is Primitive;
56
- readonly isDate: (value: unknown) => value is Date;
57
- readonly isPlainObject: (value: unknown) => value is LiteralObject;
58
- readonly normalize: <T, R = unknown>(data: T) => R;
59
- };
60
- /** Safe JSON stringify/parse that never throws. */
61
- private static _JSON;
62
- static get JSON(): {
63
- readonly stringify: (value: unknown, space?: number) => string;
64
- readonly parse: <T = unknown>(text: string, reviver?: ((this: any, key: string, value: any) => any) | undefined) => T | null;
65
- };
66
- /** URL encoding/decoding with malformed-character recovery. */
67
- private static _URL;
68
- static get URL(): {
69
- readonly encode: (value: string, component?: boolean | ((value: string) => string)) => string;
70
- readonly decode: (value: string, component?: boolean | ((value: string) => string)) => string;
71
- readonly build: (uri: string, params?: Record<string, Primitive> | null) => string;
72
- };
73
- /** Query string parse/stringify with configurable array formats. */
74
- private static _queryString;
75
- static get queryString(): {
76
- readonly parse: (query: string) => Record<string, string>;
77
- readonly stringify: (params: Record<string, unknown>, options?: SerializeQueryOptions) => string;
78
- };
79
- }
80
- export {};
package/dist/serialize.js DELETED
@@ -1 +0,0 @@
1
- "use strict";var e=require("./utilities/freeze.js"),t=require("./utilities/get.js"),r=require("./utilities/object.js"),i=require("./utilities/is-function.js");class n{static interpolate(e,r={}){return e&&"string"==typeof e&&e.trim().length&&e.includes("{")&&e.includes("}")?e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(e,i)=>{const n=t.get(r,i);return null==n||"object"==typeof n?"":String(n)}):e}static get Primitive(){var t;return null!==(t=n._primitive)&&void 0!==t?t:n._primitive=e.freeze({isString:e=>"string"==typeof e,isNumber:e=>"number"==typeof e&&Number.isFinite(e),isBoolean:e=>"boolean"==typeof e,isPrimitive:e=>!r.isObjectable(e),isDate:e=>e instanceof Date&&!Number.isNaN(e.getTime()),isPlainObject:r.isLiteralObject,normalize(e){const t=n.Primitive;if(t.isPrimitive(e))return"bigint"==typeof e?e.toString():e;if(t.isDate(e))return e.toISOString();if(Array.isArray(e))return e.map(e=>t.normalize(e));if(r.isLiteralObject(e)){const i={};for(const n in e)if(r.hasOwnProperty(e,n)){const r=e[n];void 0!==r&&(i[n]=t.normalize(r))}return i}return e&&r.hasOwnProperty(e,"toJSON")&&i.isFunction(e.toJSON)?e.toJSON():{}}})}static get JSON(){var t;return null!==(t=n._JSON)&&void 0!==t?t:n._JSON=e.freeze({stringify:(e,t)=>{var r;try{const i=n.Primitive.normalize(e);return null!==(r=JSON.stringify(i,null,t))&&void 0!==r?r:""}catch(e){return""}},parse:(e,t)=>{if(!e)return null;try{return JSON.parse(e,t)}catch(e){return null}}})}static get URL(){var t;return null!==(t=n._URL)&&void 0!==t?t:n._URL=e.freeze({encode(e,t=!0){if(!e)return"";if("function"==typeof t)return t(e);try{return t?encodeURIComponent(e):encodeURI(e)}catch(r){const i=e.replace(/[\uD800-\uDFFF]/g,"");return t?encodeURIComponent(i):encodeURI(i)}},decode:(e,t=!0)=>{if(!e)return"";if("function"==typeof t)return t(e);const r=t?decodeURIComponent:decodeURI;return(t?e.replace(/\+/g,"%20"):e).replace(/(%[0-9A-F]{2})+/gi,e=>{try{return r(e)}catch(t){return e}})},build:(e,t)=>e?t&&"object"==typeof t?e.replace(/:([a-zA-Z\d_]+)/g,(e,r)=>{const i=t[r];return null==i?e:n.URL.encode(String(i),!0)}):e:""})}static get queryString(){var t;return null!==(t=n._queryString)&&void 0!==t?t:n._queryString=e.freeze({parse(e){if(!e)return{};const t=e.startsWith("?")?e.slice(1):e,r={};return t.split("&").forEach(e=>{if(!e)return;const[t,i]=e.split("=");t&&(r[n.URL.decode(t)]=i?n.URL.decode(i):"")}),r},stringify(e,t={}){if(null===e||"object"!=typeof e)return"";const{arrayFormat:r="none",arrayFormatSeparator:i=",",skipNull:o=!1,skipEmptyString:s=!1,encode:u=!0,strict:c=!0,sort:a=!1}=t,l=e=>e.length>0&&/^[a-zA-Z0-9_\-.[\]]+$/.test(e),f=e=>u?n.URL.encode(e,u):e,p=[],y=(e,t)=>{if(Array.isArray(t)){if("comma"===r||"separator"===r){const r=t.filter(e=>null!=e&&""!==e);return void(r.length>0&&p.push(`${f(e)}=${f(r.map(String).join(i))}`))}t.forEach((t,i)=>{let n=e;"bracket"===r?n=`${e}[]`:"index"===r&&(n=`${e}[${i}]`),y(n,t)})}else if(n.Primitive.isPlainObject(t))for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&y(`${e}[${r}]`,t[r]);else null!=t?""!==t?"boolean"!=typeof t?n.Primitive.isDate(t)?p.push(`${f(e)}=${f(t.toISOString())}`):p.push(`${f(e)}=${f(String(t))}`):p.push(`${f(e)}=${t?"true":"false"}`):s||p.push(`${f(e)}=`):o||p.push(`${f(e)}=`)};let g=Object.keys(e);a&&(g="function"==typeof a?g.sort(a):g.sort());for(const t of g)c&&!l(t)||y(t,e[t]);return p.join("&")}})}}exports.Serialize=n;
@@ -1 +0,0 @@
1
- import{freeze as t}from"./utilities/freeze.mjs";import{get as e}from"./utilities/get.mjs";import{isLiteralObject as r,hasOwnProperty as i,isObjectable as n}from"./utilities/object.mjs";import{isFunction as o}from"./utilities/is-function.mjs";class s{static interpolate(t,r={}){return t&&"string"==typeof t&&t.trim().length&&t.includes("{")&&t.includes("}")?t.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(t,i)=>{const n=e(r,i);return null==n||"object"==typeof n?"":String(n)}):t}static get Primitive(){var e;return null!==(e=s._primitive)&&void 0!==e?e:s._primitive=t({isString:t=>"string"==typeof t,isNumber:t=>"number"==typeof t&&Number.isFinite(t),isBoolean:t=>"boolean"==typeof t,isPrimitive:t=>!n(t),isDate:t=>t instanceof Date&&!Number.isNaN(t.getTime()),isPlainObject:r,normalize(t){const e=s.Primitive;if(e.isPrimitive(t))return"bigint"==typeof t?t.toString():t;if(e.isDate(t))return t.toISOString();if(Array.isArray(t))return t.map(t=>e.normalize(t));if(r(t)){const r={};for(const n in t)if(i(t,n)){const i=t[n];void 0!==i&&(r[n]=e.normalize(i))}return r}return t&&i(t,"toJSON")&&o(t.toJSON)?t.toJSON():{}}})}static get JSON(){var e;return null!==(e=s._JSON)&&void 0!==e?e:s._JSON=t({stringify:(t,e)=>{var r;try{const i=s.Primitive.normalize(t);return null!==(r=JSON.stringify(i,null,e))&&void 0!==r?r:""}catch(t){return""}},parse:(t,e)=>{if(!t)return null;try{return JSON.parse(t,e)}catch(t){return null}}})}static get URL(){var e;return null!==(e=s._URL)&&void 0!==e?e:s._URL=t({encode(t,e=!0){if(!t)return"";if("function"==typeof e)return e(t);try{return e?encodeURIComponent(t):encodeURI(t)}catch(r){const i=t.replace(/[\uD800-\uDFFF]/g,"");return e?encodeURIComponent(i):encodeURI(i)}},decode:(t,e=!0)=>{if(!t)return"";if("function"==typeof e)return e(t);const r=e?decodeURIComponent:decodeURI;return(e?t.replace(/\+/g,"%20"):t).replace(/(%[0-9A-F]{2})+/gi,t=>{try{return r(t)}catch(e){return t}})},build:(t,e)=>t?e&&"object"==typeof e?t.replace(/:([a-zA-Z\d_]+)/g,(t,r)=>{const i=e[r];return null==i?t:s.URL.encode(String(i),!0)}):t:""})}static get queryString(){var e;return null!==(e=s._queryString)&&void 0!==e?e:s._queryString=t({parse(t){if(!t)return{};const e=t.startsWith("?")?t.slice(1):t,r={};return e.split("&").forEach(t=>{if(!t)return;const[e,i]=t.split("=");e&&(r[s.URL.decode(e)]=i?s.URL.decode(i):"")}),r},stringify(t,e={}){if(null===t||"object"!=typeof t)return"";const{arrayFormat:r="none",arrayFormatSeparator:i=",",skipNull:n=!1,skipEmptyString:o=!1,encode:u=!0,strict:c=!0,sort:a=!1}=e,l=t=>t.length>0&&/^[a-zA-Z0-9_\-.[\]]+$/.test(t),f=t=>u?s.URL.encode(t,u):t,p=[],m=(t,e)=>{if(Array.isArray(e)){if("comma"===r||"separator"===r){const r=e.filter(t=>null!=t&&""!==t);return void(r.length>0&&p.push(`${f(t)}=${f(r.map(String).join(i))}`))}e.forEach((e,i)=>{let n=t;"bracket"===r?n=`${t}[]`:"index"===r&&(n=`${t}[${i}]`),m(n,e)})}else if(s.Primitive.isPlainObject(e))for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&m(`${t}[${r}]`,e[r]);else null!=e?""!==e?"boolean"!=typeof e?s.Primitive.isDate(e)?p.push(`${f(t)}=${f(e.toISOString())}`):p.push(`${f(t)}=${f(String(e))}`):p.push(`${f(t)}=${e?"true":"false"}`):o||p.push(`${f(t)}=`):n||p.push(`${f(t)}=`)};let g=Object.keys(t);a&&(g="function"==typeof a?g.sort(a):g.sort());for(const e of g)c&&!l(e)||m(e,t[e]);return p.join("&")}})}}export{s as Serialize};
package/dist/syhemo.d.ts DELETED
@@ -1,102 +0,0 @@
1
- import { Subscriber } from "./subscriber";
2
- import type { LogEntry } from "./logger";
3
- export interface MemorySnapshot {
4
- rss: number;
5
- heapUsed: number;
6
- heapTotal: number;
7
- external: number;
8
- arrayBuffers: number;
9
- }
10
- export interface CpuSnapshot {
11
- model: string;
12
- count: number;
13
- usage: number;
14
- }
15
- export interface HeapSnapshot {
16
- totalHeapSize: number;
17
- usedHeapSize: number;
18
- heapSizeLimit: number;
19
- mallocedMemory: number;
20
- nativeContexts: number;
21
- detachedContexts: number;
22
- }
23
- export interface ModuleInfo {
24
- path: string;
25
- count: number;
26
- }
27
- export interface HandleSnapshot {
28
- timers: number;
29
- sockets: number;
30
- requests: number;
31
- total: number;
32
- }
33
- export interface EventLoopSnapshot {
34
- lagMs: number;
35
- min: number;
36
- max: number;
37
- mean: number;
38
- p99: number;
39
- }
40
- export interface LogRateSnapshot {
41
- errors: number;
42
- warns: number;
43
- total: number;
44
- }
45
- export interface HttpSnapshot {
46
- totalRequests: number;
47
- recentRequests: number;
48
- avgLatency: number;
49
- }
50
- export interface DbPoolSnapshot {
51
- connected: boolean;
52
- }
53
- export interface MetricSnapshot {
54
- timestamp: number;
55
- memory: MemorySnapshot;
56
- cpu: CpuSnapshot;
57
- heap: HeapSnapshot;
58
- handles: HandleSnapshot;
59
- modules: {
60
- count: number;
61
- top: ModuleInfo[];
62
- };
63
- eventLoop: EventLoopSnapshot;
64
- logRate: LogRateSnapshot;
65
- http: HttpSnapshot;
66
- dbPool: DbPoolSnapshot;
67
- system: {
68
- platform: string;
69
- arch: string;
70
- nodeVersion: string;
71
- totalMemory: number;
72
- freeMemory: number;
73
- uptime: number;
74
- loadAvg: number[];
75
- };
76
- }
77
- export interface SyhemoState {
78
- current: MetricSnapshot | null;
79
- snapshots: MetricSnapshot[];
80
- logs: LogEntry[];
81
- started: boolean;
82
- }
83
- declare const syhemoEvents: {
84
- readonly metrics: {
85
- readonly snapshot: string;
86
- };
87
- };
88
- type SyhemoEvents = typeof syhemoEvents;
89
- export declare function recordHttpRequest(latencyMs: number): void;
90
- export interface SyhemoOptions {
91
- interval?: number;
92
- db?: () => boolean;
93
- }
94
- export declare class Syhemo extends Subscriber<SyhemoState, SyhemoEvents> {
95
- private timer;
96
- private readonly logger;
97
- constructor();
98
- start(options?: SyhemoOptions): void;
99
- stop(): void;
100
- private collect;
101
- }
102
- export {};
package/dist/syhemo.js DELETED
@@ -1 +0,0 @@
1
- "use strict";var node_perf_hooks=require("node:perf_hooks"),subscriber=require("./subscriber.js"),utilities_freeze=require("./utilities/freeze.js"),logger=require("./logger.js"),v8=require("v8"),os=require("os");function _interopNamespace(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(o){if("default"!==o){var s=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,s.get?s:{enumerable:!0,get:function(){return e[o]}})}}),t.default=e,Object.freeze(t)}var v8__namespace=_interopNamespace(v8),os__namespace=_interopNamespace(os);const syhemoEvents=utilities_freeze.freeze({metrics:{snapshot:"$syhemo:metrics:snapshot"}}),MB=1048576;function collectMemory(){const e=process.memoryUsage();return{rss:Math.round(e.rss/MB*100)/100,heapUsed:Math.round(e.heapUsed/MB*100)/100,heapTotal:Math.round(e.heapTotal/MB*100)/100,external:Math.round(e.external/MB*100)/100,arrayBuffers:Math.round(e.arrayBuffers/MB*100)/100}}let prevCpuUsage=null;function collectCpu(){var e,t;const o=os__namespace.cpus();let s=0;if(prevCpuUsage&&prevCpuUsage.length===o.length){let e=0,t=0;for(let s=0;s<o.length;s++){const r=prevCpuUsage[s].times,n=o[s].times,a=r.user+r.nice+r.sys+r.idle+r.irq;e+=n.user+n.nice+n.sys+n.idle+n.irq-a,t+=n.idle-r.idle}s=e>0?Math.round(1e4*(1-t/e))/100:0}return prevCpuUsage=o,{model:null!==(t=null===(e=o[0])||void 0===e?void 0:e.model)&&void 0!==t?t:"unknown",count:o.length,usage:s}}function collectHeap(){const e=v8__namespace.getHeapStatistics();return{totalHeapSize:Math.round(e.total_heap_size/MB*100)/100,usedHeapSize:Math.round(e.used_heap_size/MB*100)/100,heapSizeLimit:Math.round(e.heap_size_limit/MB*100)/100,mallocedMemory:Math.round(e.malloced_memory/MB*100)/100,nativeContexts:e.number_of_native_contexts,detachedContexts:e.number_of_detached_contexts}}function collectHandles(){var e,t,o,s,r,n;const a=null!==(t=null===(e=process._getActiveHandles)||void 0===e?void 0:e.call(process))&&void 0!==t?t:[],c=null!==(s=null===(o=process._getActiveRequests)||void 0===o?void 0:o.call(process))&&void 0!==s?s:[];let l=0,u=0;for(const e of a){const t=null!==(n=null===(r=null==e?void 0:e.constructor)||void 0===r?void 0:r.name)&&void 0!==n?n:"";"Timeout"===t||"Timer"===t||"Immediate"===t?l++:"Socket"!==t&&"TCP"!==t&&"TLSSocket"!==t||u++}return{timers:l,sockets:u,requests:c.length,total:a.length+c.length}}function collectModules(){var _a;try{const cache=eval("typeof require !== 'undefined' && require.cache")||{},keys=Object.keys(cache),count=keys.length,groups=new Map;for(const e of keys){const t=e.match(/node_modules\/([^/]+)/),o=t?`node_modules/${t[1]}`:e.replace(process.cwd(),".");groups.set(o,(null!==(_a=groups.get(o))&&void 0!==_a?_a:0)+1)}const top=Array.from(groups.entries()).sort((e,t)=>t[1]-e[1]).slice(0,20).map(([e,t])=>({path:e,count:t}));return{count:count,top:top}}catch(e){return{count:0,top:[]}}}const histogram=node_perf_hooks.monitorEventLoopDelay({resolution:10});function collectEventLoop(){const e={lagMs:Math.round(histogram.mean/1e6*100)/100,min:Math.round(histogram.min/1e6*100)/100,max:Math.round(histogram.max/1e6*100)/100,mean:Math.round(histogram.mean/1e6*100)/100,p99:Math.round(histogram.percentile(99)/1e6*100)/100};return histogram.reset(),e}histogram.enable();let httpTotalRequests=0,httpRecentRequests=0,httpLatencySum=0,httpLatencySamples=0;function recordHttpRequest(e){httpTotalRequests++,httpRecentRequests++,httpLatencySum+=e,httpLatencySamples++}function collectHttp(){const e=httpLatencySamples>0?Math.round(httpLatencySum/httpLatencySamples*100)/100:0,t={totalRequests:httpTotalRequests,recentRequests:httpRecentRequests,avgLatency:e};return httpRecentRequests=0,httpLatencySum=0,httpLatencySamples=0,t}let dbChecker=null;function collectDbPool(){return{connected:!!dbChecker&&dbChecker()}}function collectSnapshot(){return{timestamp:Date.now(),memory:collectMemory(),cpu:collectCpu(),heap:collectHeap(),handles:collectHandles(),modules:collectModules(),eventLoop:collectEventLoop(),logRate:logger.Logger.drainCounts(),http:collectHttp(),dbPool:collectDbPool(),system:{platform:os__namespace.platform(),arch:os__namespace.arch(),nodeVersion:process.version,totalMemory:Math.round(os__namespace.totalmem()/MB),freeMemory:Math.round(os__namespace.freemem()/MB),uptime:Math.round(process.uptime()),loadAvg:os__namespace.loadavg().map(e=>Math.round(100*e)/100)}}}const MAX_SNAPSHOTS=60;class Syhemo extends subscriber.Subscriber{constructor(){super({current:null,snapshots:[],logs:[],started:!1},syhemoEvents),this.timer=null,this.logger=new logger.Logger("Syhemo")}start(e={}){if(this.getState().started)return;const{interval:t=5e3,db:o}=e;o&&(dbChecker=o),this.setState({started:!0}),this.collect(),this.timer=setInterval(()=>this.collect(),t),this.logger.log(`Started (interval: ${t}ms)`)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.setState({started:!1}),this.logger.log("Stopped")}collect(){try{const e=collectSnapshot(),t=this.getState().snapshots,o=t.length>=MAX_SNAPSHOTS?[...t.slice(1),e]:[...t,e],s=logger.Logger.getLogs();this.setState({current:e,snapshots:o,logs:s}),this.dispatch(syhemoEvents.metrics.snapshot,e),this.logger.log(`Snapshot completed (count: ${o.length})`)}catch(e){this.logger.error(`Collection failed: ${e}`)}}}exports.Syhemo=Syhemo,exports.recordHttpRequest=recordHttpRequest;
package/dist/syhemo.mjs DELETED
@@ -1 +0,0 @@
1
- import{monitorEventLoopDelay}from"node:perf_hooks";import{Subscriber}from"./subscriber.mjs";import{freeze}from"./utilities/freeze.mjs";import{Logger}from"./logger.mjs";import*as v8 from"v8";import*as os from"os";const syhemoEvents=freeze({metrics:{snapshot:"$syhemo:metrics:snapshot"}}),MB=1048576;function collectMemory(){const e=process.memoryUsage();return{rss:Math.round(e.rss/MB*100)/100,heapUsed:Math.round(e.heapUsed/MB*100)/100,heapTotal:Math.round(e.heapTotal/MB*100)/100,external:Math.round(e.external/MB*100)/100,arrayBuffers:Math.round(e.arrayBuffers/MB*100)/100}}let prevCpuUsage=null;function collectCpu(){var e,t;const o=os.cpus();let s=0;if(prevCpuUsage&&prevCpuUsage.length===o.length){let e=0,t=0;for(let s=0;s<o.length;s++){const r=prevCpuUsage[s].times,n=o[s].times,l=r.user+r.nice+r.sys+r.idle+r.irq;e+=n.user+n.nice+n.sys+n.idle+n.irq-l,t+=n.idle-r.idle}s=e>0?Math.round(1e4*(1-t/e))/100:0}return prevCpuUsage=o,{model:null!==(t=null===(e=o[0])||void 0===e?void 0:e.model)&&void 0!==t?t:"unknown",count:o.length,usage:s}}function collectHeap(){const e=v8.getHeapStatistics();return{totalHeapSize:Math.round(e.total_heap_size/MB*100)/100,usedHeapSize:Math.round(e.used_heap_size/MB*100)/100,heapSizeLimit:Math.round(e.heap_size_limit/MB*100)/100,mallocedMemory:Math.round(e.malloced_memory/MB*100)/100,nativeContexts:e.number_of_native_contexts,detachedContexts:e.number_of_detached_contexts}}function collectHandles(){var e,t,o,s,r,n;const l=null!==(t=null===(e=process._getActiveHandles)||void 0===e?void 0:e.call(process))&&void 0!==t?t:[],a=null!==(s=null===(o=process._getActiveRequests)||void 0===o?void 0:o.call(process))&&void 0!==s?s:[];let c=0,i=0;for(const e of l){const t=null!==(n=null===(r=null==e?void 0:e.constructor)||void 0===r?void 0:r.name)&&void 0!==n?n:"";"Timeout"===t||"Timer"===t||"Immediate"===t?c++:"Socket"!==t&&"TCP"!==t&&"TLSSocket"!==t||i++}return{timers:c,sockets:i,requests:a.length,total:l.length+a.length}}function collectModules(){var _a;try{const cache=eval("typeof require !== 'undefined' && require.cache")||{},keys=Object.keys(cache),count=keys.length,groups=new Map;for(const e of keys){const t=e.match(/node_modules\/([^/]+)/),o=t?`node_modules/${t[1]}`:e.replace(process.cwd(),".");groups.set(o,(null!==(_a=groups.get(o))&&void 0!==_a?_a:0)+1)}const top=Array.from(groups.entries()).sort((e,t)=>t[1]-e[1]).slice(0,20).map(([e,t])=>({path:e,count:t}));return{count:count,top:top}}catch(e){return{count:0,top:[]}}}const histogram=monitorEventLoopDelay({resolution:10});function collectEventLoop(){const e={lagMs:Math.round(histogram.mean/1e6*100)/100,min:Math.round(histogram.min/1e6*100)/100,max:Math.round(histogram.max/1e6*100)/100,mean:Math.round(histogram.mean/1e6*100)/100,p99:Math.round(histogram.percentile(99)/1e6*100)/100};return histogram.reset(),e}histogram.enable();let httpTotalRequests=0,httpRecentRequests=0,httpLatencySum=0,httpLatencySamples=0;function recordHttpRequest(e){httpTotalRequests++,httpRecentRequests++,httpLatencySum+=e,httpLatencySamples++}function collectHttp(){const e=httpLatencySamples>0?Math.round(httpLatencySum/httpLatencySamples*100)/100:0,t={totalRequests:httpTotalRequests,recentRequests:httpRecentRequests,avgLatency:e};return httpRecentRequests=0,httpLatencySum=0,httpLatencySamples=0,t}let dbChecker=null;function collectDbPool(){return{connected:!!dbChecker&&dbChecker()}}function collectSnapshot(){return{timestamp:Date.now(),memory:collectMemory(),cpu:collectCpu(),heap:collectHeap(),handles:collectHandles(),modules:collectModules(),eventLoop:collectEventLoop(),logRate:Logger.drainCounts(),http:collectHttp(),dbPool:collectDbPool(),system:{platform:os.platform(),arch:os.arch(),nodeVersion:process.version,totalMemory:Math.round(os.totalmem()/MB),freeMemory:Math.round(os.freemem()/MB),uptime:Math.round(process.uptime()),loadAvg:os.loadavg().map(e=>Math.round(100*e)/100)}}}const MAX_SNAPSHOTS=60;class Syhemo extends Subscriber{constructor(){super({current:null,snapshots:[],logs:[],started:!1},syhemoEvents),this.timer=null,this.logger=new Logger("Syhemo")}start(e={}){if(this.getState().started)return;const{interval:t=5e3,db:o}=e;o&&(dbChecker=o),this.setState({started:!0}),this.collect(),this.timer=setInterval(()=>this.collect(),t),this.logger.log(`Started (interval: ${t}ms)`)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.setState({started:!1}),this.logger.log("Stopped")}collect(){try{const e=collectSnapshot(),t=this.getState().snapshots,o=t.length>=MAX_SNAPSHOTS?[...t.slice(1),e]:[...t,e],s=Logger.getLogs();this.setState({current:e,snapshots:o,logs:s}),this.dispatch(syhemoEvents.metrics.snapshot,e),this.logger.log(`Snapshot completed (count: ${o.length})`)}catch(e){this.logger.error(`Collection failed: ${e}`)}}}export{Syhemo,recordHttpRequest};
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes