@ecosy/core 0.2.1 → 0.3.1
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/README.md +31 -19
- package/dist/env.d.ts +26 -0
- package/dist/env.js +1 -0
- package/dist/env.mjs +1 -0
- package/dist/http.d.ts +116 -9
- package/dist/http.js +1 -1
- package/dist/http.mjs +1 -1
- package/dist/index.d.ts +1 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/serialize.js +1 -1
- package/dist/serialize.mjs +1 -1
- package/dist/subscriber.js +1 -1
- package/dist/subscriber.mjs +1 -1
- package/dist/syhemo.js +1 -1
- package/dist/syhemo.mjs +1 -1
- package/dist/utilities/filelist.js +1 -1
- package/dist/utilities/filelist.mjs +1 -1
- package/dist/utilities/{object-to-formdata.d.ts → formdata.d.ts} +2 -0
- package/dist/utilities/formdata.js +1 -0
- package/dist/utilities/formdata.mjs +1 -0
- package/dist/utilities/index.d.ts +4 -5
- package/dist/utilities/index.js +1 -1
- package/dist/utilities/index.mjs +1 -1
- package/dist/utilities/is-function.js +1 -1
- package/dist/utilities/is-function.mjs +1 -1
- package/dist/utilities/sanitize-mime.d.ts +11 -0
- package/dist/utilities/sanitize-mime.js +1 -0
- package/dist/utilities/sanitize-mime.mjs +1 -0
- package/dist/utilities/string.d.ts +31 -0
- package/dist/utilities/string.js +1 -0
- package/dist/utilities/string.mjs +1 -0
- package/package.json +14 -2
- package/dist/utilities/object-to-formdata.js +0 -1
- package/dist/utilities/object-to-formdata.mjs +0 -1
- package/dist/utilities/pascal-to-kebab.d.ts +0 -15
- package/dist/utilities/pascal-to-kebab.js +0 -1
- package/dist/utilities/pascal-to-kebab.mjs +0 -1
- package/dist/utilities/to-string.d.ts +0 -13
- package/dist/utilities/to-string.js +0 -1
- package/dist/utilities/to-string.mjs +0 -1
- package/dist/utilities/ucfirst.d.ts +0 -12
- package/dist/utilities/ucfirst.js +0 -1
- package/dist/utilities/ucfirst.mjs +0 -1
package/README.md
CHANGED
|
@@ -12,18 +12,19 @@ yarn add @ecosy/core
|
|
|
12
12
|
|
|
13
13
|
### Subpath Imports
|
|
14
14
|
|
|
15
|
-
| Entry point
|
|
16
|
-
|
|
17
|
-
| `@ecosy/core`
|
|
18
|
-
| `@ecosy/core/types`
|
|
19
|
-
| `@ecosy/core/utilities`
|
|
20
|
-
| `@ecosy/core/
|
|
21
|
-
| `@ecosy/core/
|
|
22
|
-
| `@ecosy/core/
|
|
23
|
-
| `@ecosy/core/
|
|
24
|
-
| `@ecosy/core/
|
|
25
|
-
| `@ecosy/core/
|
|
26
|
-
| `@ecosy/core/
|
|
15
|
+
| Entry point | Description |
|
|
16
|
+
| ------------------------ | --------------------------------------------- |
|
|
17
|
+
| `@ecosy/core` | Re-exports all modules (except `syhemo`) |
|
|
18
|
+
| `@ecosy/core/types` | TypeScript type utilities |
|
|
19
|
+
| `@ecosy/core/utilities` | Runtime utility functions |
|
|
20
|
+
| `@ecosy/core/env` | `getEnv()` — safe `process.env` access |
|
|
21
|
+
| `@ecosy/core/subscriber` | Pub/sub event emitter with state |
|
|
22
|
+
| `@ecosy/core/http` | HTTP client, Endpoint registry, uploads |
|
|
23
|
+
| `@ecosy/core/logger` | Structured logger with log levels |
|
|
24
|
+
| `@ecosy/core/syhemo` | System health monitor (Node-only) |
|
|
25
|
+
| `@ecosy/core/serialize` | Serialization engine (JSON, URL, queryString) |
|
|
26
|
+
| `@ecosy/core/slugify` | Unicode-safe string slugifier |
|
|
27
|
+
| `@ecosy/core/searchify` | Diacritic-insensitive fuzzy search |
|
|
27
28
|
|
|
28
29
|
### Types
|
|
29
30
|
|
|
@@ -38,6 +39,9 @@ Deep utility types for TypeScript — `Freezable<T>`, `PartialLiteral<T>`, `Prom
|
|
|
38
39
|
- **`flatten`** / **`flattenToArray`** — Object flattening
|
|
39
40
|
- **`get`** — Safe deep path resolution (`"a.b[0].c"`)
|
|
40
41
|
- **`defer`** / **`deferAsync`** — rAF + setTimeout scheduling with cancel
|
|
42
|
+
- **`sanitizeMime`** / **`MIME_REGEX`** — validate and normalize MIME strings
|
|
43
|
+
- **`isFormData`** / **`objectToFormData`** — FormData detection and conversion
|
|
44
|
+
- **`toString`** / **`ucfirst`** / **`pascalToKebab`** — string helpers
|
|
41
45
|
- Type guards: `isFunction`, `isObject`, `isLiteralObject`, `isComplexObject`, `isObjectable`, `hasOwnProperty`
|
|
42
46
|
|
|
43
47
|
### Subscriber
|
|
@@ -46,11 +50,18 @@ Pub/sub event emitter with built-in state management, async once, and typed wiri
|
|
|
46
50
|
|
|
47
51
|
### Http
|
|
48
52
|
|
|
49
|
-
Configurable HTTP client with request/response interceptors, auth token injection, URL interpolation via Serialize,
|
|
53
|
+
Configurable HTTP client with request/response interceptors, auth token injection, URL interpolation via Serialize, XHR-based upload with progress tracking, and `multipart/related` upload for Google-style APIs.
|
|
54
|
+
|
|
55
|
+
- **`Endpoint`** — Central registry for grouping service endpoints (`Endpoint.register("drive", { … })`), also exposed as `Http.Endpoint`
|
|
56
|
+
- **`HttpMethod`** / **`HttpUpload`** — Enums covering HTTP verbs and upload modes (`UPLOAD`, `RELATED`)
|
|
57
|
+
- **`http.upload(url, files, options)`** — XHR upload with progress events
|
|
58
|
+
- **`http.related(url, bytes, { metadata, contentType })`** — `multipart/related` upload with JSON metadata + binary body
|
|
59
|
+
- **`Http.createFactory({ http, endpoint })`** — Typed endpoint factory keyed by registered service names
|
|
50
60
|
|
|
51
61
|
### Serialize
|
|
52
62
|
|
|
53
63
|
Centralized serialization engine:
|
|
64
|
+
|
|
54
65
|
- **`Serialize.Primitive`** — Type guards and deep normalization (BigInt, Date, undefined stripping)
|
|
55
66
|
- **`Serialize.JSON`** — Safe stringify/parse that never throws
|
|
56
67
|
- **`Serialize.URL`** — Robust encode/decode with `:param` URL building
|
|
@@ -67,12 +78,13 @@ Full API reference and guides: **[docs.ecosy.io](https://docs.ecosy.io)**
|
|
|
67
78
|
|
|
68
79
|
## Related Packages
|
|
69
80
|
|
|
70
|
-
| Package
|
|
71
|
-
|
|
72
|
-
| [`@ecosy/datekit`](https://github.com/material-atomic/ecosy-datekit) | Headless date utilities (Dateify, Dayify, Monthify, Yearify)
|
|
73
|
-
| [`@ecosy/mailer`](https://github.com/material-atomic/ecosy-mailer)
|
|
74
|
-
| [`@ecosy/store`](https://github.com/material-atomic/ecosy-store)
|
|
75
|
-
| [`@ecosy/react`](https://github.com/material-atomic/ecosy-react)
|
|
81
|
+
| Package | Description |
|
|
82
|
+
| -------------------------------------------------------------------- | --------------------------------------------------------------- |
|
|
83
|
+
| [`@ecosy/datekit`](https://github.com/material-atomic/ecosy-datekit) | Headless date utilities (Dateify, Dayify, Monthify, Yearify) |
|
|
84
|
+
| [`@ecosy/mailer`](https://github.com/material-atomic/ecosy-mailer) | Email engine with template formatting, retry, and rate limiting |
|
|
85
|
+
| [`@ecosy/store`](https://github.com/material-atomic/ecosy-store) | State management with slices, reducers, and `configureStore` |
|
|
86
|
+
| [`@ecosy/react`](https://github.com/material-atomic/ecosy-react) | React hooks for `@ecosy/store` |
|
|
87
|
+
| [`@ecosy/googleapis`](https://github.com/material-atomic/ecosy-googleapis) | Google Drive / OAuth2 client built on `@ecosy/core/http` |
|
|
76
88
|
|
|
77
89
|
## License
|
|
78
90
|
|
package/dist/env.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type EnvSource = Record<string, string | undefined>;
|
|
2
|
+
/**
|
|
3
|
+
* Returns an env source object for the current runtime.
|
|
4
|
+
* Called once per `getEnv` invocation to resolve the global source.
|
|
5
|
+
*/
|
|
6
|
+
export type EnvGetter = () => EnvSource;
|
|
7
|
+
/**
|
|
8
|
+
* Read an environment variable across runtimes.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* // Basic — uses getter (default: process.env → import.meta.env)
|
|
13
|
+
* getEnv("API_URL", "/api")
|
|
14
|
+
*
|
|
15
|
+
* // Per-call source (e.g. Hono ctx.env)
|
|
16
|
+
* getEnv("API_URL", "/api", ctx.env)
|
|
17
|
+
*
|
|
18
|
+
* // Custom getter for a specific runtime
|
|
19
|
+
* getEnv.getter(() => Deno.env.toObject());
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export declare function getEnv(key: string, defaultValue?: string, ...sources: Array<EnvSource | undefined>): string | undefined;
|
|
23
|
+
export declare namespace getEnv {
|
|
24
|
+
var _getter: EnvGetter;
|
|
25
|
+
var getter: (fn: EnvGetter) => void;
|
|
26
|
+
}
|
package/dist/env.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var t=require("./utilities/object.js");function e(t,i,...r){for(const e of r)if(e&&t in e&&void 0!==e[t])return e[t];const n=e._getter();return t in n&&void 0!==n[t]?n[t]:i}e._getter=function(){if("undefined"!=typeof globalThis&&"process"in globalThis){const e=globalThis.process;if((null==e?void 0:e.env)&&t.isLiteralObject(e.env))return e.env}try{const e=void 0;if(e&&t.isLiteralObject(e))return e}catch(t){}return{}},e.getter=t=>{e._getter=t},exports.getEnv=e;
|
package/dist/env.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isLiteralObject as t}from"./utilities/object.mjs";function e(t,n,...o){for(const e of o)if(e&&t in e&&void 0!==e[t])return e[t];const r=e._getter();return t in r&&void 0!==r[t]?r[t]:n}e._getter=function(){if("undefined"!=typeof globalThis&&"process"in globalThis){const e=globalThis.process;if((null==e?void 0:e.env)&&t(e.env))return e.env}try{const e=import.meta.env;if(e&&t(e))return e}catch(t){}return{}},e.getter=t=>{e._getter=t};export{e as getEnv};
|
package/dist/http.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type FileListLike } from "./utilities";
|
|
1
|
+
import { type FileListLike } from "./utilities/filelist";
|
|
2
2
|
/** Default base URL for HTTP requests, sourced from `API_URL` env variable. */
|
|
3
3
|
export declare const DEFAULT_BASE_URL: string | undefined;
|
|
4
4
|
/** Authentication token storage key, sourced from `API_AUTH_TOKEN_KEY` env variable. */
|
|
@@ -17,6 +17,11 @@ export declare enum HttpMethod {
|
|
|
17
17
|
HEAD = "HEAD",
|
|
18
18
|
OPTIONS = "OPTIONS"
|
|
19
19
|
}
|
|
20
|
+
/** Upload method types for {@link Http.createFactory}. */
|
|
21
|
+
export declare enum HttpUpload {
|
|
22
|
+
UPLOAD = "UPLOAD",
|
|
23
|
+
RELATED = "RELATED"
|
|
24
|
+
}
|
|
20
25
|
/** Accepted query parameter formats for HTTP requests. */
|
|
21
26
|
export type HttpQuery = string | Record<string, string | number | boolean | undefined> | Array<[string, string | number | boolean | undefined]> | URLSearchParams;
|
|
22
27
|
/** Configuration object for an HTTP request. */
|
|
@@ -28,6 +33,31 @@ export interface HttpRequest<Body = unknown, Params = Record<string, unknown>, Q
|
|
|
28
33
|
query?: Query;
|
|
29
34
|
params?: Params;
|
|
30
35
|
signal?: AbortSignal;
|
|
36
|
+
/**
|
|
37
|
+
* Pass-through bag for `fetch`'s `RequestInit` options that the
|
|
38
|
+
* library does not manage itself (`credentials`, `cache`, `mode`,
|
|
39
|
+
* `redirect`, `referrer`, `referrerPolicy`, `integrity`, `keepalive`,
|
|
40
|
+
* `priority`, `duplex`) plus framework extensions (`next` on Next.js,
|
|
41
|
+
* `cf` on Cloudflare Workers, `dispatcher` on undici).
|
|
42
|
+
*
|
|
43
|
+
* Lib-level fields (`method`, `headers`, `body`, `signal`) cannot be
|
|
44
|
+
* overridden here — they are applied after this bag is spread.
|
|
45
|
+
* Unknown keys are silently dropped, so a compromised caller cannot
|
|
46
|
+
* smuggle arbitrary fields into `fetch`.
|
|
47
|
+
*/
|
|
48
|
+
configs?: Record<string, unknown>;
|
|
49
|
+
}
|
|
50
|
+
/** Constructor options for {@link Http}. */
|
|
51
|
+
export interface HttpOptions {
|
|
52
|
+
/** Base URL prepended to every relative request path. */
|
|
53
|
+
baseURL?: string;
|
|
54
|
+
/**
|
|
55
|
+
* Additional origins (besides `baseURL`'s origin) that absolute URLs
|
|
56
|
+
* and redirect responses are permitted to reach. Any other origin is
|
|
57
|
+
* rejected before the request is sent and, for redirects, before the
|
|
58
|
+
* response body is returned.
|
|
59
|
+
*/
|
|
60
|
+
allowedOrigins?: ReadonlyArray<string>;
|
|
31
61
|
}
|
|
32
62
|
/** Storage adapter interface for reading/writing auth tokens (e.g. `localStorage`). */
|
|
33
63
|
export interface HttpStorage {
|
|
@@ -66,6 +96,15 @@ export interface HttpUploadOptions extends Pick<HttpRequest, "headers" | "params
|
|
|
66
96
|
name: string;
|
|
67
97
|
body?: Record<string, unknown>;
|
|
68
98
|
}
|
|
99
|
+
/** Options for a multipart/related upload (e.g. Google Drive). */
|
|
100
|
+
export interface HttpRelatedOptions extends Pick<HttpRequest, "headers" | "params" | "signal" | "query"> {
|
|
101
|
+
/** JSON metadata object (will be serialized as the first part). */
|
|
102
|
+
metadata: Record<string, unknown>;
|
|
103
|
+
/** MIME type of the metadata part. Default: "application/json" */
|
|
104
|
+
metadataMimeType?: string;
|
|
105
|
+
/** MIME type of the file content. */
|
|
106
|
+
contentType: string;
|
|
107
|
+
}
|
|
69
108
|
/** Options for creating an HTTP factory via {@link Http.createFactory}. */
|
|
70
109
|
export interface HttpFactoryOptions {
|
|
71
110
|
baseURL?: string;
|
|
@@ -78,6 +117,14 @@ export interface HttpFactory<T = unknown, Args extends any[] = [], E = unknown>
|
|
|
78
117
|
key: string;
|
|
79
118
|
fn: (...args: Args) => Promise<HttpResponse<T, E>>;
|
|
80
119
|
}
|
|
120
|
+
/** Central registry for grouping endpoint URLs by service name. */
|
|
121
|
+
export declare class Endpoint {
|
|
122
|
+
private static registered;
|
|
123
|
+
static register(service: string, endpoints: Record<string, string>): typeof Endpoint;
|
|
124
|
+
static all(): {
|
|
125
|
+
[x: string]: Record<string, string>;
|
|
126
|
+
};
|
|
127
|
+
}
|
|
81
128
|
/**
|
|
82
129
|
* HTTP client with interceptors, auth token management, file uploads,
|
|
83
130
|
* and a factory pattern for endpoint generation.
|
|
@@ -92,12 +139,23 @@ export interface HttpFactory<T = unknown, Args extends any[] = [], E = unknown>
|
|
|
92
139
|
* ```
|
|
93
140
|
*/
|
|
94
141
|
export declare class Http {
|
|
95
|
-
private readonly baseURL;
|
|
96
142
|
static readonly method: typeof HttpMethod;
|
|
143
|
+
static readonly Endpoint: typeof Endpoint;
|
|
97
144
|
static authTokenKey: string;
|
|
98
145
|
static authHeaderKey: string;
|
|
99
146
|
static authHeaderType: string;
|
|
100
147
|
static authDetectToken: string[];
|
|
148
|
+
/**
|
|
149
|
+
* One-shot headers merged into the very next request across all
|
|
150
|
+
* instances, then cleared. Intended for request-scoped values like
|
|
151
|
+
* CSRF tokens or correlation IDs that callers don't want to thread
|
|
152
|
+
* through every call site.
|
|
153
|
+
*
|
|
154
|
+
* Note: this is a process-wide mutable static. In concurrent async
|
|
155
|
+
* contexts (e.g. multiple tenants sharing one process) it is the
|
|
156
|
+
* caller's responsibility to ensure the set → dispatch → reset
|
|
157
|
+
* sequence is not interleaved.
|
|
158
|
+
*/
|
|
101
159
|
static extraHeaders: Record<string, string> | null;
|
|
102
160
|
static storage: HttpStorage | null;
|
|
103
161
|
private defaultHeaders;
|
|
@@ -105,7 +163,34 @@ export declare class Http {
|
|
|
105
163
|
private storage;
|
|
106
164
|
private static interceptors;
|
|
107
165
|
private interceptors;
|
|
108
|
-
|
|
166
|
+
private readonly baseURL;
|
|
167
|
+
private readonly allowedOrigins;
|
|
168
|
+
/**
|
|
169
|
+
* @param init - Either a base URL string (backwards-compatible form)
|
|
170
|
+
* or an {@link HttpOptions} object. Using the object form lets
|
|
171
|
+
* callers opt in to additional origins that absolute URLs and
|
|
172
|
+
* redirect responses are permitted to reach. Any other origin is
|
|
173
|
+
* rejected before the request is sent and, for redirects, before
|
|
174
|
+
* the response body is returned.
|
|
175
|
+
*
|
|
176
|
+
* @example
|
|
177
|
+
* ```ts
|
|
178
|
+
* new Http("https://api.example.com");
|
|
179
|
+
* new Http({
|
|
180
|
+
* baseURL: "https://api.example.com",
|
|
181
|
+
* allowedOrigins: ["https://cdn.example.com"],
|
|
182
|
+
* });
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
constructor(init?: string | HttpOptions);
|
|
186
|
+
/** Whether `origin` is this instance's baseURL origin or an explicitly allowed one. */
|
|
187
|
+
private isAllowedOrigin;
|
|
188
|
+
/**
|
|
189
|
+
* If a request was sent with credentials (Authorization / Cookie) and
|
|
190
|
+
* ended up at a different origin via redirect, refuse to return the
|
|
191
|
+
* response. Defends against token exfil via server-controlled 3xx.
|
|
192
|
+
*/
|
|
193
|
+
private assertSameOriginResponse;
|
|
109
194
|
/** Register a global interceptor (applies to all `Http` instances). */
|
|
110
195
|
static on(...params: HttpInterceptorParameters): void;
|
|
111
196
|
/** Remove a global interceptor. */
|
|
@@ -115,8 +200,6 @@ export declare class Http {
|
|
|
115
200
|
/** Type guard that checks whether a value is a valid {@link HttpQuery}. */
|
|
116
201
|
isValidQuery(query: unknown): query is HttpQuery;
|
|
117
202
|
getQuery<Params extends Record<string, unknown>>(options: HttpRequest<unknown, Params>): string;
|
|
118
|
-
/** Type guard that checks whether a body is a `FormData` instance. */
|
|
119
|
-
isFormData(body: unknown): body is FormData;
|
|
120
203
|
/** Merge additional default headers into this instance. */
|
|
121
204
|
addHeaders(headers: Record<string, string>): void;
|
|
122
205
|
/** Register an instance-level interceptor. */
|
|
@@ -132,10 +215,21 @@ export declare class Http {
|
|
|
132
215
|
getHeaders(headers?: Record<string, string>, isFormData?: boolean): {
|
|
133
216
|
[x: string]: string;
|
|
134
217
|
};
|
|
135
|
-
/**
|
|
218
|
+
/**
|
|
219
|
+
* Build the full URL from base URL, path, query string, and path params.
|
|
220
|
+
*
|
|
221
|
+
* Security rules applied here (see SECURITY audit):
|
|
222
|
+
* - Absolute URLs must use `http`/`https` and their origin must match
|
|
223
|
+
* `baseURL`'s origin or an entry in `allowedOrigins`.
|
|
224
|
+
* - Protocol-relative URLs (`//host/…`) are rejected — they silently
|
|
225
|
+
* flip the target host.
|
|
226
|
+
* - Path params (`{id}`) are URL-encoded by `interpolateURL`
|
|
227
|
+
* so a value of `"../admin"` cannot traverse the path.
|
|
228
|
+
* - Proto-pollution keys in `params` are stripped.
|
|
229
|
+
*/
|
|
136
230
|
getURL(options: HttpRequest): string;
|
|
137
|
-
/** Serialize the request body (JSON or
|
|
138
|
-
getBody(options: HttpRequest): string | FormData | undefined;
|
|
231
|
+
/** Serialize the request body (JSON, FormData, or binary). Returns `undefined` for bodyless methods. */
|
|
232
|
+
getBody(options: HttpRequest): string | FormData | Uint8Array | ArrayBuffer | undefined;
|
|
139
233
|
/** Execute a full HTTP request with all interceptors applied. */
|
|
140
234
|
request<T = unknown, E = unknown>(options: HttpRequest): Promise<HttpResponse<T, E>>;
|
|
141
235
|
/** Perform a GET request. */
|
|
@@ -157,6 +251,19 @@ export declare class Http {
|
|
|
157
251
|
* Falls back to `XMLHttpRequest` when `onProgress` is provided for progress tracking.
|
|
158
252
|
*/
|
|
159
253
|
upload<T = unknown, E = unknown>(url: string, file: File | File[] | FileListLike, options?: HttpUploadOptions): Promise<HttpResponse<T, E>>;
|
|
254
|
+
/**
|
|
255
|
+
* Upload with multipart/related format.
|
|
256
|
+
* Builds a proper multipart/related body with JSON metadata + binary file content.
|
|
257
|
+
*
|
|
258
|
+
* @example
|
|
259
|
+
* ```ts
|
|
260
|
+
* const result = await http.related<DriveFile>("/files?uploadType=multipart", fileBuffer, {
|
|
261
|
+
* metadata: { name: "photo.jpg", parents: ["folderId"] },
|
|
262
|
+
* contentType: "image/jpeg",
|
|
263
|
+
* });
|
|
264
|
+
* ```
|
|
265
|
+
*/
|
|
266
|
+
related<T = unknown, E = unknown>(url: string, fileData: ArrayBuffer | Uint8Array, options: HttpRelatedOptions): Promise<HttpResponse<T, E>>;
|
|
160
267
|
/**
|
|
161
268
|
* Creates a factory function that generates typed endpoint descriptors.
|
|
162
269
|
* Each descriptor has a `key` and an async `fn` that performs the HTTP call.
|
|
@@ -172,5 +279,5 @@ export declare class Http {
|
|
|
172
279
|
* const { data } = await getUsers.fn();
|
|
173
280
|
* ```
|
|
174
281
|
*/
|
|
175
|
-
static createFactory(options?: HttpFactoryOptions): <T, Args extends any[] = [], E = unknown>(key: string, method?: HttpMethod |
|
|
282
|
+
static createFactory(options?: HttpFactoryOptions): <T, Args extends any[] = [], E = unknown>(key: string, method?: HttpMethod | HttpUpload) => HttpFactory<T, Args, E>;
|
|
176
283
|
}
|
package/dist/http.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";require("./utilities/clone.js");var t=require("./utilities/filelist.js"),e=require("./utilities/flatten.js"),s=require("./utilities/object.js"),r=require("./utilities/object-to-formdata.js"),o=require("./serialize.js");function n(t,e){var r;return"undefined"!=typeof process&&s.isLiteralObject(process.env)&&null!==(r=process.env[t])&&void 0!==r?r:e}const a=n("API_URL","/"),i=n("API_AUTH_TOKEN_KEY"),c=n("API_AUTH_HEADER_KEY"),p=n("API_AUTH_HEADER_TYPE");var u;exports.HttpMethod=void 0,(u=exports.HttpMethod||(exports.HttpMethod={})).GET="GET",u.POST="POST",u.PUT="PUT",u.DELETE="DELETE",u.PATCH="PATCH",u.HEAD="HEAD",u.OPTIONS="OPTIONS";class d{constructor(t=a){this.baseURL=t,this.defaultHeaders={"Content-Type":"application/json"},this.method=d.method,this.storage=d.storage,this.interceptors={request:[],response:[],transform:[],error:[]}}static on(...t){const[e,s]=t,r=d.interceptors[e];r.includes(s)||r.push(s),d.interceptors[e]=r}static off(...t){const[e,s]=t,r=d.interceptors[e];d.interceptors[e]=r.filter(t=>t!==s)}setStorage(t){this.storage=t}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]&&o.Serialize.Primitive.isPrimitive(t[1])):"object"==typeof t&&null!==t&&Object.values(t).every(t=>o.Serialize.Primitive.isPrimitive(t)))}getQuery(t){const{method:e,body:s,query:r}=t,n=e===exports.HttpMethod.GET&&this.isValidQuery(s)?s:r;return n&&"object"==typeof n?n instanceof URLSearchParams?n.toString():o.Serialize.queryString.stringify(n,{skipNull:!0,skipEmptyString:!0}):"string"==typeof n?n:""}isFormData(t){return t instanceof FormData}addHeaders(t){this.defaultHeaders=Object.assign(Object.assign({},this.defaultHeaders),t)}on(...t){const[e,s]=t,r=this.interceptors[e];return r.includes(s)||r.push(s),this.interceptors[e]=r,this}off(...t){const[e,s]=t,r=this.interceptors[e];return this.interceptors[e]=r.filter(t=>t!==s),this}getToken(){const t=i||d.authTokenKey,e=c||d.authHeaderKey,s=p||d.authHeaderType;if(!t||!e)return{key:e,value:""};let r="";this.storage&&(r=this.storage.getItem(t)||"");const o={key:e,value:""};return r&&(o.value=r,s&&(o.value=`${s} ${r}`)),o}getHeaders(t={},e){const s=this.getToken();s.key in t&&t[s.key]||(t[s.key]=s.value),e&&"Content-Type"in t?delete t["Content-Type"]:t["Content-Type"]=t["Content-Type"]||this.defaultHeaders["Content-Type"]||"application/json";const r=Object.assign(Object.assign(Object.assign({},this.defaultHeaders),t),d.extraHeaders||{});return d.extraHeaders=null,r}getURL(t){var e;const{url:s,params:r={}}=t,n=this.getQuery(t);let a=s;if(s)if(s.match(/^https?:\/\//))a=s;else{a=`${null===(e=this.baseURL)||void 0===e?void 0:e.replace(/\/+$/,"")}/${s.replace(/^\/+/,"")}`}if(n){const t=a.includes("?")?"&":"?";a+=`${t}${n}`}return o.Serialize.interpolate(a,r)}getBody(t){const{method:e,body:s}=t;if(e!==exports.HttpMethod.GET&&e!==exports.HttpMethod.HEAD&&e!==exports.HttpMethod.OPTIONS&&e!==exports.HttpMethod.DELETE)return e!==exports.HttpMethod.POST&&e!==exports.HttpMethod.PUT&&e!==exports.HttpMethod.PATCH||!this.isFormData(s)?void 0!==s?JSON.stringify(s):void 0:s}async request(t){const{method:e=exports.HttpMethod.GET}=t;try{let s=Object.assign({},t);const r=[...d.interceptors.request,...this.interceptors.request];for(const t of r)s=await t(s);const o=this.getURL(s),n=this.getHeaders(s.headers||{});this.isFormData(s.body)&&"Content-Type"in n&&delete n["Content-Type"];const a=await fetch(o,{method:s.method||e,headers:n,body:this.getBody(s),signal:s.signal}),i=a.headers.get("Content-Type")||"";let c=null;c=i.includes("application/json")?await a.json():await a.text();const p=[...d.interceptors.transform,...this.interceptors.transform];let u=c;for(const t of p)u=await t(u);const l=[...d.interceptors.response,...this.interceptors.response];let h=a;for(const t of l)h=await t(h);const f={};h.headers.forEach((t,e)=>{f[e]=t});const y=h.ok;let T=null;if(!y){T=c.error||c;const t=[...d.interceptors.error,...this.interceptors.error];for(const e of t)T=await e(T)}return{data:u,success:y,error:y?null:T,status:h.status,statusText:h.statusText,headers:f}}catch(t){let e=t instanceof Error?t:new Error(String(t));const s=[...d.interceptors.error,...this.interceptors.error];for(const t of s)e=await t(e);return{data:null,status:0,statusText:"Error",headers:{},error:e,success:!1}}}get(t,e,s){return this.request(Object.assign(Object.assign({},s),{method:exports.HttpMethod.GET,url:t,query:e}))}post(t,e,s){return this.request(Object.assign(Object.assign({},s),{method:exports.HttpMethod.POST,url:t,body:e}))}put(t,e,s){return this.request(Object.assign(Object.assign({},s),{method:exports.HttpMethod.PUT,url:t,body:e}))}patch(t,e,s){return this.request(Object.assign(Object.assign({},s),{method:exports.HttpMethod.PATCH,url:t,body:e}))}delete(t,e){return this.request(Object.assign(Object.assign({},e),{method:exports.HttpMethod.DELETE,url:t}))}head(t,e){return this.request(Object.assign(Object.assign({},e),{method:exports.HttpMethod.HEAD,url:t}))}options(t,e){return this.request(Object.assign(Object.assign({},e),{method:exports.HttpMethod.OPTIONS,url:t}))}upload(s,o,n){const a=(null==n?void 0:n.body)?r.objectToFormData(n.body):new FormData;let i=(null==n?void 0:n.name)||"file";if(Array.isArray(o)?(i.endsWith("[]")&&(i=i.slice(0,-2)),o.forEach((t,e)=>{a.append(`${i}[${e}]`,t,t.name)})):t.isFileList(o)?(i.endsWith("[]")&&(i=i.slice(0,-2)),Array.from(o).forEach((t,e)=>{a.append(`${i}[${e}]`,t,t.name)})):a.append(i,o,o.name),null==n?void 0:n.body){const t=e.flatten(n.body);Object.entries(t).forEach(([t,e])=>{null!=e&&a.append(t,String(e))})}return(null==n?void 0:n.onProgress)&&"undefined"!=typeof XMLHttpRequest?new Promise(async t=>{try{let e=Object.assign(Object.assign({},n),{method:exports.HttpMethod.POST,url:s,body:a});const r=[...d.interceptors.request,...this.interceptors.request];for(const t of r)e=await t(e);const o=this.getURL(e),i=this.getHeaders(e.headers||{},!0),c=new XMLHttpRequest;c.upload.addEventListener("progress",t=>{var e;if(t.lengthComputable){const s=Math.round(t.loaded/t.total*100);null===(e=n.onProgress)||void 0===e||e.call(n,{loaded:t.loaded,total:t.total,percentage:s})}}),c.addEventListener("load",async()=>{try{const e=c.getResponseHeader("Content-Type")||"";let s=null;s=e.includes("application/json")?JSON.parse(c.responseText):c.responseText;const r=[...d.interceptors.transform,...this.interceptors.transform];let o=s;for(const t of r)o=await t(o);const n=[...d.interceptors.response,...this.interceptors.response];let a=new Response(c.responseText,{status:c.status,statusText:c.statusText,headers:i});for(const t of n)a=await t(a);const p={};a.headers.forEach((t,e)=>{p[e]=t});const u=a.ok;t({data:o,success:u,error:u?null:o,status:a.status,statusText:a.statusText,headers:p})}catch(e){const s=[...d.interceptors.error,...this.interceptors.error];for(const t of s)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}}),c.addEventListener("error",e=>{const s=[...d.interceptors.error,...this.interceptors.error];for(const t of s)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}),c.addEventListener("abort",()=>{t({data:null,status:0,statusText:"Aborted",headers:{},error:null,success:!1})}),c.open(e.method||exports.HttpMethod.POST,o,!0),Object.entries(i).forEach(([t,e])=>{"content-type"!==(null==t?void 0:t.toLowerCase())&&e&&c.setRequestHeader(t,e)}),c.send(e.body)}catch(e){const s=[...d.interceptors.error,...this.interceptors.error];for(const t of s)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}}):this.request({method:exports.HttpMethod.POST,url:s,body:a,headers:null==n?void 0:n.headers,params:null==n?void 0:n.params,signal:null==n?void 0:n.signal,query:null==n?void 0:n.query})}static createFactory(t={}){const s=t.http||new d(t.baseURL);return function(r,o){const n=e.flatten("function"==typeof t.endpoint?t.endpoint():t.endpoint||{})[r];return{key:r,fn:async(...e)=>{const r="function"==typeof t.storage?await t.storage():t.storage;switch(r&&s.setStorage(r),o){case exports.HttpMethod.POST:return await s.post(n,...e);case exports.HttpMethod.PUT:return await s.put(n,...e);case exports.HttpMethod.PATCH:return await s.patch(n,...e);case exports.HttpMethod.DELETE:return await s.delete(n,...e);case exports.HttpMethod.HEAD:return await s.head(n,...e);case exports.HttpMethod.OPTIONS:return await s.options(n,...e);case"UPLOAD":return await s.upload(n,...e);default:return await s.get(n,...e)}}}}}}d.method=exports.HttpMethod,d.authTokenKey="access_token",d.authHeaderKey="Authorization",d.authHeaderType="Bearer",d.authDetectToken=["localStorage","sessionStorage","cookie"],d.extraHeaders=null,d.storage=null,d.interceptors={request:[],response:[],transform:[],error:[]},exports.API_AUTH_HEADER_KEY=c,exports.API_AUTH_HEADER_TYPE=p,exports.API_AUTH_TOKEN_KEY=i,exports.DEFAULT_BASE_URL=a,exports.Http=d;
|
|
1
|
+
"use strict";var t=require("./utilities/filelist.js"),e=require("./utilities/flatten.js"),r=require("./utilities/formdata.js"),s=require("./utilities/get.js"),o=require("./utilities/sanitize-mime.js"),n=require("./serialize.js"),i=require("./env.js");function a(t){try{return new URL(t).origin}catch(t){return null}}const c=new Set(["__proto__","constructor","prototype"]),d=new Set(["credentials","cache","mode","redirect","referrer","referrerPolicy","integrity","keepalive","priority","duplex","window","next","cf","dispatcher"]);function l(t){const e=Object.create(null);for(const r of Object.keys(t))c.has(r)||(e[r]=t[r]);return e}const p=i.getEnv("API_URL","/"),u=i.getEnv("API_AUTH_TOKEN_KEY"),h=i.getEnv("API_AUTH_HEADER_KEY"),g=i.getEnv("API_AUTH_HEADER_TYPE");var f,y;exports.HttpMethod=void 0,(f=exports.HttpMethod||(exports.HttpMethod={})).GET="GET",f.POST="POST",f.PUT="PUT",f.DELETE="DELETE",f.PATCH="PATCH",f.HEAD="HEAD",f.OPTIONS="OPTIONS",exports.HttpUpload=void 0,(y=exports.HttpUpload||(exports.HttpUpload={})).UPLOAD="UPLOAD",y.RELATED="RELATED";class T{static register(t,e){return this.registered[t]=Object.assign({},e),this}static all(){return Object.assign({},this.registered)}}T.registered={};class E{constructor(t){var e,r,s,o;this.defaultHeaders={"Content-Type":"application/json"},this.method=E.method,this.storage=E.storage,this.interceptors={request:[],response:[],transform:[],error:[]};const n="string"==typeof t||void 0===t?{baseURL:null!=t?t:p}:{baseURL:null!==(e=t.baseURL)&&void 0!==e?e:p,allowedOrigins:t.allowedOrigins};this.baseURL=null!==(s=null!==(r=n.baseURL)&&void 0!==r?r:p)&&void 0!==s?s:"/";const i=new Set;for(const t of null!==(o=n.allowedOrigins)&&void 0!==o?o:[]){const e=a(t);if(!e)throw new Error(`Http: invalid allowedOrigins entry: ${t}`);i.add(e)}const c=a(this.baseURL);c&&i.add(c),this.allowedOrigins=i}isAllowedOrigin(t){return 0===this.allowedOrigins.size||this.allowedOrigins.has(t)}assertSameOriginResponse(t,e,r){const s=Object.keys(r).some(t=>"authorization"===t.toLowerCase()&&!!r[t]),o=Object.keys(r).some(t=>"cookie"===t.toLowerCase()&&!!r[t]);if(!s&&!o)return;const n=a(t);if(!n)return;const i=e.url?a(e.url):null;if(i&&i!==n&&!this.isAllowedOrigin(i))throw new Error(`Http: credentialed request was redirected from ${n} to untrusted origin ${i}`)}static on(...t){const[e,r]=t,s=E.interceptors[e];s.includes(r)||s.push(r),E.interceptors[e]=s}static off(...t){const[e,r]=t,s=E.interceptors[e];E.interceptors[e]=s.filter(t=>t!==r)}setStorage(t){this.storage=t}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]&&n.Serialize.Primitive.isPrimitive(t[1])):"object"==typeof t&&null!==t&&Object.values(t).every(t=>n.Serialize.Primitive.isPrimitive(t)))}getQuery(t){const{method:e,body:r,query:s}=t,o=e===exports.HttpMethod.GET&&this.isValidQuery(r)?r:s;if(!o||"object"!=typeof o)return"string"==typeof o?o:"";if(o instanceof URLSearchParams)return o.toString();const i=l(o);return n.Serialize.queryString.stringify(i,{skipNull:!0,skipEmptyString:!0})}addHeaders(t){this.defaultHeaders=Object.assign(Object.assign({},this.defaultHeaders),t)}on(...t){const[e,r]=t,s=this.interceptors[e];return s.includes(r)||s.push(r),this.interceptors[e]=s,this}off(...t){const[e,r]=t,s=this.interceptors[e];return this.interceptors[e]=s.filter(t=>t!==r),this}getToken(){const t=u||E.authTokenKey,e=h||E.authHeaderKey,r=g||E.authHeaderType;if(!t||!e)return{key:e,value:""};let s="";this.storage&&(s=this.storage.getItem(t)||"");const o={key:e,value:""};return s&&/^[\x21-\x7E]+$/.test(s)&&(o.value=r?`${r} ${s}`:s),o}getHeaders(t={},e){const r=this.getToken();r.key in t&&t[r.key]||(t[r.key]=r.value),e&&"Content-Type"in t?delete t["Content-Type"]:t["Content-Type"]=t["Content-Type"]||this.defaultHeaders["Content-Type"]||"application/json";const s=Object.assign(Object.assign(Object.assign({},this.defaultHeaders),t),E.extraHeaders||{});return E.extraHeaders=null,s}getURL(t){const{url:e="",params:r={}}=t,o=this.getQuery(t);let i;if(e){if(e.startsWith("//"))throw new Error(`Http: protocol-relative URLs are not allowed: ${e}`);if(/^[a-z][a-z0-9+.-]*:/i.test(e)){let t;try{t=new URL(e)}catch(t){throw new Error(`Http: invalid absolute URL: ${e}`)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Error(`Http: unsupported URL scheme: ${t.protocol}`);if(!this.isAllowedOrigin(t.origin))throw new Error(`Http: URL origin '${t.origin}' is not in allowedOrigins`);i=t.toString()}else{const t=(this.baseURL||"/").replace(/\/+$/,""),r=e.replace(/^\/+/,"");i=t?`${t}/${r}`:`/${r}`}}else i=this.baseURL||"/";if(o){const t=i.includes("?")?"&":"?";i+=`${t}${o}`}if(!i.includes("{")||!i.includes("}"))return i;const a=Array.isArray(r)?r:l(r);return i.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(t,e)=>{const r=s.get(a,e);return null==r||"object"==typeof r?"":n.Serialize.URL.encode(String(r))})}getBody(t){const{method:e,body:s}=t;if(e!==exports.HttpMethod.GET&&e!==exports.HttpMethod.HEAD&&e!==exports.HttpMethod.OPTIONS&&e!==exports.HttpMethod.DELETE)return e!==exports.HttpMethod.POST&&e!==exports.HttpMethod.PUT&&e!==exports.HttpMethod.PATCH||!r.isFormData(s)?s instanceof Uint8Array||s instanceof ArrayBuffer?s:void 0!==s?JSON.stringify(s):void 0:s}async request(t){const{method:e=exports.HttpMethod.GET}=t;try{let s=Object.assign({},t);const o=[...E.interceptors.request,...this.interceptors.request];for(const t of o)s=await t(s);const n=this.getURL(s),i=this.getHeaders(s.headers||{});r.isFormData(s.body)&&"Content-Type"in i&&delete i["Content-Type"];const a={};if(s.configs)for(const t of Object.keys(s.configs))d.has(t)&&(a[t]=s.configs[t]);const c=await fetch(n,Object.assign(Object.assign({},a),{method:s.method||e,headers:i,body:this.getBody(s),signal:s.signal}));this.assertSameOriginResponse(n,c,i);const l=c.headers.get("Content-Type")||"";let p=null;p=l.includes("application/json")?await c.json():await c.text();const u=[...E.interceptors.transform,...this.interceptors.transform];let h=p;for(const t of u)h=await t(h);const g=[...E.interceptors.response,...this.interceptors.response];let f=c;for(const t of g)f=await t(f);const y={};f.headers.forEach((t,e)=>{y[e]=t});const T=f.ok;let H=null;if(!T){H=p.error||p;const t=[...E.interceptors.error,...this.interceptors.error];for(const e of t)H=await e(H)}return{data:h,success:T,error:T?null:H,status:f.status,statusText:f.statusText,headers:y}}catch(t){let e=t instanceof Error?t:new Error(String(t));const r=[...E.interceptors.error,...this.interceptors.error];for(const t of r)e=await t(e);return{data:null,status:0,statusText:"Error",headers:{},error:e,success:!1}}}get(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:exports.HttpMethod.GET,url:t,query:e}))}post(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:exports.HttpMethod.POST,url:t,body:e}))}put(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:exports.HttpMethod.PUT,url:t,body:e}))}patch(t,e,r){return this.request(Object.assign(Object.assign({},r),{method:exports.HttpMethod.PATCH,url:t,body:e}))}delete(t,e){return this.request(Object.assign(Object.assign({},e),{method:exports.HttpMethod.DELETE,url:t}))}head(t,e){return this.request(Object.assign(Object.assign({},e),{method:exports.HttpMethod.HEAD,url:t}))}options(t,e){return this.request(Object.assign(Object.assign({},e),{method:exports.HttpMethod.OPTIONS,url:t}))}upload(s,o,n){const i=(null==n?void 0:n.body)?r.objectToFormData(n.body):new FormData;let a=(null==n?void 0:n.name)||"file";if(Array.isArray(o)?(a.endsWith("[]")&&(a=a.slice(0,-2)),o.forEach((t,e)=>{i.append(`${a}[${e}]`,t,t.name)})):t.isFileList(o)?(a.endsWith("[]")&&(a=a.slice(0,-2)),Array.from(o).forEach((t,e)=>{i.append(`${a}[${e}]`,t,t.name)})):i.append(a,o,o.name),null==n?void 0:n.body){const t=e.flatten(n.body);Object.entries(t).forEach(([t,e])=>{null!=e&&i.append(t,String(e))})}return(null==n?void 0:n.onProgress)&&"undefined"!=typeof XMLHttpRequest?new Promise(async t=>{try{let e=Object.assign(Object.assign({},n),{method:exports.HttpMethod.POST,url:s,body:i});const r=[...E.interceptors.request,...this.interceptors.request];for(const t of r)e=await t(e);const o=this.getURL(e),a=this.getHeaders(e.headers||{},!0),c=new XMLHttpRequest;c.upload.addEventListener("progress",t=>{var e;if(t.lengthComputable){const r=Math.round(t.loaded/t.total*100);null===(e=n.onProgress)||void 0===e||e.call(n,{loaded:t.loaded,total:t.total,percentage:r})}}),c.addEventListener("load",async()=>{try{const e=c.getResponseHeader("Content-Type")||"";let r=null;r=e.includes("application/json")?JSON.parse(c.responseText):c.responseText;const s=[...E.interceptors.transform,...this.interceptors.transform];let o=r;for(const t of s)o=await t(o);const n=[...E.interceptors.response,...this.interceptors.response];let i=new Response(c.responseText,{status:c.status,statusText:c.statusText,headers:a});for(const t of n)i=await t(i);const d={};i.headers.forEach((t,e)=>{d[e]=t});const l=i.ok;t({data:o,success:l,error:l?null:o,status:i.status,statusText:i.statusText,headers:d})}catch(e){const r=[...E.interceptors.error,...this.interceptors.error];for(const t of r)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}}),c.addEventListener("error",e=>{const r=[...E.interceptors.error,...this.interceptors.error];for(const t of r)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}),c.addEventListener("abort",()=>{t({data:null,status:0,statusText:"Aborted",headers:{},error:null,success:!1})}),c.open(e.method||exports.HttpMethod.POST,o,!0),Object.entries(a).forEach(([t,e])=>{"content-type"!==(null==t?void 0:t.toLowerCase())&&e&&c.setRequestHeader(t,e)}),c.send(e.body)}catch(e){const r=[...E.interceptors.error,...this.interceptors.error];for(const t of r)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}}):this.request({method:exports.HttpMethod.POST,url:s,body:i,headers:null==n?void 0:n.headers,params:null==n?void 0:n.params,signal:null==n?void 0:n.signal,query:null==n?void 0:n.query})}related(t,e,r){const s=o.sanitizeMime(r.contentType),n=o.sanitizeMime(r.metadataMimeType||"application/json"),i=`----related-boundary-${Date.now()}-${Math.random().toString(36).slice(2)}`,a=JSON.stringify(r.metadata),c=new TextEncoder,d=c.encode(`--${i}\r\nContent-Type: ${n}; charset=UTF-8\r\n\r\n`+a+"\r\n"),l=c.encode(`--${i}\r\nContent-Type: ${s}\r\nContent-Transfer-Encoding: binary\r\n\r\n`),p=c.encode(`\r\n--${i}--`),u=e instanceof Uint8Array?e:new Uint8Array(e),h=new Uint8Array(d.length+l.length+u.length+p.length);return[d,l,u,p].reduce((t,e)=>(h.set(e,t),t+e.length),0),this.request({method:exports.HttpMethod.POST,url:t,body:h,headers:Object.assign(Object.assign({},r.headers||{}),{"Content-Type":`multipart/related; boundary=${i}`}),params:r.params,signal:r.signal,query:r.query})}static createFactory(t={}){const r=t.http||new E(t.baseURL);return function(s,o){const n=e.flatten("function"==typeof t.endpoint?t.endpoint():t.endpoint||{})[s];return{key:s,fn:async(...e)=>{const s="function"==typeof t.storage?await t.storage():t.storage;switch(s&&r.setStorage(s),o){case exports.HttpMethod.POST:return await r.post(n,...e);case exports.HttpMethod.PUT:return await r.put(n,...e);case exports.HttpMethod.PATCH:return await r.patch(n,...e);case exports.HttpMethod.DELETE:return await r.delete(n,...e);case exports.HttpMethod.HEAD:return await r.head(n,...e);case exports.HttpMethod.OPTIONS:return await r.options(n,...e);case exports.HttpUpload.UPLOAD:return await r.upload(n,...e);case exports.HttpUpload.RELATED:return await r.related(n,...e);default:return await r.get(n,...e)}}}}}}E.method=exports.HttpMethod,E.Endpoint=T,E.authTokenKey="access_token",E.authHeaderKey="Authorization",E.authHeaderType="Bearer",E.authDetectToken=["localStorage","sessionStorage","cookie"],E.extraHeaders=null,E.storage=null,E.interceptors={request:[],response:[],transform:[],error:[]},exports.API_AUTH_HEADER_KEY=h,exports.API_AUTH_HEADER_TYPE=g,exports.API_AUTH_TOKEN_KEY=u,exports.DEFAULT_BASE_URL=p,exports.Endpoint=T,exports.Http=E;
|
package/dist/http.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./utilities/clone.mjs";import{isFileList as t}from"./utilities/filelist.mjs";import{flatten as e}from"./utilities/flatten.mjs";import{isLiteralObject as s}from"./utilities/object.mjs";import{objectToFormData as r}from"./utilities/object-to-formdata.mjs";import{Serialize as o}from"./serialize.mjs";function n(t,e){var r;return"undefined"!=typeof process&&s(process.env)&&null!==(r=process.env[t])&&void 0!==r?r:e}const a=n("API_URL","/"),i=n("API_AUTH_TOKEN_KEY"),c=n("API_AUTH_HEADER_KEY"),u=n("API_AUTH_HEADER_TYPE");var l;!function(t){t.GET="GET",t.POST="POST",t.PUT="PUT",t.DELETE="DELETE",t.PATCH="PATCH",t.HEAD="HEAD",t.OPTIONS="OPTIONS"}(l||(l={}));class d{constructor(t=a){this.baseURL=t,this.defaultHeaders={"Content-Type":"application/json"},this.method=d.method,this.storage=d.storage,this.interceptors={request:[],response:[],transform:[],error:[]}}static on(...t){const[e,s]=t,r=d.interceptors[e];r.includes(s)||r.push(s),d.interceptors[e]=r}static off(...t){const[e,s]=t,r=d.interceptors[e];d.interceptors[e]=r.filter(t=>t!==s)}setStorage(t){this.storage=t}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]&&o.Primitive.isPrimitive(t[1])):"object"==typeof t&&null!==t&&Object.values(t).every(t=>o.Primitive.isPrimitive(t)))}getQuery(t){const{method:e,body:s,query:r}=t,n=e===l.GET&&this.isValidQuery(s)?s:r;return n&&"object"==typeof n?n instanceof URLSearchParams?n.toString():o.queryString.stringify(n,{skipNull:!0,skipEmptyString:!0}):"string"==typeof n?n:""}isFormData(t){return t instanceof FormData}addHeaders(t){this.defaultHeaders=Object.assign(Object.assign({},this.defaultHeaders),t)}on(...t){const[e,s]=t,r=this.interceptors[e];return r.includes(s)||r.push(s),this.interceptors[e]=r,this}off(...t){const[e,s]=t,r=this.interceptors[e];return this.interceptors[e]=r.filter(t=>t!==s),this}getToken(){const t=i||d.authTokenKey,e=c||d.authHeaderKey,s=u||d.authHeaderType;if(!t||!e)return{key:e,value:""};let r="";this.storage&&(r=this.storage.getItem(t)||"");const o={key:e,value:""};return r&&(o.value=r,s&&(o.value=`${s} ${r}`)),o}getHeaders(t={},e){const s=this.getToken();s.key in t&&t[s.key]||(t[s.key]=s.value),e&&"Content-Type"in t?delete t["Content-Type"]:t["Content-Type"]=t["Content-Type"]||this.defaultHeaders["Content-Type"]||"application/json";const r=Object.assign(Object.assign(Object.assign({},this.defaultHeaders),t),d.extraHeaders||{});return d.extraHeaders=null,r}getURL(t){var e;const{url:s,params:r={}}=t,n=this.getQuery(t);let a=s;if(s)if(s.match(/^https?:\/\//))a=s;else{a=`${null===(e=this.baseURL)||void 0===e?void 0:e.replace(/\/+$/,"")}/${s.replace(/^\/+/,"")}`}if(n){const t=a.includes("?")?"&":"?";a+=`${t}${n}`}return o.interpolate(a,r)}getBody(t){const{method:e,body:s}=t;if(e!==l.GET&&e!==l.HEAD&&e!==l.OPTIONS&&e!==l.DELETE)return e!==l.POST&&e!==l.PUT&&e!==l.PATCH||!this.isFormData(s)?void 0!==s?JSON.stringify(s):void 0:s}async request(t){const{method:e=l.GET}=t;try{let s=Object.assign({},t);const r=[...d.interceptors.request,...this.interceptors.request];for(const t of r)s=await t(s);const o=this.getURL(s),n=this.getHeaders(s.headers||{});this.isFormData(s.body)&&"Content-Type"in n&&delete n["Content-Type"];const a=await fetch(o,{method:s.method||e,headers:n,body:this.getBody(s),signal:s.signal}),i=a.headers.get("Content-Type")||"";let c=null;c=i.includes("application/json")?await a.json():await a.text();const u=[...d.interceptors.transform,...this.interceptors.transform];let l=c;for(const t of u)l=await t(l);const p=[...d.interceptors.response,...this.interceptors.response];let h=a;for(const t of p)h=await t(h);const f={};h.headers.forEach((t,e)=>{f[e]=t});const y=h.ok;let g=null;if(!y){g=c.error||c;const t=[...d.interceptors.error,...this.interceptors.error];for(const e of t)g=await e(g)}return{data:l,success:y,error:y?null:g,status:h.status,statusText:h.statusText,headers:f}}catch(t){let e=t instanceof Error?t:new Error(String(t));const s=[...d.interceptors.error,...this.interceptors.error];for(const t of s)e=await t(e);return{data:null,status:0,statusText:"Error",headers:{},error:e,success:!1}}}get(t,e,s){return this.request(Object.assign(Object.assign({},s),{method:l.GET,url:t,query:e}))}post(t,e,s){return this.request(Object.assign(Object.assign({},s),{method:l.POST,url:t,body:e}))}put(t,e,s){return this.request(Object.assign(Object.assign({},s),{method:l.PUT,url:t,body:e}))}patch(t,e,s){return this.request(Object.assign(Object.assign({},s),{method:l.PATCH,url:t,body:e}))}delete(t,e){return this.request(Object.assign(Object.assign({},e),{method:l.DELETE,url:t}))}head(t,e){return this.request(Object.assign(Object.assign({},e),{method:l.HEAD,url:t}))}options(t,e){return this.request(Object.assign(Object.assign({},e),{method:l.OPTIONS,url:t}))}upload(s,o,n){const a=(null==n?void 0:n.body)?r(n.body):new FormData;let i=(null==n?void 0:n.name)||"file";if(Array.isArray(o)?(i.endsWith("[]")&&(i=i.slice(0,-2)),o.forEach((t,e)=>{a.append(`${i}[${e}]`,t,t.name)})):t(o)?(i.endsWith("[]")&&(i=i.slice(0,-2)),Array.from(o).forEach((t,e)=>{a.append(`${i}[${e}]`,t,t.name)})):a.append(i,o,o.name),null==n?void 0:n.body){const t=e(n.body);Object.entries(t).forEach(([t,e])=>{null!=e&&a.append(t,String(e))})}return(null==n?void 0:n.onProgress)&&"undefined"!=typeof XMLHttpRequest?new Promise(async t=>{try{let e=Object.assign(Object.assign({},n),{method:l.POST,url:s,body:a});const r=[...d.interceptors.request,...this.interceptors.request];for(const t of r)e=await t(e);const o=this.getURL(e),i=this.getHeaders(e.headers||{},!0),c=new XMLHttpRequest;c.upload.addEventListener("progress",t=>{var e;if(t.lengthComputable){const s=Math.round(t.loaded/t.total*100);null===(e=n.onProgress)||void 0===e||e.call(n,{loaded:t.loaded,total:t.total,percentage:s})}}),c.addEventListener("load",async()=>{try{const e=c.getResponseHeader("Content-Type")||"";let s=null;s=e.includes("application/json")?JSON.parse(c.responseText):c.responseText;const r=[...d.interceptors.transform,...this.interceptors.transform];let o=s;for(const t of r)o=await t(o);const n=[...d.interceptors.response,...this.interceptors.response];let a=new Response(c.responseText,{status:c.status,statusText:c.statusText,headers:i});for(const t of n)a=await t(a);const u={};a.headers.forEach((t,e)=>{u[e]=t});const l=a.ok;t({data:o,success:l,error:l?null:o,status:a.status,statusText:a.statusText,headers:u})}catch(e){const s=[...d.interceptors.error,...this.interceptors.error];for(const t of s)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}}),c.addEventListener("error",e=>{const s=[...d.interceptors.error,...this.interceptors.error];for(const t of s)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}),c.addEventListener("abort",()=>{t({data:null,status:0,statusText:"Aborted",headers:{},error:null,success:!1})}),c.open(e.method||l.POST,o,!0),Object.entries(i).forEach(([t,e])=>{"content-type"!==(null==t?void 0:t.toLowerCase())&&e&&c.setRequestHeader(t,e)}),c.send(e.body)}catch(e){const s=[...d.interceptors.error,...this.interceptors.error];for(const t of s)t(e);t({data:null,status:0,statusText:"Error",headers:{},error:e,success:!1})}}):this.request({method:l.POST,url:s,body:a,headers:null==n?void 0:n.headers,params:null==n?void 0:n.params,signal:null==n?void 0:n.signal,query:null==n?void 0:n.query})}static createFactory(t={}){const s=t.http||new d(t.baseURL);return function(r,o){const n=e("function"==typeof t.endpoint?t.endpoint():t.endpoint||{})[r];return{key:r,fn:async(...e)=>{const r="function"==typeof t.storage?await t.storage():t.storage;switch(r&&s.setStorage(r),o){case l.POST:return await s.post(n,...e);case l.PUT:return await s.put(n,...e);case l.PATCH:return await s.patch(n,...e);case l.DELETE:return await s.delete(n,...e);case l.HEAD:return await s.head(n,...e);case l.OPTIONS:return await s.options(n,...e);case"UPLOAD":return await s.upload(n,...e);default:return await s.get(n,...e)}}}}}}d.method=l,d.authTokenKey="access_token",d.authHeaderKey="Authorization",d.authHeaderType="Bearer",d.authDetectToken=["localStorage","sessionStorage","cookie"],d.extraHeaders=null,d.storage=null,d.interceptors={request:[],response:[],transform:[],error:[]};export{c as API_AUTH_HEADER_KEY,u as API_AUTH_HEADER_TYPE,i as API_AUTH_TOKEN_KEY,a as DEFAULT_BASE_URL,d as Http,l as HttpMethod};
|
|
1
|
+
import{isFileList as e}from"./utilities/filelist.mjs";import{flatten as t}from"./utilities/flatten.mjs";import{isFormData as r,objectToFormData as s}from"./utilities/formdata.mjs";import{get as n}from"./utilities/get.mjs";import{sanitizeMime as o}from"./utilities/sanitize-mime.mjs";import{Serialize as i}from"./serialize.mjs";import{getEnv as a}from"./env.mjs";function c(e){try{return new URL(e).origin}catch(e){return null}}const l=new Set(["__proto__","constructor","prototype"]),u=new Set(["credentials","cache","mode","redirect","referrer","referrerPolicy","integrity","keepalive","priority","duplex","window","next","cf","dispatcher"]);function d(e){const t=Object.create(null);for(const r of Object.keys(e))l.has(r)||(t[r]=e[r]);return t}const p=a("API_URL","/"),h=a("API_AUTH_TOKEN_KEY"),f=a("API_AUTH_HEADER_KEY"),g=a("API_AUTH_HEADER_TYPE");var y,m;!function(e){e.GET="GET",e.POST="POST",e.PUT="PUT",e.DELETE="DELETE",e.PATCH="PATCH",e.HEAD="HEAD",e.OPTIONS="OPTIONS"}(y||(y={})),function(e){e.UPLOAD="UPLOAD",e.RELATED="RELATED"}(m||(m={}));class T{static register(e,t){return this.registered[e]=Object.assign({},t),this}static all(){return Object.assign({},this.registered)}}T.registered={};class O{constructor(e){var t,r,s,n;this.defaultHeaders={"Content-Type":"application/json"},this.method=O.method,this.storage=O.storage,this.interceptors={request:[],response:[],transform:[],error:[]};const o="string"==typeof e||void 0===e?{baseURL:null!=e?e:p}:{baseURL:null!==(t=e.baseURL)&&void 0!==t?t:p,allowedOrigins:e.allowedOrigins};this.baseURL=null!==(s=null!==(r=o.baseURL)&&void 0!==r?r:p)&&void 0!==s?s:"/";const i=new Set;for(const e of null!==(n=o.allowedOrigins)&&void 0!==n?n:[]){const t=c(e);if(!t)throw new Error(`Http: invalid allowedOrigins entry: ${e}`);i.add(t)}const a=c(this.baseURL);a&&i.add(a),this.allowedOrigins=i}isAllowedOrigin(e){return 0===this.allowedOrigins.size||this.allowedOrigins.has(e)}assertSameOriginResponse(e,t,r){const s=Object.keys(r).some(e=>"authorization"===e.toLowerCase()&&!!r[e]),n=Object.keys(r).some(e=>"cookie"===e.toLowerCase()&&!!r[e]);if(!s&&!n)return;const o=c(e);if(!o)return;const i=t.url?c(t.url):null;if(i&&i!==o&&!this.isAllowedOrigin(i))throw new Error(`Http: credentialed request was redirected from ${o} to untrusted origin ${i}`)}static on(...e){const[t,r]=e,s=O.interceptors[t];s.includes(r)||s.push(r),O.interceptors[t]=s}static off(...e){const[t,r]=e,s=O.interceptors[t];O.interceptors[t]=s.filter(e=>e!==r)}setStorage(e){this.storage=e}isValidQuery(e){return"string"==typeof e||e instanceof URLSearchParams||(Array.isArray(e)?e.every(e=>Array.isArray(e)&&2===e.length&&"string"==typeof e[0]&&i.Primitive.isPrimitive(e[1])):"object"==typeof e&&null!==e&&Object.values(e).every(e=>i.Primitive.isPrimitive(e)))}getQuery(e){const{method:t,body:r,query:s}=e,n=t===y.GET&&this.isValidQuery(r)?r:s;if(!n||"object"!=typeof n)return"string"==typeof n?n:"";if(n instanceof URLSearchParams)return n.toString();const o=d(n);return i.queryString.stringify(o,{skipNull:!0,skipEmptyString:!0})}addHeaders(e){this.defaultHeaders=Object.assign(Object.assign({},this.defaultHeaders),e)}on(...e){const[t,r]=e,s=this.interceptors[t];return s.includes(r)||s.push(r),this.interceptors[t]=s,this}off(...e){const[t,r]=e,s=this.interceptors[t];return this.interceptors[t]=s.filter(e=>e!==r),this}getToken(){const e=h||O.authTokenKey,t=f||O.authHeaderKey,r=g||O.authHeaderType;if(!e||!t)return{key:t,value:""};let s="";this.storage&&(s=this.storage.getItem(e)||"");const n={key:t,value:""};return s&&/^[\x21-\x7E]+$/.test(s)&&(n.value=r?`${r} ${s}`:s),n}getHeaders(e={},t){const r=this.getToken();r.key in e&&e[r.key]||(e[r.key]=r.value),t&&"Content-Type"in e?delete e["Content-Type"]:e["Content-Type"]=e["Content-Type"]||this.defaultHeaders["Content-Type"]||"application/json";const s=Object.assign(Object.assign(Object.assign({},this.defaultHeaders),e),O.extraHeaders||{});return O.extraHeaders=null,s}getURL(e){const{url:t="",params:r={}}=e,s=this.getQuery(e);let o;if(t){if(t.startsWith("//"))throw new Error(`Http: protocol-relative URLs are not allowed: ${t}`);if(/^[a-z][a-z0-9+.-]*:/i.test(t)){let e;try{e=new URL(t)}catch(e){throw new Error(`Http: invalid absolute URL: ${t}`)}if("http:"!==e.protocol&&"https:"!==e.protocol)throw new Error(`Http: unsupported URL scheme: ${e.protocol}`);if(!this.isAllowedOrigin(e.origin))throw new Error(`Http: URL origin '${e.origin}' is not in allowedOrigins`);o=e.toString()}else{const e=(this.baseURL||"/").replace(/\/+$/,""),r=t.replace(/^\/+/,"");o=e?`${e}/${r}`:`/${r}`}}else o=this.baseURL||"/";if(s){const e=o.includes("?")?"&":"?";o+=`${e}${s}`}if(!o.includes("{")||!o.includes("}"))return o;const a=Array.isArray(r)?r:d(r);return o.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(e,t)=>{const r=n(a,t);return null==r||"object"==typeof r?"":i.URL.encode(String(r))})}getBody(e){const{method:t,body:s}=e;if(t!==y.GET&&t!==y.HEAD&&t!==y.OPTIONS&&t!==y.DELETE)return t!==y.POST&&t!==y.PUT&&t!==y.PATCH||!r(s)?s instanceof Uint8Array||s instanceof ArrayBuffer?s:void 0!==s?JSON.stringify(s):void 0:s}async request(e){const{method:t=y.GET}=e;try{let s=Object.assign({},e);const n=[...O.interceptors.request,...this.interceptors.request];for(const e of n)s=await e(s);const o=this.getURL(s),i=this.getHeaders(s.headers||{});r(s.body)&&"Content-Type"in i&&delete i["Content-Type"];const a={};if(s.configs)for(const e of Object.keys(s.configs))u.has(e)&&(a[e]=s.configs[e]);const c=await fetch(o,Object.assign(Object.assign({},a),{method:s.method||t,headers:i,body:this.getBody(s),signal:s.signal}));this.assertSameOriginResponse(o,c,i);const l=c.headers.get("Content-Type")||"";let d=null;d=l.includes("application/json")?await c.json():await c.text();const p=[...O.interceptors.transform,...this.interceptors.transform];let h=d;for(const e of p)h=await e(h);const f=[...O.interceptors.response,...this.interceptors.response];let g=c;for(const e of f)g=await e(g);const y={};g.headers.forEach((e,t)=>{y[t]=e});const m=g.ok;let T=null;if(!m){T=d.error||d;const e=[...O.interceptors.error,...this.interceptors.error];for(const t of e)T=await t(T)}return{data:h,success:m,error:m?null:T,status:g.status,statusText:g.statusText,headers:y}}catch(e){let t=e instanceof Error?e:new Error(String(e));const r=[...O.interceptors.error,...this.interceptors.error];for(const e of r)t=await e(t);return{data:null,status:0,statusText:"Error",headers:{},error:t,success:!1}}}get(e,t,r){return this.request(Object.assign(Object.assign({},r),{method:y.GET,url:e,query:t}))}post(e,t,r){return this.request(Object.assign(Object.assign({},r),{method:y.POST,url:e,body:t}))}put(e,t,r){return this.request(Object.assign(Object.assign({},r),{method:y.PUT,url:e,body:t}))}patch(e,t,r){return this.request(Object.assign(Object.assign({},r),{method:y.PATCH,url:e,body:t}))}delete(e,t){return this.request(Object.assign(Object.assign({},t),{method:y.DELETE,url:e}))}head(e,t){return this.request(Object.assign(Object.assign({},t),{method:y.HEAD,url:e}))}options(e,t){return this.request(Object.assign(Object.assign({},t),{method:y.OPTIONS,url:e}))}upload(r,n,o){const i=(null==o?void 0:o.body)?s(o.body):new FormData;let a=(null==o?void 0:o.name)||"file";if(Array.isArray(n)?(a.endsWith("[]")&&(a=a.slice(0,-2)),n.forEach((e,t)=>{i.append(`${a}[${t}]`,e,e.name)})):e(n)?(a.endsWith("[]")&&(a=a.slice(0,-2)),Array.from(n).forEach((e,t)=>{i.append(`${a}[${t}]`,e,e.name)})):i.append(a,n,n.name),null==o?void 0:o.body){const e=t(o.body);Object.entries(e).forEach(([e,t])=>{null!=t&&i.append(e,String(t))})}return(null==o?void 0:o.onProgress)&&"undefined"!=typeof XMLHttpRequest?new Promise(async e=>{try{let t=Object.assign(Object.assign({},o),{method:y.POST,url:r,body:i});const s=[...O.interceptors.request,...this.interceptors.request];for(const e of s)t=await e(t);const n=this.getURL(t),a=this.getHeaders(t.headers||{},!0),c=new XMLHttpRequest;c.upload.addEventListener("progress",e=>{var t;if(e.lengthComputable){const r=Math.round(e.loaded/e.total*100);null===(t=o.onProgress)||void 0===t||t.call(o,{loaded:e.loaded,total:e.total,percentage:r})}}),c.addEventListener("load",async()=>{try{const t=c.getResponseHeader("Content-Type")||"";let r=null;r=t.includes("application/json")?JSON.parse(c.responseText):c.responseText;const s=[...O.interceptors.transform,...this.interceptors.transform];let n=r;for(const e of s)n=await e(n);const o=[...O.interceptors.response,...this.interceptors.response];let i=new Response(c.responseText,{status:c.status,statusText:c.statusText,headers:a});for(const e of o)i=await e(i);const l={};i.headers.forEach((e,t)=>{l[t]=e});const u=i.ok;e({data:n,success:u,error:u?null:n,status:i.status,statusText:i.statusText,headers:l})}catch(t){const r=[...O.interceptors.error,...this.interceptors.error];for(const e of r)e(t);e({data:null,status:0,statusText:"Error",headers:{},error:t,success:!1})}}),c.addEventListener("error",t=>{const r=[...O.interceptors.error,...this.interceptors.error];for(const e of r)e(t);e({data:null,status:0,statusText:"Error",headers:{},error:t,success:!1})}),c.addEventListener("abort",()=>{e({data:null,status:0,statusText:"Aborted",headers:{},error:null,success:!1})}),c.open(t.method||y.POST,n,!0),Object.entries(a).forEach(([e,t])=>{"content-type"!==(null==e?void 0:e.toLowerCase())&&t&&c.setRequestHeader(e,t)}),c.send(t.body)}catch(t){const r=[...O.interceptors.error,...this.interceptors.error];for(const e of r)e(t);e({data:null,status:0,statusText:"Error",headers:{},error:t,success:!1})}}):this.request({method:y.POST,url:r,body:i,headers:null==o?void 0:o.headers,params:null==o?void 0:o.params,signal:null==o?void 0:o.signal,query:null==o?void 0:o.query})}related(e,t,r){const s=o(r.contentType),n=o(r.metadataMimeType||"application/json"),i=`----related-boundary-${Date.now()}-${Math.random().toString(36).slice(2)}`,a=JSON.stringify(r.metadata),c=new TextEncoder,l=c.encode(`--${i}\r\nContent-Type: ${n}; charset=UTF-8\r\n\r\n`+a+"\r\n"),u=c.encode(`--${i}\r\nContent-Type: ${s}\r\nContent-Transfer-Encoding: binary\r\n\r\n`),d=c.encode(`\r\n--${i}--`),p=t instanceof Uint8Array?t:new Uint8Array(t),h=new Uint8Array(l.length+u.length+p.length+d.length);return[l,u,p,d].reduce((e,t)=>(h.set(t,e),e+t.length),0),this.request({method:y.POST,url:e,body:h,headers:Object.assign(Object.assign({},r.headers||{}),{"Content-Type":`multipart/related; boundary=${i}`}),params:r.params,signal:r.signal,query:r.query})}static createFactory(e={}){const r=e.http||new O(e.baseURL);return function(s,n){const o=t("function"==typeof e.endpoint?e.endpoint():e.endpoint||{})[s];return{key:s,fn:async(...t)=>{const s="function"==typeof e.storage?await e.storage():e.storage;switch(s&&r.setStorage(s),n){case y.POST:return await r.post(o,...t);case y.PUT:return await r.put(o,...t);case y.PATCH:return await r.patch(o,...t);case y.DELETE:return await r.delete(o,...t);case y.HEAD:return await r.head(o,...t);case y.OPTIONS:return await r.options(o,...t);case m.UPLOAD:return await r.upload(o,...t);case m.RELATED:return await r.related(o,...t);default:return await r.get(o,...t)}}}}}}O.method=y,O.Endpoint=T,O.authTokenKey="access_token",O.authHeaderKey="Authorization",O.authHeaderType="Bearer",O.authDetectToken=["localStorage","sessionStorage","cookie"],O.extraHeaders=null,O.storage=null,O.interceptors={request:[],response:[],transform:[],error:[]};export{f as API_AUTH_HEADER_KEY,g as API_AUTH_HEADER_TYPE,h as API_AUTH_TOKEN_KEY,p as DEFAULT_BASE_URL,T as Endpoint,O as Http,y as HttpMethod,m as HttpUpload};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
+
export * from "./env";
|
|
1
2
|
export * from "./http";
|
|
2
3
|
export * from "./logger";
|
|
3
4
|
export * from "./searchify";
|
|
4
5
|
export * from "./serialize";
|
|
5
6
|
export * from "./slugify";
|
|
6
7
|
export * from "./subscriber";
|
|
7
|
-
export * from "./syhemo";
|
|
8
8
|
export * from "./utilities";
|
|
9
9
|
export type * from "./http";
|
|
10
10
|
export type * from "./logger";
|
|
@@ -12,6 +12,5 @@ export type * from "./searchify";
|
|
|
12
12
|
export type * from "./serialize";
|
|
13
13
|
export type * from "./slugify";
|
|
14
14
|
export type * from "./subscriber";
|
|
15
|
-
export type * from "./syhemo";
|
|
16
15
|
export type * from "./utilities";
|
|
17
16
|
export type * from "./types";
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./
|
|
1
|
+
"use strict";var e=require("./env.js"),t=require("./http.js"),r=require("./logger.js");require("./searchify.js");var i=require("./serialize.js"),s=require("./slugify.js"),o=require("./subscriber.js"),p=require("./utilities/clone.js"),u=require("./utilities/defer.js"),a=require("./utilities/filelist.js"),l=require("./utilities/flatten.js"),x=require("./utilities/freeze.js"),n=require("./utilities/get.js"),E=require("./utilities/is-equal.js"),c=require("./utilities/is-function.js"),j=require("./utilities/object.js"),A=require("./utilities/merge.js"),b=require("./utilities/formdata.js"),f=require("./utilities/sanitize-mime.js"),_=require("./utilities/string.js");exports.getEnv=e.getEnv,exports.API_AUTH_HEADER_KEY=t.API_AUTH_HEADER_KEY,exports.API_AUTH_HEADER_TYPE=t.API_AUTH_HEADER_TYPE,exports.API_AUTH_TOKEN_KEY=t.API_AUTH_TOKEN_KEY,exports.DEFAULT_BASE_URL=t.DEFAULT_BASE_URL,exports.Endpoint=t.Endpoint,exports.Http=t.Http,Object.defineProperty(exports,"HttpMethod",{enumerable:!0,get:function(){return t.HttpMethod}}),Object.defineProperty(exports,"HttpUpload",{enumerable:!0,get:function(){return t.HttpUpload}}),exports.Logger=r.Logger,exports.Serialize=i.Serialize,exports.DEFAULT_TRANSFORMER=s.DEFAULT_TRANSFORMER,exports.slugify=s.slugify,exports.Subscriber=o.Subscriber,exports.clone=p.clone,exports.defer=u.defer,exports.deferAsync=u.deferAsync,exports.isFileList=a.isFileList,exports.escapeRegexKey=l.escapeRegexKey,exports.flatten=l.flatten,exports.flattenToArray=l.flattenToArray,exports.freeze=x.freeze,exports.get=n.get,exports.isEqual=E.isEqual,exports.isFunction=c.isFunction,exports.hasOwnProperty=j.hasOwnProperty,exports.isComplexObject=j.isComplexObject,exports.isLiteralObject=j.isLiteralObject,exports.isObject=j.isObject,exports.isObjectable=j.isObjectable,exports.merge=A.merge,exports.isFormData=b.isFormData,exports.objectToFormData=b.objectToFormData,exports.MIME_REGEX=f.MIME_REGEX,exports.sanitizeMime=f.sanitizeMime,exports.pascalToKebab=_.pascalToKebab,exports.toString=_.toString,exports.ucfirst=_.ucfirst;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{API_AUTH_HEADER_KEY,API_AUTH_HEADER_TYPE,API_AUTH_TOKEN_KEY,DEFAULT_BASE_URL,Http,HttpMethod}from"./http.mjs";export{Logger}from"./logger.mjs";import"./searchify.mjs";export{Serialize}from"./serialize.mjs";export{DEFAULT_TRANSFORMER,slugify}from"./slugify.mjs";export{Subscriber}from"./subscriber.mjs";export{
|
|
1
|
+
export{getEnv}from"./env.mjs";export{API_AUTH_HEADER_KEY,API_AUTH_HEADER_TYPE,API_AUTH_TOKEN_KEY,DEFAULT_BASE_URL,Endpoint,Http,HttpMethod,HttpUpload}from"./http.mjs";export{Logger}from"./logger.mjs";import"./searchify.mjs";export{Serialize}from"./serialize.mjs";export{DEFAULT_TRANSFORMER,slugify}from"./slugify.mjs";export{Subscriber}from"./subscriber.mjs";export{clone}from"./utilities/clone.mjs";export{defer,deferAsync}from"./utilities/defer.mjs";export{isFileList}from"./utilities/filelist.mjs";export{escapeRegexKey,flatten,flattenToArray}from"./utilities/flatten.mjs";export{freeze}from"./utilities/freeze.mjs";export{get}from"./utilities/get.mjs";export{isEqual}from"./utilities/is-equal.mjs";export{isFunction}from"./utilities/is-function.mjs";export{hasOwnProperty,isComplexObject,isLiteralObject,isObject,isObjectable}from"./utilities/object.mjs";export{merge}from"./utilities/merge.mjs";export{isFormData,objectToFormData}from"./utilities/formdata.mjs";export{MIME_REGEX,sanitizeMime}from"./utilities/sanitize-mime.mjs";export{pascalToKebab,toString,ucfirst}from"./utilities/string.mjs";
|
package/dist/serialize.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";
|
|
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;
|
package/dist/serialize.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
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/subscriber.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./utilities/clone.js"),s=require("./utilities/freeze.js"),t=require("./utilities/is-equal.js"),i=require("./utilities/object.js"),r=require("./utilities/merge.js"),
|
|
1
|
+
"use strict";var e=require("./utilities/clone.js"),s=require("./utilities/freeze.js"),t=require("./utilities/is-equal.js"),i=require("./utilities/object.js"),r=require("./utilities/merge.js"),n=require("./utilities/string.js");class l extends Set{}class a extends Map{}const h=s.freeze({state:{change:"$state:change"}});exports.Subscriber=class{get shallow(){return s.freeze({merge:this._shallow.merge,clone:this._shallow.clone,isEqual:this._shallow.isEqual})}set shallow(e){this._shallow=this._shallow.merge(this._shallow,e)}constructor(i,n){this._state={},this.listeners=new a,this._shallow={merge:r.merge,clone:e.clone,isEqual:t.isEqual},this._events=s.freeze(h),this._state=null!=i?i:{},this._events=s.freeze(Object.assign(Object.assign({},this._events),n))}subscribe(e,s){return this.listeners.has(e)||this.listeners.set(e,new l),this.listeners.get(e).add(s),()=>{var t;null===(t=this.listeners.get(e))||void 0===t||t.delete(s)}}dispatch(e,s){this.listeners.has(e)&&this.listeners.get(e).forEach(e=>{e(...void 0===s?[]:[s])})}getState(){return this._state}setState(e){const s=this._shallow.merge(this._state,e);this._shallow.isEqual(this._state,s)||(this._state=s,this.dispatch(this._events.state.change,this._shallow.clone(s)))}onStateChange(e){return this.subscribe(this._events.state.change,e)}async subscribeAsyncOnce(e,s,t){let i,r;try{return await new Promise((n,l)=>{if(null==t?void 0:t.aborted)return l(new Error("Operation cancelled"));i=this.subscribe(e,e=>{null==s||s(e),n(e)}),t&&(r=()=>l(new Error("Operation cancelled")),t.addEventListener("abort",r,{once:!0}))})}finally{null==i||i(),t&&r&&t.removeEventListener("abort",r)}}static wire(e,t){for(const r in t){if(r in e)throw new Error(`[Subscriber.wire] "${r}" is invalid.`);const l=t[r];if(!i.isLiteralObject(l))continue;const a=Object.keys(l).reduce((s,t)=>{const i=l[t];return s[t]=s=>{e.dispatch(i,s)},s[`on${n.ucfirst(t)}`]=s=>e.subscribe(i,s),s},{});Object.defineProperty(e,r,{value:s.freeze(a),writable:!1,enumerable:!0,configurable:!1})}return e}};
|
package/dist/subscriber.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{clone as e}from"./utilities/clone.mjs";import{freeze as t}from"./utilities/freeze.mjs";import{isEqual as s}from"./utilities/is-equal.mjs";import{isLiteralObject as i}from"./utilities/object.mjs";import{merge as r}from"./utilities/merge.mjs";import{ucfirst as n}from"./utilities/
|
|
1
|
+
import{clone as e}from"./utilities/clone.mjs";import{freeze as t}from"./utilities/freeze.mjs";import{isEqual as s}from"./utilities/is-equal.mjs";import{isLiteralObject as i}from"./utilities/object.mjs";import{merge as r}from"./utilities/merge.mjs";import{ucfirst as n}from"./utilities/string.mjs";class l extends Set{}class a extends Map{}const o=t({state:{change:"$state:change"}});class h{get shallow(){return t({merge:this._shallow.merge,clone:this._shallow.clone,isEqual:this._shallow.isEqual})}set shallow(e){this._shallow=this._shallow.merge(this._shallow,e)}constructor(i,n){this._state={},this.listeners=new a,this._shallow={merge:r,clone:e,isEqual:s},this._events=t(o),this._state=null!=i?i:{},this._events=t(Object.assign(Object.assign({},this._events),n))}subscribe(e,t){return this.listeners.has(e)||this.listeners.set(e,new l),this.listeners.get(e).add(t),()=>{var s;null===(s=this.listeners.get(e))||void 0===s||s.delete(t)}}dispatch(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(e=>{e(...void 0===t?[]:[t])})}getState(){return this._state}setState(e){const t=this._shallow.merge(this._state,e);this._shallow.isEqual(this._state,t)||(this._state=t,this.dispatch(this._events.state.change,this._shallow.clone(t)))}onStateChange(e){return this.subscribe(this._events.state.change,e)}async subscribeAsyncOnce(e,t,s){let i,r;try{return await new Promise((n,l)=>{if(null==s?void 0:s.aborted)return l(new Error("Operation cancelled"));i=this.subscribe(e,e=>{null==t||t(e),n(e)}),s&&(r=()=>l(new Error("Operation cancelled")),s.addEventListener("abort",r,{once:!0}))})}finally{null==i||i(),s&&r&&s.removeEventListener("abort",r)}}static wire(e,s){for(const r in s){if(r in e)throw new Error(`[Subscriber.wire] "${r}" is invalid.`);const l=s[r];if(!i(l))continue;const a=Object.keys(l).reduce((t,s)=>{const i=l[s];return t[s]=t=>{e.dispatch(i,t)},t[`on${n(s)}`]=t=>e.subscribe(i,t),t},{});Object.defineProperty(e,r,{value:t(a),writable:!1,enumerable:!0,configurable:!1})}return e}}export{h as Subscriber};
|
package/dist/syhemo.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var node_perf_hooks=require("node:perf_hooks"),subscriber=require("./subscriber.js")
|
|
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
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{monitorEventLoopDelay}from"node:perf_hooks";import{Subscriber}from"./subscriber.mjs";import
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var i=require("./is-function.js"),t=require("./
|
|
1
|
+
"use strict";var i=require("./is-function.js"),t=require("./string.js");exports.isFileList=function(e){return"undefined"!=typeof FileList&&e instanceof FileList||"object"==typeof e&&null!==e&&"[object FileList]"===t.toString(e)&&"length"in e&&"item"in e&&i.isFunction(e.item)};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isFunction as
|
|
1
|
+
import{isFunction as i}from"./is-function.mjs";import{toString as t}from"./string.mjs";function e(e){return"undefined"!=typeof FileList&&e instanceof FileList||"object"==typeof e&&null!==e&&"[object FileList]"===t(e)&&"length"in e&&"item"in e&&i(e.item)}export{e as isFileList};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** Type guard that checks whether a value is a `FormData` instance. */
|
|
2
|
+
export declare function isFormData(body: unknown): body is FormData;
|
|
1
3
|
/**
|
|
2
4
|
* Recursively converts a value into a `FormData` instance.
|
|
3
5
|
* Handles Date, File, Blob, FileList, arrays, nested objects, and primitives.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var t=require("./filelist.js");exports.isFormData=function(t){return t instanceof FormData},exports.objectToFormData=function r(n,e=new FormData,a=""){return null==n||(n instanceof Date?e.append(a,n.toISOString()):n instanceof File||n instanceof Blob?e.append(a,n):t.isFileList(n)?Array.from(n).forEach((t,r)=>{const n=a?`${a}[${r}]`:String(r);e.append(n,t,t.name)}):Array.isArray(n)?n.forEach((t,n)=>{const o=a?`${a}[${n}]`:String(n);r(t,e,o)}):"object"==typeof n?Object.entries(n).forEach(([t,n])=>{r(n,e,a?`${a}[${t}]`:t)}):e.append(a,String(n))),e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isFileList as n}from"./filelist.mjs";function t(n){return n instanceof FormData}function r(t,e=new FormData,o=""){return null==t||(t instanceof Date?e.append(o,t.toISOString()):t instanceof File||t instanceof Blob?e.append(o,t):n(t)?Array.from(t).forEach((n,t)=>{const r=o?`${o}[${t}]`:String(t);e.append(r,n,n.name)}):Array.isArray(t)?t.forEach((n,t)=>{const a=o?`${o}[${t}]`:String(t);r(n,e,a)}):"object"==typeof t?Object.entries(t).forEach(([n,t])=>{r(t,e,o?`${o}[${n}]`:n)}):e.append(o,String(t))),e}export{t as isFormData,r as objectToFormData};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { clone } from "./clone";
|
|
2
|
-
export { defer, deferAsync, type DeferIds, type DeferCallback, type CancelablePromise } from "./defer";
|
|
2
|
+
export { defer, deferAsync, type DeferIds, type DeferCallback, type CancelablePromise, } from "./defer";
|
|
3
3
|
export { isFileList, type FileListLike } from "./filelist";
|
|
4
4
|
export { flatten, flattenToArray, escapeRegexKey, type ObjectOf } from "./flatten";
|
|
5
5
|
export { freeze } from "./freeze";
|
|
@@ -8,7 +8,6 @@ export { isEqual } from "./is-equal";
|
|
|
8
8
|
export { isFunction } from "./is-function";
|
|
9
9
|
export { isLiteralObject, isComplexObject, isObject, isObjectable, hasOwnProperty } from "./object";
|
|
10
10
|
export { merge } from "./merge";
|
|
11
|
-
export { objectToFormData } from "./
|
|
12
|
-
export {
|
|
13
|
-
export { toString } from "./
|
|
14
|
-
export { ucfirst } from "./ucfirst";
|
|
11
|
+
export { isFormData, objectToFormData } from "./formdata";
|
|
12
|
+
export { MIME_REGEX, sanitizeMime } from "./sanitize-mime";
|
|
13
|
+
export { toString, ucfirst, pascalToKebab } from "./string";
|
package/dist/utilities/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./clone.js"),r=require("./defer.js"),t=require("./filelist.js"),s=require("./flatten.js"),
|
|
1
|
+
"use strict";var e=require("./clone.js"),r=require("./defer.js"),t=require("./filelist.js"),s=require("./flatten.js"),i=require("./freeze.js"),o=require("./get.js"),a=require("./is-equal.js"),p=require("./is-function.js"),x=require("./object.js"),c=require("./merge.js"),j=require("./formdata.js"),n=require("./sanitize-mime.js"),l=require("./string.js");exports.clone=e.clone,exports.defer=r.defer,exports.deferAsync=r.deferAsync,exports.isFileList=t.isFileList,exports.escapeRegexKey=s.escapeRegexKey,exports.flatten=s.flatten,exports.flattenToArray=s.flattenToArray,exports.freeze=i.freeze,exports.get=o.get,exports.isEqual=a.isEqual,exports.isFunction=p.isFunction,exports.hasOwnProperty=x.hasOwnProperty,exports.isComplexObject=x.isComplexObject,exports.isLiteralObject=x.isLiteralObject,exports.isObject=x.isObject,exports.isObjectable=x.isObjectable,exports.merge=c.merge,exports.isFormData=j.isFormData,exports.objectToFormData=j.objectToFormData,exports.MIME_REGEX=n.MIME_REGEX,exports.sanitizeMime=n.sanitizeMime,exports.pascalToKebab=l.pascalToKebab,exports.toString=l.toString,exports.ucfirst=l.ucfirst;
|
package/dist/utilities/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{clone}from"./clone.mjs";export{defer,deferAsync}from"./defer.mjs";export{isFileList}from"./filelist.mjs";export{escapeRegexKey,flatten,flattenToArray}from"./flatten.mjs";export{freeze}from"./freeze.mjs";export{get}from"./get.mjs";export{isEqual}from"./is-equal.mjs";export{isFunction}from"./is-function.mjs";export{hasOwnProperty,isComplexObject,isLiteralObject,isObject,isObjectable}from"./object.mjs";export{merge}from"./merge.mjs";export{objectToFormData}from"./
|
|
1
|
+
export{clone}from"./clone.mjs";export{defer,deferAsync}from"./defer.mjs";export{isFileList}from"./filelist.mjs";export{escapeRegexKey,flatten,flattenToArray}from"./flatten.mjs";export{freeze}from"./freeze.mjs";export{get}from"./get.mjs";export{isEqual}from"./is-equal.mjs";export{isFunction}from"./is-function.mjs";export{hasOwnProperty,isComplexObject,isLiteralObject,isObject,isObjectable}from"./object.mjs";export{merge}from"./merge.mjs";export{isFormData,objectToFormData}from"./formdata.mjs";export{MIME_REGEX,sanitizeMime}from"./sanitize-mime.mjs";export{pascalToKebab,toString,ucfirst}from"./string.mjs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var n=require("./string.js");exports.isFunction=function(t){return"function"==typeof t||["[object Function]","[object AsyncFunction]","[object GeneratorFunction]"].includes(n.toString(t))};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toString as n}from"./
|
|
1
|
+
import{toString as n}from"./string.mjs";function t(t){return"function"==typeof t||["[object Function]","[object AsyncFunction]","[object GeneratorFunction]"].includes(n(t))}export{t as isFunction};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** RFC 2045 MIME type pattern: `type/subtype` with optional `;parameter=value`. */
|
|
2
|
+
export declare const MIME_REGEX: RegExp;
|
|
3
|
+
/**
|
|
4
|
+
* Validate and sanitize a MIME type string.
|
|
5
|
+
*
|
|
6
|
+
* Returns the input unchanged if valid, empty string if malformed.
|
|
7
|
+
* This prevents attackers from smuggling values like `application/php/jpeg`
|
|
8
|
+
* through to the upstream API — the empty Content-Type lets the API
|
|
9
|
+
* server reject the payload on its own terms instead of crashing ours.
|
|
10
|
+
*/
|
|
11
|
+
export declare function sanitizeMime(value: string): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const t=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-^_.+]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-^_.+]*(;\s*[\w.-]+=[\w.-]+)*$/;exports.MIME_REGEX=t,exports.sanitizeMime=function(s){return t.test(s)?s:""};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-^_.+]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-^_.+]*(;\s*[\w.-]+=[\w.-]+)*$/;function a(a){return t.test(a)?a:""}export{t as MIME_REGEX,a as sanitizeMime};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Returns the internal `[[Class]]` tag of a value using `Object.prototype.toString`.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* ```ts
|
|
6
|
+
* toString([]); // "[object Array]"
|
|
7
|
+
* toString(null); // "[object Null]"
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
export declare function toString(value: unknown): string;
|
|
11
|
+
/**
|
|
12
|
+
* Capitalizes the first character of a string.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* ucfirst("hello"); // "Hello"
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export declare function ucfirst<T extends string>(str: T): Capitalize<T>;
|
|
20
|
+
/**
|
|
21
|
+
* Converts a PascalCase or camelCase string to kebab-case.
|
|
22
|
+
* Handles consecutive uppercase characters (e.g. acronyms) gracefully.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* pascalToKebab("MyComponent"); // "my-component"
|
|
27
|
+
* pascalToKebab("HTMLParser"); // "html-parser"
|
|
28
|
+
* pascalToKebab("camelCase"); // "camel-case"
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export declare function pascalToKebab(str: string): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.pascalToKebab=function(t){return t?t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").toLowerCase():t},exports.toString=function(t){return Object.prototype.toString.call(t)},exports.ucfirst=function(t){return t.charAt(0).toUpperCase()+t.slice(1)};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){return Object.prototype.toString.call(e)}function t(e){return e.charAt(0).toUpperCase()+e.slice(1)}function r(e){return e?e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").toLowerCase():e}export{r as pascalToKebab,e as toString,t as ucfirst};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecosy/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "A modular, tree-shakable collection of essential utilities, serialization primitives, and event-driven patterns for modern TypeScript applications",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|
|
@@ -15,51 +15,61 @@
|
|
|
15
15
|
],
|
|
16
16
|
"exports": {
|
|
17
17
|
".": {
|
|
18
|
+
"source": "./src/index.ts",
|
|
18
19
|
"types": "./dist/index.d.ts",
|
|
19
20
|
"import": "./dist/index.mjs",
|
|
20
21
|
"require": "./dist/index.js"
|
|
21
22
|
},
|
|
22
23
|
"./types": {
|
|
24
|
+
"source": "./src/types/index.ts",
|
|
23
25
|
"types": "./dist/types/index.d.ts",
|
|
24
26
|
"import": "./dist/types/index.mjs",
|
|
25
27
|
"require": "./dist/types/index.js"
|
|
26
28
|
},
|
|
27
29
|
"./utilities": {
|
|
30
|
+
"source": "./src/utilities/index.ts",
|
|
28
31
|
"types": "./dist/utilities/index.d.ts",
|
|
29
32
|
"import": "./dist/utilities/index.mjs",
|
|
30
33
|
"require": "./dist/utilities/index.js"
|
|
31
34
|
},
|
|
32
35
|
"./subscriber": {
|
|
36
|
+
"source": "./src/subscriber.ts",
|
|
33
37
|
"types": "./dist/subscriber.d.ts",
|
|
34
38
|
"import": "./dist/subscriber.mjs",
|
|
35
39
|
"require": "./dist/subscriber.js"
|
|
36
40
|
},
|
|
37
41
|
"./http": {
|
|
42
|
+
"source": "./src/http.ts",
|
|
38
43
|
"types": "./dist/http.d.ts",
|
|
39
44
|
"import": "./dist/http.mjs",
|
|
40
45
|
"require": "./dist/http.js"
|
|
41
46
|
},
|
|
42
47
|
"./logger": {
|
|
48
|
+
"source": "./src/logger.ts",
|
|
43
49
|
"types": "./dist/logger.d.ts",
|
|
44
50
|
"import": "./dist/logger.mjs",
|
|
45
51
|
"require": "./dist/logger.js"
|
|
46
52
|
},
|
|
47
53
|
"./syhemo": {
|
|
54
|
+
"source": "./src/syhemo.ts",
|
|
48
55
|
"types": "./dist/syhemo.d.ts",
|
|
49
56
|
"import": "./dist/syhemo.mjs",
|
|
50
57
|
"require": "./dist/syhemo.js"
|
|
51
58
|
},
|
|
52
59
|
"./serialize": {
|
|
60
|
+
"source": "./src/serialize.ts",
|
|
53
61
|
"types": "./dist/serialize.d.ts",
|
|
54
62
|
"import": "./dist/serialize.mjs",
|
|
55
63
|
"require": "./dist/serialize.js"
|
|
56
64
|
},
|
|
57
65
|
"./slugify": {
|
|
66
|
+
"source": "./src/slugify.ts",
|
|
58
67
|
"types": "./dist/slugify.d.ts",
|
|
59
68
|
"import": "./dist/slugify.mjs",
|
|
60
69
|
"require": "./dist/slugify.js"
|
|
61
70
|
},
|
|
62
71
|
"./searchify": {
|
|
72
|
+
"source": "./src/searchify.ts",
|
|
63
73
|
"types": "./dist/searchify.d.ts",
|
|
64
74
|
"import": "./dist/searchify.mjs",
|
|
65
75
|
"require": "./dist/searchify.js"
|
|
@@ -96,6 +106,7 @@
|
|
|
96
106
|
"@eslint/js": "^10.0.1",
|
|
97
107
|
"@rollup/plugin-terser": "^1.0.0",
|
|
98
108
|
"@rollup/plugin-typescript": "^12.3.0",
|
|
109
|
+
"@types/node": "^25.6.0",
|
|
99
110
|
"@typescript-eslint/eslint-plugin": "^8.57.1",
|
|
100
111
|
"@typescript-eslint/parser": "^8.57.1",
|
|
101
112
|
"eslint": "^10.1.0",
|
|
@@ -105,6 +116,7 @@
|
|
|
105
116
|
"prettier": "^3.8.1",
|
|
106
117
|
"rimraf": "^6.1.3",
|
|
107
118
|
"rollup": "^4.59.1",
|
|
108
|
-
"
|
|
119
|
+
"tslib": "^2.8.1",
|
|
120
|
+
"typescript": "^6.0.2"
|
|
109
121
|
}
|
|
110
122
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var t=require("./filelist.js");exports.objectToFormData=function e(r,n=new FormData,a=""){return null==r||(r instanceof Date?n.append(a,r.toISOString()):r instanceof File||r instanceof Blob?n.append(a,r):t.isFileList(r)?Array.from(r).forEach((t,e)=>{const r=a?`${a}[${e}]`:String(e);n.append(r,t,t.name)}):Array.isArray(r)?r.forEach((t,r)=>{const o=a?`${a}[${r}]`:String(r);e(t,n,o)}):"object"==typeof r?Object.entries(r).forEach(([t,r])=>{e(r,n,a?`${a}[${t}]`:t)}):n.append(a,String(r))),n};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{isFileList as n}from"./filelist.mjs";function r(t,e=new FormData,o=""){return null==t||(t instanceof Date?e.append(o,t.toISOString()):t instanceof File||t instanceof Blob?e.append(o,t):n(t)?Array.from(t).forEach((n,r)=>{const t=o?`${o}[${r}]`:String(r);e.append(t,n,n.name)}):Array.isArray(t)?t.forEach((n,t)=>{const a=o?`${o}[${t}]`:String(t);r(n,e,a)}):"object"==typeof t?Object.entries(t).forEach(([n,t])=>{r(t,e,o?`${o}[${n}]`:n)}):e.append(o,String(t))),e}export{r as objectToFormData};
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Converts a PascalCase or camelCase string to kebab-case.
|
|
3
|
-
* Handles consecutive uppercase characters (e.g. acronyms) gracefully.
|
|
4
|
-
*
|
|
5
|
-
* @param str - The string to convert.
|
|
6
|
-
* @returns The kebab-case version of the string.
|
|
7
|
-
*
|
|
8
|
-
* @example
|
|
9
|
-
* ```ts
|
|
10
|
-
* pascalToKebab("MyComponent"); // "my-component"
|
|
11
|
-
* pascalToKebab("HTMLParser"); // "html-parser"
|
|
12
|
-
* pascalToKebab("camelCase"); // "camel-case"
|
|
13
|
-
* ```
|
|
14
|
-
*/
|
|
15
|
-
export declare function pascalToKebab(str: string): string;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";exports.pascalToKebab=function(e){return e?e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").toLowerCase():e};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function e(e){return e?e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z][a-z])/g,"$1-$2").toLowerCase():e}export{e as pascalToKebab};
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Returns the internal `[[Class]]` tag of a value using `Object.prototype.toString`.
|
|
3
|
-
*
|
|
4
|
-
* @param value - The value to get the string tag for.
|
|
5
|
-
* @returns A string like `"[object Type]"`.
|
|
6
|
-
*
|
|
7
|
-
* @example
|
|
8
|
-
* ```ts
|
|
9
|
-
* toString([]); // "[object Array]"
|
|
10
|
-
* toString(null); // "[object Null]"
|
|
11
|
-
* ```
|
|
12
|
-
*/
|
|
13
|
-
export declare function toString(value: unknown): string;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";exports.toString=function(t){return Object.prototype.toString.call(t)};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function t(t){return Object.prototype.toString.call(t)}export{t as toString};
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Capitalizes the first character of a string.
|
|
3
|
-
*
|
|
4
|
-
* @param str - The string to capitalize.
|
|
5
|
-
* @returns The string with its first character in uppercase.
|
|
6
|
-
*
|
|
7
|
-
* @example
|
|
8
|
-
* ```ts
|
|
9
|
-
* ucfirst("hello"); // "Hello"
|
|
10
|
-
* ```
|
|
11
|
-
*/
|
|
12
|
-
export declare function ucfirst<T extends string>(str: T): Capitalize<T>;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";exports.ucfirst=function(t){return t.charAt(0).toUpperCase()+t.slice(1)};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function e(e){return e.charAt(0).toUpperCase()+e.slice(1)}export{e as ucfirst};
|