@ecosy/core 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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 +40 -6
- 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. */
|
|
@@ -66,6 +71,15 @@ export interface HttpUploadOptions extends Pick<HttpRequest, "headers" | "params
|
|
|
66
71
|
name: string;
|
|
67
72
|
body?: Record<string, unknown>;
|
|
68
73
|
}
|
|
74
|
+
/** Options for a multipart/related upload (e.g. Google Drive). */
|
|
75
|
+
export interface HttpRelatedOptions extends Pick<HttpRequest, "headers" | "params" | "signal" | "query"> {
|
|
76
|
+
/** JSON metadata object (will be serialized as the first part). */
|
|
77
|
+
metadata: Record<string, unknown>;
|
|
78
|
+
/** MIME type of the metadata part. Default: "application/json" */
|
|
79
|
+
metadataMimeType?: string;
|
|
80
|
+
/** MIME type of the file content. */
|
|
81
|
+
contentType: string;
|
|
82
|
+
}
|
|
69
83
|
/** Options for creating an HTTP factory via {@link Http.createFactory}. */
|
|
70
84
|
export interface HttpFactoryOptions {
|
|
71
85
|
baseURL?: string;
|
|
@@ -78,6 +92,14 @@ export interface HttpFactory<T = unknown, Args extends any[] = [], E = unknown>
|
|
|
78
92
|
key: string;
|
|
79
93
|
fn: (...args: Args) => Promise<HttpResponse<T, E>>;
|
|
80
94
|
}
|
|
95
|
+
/** Central registry for grouping endpoint URLs by service name. */
|
|
96
|
+
export declare class Endpoint {
|
|
97
|
+
private static registered;
|
|
98
|
+
static register(service: string, endpoints: Record<string, string>): typeof Endpoint;
|
|
99
|
+
static all(): {
|
|
100
|
+
[x: string]: Record<string, string>;
|
|
101
|
+
};
|
|
102
|
+
}
|
|
81
103
|
/**
|
|
82
104
|
* HTTP client with interceptors, auth token management, file uploads,
|
|
83
105
|
* and a factory pattern for endpoint generation.
|
|
@@ -94,6 +116,7 @@ export interface HttpFactory<T = unknown, Args extends any[] = [], E = unknown>
|
|
|
94
116
|
export declare class Http {
|
|
95
117
|
private readonly baseURL;
|
|
96
118
|
static readonly method: typeof HttpMethod;
|
|
119
|
+
static readonly Endpoint: typeof Endpoint;
|
|
97
120
|
static authTokenKey: string;
|
|
98
121
|
static authHeaderKey: string;
|
|
99
122
|
static authHeaderType: string;
|
|
@@ -115,8 +138,6 @@ export declare class Http {
|
|
|
115
138
|
/** Type guard that checks whether a value is a valid {@link HttpQuery}. */
|
|
116
139
|
isValidQuery(query: unknown): query is HttpQuery;
|
|
117
140
|
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
141
|
/** Merge additional default headers into this instance. */
|
|
121
142
|
addHeaders(headers: Record<string, string>): void;
|
|
122
143
|
/** Register an instance-level interceptor. */
|
|
@@ -134,8 +155,8 @@ export declare class Http {
|
|
|
134
155
|
};
|
|
135
156
|
/** Build the full URL from base URL, path, query string, and path params. */
|
|
136
157
|
getURL(options: HttpRequest): string;
|
|
137
|
-
/** Serialize the request body (JSON or
|
|
138
|
-
getBody(options: HttpRequest): string | FormData | undefined;
|
|
158
|
+
/** Serialize the request body (JSON, FormData, or binary). Returns `undefined` for bodyless methods. */
|
|
159
|
+
getBody(options: HttpRequest): string | FormData | Uint8Array | ArrayBuffer | undefined;
|
|
139
160
|
/** Execute a full HTTP request with all interceptors applied. */
|
|
140
161
|
request<T = unknown, E = unknown>(options: HttpRequest): Promise<HttpResponse<T, E>>;
|
|
141
162
|
/** Perform a GET request. */
|
|
@@ -157,6 +178,19 @@ export declare class Http {
|
|
|
157
178
|
* Falls back to `XMLHttpRequest` when `onProgress` is provided for progress tracking.
|
|
158
179
|
*/
|
|
159
180
|
upload<T = unknown, E = unknown>(url: string, file: File | File[] | FileListLike, options?: HttpUploadOptions): Promise<HttpResponse<T, E>>;
|
|
181
|
+
/**
|
|
182
|
+
* Upload with multipart/related format.
|
|
183
|
+
* Builds a proper multipart/related body with JSON metadata + binary file content.
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* ```ts
|
|
187
|
+
* const result = await http.related<DriveFile>("/files?uploadType=multipart", fileBuffer, {
|
|
188
|
+
* metadata: { name: "photo.jpg", parents: ["folderId"] },
|
|
189
|
+
* contentType: "image/jpeg",
|
|
190
|
+
* });
|
|
191
|
+
* ```
|
|
192
|
+
*/
|
|
193
|
+
related<T = unknown, E = unknown>(url: string, fileData: ArrayBuffer | Uint8Array, options: HttpRelatedOptions): Promise<HttpResponse<T, E>>;
|
|
160
194
|
/**
|
|
161
195
|
* Creates a factory function that generates typed endpoint descriptors.
|
|
162
196
|
* Each descriptor has a `key` and an async `fn` that performs the HTTP call.
|
|
@@ -172,5 +206,5 @@ export declare class Http {
|
|
|
172
206
|
* const { data } = await getUsers.fn();
|
|
173
207
|
* ```
|
|
174
208
|
*/
|
|
175
|
-
static createFactory(options?: HttpFactoryOptions): <T, Args extends any[] = [], E = unknown>(key: string, method?: HttpMethod |
|
|
209
|
+
static createFactory(options?: HttpFactoryOptions): <T, Args extends any[] = [], E = unknown>(key: string, method?: HttpMethod | HttpUpload) => HttpFactory<T, Args, E>;
|
|
176
210
|
}
|
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/sanitize-mime.js"),o=require("./serialize.js"),n=require("./env.js");const a=n.getEnv("API_URL","/"),i=n.getEnv("API_AUTH_TOKEN_KEY"),c=n.getEnv("API_AUTH_HEADER_KEY"),p=n.getEnv("API_AUTH_HEADER_TYPE");var d,u;exports.HttpMethod=void 0,(d=exports.HttpMethod||(exports.HttpMethod={})).GET="GET",d.POST="POST",d.PUT="PUT",d.DELETE="DELETE",d.PATCH="PATCH",d.HEAD="HEAD",d.OPTIONS="OPTIONS",exports.HttpUpload=void 0,(u=exports.HttpUpload||(exports.HttpUpload={})).UPLOAD="UPLOAD",u.RELATED="RELATED";class l{static register(t,e){return this.registered[t]=Object.assign({},e),this}static all(){return Object.assign({},this.registered)}}l.registered={};class h{constructor(t=a){this.baseURL=t,this.defaultHeaders={"Content-Type":"application/json"},this.method=h.method,this.storage=h.storage,this.interceptors={request:[],response:[],transform:[],error:[]}}static on(...t){const[e,r]=t,s=h.interceptors[e];s.includes(r)||s.push(r),h.interceptors[e]=s}static off(...t){const[e,r]=t,s=h.interceptors[e];h.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]&&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:r,query:s}=t,n=e===exports.HttpMethod.GET&&this.isValidQuery(r)?r:s;return n&&"object"==typeof n?n instanceof URLSearchParams?n.toString():o.Serialize.queryString.stringify(n,{skipNull:!0,skipEmptyString:!0}):"string"==typeof n?n:""}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=i||h.authTokenKey,e=c||h.authHeaderKey,r=p||h.authHeaderType;if(!t||!e)return{key:e,value:""};let s="";this.storage&&(s=this.storage.getItem(t)||"");const o={key:e,value:""};return s&&(o.value=s,r&&(o.value=`${r} ${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),h.extraHeaders||{});return h.extraHeaders=null,s}getURL(t){var e;const{url:r,params:s={}}=t,n=this.getQuery(t);let a=r;if(r)if(r.match(/^https?:\/\//))a=r;else{a=`${null===(e=this.baseURL)||void 0===e?void 0:e.replace(/\/+$/,"")}/${r.replace(/^\/+/,"")}`}if(n){const t=a.includes("?")?"&":"?";a+=`${t}${n}`}return o.Serialize.interpolate(a,s)}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=[...h.interceptors.request,...this.interceptors.request];for(const t of o)s=await t(s);const n=this.getURL(s),a=this.getHeaders(s.headers||{});r.isFormData(s.body)&&"Content-Type"in a&&delete a["Content-Type"];const i=await fetch(n,{method:s.method||e,headers:a,body:this.getBody(s),signal:s.signal}),c=i.headers.get("Content-Type")||"";let p=null;p=c.includes("application/json")?await i.json():await i.text();const d=[...h.interceptors.transform,...this.interceptors.transform];let u=p;for(const t of d)u=await t(u);const l=[...h.interceptors.response,...this.interceptors.response];let g=i;for(const t of l)g=await t(g);const y={};g.headers.forEach((t,e)=>{y[e]=t});const T=g.ok;let f=null;if(!T){f=p.error||p;const t=[...h.interceptors.error,...this.interceptors.error];for(const e of t)f=await e(f)}return{data:u,success:T,error:T?null:f,status:g.status,statusText:g.statusText,headers:y}}catch(t){let e=t instanceof Error?t:new Error(String(t));const r=[...h.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 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=[...h.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 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=[...h.interceptors.transform,...this.interceptors.transform];let o=r;for(const t of s)o=await t(o);const n=[...h.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 d=a.ok;t({data:o,success:d,error:d?null:o,status:a.status,statusText:a.statusText,headers:p})}catch(e){const r=[...h.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=[...h.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(i).forEach(([t,e])=>{"content-type"!==(null==t?void 0:t.toLowerCase())&&e&&c.setRequestHeader(t,e)}),c.send(e.body)}catch(e){const r=[...h.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: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})}related(t,e,r){const o=s.sanitizeMime(r.contentType),n=s.sanitizeMime(r.metadataMimeType||"application/json"),a=`----related-boundary-${Date.now()}-${Math.random().toString(36).slice(2)}`,i=JSON.stringify(r.metadata),c=new TextEncoder,p=c.encode(`--${a}\r\nContent-Type: ${n}; charset=UTF-8\r\n\r\n`+i+"\r\n"),d=c.encode(`--${a}\r\nContent-Type: ${o}\r\nContent-Transfer-Encoding: binary\r\n\r\n`),u=c.encode(`\r\n--${a}--`),l=e instanceof Uint8Array?e:new Uint8Array(e),h=new Uint8Array(p.length+d.length+l.length+u.length);return[p,d,l,u].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=${a}`}),params:r.params,signal:r.signal,query:r.query})}static createFactory(t={}){const r=t.http||new h(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)}}}}}}h.method=exports.HttpMethod,h.Endpoint=l,h.authTokenKey="access_token",h.authHeaderKey="Authorization",h.authHeaderType="Bearer",h.authDetectToken=["localStorage","sessionStorage","cookie"],h.extraHeaders=null,h.storage=null,h.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.Endpoint=l,exports.Http=h;
|
package/dist/http.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
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{sanitizeMime as n}from"./utilities/sanitize-mime.mjs";import{Serialize as o}from"./serialize.mjs";import{getEnv as a}from"./env.mjs";const i=a("API_URL","/"),c=a("API_AUTH_TOKEN_KEY"),u=a("API_AUTH_HEADER_KEY"),d=a("API_AUTH_HEADER_TYPE");var l,p;!function(e){e.GET="GET",e.POST="POST",e.PUT="PUT",e.DELETE="DELETE",e.PATCH="PATCH",e.HEAD="HEAD",e.OPTIONS="OPTIONS"}(l||(l={})),function(e){e.UPLOAD="UPLOAD",e.RELATED="RELATED"}(p||(p={}));class h{static register(e,t){return this.registered[e]=Object.assign({},t),this}static all(){return Object.assign({},this.registered)}}h.registered={};class f{constructor(e=i){this.baseURL=e,this.defaultHeaders={"Content-Type":"application/json"},this.method=f.method,this.storage=f.storage,this.interceptors={request:[],response:[],transform:[],error:[]}}static on(...e){const[t,r]=e,s=f.interceptors[t];s.includes(r)||s.push(r),f.interceptors[t]=s}static off(...e){const[t,r]=e,s=f.interceptors[t];f.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]&&o.Primitive.isPrimitive(e[1])):"object"==typeof e&&null!==e&&Object.values(e).every(e=>o.Primitive.isPrimitive(e)))}getQuery(e){const{method:t,body:r,query:s}=e,n=t===l.GET&&this.isValidQuery(r)?r:s;return n&&"object"==typeof n?n instanceof URLSearchParams?n.toString():o.queryString.stringify(n,{skipNull:!0,skipEmptyString:!0}):"string"==typeof n?n:""}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=c||f.authTokenKey,t=u||f.authHeaderKey,r=d||f.authHeaderType;if(!e||!t)return{key:t,value:""};let s="";this.storage&&(s=this.storage.getItem(e)||"");const n={key:t,value:""};return s&&(n.value=s,r&&(n.value=`${r} ${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),f.extraHeaders||{});return f.extraHeaders=null,s}getURL(e){var t;const{url:r,params:s={}}=e,n=this.getQuery(e);let a=r;if(r)if(r.match(/^https?:\/\//))a=r;else{a=`${null===(t=this.baseURL)||void 0===t?void 0:t.replace(/\/+$/,"")}/${r.replace(/^\/+/,"")}`}if(n){const e=a.includes("?")?"&":"?";a+=`${e}${n}`}return o.interpolate(a,s)}getBody(e){const{method:t,body:s}=e;if(t!==l.GET&&t!==l.HEAD&&t!==l.OPTIONS&&t!==l.DELETE)return t!==l.POST&&t!==l.PUT&&t!==l.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=l.GET}=e;try{let s=Object.assign({},e);const n=[...f.interceptors.request,...this.interceptors.request];for(const e of n)s=await e(s);const o=this.getURL(s),a=this.getHeaders(s.headers||{});r(s.body)&&"Content-Type"in a&&delete a["Content-Type"];const i=await fetch(o,{method:s.method||t,headers:a,body:this.getBody(s),signal:s.signal}),c=i.headers.get("Content-Type")||"";let u=null;u=c.includes("application/json")?await i.json():await i.text();const d=[...f.interceptors.transform,...this.interceptors.transform];let l=u;for(const e of d)l=await e(l);const p=[...f.interceptors.response,...this.interceptors.response];let h=i;for(const e of p)h=await e(h);const y={};h.headers.forEach((e,t)=>{y[t]=e});const g=h.ok;let T=null;if(!g){T=u.error||u;const e=[...f.interceptors.error,...this.interceptors.error];for(const t of e)T=await t(T)}return{data:l,success:g,error:g?null:T,status:h.status,statusText:h.statusText,headers:y}}catch(e){let t=e instanceof Error?e:new Error(String(e));const r=[...f.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:l.GET,url:e,query:t}))}post(e,t,r){return this.request(Object.assign(Object.assign({},r),{method:l.POST,url:e,body:t}))}put(e,t,r){return this.request(Object.assign(Object.assign({},r),{method:l.PUT,url:e,body:t}))}patch(e,t,r){return this.request(Object.assign(Object.assign({},r),{method:l.PATCH,url:e,body:t}))}delete(e,t){return this.request(Object.assign(Object.assign({},t),{method:l.DELETE,url:e}))}head(e,t){return this.request(Object.assign(Object.assign({},t),{method:l.HEAD,url:e}))}options(e,t){return this.request(Object.assign(Object.assign({},t),{method:l.OPTIONS,url:e}))}upload(r,n,o){const a=(null==o?void 0:o.body)?s(o.body):new FormData;let i=(null==o?void 0:o.name)||"file";if(Array.isArray(n)?(i.endsWith("[]")&&(i=i.slice(0,-2)),n.forEach((e,t)=>{a.append(`${i}[${t}]`,e,e.name)})):e(n)?(i.endsWith("[]")&&(i=i.slice(0,-2)),Array.from(n).forEach((e,t)=>{a.append(`${i}[${t}]`,e,e.name)})):a.append(i,n,n.name),null==o?void 0:o.body){const e=t(o.body);Object.entries(e).forEach(([e,t])=>{null!=t&&a.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:l.POST,url:r,body:a});const s=[...f.interceptors.request,...this.interceptors.request];for(const e of s)t=await e(t);const n=this.getURL(t),i=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=[...f.interceptors.transform,...this.interceptors.transform];let n=r;for(const e of s)n=await e(n);const o=[...f.interceptors.response,...this.interceptors.response];let a=new Response(c.responseText,{status:c.status,statusText:c.statusText,headers:i});for(const e of o)a=await e(a);const u={};a.headers.forEach((e,t)=>{u[t]=e});const d=a.ok;e({data:n,success:d,error:d?null:n,status:a.status,statusText:a.statusText,headers:u})}catch(t){const r=[...f.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=[...f.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||l.POST,n,!0),Object.entries(i).forEach(([e,t])=>{"content-type"!==(null==e?void 0:e.toLowerCase())&&t&&c.setRequestHeader(e,t)}),c.send(t.body)}catch(t){const r=[...f.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:l.POST,url:r,body:a,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=n(r.contentType),o=n(r.metadataMimeType||"application/json"),a=`----related-boundary-${Date.now()}-${Math.random().toString(36).slice(2)}`,i=JSON.stringify(r.metadata),c=new TextEncoder,u=c.encode(`--${a}\r\nContent-Type: ${o}; charset=UTF-8\r\n\r\n`+i+"\r\n"),d=c.encode(`--${a}\r\nContent-Type: ${s}\r\nContent-Transfer-Encoding: binary\r\n\r\n`),p=c.encode(`\r\n--${a}--`),h=t instanceof Uint8Array?t:new Uint8Array(t),f=new Uint8Array(u.length+d.length+h.length+p.length);return[u,d,h,p].reduce((e,t)=>(f.set(t,e),e+t.length),0),this.request({method:l.POST,url:e,body:f,headers:Object.assign(Object.assign({},r.headers||{}),{"Content-Type":`multipart/related; boundary=${a}`}),params:r.params,signal:r.signal,query:r.query})}static createFactory(e={}){const r=e.http||new f(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 l.POST:return await r.post(o,...t);case l.PUT:return await r.put(o,...t);case l.PATCH:return await r.patch(o,...t);case l.DELETE:return await r.delete(o,...t);case l.HEAD:return await r.head(o,...t);case l.OPTIONS:return await r.options(o,...t);case p.UPLOAD:return await r.upload(o,...t);case p.RELATED:return await r.related(o,...t);default:return await r.get(o,...t)}}}}}}f.method=l,f.Endpoint=h,f.authTokenKey="access_token",f.authHeaderKey="Authorization",f.authHeaderType="Bearer",f.authDetectToken=["localStorage","sessionStorage","cookie"],f.extraHeaders=null,f.storage=null,f.interceptors={request:[],response:[],transform:[],error:[]};export{u as API_AUTH_HEADER_KEY,d as API_AUTH_HEADER_TYPE,c as API_AUTH_TOKEN_KEY,i as DEFAULT_BASE_URL,h as Endpoint,f as Http,l as HttpMethod,p 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.0",
|
|
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};
|