@defjs/core 0.1.0 → 0.2.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/index.d.ts CHANGED
@@ -119,10 +119,6 @@ export interface HttpRequest {
119
119
  /** when use fetch handler, no upload progress */
120
120
  uploadProgress?: HttpProgressFn;
121
121
  downloadProgress?: HttpProgressFn;
122
- /**
123
- * default:body
124
- */
125
- observe?: "body" | "response";
126
122
  abort?: AbortSignal;
127
123
  }
128
124
  export type RequestInputValue<T> = T extends Field<infer V> ? V : T extends {
@@ -130,15 +126,15 @@ export type RequestInputValue<T> = T extends Field<infer V> ? V : T extends {
130
126
  } ? {
131
127
  [K in keyof T]: RequestInputValue<T[K]>;
132
128
  } : never;
133
- export type DoRequestOptions = {
129
+ export type UseRequestOptions = {
134
130
  abort?: AbortSignal;
135
131
  handler?: HttpHandler;
136
132
  client?: Client;
137
133
  timeout?: number;
138
134
  };
139
- export type ObserveType<Observe, Output> = Observe extends "body" ? Output : Observe extends "response" ? HttpResponse<Output> : never;
140
- export type UseRequestFn<Input, Output, Observe> = {
141
- doRequest: Input extends undefined ? (options?: DoRequestOptions) => Promise<ObserveType<Observe, Output>> : RequestInputValue<Input> extends RequestInputValue<Input> | undefined ? (input?: RequestInputValue<Input>, options?: DoRequestOptions) => Promise<ObserveType<Observe, Output>> : (input: RequestInputValue<Input>, options?: DoRequestOptions) => Promise<ObserveType<Observe, Output>>;
135
+ export type UseRequestFn<Input, Output> = {
136
+ doRequest: undefined extends RequestInputValue<Input> ? (input?: RequestInputValue<Input>) => Promise<HttpResponse<Output>> : (input: RequestInputValue<Input>) => Promise<HttpResponse<Output>>;
137
+ cancel: () => void;
142
138
  getInitValue: () => Input extends Field<infer V> ? V : Input extends {
143
139
  [K in keyof Input]: Field<any>;
144
140
  } ? {
@@ -147,20 +143,18 @@ export type UseRequestFn<Input, Output, Observe> = {
147
143
  setUploadProgress: (fn: HttpProgressFn) => void;
148
144
  setDownloadProgress: (fn: HttpProgressFn) => void;
149
145
  };
150
- export interface DefineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined, Output = unknown, Observe extends "body" | "response" = "body"> {
151
- (): UseRequestFn<Input, Output, Observe>;
152
- withField<I extends Field<any> | Record<PropertyKey, Field<any>>>(value: I): DefineRequest<I, Output, Observe>;
153
- withInterceptors(value: InterceptorFn[]): DefineRequest<Input, Output, Observe>;
154
- withContext(value: HttpContext): DefineRequest<Input, Output, Observe>;
155
- withCredentials(value: boolean): DefineRequest<Input, Output, Observe>;
156
- withValidators(value: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[]): DefineRequest<Input, Output, Observe>;
157
- withTransformResponse<O>(fn: TransformResponseFn<O>): DefineRequest<Input, O, Observe>;
158
- withObserve(value: "body"): DefineRequest<Input, Output, "body">;
159
- withObserve(value: "response"): DefineRequest<Input, Output, "response">;
160
- withResponseType(value: "json"): DefineRequest<Input, Output, Observe>;
161
- withResponseType(value: "text"): DefineRequest<Input, string, Observe>;
162
- withResponseType(value: "blob"): DefineRequest<Input, Blob, Observe>;
163
- withResponseType(value: "arraybuffer"): DefineRequest<Input, ArrayBuffer, Observe>;
146
+ export interface DefineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined, Output = unknown> {
147
+ (options?: UseRequestOptions): UseRequestFn<Input, Output>;
148
+ withField<I extends Field<any> | Record<PropertyKey, Field<any>>>(value: I): DefineRequest<I, Output>;
149
+ withInterceptors(value: InterceptorFn[]): DefineRequest<Input, Output>;
150
+ withContext(value: HttpContext): DefineRequest<Input, Output>;
151
+ withCredentials(value: boolean): DefineRequest<Input, Output>;
152
+ withValidators(value: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[]): DefineRequest<Input, Output>;
153
+ withTransformResponse<O>(fn: TransformResponseFn<O>): DefineRequest<Input, O>;
154
+ withResponseType(value: "json"): DefineRequest<Input, Output>;
155
+ withResponseType(value: "text"): DefineRequest<Input, string>;
156
+ withResponseType(value: "blob"): DefineRequest<Input, Blob>;
157
+ withResponseType(value: "arraybuffer"): DefineRequest<Input, ArrayBuffer>;
164
158
  }
165
159
  export declare function defineRequest<Output>(endpoint: string): DefineRequest<undefined, Output>;
166
160
  export declare function defineRequest<Output>(method: string, endpoint: string): DefineRequest<undefined, Output>;
@@ -168,17 +162,14 @@ export type HttpHandler = (req: HttpRequest) => Promise<HttpResponse<unknown>>;
168
162
  export declare function fetchHandler(httpRequest: HttpRequest): Promise<HttpResponse<unknown>>;
169
163
  export interface ClientOptions {
170
164
  host: string;
171
- /** Default: true */
172
- strict?: boolean;
173
165
  interceptors?: InterceptorFn[];
174
166
  handler?: HttpHandler;
175
167
  }
176
- export interface ClientConfig {
168
+ export type ClientConfig = {
177
169
  host: string;
178
- strict: boolean;
179
170
  handler: HttpHandler;
180
- interceptors?: InterceptorFn[];
181
- }
171
+ interceptors: InterceptorFn[];
172
+ };
182
173
  declare const CLIENT: unique symbol;
183
174
  export type Client = {
184
175
  readonly [CLIENT]: ClientConfig;
package/index.js CHANGED
@@ -307,7 +307,6 @@ function defineRequest(...args) {
307
307
  let interceptors = [];
308
308
  let responseType = "json";
309
309
  let context2;
310
- let observe = "body";
311
310
  let withCredentials = false;
312
311
  let validators = [];
313
312
  let transformResponse;
@@ -325,10 +324,30 @@ function defineRequest(...args) {
325
324
  default:
326
325
  throw new Error("Invalid arguments");
327
326
  }
328
- const fn = () => {
327
+ const fn = (options) => {
328
+ const timeout = options?.timeout || 0;
329
+ const client2 = options?.client || getGlobalClient();
330
+ const clientOptions = getClientConfig(client2);
331
+ const handler2 = options?.handler || clientOptions?.handler || getGlobalHttpHandler();
332
+ if (!handler2) {
333
+ throw ERR_NOT_FOUND_HANDLER;
334
+ }
329
335
  let uploadProgress;
330
336
  let downloadProgress;
331
- let abortSignal;
337
+ let abortController;
338
+ const abortSignal = [];
339
+ if (options?.abort) {
340
+ abortSignal.push(options.abort);
341
+ } else {
342
+ abortController = new AbortController;
343
+ abortSignal.push(abortController.signal);
344
+ }
345
+ if (timeout > 0) {
346
+ abortSignal.push(AbortSignal.timeout(timeout));
347
+ }
348
+ const cancel = () => {
349
+ abortController?.abort();
350
+ };
332
351
  const getInitValue = () => __buildFieldDefaultValue(field3);
333
352
  const setUploadProgress = (fn2) => {
334
353
  uploadProgress = fn2;
@@ -338,38 +357,17 @@ function defineRequest(...args) {
338
357
  };
339
358
  const doRequest = async (...args2) => {
340
359
  let input;
341
- let doRequestOptions;
342
- switch (args2.length) {
343
- case 1: {
344
- if (requiredInput) {
345
- input = args2[0];
346
- } else {
347
- doRequestOptions = args2[0];
348
- }
349
- break;
350
- }
351
- case 2: {
352
- input = args2[0];
353
- doRequestOptions = args2[1];
354
- break;
355
- }
360
+ if (requiredInput && args2.length === 1) {
361
+ input = args2[0];
356
362
  }
357
363
  if (requiredInput && !input) {
358
- throw new Error(`Because the request has input, the first argument must be the input value`);
364
+ throw new Error(`Because the request has input, the argument must be the input value`);
359
365
  }
360
366
  if (validators.length > 0) {
361
367
  for (const fn2 of validators) {
362
368
  fn2(input);
363
369
  }
364
370
  }
365
- const timeout = doRequestOptions?.timeout || 0;
366
- if (doRequestOptions?.abort) {
367
- abortSignal = doRequestOptions.abort;
368
- } else if (timeout > 0) {
369
- abortSignal = AbortSignal.timeout(timeout);
370
- }
371
- const client2 = isClient(doRequestOptions?.client) ? doRequestOptions.client : getGlobalClient();
372
- const clientOptions = getClientConfig(client2);
373
371
  const req = {
374
372
  host: clientOptions?.host,
375
373
  method,
@@ -380,20 +378,15 @@ function defineRequest(...args) {
380
378
  withCredentials,
381
379
  responseType,
382
380
  context: context2 || makeHttpContext(),
383
- observe,
384
381
  uploadProgress,
385
382
  downloadProgress,
386
383
  timeout,
387
- abort: abortSignal
384
+ abort: AbortSignal.any(abortSignal)
388
385
  };
389
- const handler2 = doRequestOptions?.handler || clientOptions?.handler || getGlobalHttpHandler();
390
- if (!handler2) {
391
- throw ERR_NOT_FOUND_HANDLER;
392
- }
393
386
  if (requiredInput && field3) {
394
387
  await __fillRequestFromField(req, field3, input);
395
388
  }
396
- const chain = makeInterceptorChain([...interceptors]);
389
+ const chain = makeInterceptorChain([...clientOptions.interceptors, ...interceptors]);
397
390
  let res = await chain(req, handler2);
398
391
  if (typeof transformResponse === "function") {
399
392
  try {
@@ -405,17 +398,11 @@ function defineRequest(...args) {
405
398
  throw new HttpErrorResponse({ error: error3 });
406
399
  }
407
400
  }
408
- switch (req.observe) {
409
- case "body":
410
- return res.body;
411
- case "response":
412
- return res;
413
- default:
414
- throw ERR_OBSERVE;
415
- }
401
+ return res;
416
402
  };
417
403
  return {
418
404
  doRequest,
405
+ cancel,
419
406
  getInitValue,
420
407
  setUploadProgress,
421
408
  setDownloadProgress
@@ -446,10 +433,6 @@ function defineRequest(...args) {
446
433
  transformResponse = value;
447
434
  return fn;
448
435
  };
449
- fn.withObserve = (value) => {
450
- observe = value;
451
- return fn;
452
- };
453
436
  fn.withResponseType = (value) => {
454
437
  responseType = value;
455
438
  return fn;
@@ -752,7 +735,6 @@ function getClientConfig(client2) {
752
735
  function createClient(options) {
753
736
  const conf = {
754
737
  host: options.host,
755
- strict: options.strict ?? true,
756
738
  interceptors: options.interceptors ?? [],
757
739
  handler: options.handler || fetchHandler
758
740
  };
package/index.min.js CHANGED
@@ -1 +1 @@
1
- var X=new Error("ERR_ABORTED"),W=new Error("ERR_TIMEOUT"),wt=new Error("ERR_NETWORK"),J=new Error("ERR_NOT_FOUND_HANDLER"),j=new Error("ERR_OBSERVE"),h=new Error("ERR_NOT_SET_ALIAS"),Q=new Error("ERR_UNSUPPORTED_FIELD_TYPE"),Y=new Error("ERR_INVALID_CLIENT"),Z=new Error("ERR_NOT_FOUND_GLOBAL_CLIENT"),B=new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN"),it=new Error("ERR_UNKNOWN");class m extends Error{status;statusText;url;headers;body;constructor(t){const n=t?.status??0,r=t?.statusText??"",o=n>=200&&n<300,T=t?.headers??new Headers,H=t?.url??"",f=t?.body??null;let R;if(o)R=`Http failure during parsing for ${H}`;else if(R=`Http failure response for ${H||"(unknown url)"}: ${n}`,r)R+=` - ${r}`;super(R,{cause:t?.error});super.name="HttpErrorResponse",this.statusText=r,this.url=H,this.headers=T,this.status=n,this.body=f}}function tt(t){const n=t.get("Content-Length");if(!n)return 0;const r=Number(n);if(isNaN(r))return 0;return r}function nt(t){return t.get("Content-Type")||""}function rt(t){const{request:n,content:r,contentType:o}=t;switch(n.responseType){case"json":{const H=new TextDecoder().decode(r);if(H==="")return null;return JSON.parse(H)}case"text":return new TextDecoder().decode(r);case"blob":return new Blob([r],{type:o});case"arraybuffer":return r.buffer;default:return null}}function ot(t,n){const r=new Uint8Array(n);let o=0;for(let T of t)r.set(T,o),o+=T.length;return r}function ft(t){return Object.defineProperty(t,et,{value:t}),t}function D(t){return typeof t==="function"&&et in t}function Rt(t){return typeof t==="object"&&t!==null&&u in t}function G(t){const n=new Map;switch(!0){case Array.isArray(t):{for(let[r,o]of t)if(D(r))n.set(r,o);break}case Rt(t):{for(let[r,o]of t[u])n.set(r,o);break}}return{set(r,o){if(!D(r))throw B;return n.set(r,o),this},get(r){if(!D(r))throw B;if(!n.has(r))n.set(r,r());return n.get(r)},del(r){return n.delete(r),this},has(r){return n.has(r)},keys(){return n.keys()},get length(){return Array.from(n.keys()).length},[u]:n}}var et=Symbol("HttpContextToken"),u=Symbol("HttpContext");function kt(t){const n={required:typeof t!=="undefined",alias:new Map,validators:[],asyncValidator:[]},r=()=>t;return Object.defineProperty(r,z,{value:n}),r.withJson=(o)=>{return n.alias.set(0,o),r},r.withForm=(o)=>{return n.alias.set(4,o),r},r.withQuery=(o)=>{return n.alias.set(1,o),r},r.withParam=(o)=>{return n.alias.set(2,o),r},r.withHeader=(o)=>{return n.alias.set(3,o),r},r.withUrlForm=(o)=>{return n.alias.set(6,o),r},r.withBody=()=>{return n.alias.set(5,void 0),r},r.withValidators=(...o)=>{return n.validators=o,r},r.withAsyncValidators=(...o)=>{return n.asyncValidator=o,r},r}function a(t){return t[z]}async function L(t,n){await Promise.all(t.map((r)=>r(n)))}function F(t){return!!t&&typeof t==="function"&&z in t}function P(t){return!!t&&typeof t==="object"&&Object.entries(t).every(([,n])=>F(n))}var z=Symbol("field");var Ct=void 0;var xt=()=>Ct;function Tt(t){return t.reduceRight((n,r)=>{return(o,T)=>r(o,(H)=>n(H,T))},(n,r)=>r(n))}function y(t){const n=t?.status??0,r=t?.statusText??"",o=t?.url??"",T=t?.headers??new Headers,H=t?.body??null;return{status:n,statusText:r,url:o,headers:T,body:H}}function Ht(t){switch(!0){case t instanceof FormData:case t instanceof Blob:case t instanceof ArrayBuffer:case t instanceof URLSearchParams:case typeof t==="string":return t;case typeof t==="object":case typeof t==="boolean":case typeof t==="number":case Array.isArray(t):return JSON.stringify(t);default:return null}}function pt(t){switch(!0){case t instanceof FormData:return"multipart/form-data";case t instanceof ArrayBuffer:return"application/octet-stream";case t instanceof Blob:return t.type||"application/octet-stream";case t instanceof URLSearchParams:return"application/x-www-form-urlencoded;charset=UTF-8";case typeof t==="string":return"text/plain";case(typeof t==="object"&&t!==null):case typeof t==="number":case typeof t==="boolean":return"application/json";default:return null}}function mt(t){if(F(t))return t();if(P(t)){const n={};for(let[r,o]of Object.entries(t))n[r]=o();return n}return}function Nt(...t){let n,r,o=!1,T,H=[],f="json",R,e="body",E=!1,s=[],w;switch(t.length){case 1:{n="GET",r=t[0];break}case 2:{n=t[0],r=t[1];break}default:throw new Error("Invalid arguments")}const x=()=>{let c,N,p;return{doRequest:async(...C)=>{let k,i;switch(C.length){case 1:{if(o)k=C[0];else i=C[0];break}case 2:{k=C[0],i=C[1];break}}if(o&&!k)throw new Error("Because the request has input, the first argument must be the input value");if(s.length>0)for(let K of s)K(k);const $=i?.timeout||0;if(i?.abort)p=i.abort;else if($>0)p=AbortSignal.timeout($);const st=V(i?.client)?i.client:b(),l=S(st),g={host:l?.host,method:n,endpoint:r,queryParams:new URLSearchParams,headers:new Headers,body:void 0,withCredentials:E,responseType:f,context:R||G(),observe:e,uploadProgress:c,downloadProgress:N,timeout:$,abort:p},v=i?.handler||l?.handler||xt();if(!v)throw J;if(o&&T)await _t(g,T,k);let I=await Tt([...H])(g,v);if(typeof w==="function")try{I=y({...I,body:w(I)})}catch(K){throw new m({error:K})}switch(g.observe){case"body":return I.body;case"response":return I;default:throw j}},getInitValue:()=>mt(T),setUploadProgress:(C)=>{c=C},setDownloadProgress:(C)=>{N=C}}};return x.withField=(c)=>{return T=c,o=!0,x},x.withInterceptors=(c)=>{return H=c,x},x.withContext=(c)=>{return R=c,x},x.withCredentials=(c)=>{return E=c,x},x.withValidators=(c)=>{return s=c,x},x.withTransformResponse=(c)=>{return w=c,x},x.withObserve=(c)=>{return e=c,x},x.withResponseType=(c)=>{return f=c,x},x}function ct(t,n){return t.replace(/:([^\/]+)/g,(r,o)=>{return n.get(o)??"undefined"})}async function _t(t,n,r){function o(e){return typeof e==="object"&&e!==null}function T(e){switch(!0){case Array.isArray(e):case(typeof e==="object"&&e!==null):return JSON.stringify(e);case(typeof e==="object"&&e===null):case typeof e==="boolean":case typeof e==="number":case typeof e==="string":return String(e);default:throw new Error("Unsupported value type")}}function H(e,E,s){if(Array.isArray(s))for(let w of s)e.append(E,T(w));else e.set(E,T(s));return e}function f(e,E,s){if(Array.isArray(s))for(let w of s)f(e,E,T(w));return e.set(E,T(s)),e}function R(e,E){switch(!0){case typeof e==="undefined":return E;case(typeof e==="object"&&e===null):return e;default:return e}}if(F(n)){let e,E,s,w=void 0;const x=R(r,n()),c=a(n);await L([...c.validators,...c.asyncValidator],x);for(let[N,p]of c.alias)switch(N){case 1:{if(!p)throw h;E=H(new URLSearchParams,p,x);break}case 2:{if(!p)throw h;e=f(new Map,p,x);break}case 3:{if(!p)throw h;s=H(new Headers,p,x);break}case 4:{if(!p)throw h;w=H(new FormData,p,x);break}case 6:{if(!p)throw h;w=H(new URLSearchParams,p,x);break}case 0:case 5:w=x;break}if(e)t.endpoint=ct(t.endpoint,e);t.queryParams=E,t.headers=s,t.body=w;return}if(P(n)&&o(r)){let e=new Map,E=new URLSearchParams,s=new Headers,w=new URLSearchParams,x=new FormData;const c={};let N=void 0,p;for(let[O,_]of Object.entries(n)){const A=a(_);for(let[q,C]of A.alias){const k=C||O,i=R(r[O],_());switch(await L([...A.validators,...A.asyncValidator],i),q){case 0:{Object.defineProperty(c,k,{value:i,writable:!0,enumerable:!0}),p=0;break}case 1:E=H(E,k,i);break;case 2:e=f(e,k,i);break;case 3:s=H(s,k,i);break;case 4:{x=H(x,k,i),p=4;break}case 6:{w=H(w,k,i),p=6;break}case 5:{N=i,p=5;break}}}}switch(t.endpoint=ct(t.endpoint,e),t.queryParams=E,t.headers=s,p){case 5:t.body=N;break;case 4:t.body=x;break;case 6:t.body=w;break;case 0:t.body=c;break}return}throw Q}function At(t){const n=new URL(t.endpoint,t.host);if(t.queryParams)n.search=t.queryParams.toString();const r=t.headers??new Headers;if(!r.has("Content-Type")){const T=pt(t.body);if(T)r.set("Content-Type",T)}if(!r.has("Accept"))r.set("Accept","application/json, text/plain, */*");const o=t.withCredentials?"include":void 0;return new Request(n,{headers:r,method:t.method,body:Ht(t.body),signal:t.abort,credentials:o})}async function d(t){const n=t.downloadProgress,r=At(t),o=t.abort;let T;try{T=await globalThis.fetch(r)}catch(c){if(o?.aborted&&o.reason instanceof Error)switch(!0){case o.reason.name==="AbortError":throw new m({error:X});case o.reason.name==="TimeoutError":throw new m({error:W})}throw new m({error:c})}const{ok:H,headers:f,status:R,statusText:e,url:E}=T,s=tt(f),w=nt(f);let x=null;if(T.body){const c=[],N=T.body.getReader();let p=0;while(!0){const{done:_,value:A}=await N.read();if(_)break;c.push(A),p+=A.length,n?.({lengthComputable:s>0,loaded:p,total:s})}const O=ot(c,p);try{x=rt({request:t,content:O,contentType:w})}catch(_){throw new m({error:_,status:R,statusText:e,headers:f,url:E})}}if(!H)throw new m({status:R,statusText:e,headers:f,url:E,body:x});return y({url:E,status:R,statusText:e,headers:f,body:x})}function V(t){return typeof t==="object"&&t!==null&&M in t}function S(t){if(!V(t))throw Y;return t[M]}function Et(t){const n={host:t.host,strict:t.strict??!0,interceptors:t.interceptors??[],handler:t.handler||d};return{[M]:n}}function ht(t,n){const o={...S(t),...n};return{[M]:o}}function b(){if(!U)throw Z;return U}function Ot(t){U=t}function It(){U=void 0}function Ft(t){U=Et(t)}var M=Symbol("Client"),U;function Ut(t,n){let r=n?.encode;if(!r){const o=globalThis.btoa;if(typeof o!=="function")throw new Error("BasicAuthInterceptor is not supported in this environment");r=(T)=>o(`${T.username}:${T.password}`)}return(o,T)=>{const H=o.headers||new Headers;return H.set("Authorization",`Basic ${r(t())}`),o.headers=H,T(o)}}var Bt=(t)=>{if(!t)return new Error("required");return null},Dt=(t)=>{if(typeof t!=="boolean"||!t)return new Error("requiredTrue");return null},Lt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length<t)return new Error(`minLength ${t}`);return null}},Pt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length>t)return new Error(`maxLength ${t}`);return null}},yt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n<t)return new Error(`minLength ${t}`);return null}},Vt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n>t)return new Error(`maxLength ${t}`);return null}},Mt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(!t.test(n))return new Error("pattern");return null}};export{Ot as setGlobalClient,It as restGlobalClient,Dt as requiredTrue,Bt as required,Mt as pattern,Lt as minLength,yt as min,Pt as maxLength,Vt as max,ft as makeHttpContextToken,G as makeHttpContext,D as isHttpContextToken,P as isFieldGroup,F as isField,V as isClient,b as getGlobalClient,kt as field,d as fetchHandler,L as doValid,Nt as defineRequest,Ft as createGlobalClient,Et as createClient,ht as cloneClient,Ut as basicAuthInterceptor,m as HttpErrorResponse,Q as ERR_UNSUPPORTED_FIELD_TYPE,it as ERR_UNKNOWN,W as ERR_TIMEOUT,j as ERR_OBSERVE,h as ERR_NOT_SET_ALIAS,J as ERR_NOT_FOUND_HANDLER,Z as ERR_NOT_FOUND_GLOBAL_CLIENT,wt as ERR_NETWORK,B as ERR_INVALID_HTTP_CONTEXT_TOKEN,Y as ERR_INVALID_CLIENT,X as ERR_ABORTED};
1
+ var K=new Error("ERR_ABORTED"),X=new Error("ERR_TIMEOUT"),Ht=new Error("ERR_NETWORK"),W=new Error("ERR_NOT_FOUND_HANDLER"),pt=new Error("ERR_OBSERVE"),A=new Error("ERR_NOT_SET_ALIAS"),J=new Error("ERR_UNSUPPORTED_FIELD_TYPE"),j=new Error("ERR_INVALID_CLIENT"),Q=new Error("ERR_NOT_FOUND_GLOBAL_CLIENT"),y=new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN"),Et=new Error("ERR_UNKNOWN");class f extends Error{status;statusText;url;headers;body;constructor(t){const n=t?.status??0,r=t?.statusText??"",o=n>=200&&n<300,T=t?.headers??new Headers,s=t?.url??"",i=t?.body??null;let R;if(o)R=`Http failure during parsing for ${s}`;else if(R=`Http failure response for ${s||"(unknown url)"}: ${n}`,r)R+=` - ${r}`;super(R,{cause:t?.error});super.name="HttpErrorResponse",this.statusText=r,this.url=s,this.headers=T,this.status=n,this.body=i}}function q(t){const n=t.get("Content-Length");if(!n)return 0;const r=Number(n);if(isNaN(r))return 0;return r}function l(t){return t.get("Content-Type")||""}function v(t){const{request:n,content:r,contentType:o}=t;switch(n.responseType){case"json":{const s=new TextDecoder().decode(r);if(s==="")return null;return JSON.parse(s)}case"text":return new TextDecoder().decode(r);case"blob":return new Blob([r],{type:o});case"arraybuffer":return r.buffer;default:return null}}function tt(t,n){const r=new Uint8Array(n);let o=0;for(let T of t)r.set(T,o),o+=T.length;return r}function wt(t){return Object.defineProperty(t,nt,{value:t}),t}function P(t){return typeof t==="function"&&nt in t}function it(t){return typeof t==="object"&&t!==null&&Y in t}function Z(t){const n=new Map;switch(!0){case Array.isArray(t):{for(let[r,o]of t)if(P(r))n.set(r,o);break}case it(t):{for(let[r,o]of t[Y])n.set(r,o);break}}return{set(r,o){if(!P(r))throw y;return n.set(r,o),this},get(r){if(!P(r))throw y;if(!n.has(r))n.set(r,r());return n.get(r)},del(r){return n.delete(r),this},has(r){return n.has(r)},keys(){return n.keys()},get length(){return Array.from(n.keys()).length},[Y]:n}}var nt=Symbol("HttpContextToken"),Y=Symbol("HttpContext");function Rt(t){const n={required:typeof t!=="undefined",alias:new Map,validators:[],asyncValidator:[]},r=()=>t;return Object.defineProperty(r,a,{value:n}),r.withJson=(o)=>{return n.alias.set(0,o),r},r.withForm=(o)=>{return n.alias.set(4,o),r},r.withQuery=(o)=>{return n.alias.set(1,o),r},r.withParam=(o)=>{return n.alias.set(2,o),r},r.withHeader=(o)=>{return n.alias.set(3,o),r},r.withUrlForm=(o)=>{return n.alias.set(6,o),r},r.withBody=()=>{return n.alias.set(5,void 0),r},r.withValidators=(...o)=>{return n.validators=o,r},r.withAsyncValidators=(...o)=>{return n.asyncValidator=o,r},r}function G(t){return t[a]}async function g(t,n){await Promise.all(t.map((r)=>r(n)))}function U(t){return!!t&&typeof t==="function"&&a in t}function V(t){return!!t&&typeof t==="object"&&Object.entries(t).every(([,n])=>U(n))}var a=Symbol("field");var ft=void 0;var rt=()=>ft;function ot(t){return t.reduceRight((n,r)=>{return(o,T)=>r(o,(s)=>n(s,T))},(n,r)=>r(n))}function M(t){const n=t?.status??0,r=t?.statusText??"",o=t?.url??"",T=t?.headers??new Headers,s=t?.body??null;return{status:n,statusText:r,url:o,headers:T,body:s}}function xt(t){switch(!0){case t instanceof FormData:case t instanceof Blob:case t instanceof ArrayBuffer:case t instanceof URLSearchParams:case typeof t==="string":return t;case typeof t==="object":case typeof t==="boolean":case typeof t==="number":case Array.isArray(t):return JSON.stringify(t);default:return null}}function Tt(t){switch(!0){case t instanceof FormData:return"multipart/form-data";case t instanceof ArrayBuffer:return"application/octet-stream";case t instanceof Blob:return t.type||"application/octet-stream";case t instanceof URLSearchParams:return"application/x-www-form-urlencoded;charset=UTF-8";case typeof t==="string":return"text/plain";case(typeof t==="object"&&t!==null):case typeof t==="number":case typeof t==="boolean":return"application/json";default:return null}}function kt(t){if(U(t))return t();if(V(t)){const n={};for(let[r,o]of Object.entries(t))n[r]=o();return n}return}function mt(...t){let n,r,o=!1,T,s=[],i="json",R,e=!1,p=[],E;switch(t.length){case 1:{n="GET",r=t[0];break}case 2:{n=t[0],r=t[1];break}default:throw new Error("Invalid arguments")}const c=(x)=>{const w=x?.timeout||0,N=x?.client||z(),H=d(N),_=x?.handler||H?.handler||rt();if(!_)throw W;let k,m,F;const h=[];if(x?.abort)h.push(x.abort);else F=new AbortController,h.push(F.signal);if(w>0)h.push(AbortSignal.timeout(w));return{doRequest:async(...I)=>{let D;if(o&&I.length===1)D=I[0];if(o&&!D)throw new Error("Because the request has input, the argument must be the input value");if(p.length>0)for(let u of p)u(D);const b={host:H?.host,method:n,endpoint:r,queryParams:new URLSearchParams,headers:new Headers,body:void 0,withCredentials:e,responseType:i,context:R||Z(),uploadProgress:k,downloadProgress:m,timeout:w,abort:AbortSignal.any(h)};if(o&&T)await Ct(b,T,D);let L=await ot([...H.interceptors,...s])(b,_);if(typeof E==="function")try{L=M({...L,body:E(L)})}catch(u){throw new f({error:u})}return L},cancel:()=>{F?.abort()},getInitValue:()=>kt(T),setUploadProgress:(I)=>{k=I},setDownloadProgress:(I)=>{m=I}}};return c.withField=(x)=>{return T=x,o=!0,c},c.withInterceptors=(x)=>{return s=x,c},c.withContext=(x)=>{return R=x,c},c.withCredentials=(x)=>{return e=x,c},c.withValidators=(x)=>{return p=x,c},c.withTransformResponse=(x)=>{return E=x,c},c.withResponseType=(x)=>{return i=x,c},c}function et(t,n){return t.replace(/:([^\/]+)/g,(r,o)=>{return n.get(o)??"undefined"})}async function Ct(t,n,r){function o(e){return typeof e==="object"&&e!==null}function T(e){switch(!0){case Array.isArray(e):case(typeof e==="object"&&e!==null):return JSON.stringify(e);case(typeof e==="object"&&e===null):case typeof e==="boolean":case typeof e==="number":case typeof e==="string":return String(e);default:throw new Error("Unsupported value type")}}function s(e,p,E){if(Array.isArray(E))for(let c of E)e.append(p,T(c));else e.set(p,T(E));return e}function i(e,p,E){if(Array.isArray(E))for(let c of E)i(e,p,T(c));return e.set(p,T(E)),e}function R(e,p){switch(!0){case typeof e==="undefined":return p;case(typeof e==="object"&&e===null):return e;default:return e}}if(U(n)){let e,p,E,c=void 0;const x=R(r,n()),w=G(n);await g([...w.validators,...w.asyncValidator],x);for(let[N,H]of w.alias)switch(N){case 1:{if(!H)throw A;p=s(new URLSearchParams,H,x);break}case 2:{if(!H)throw A;e=i(new Map,H,x);break}case 3:{if(!H)throw A;E=s(new Headers,H,x);break}case 4:{if(!H)throw A;c=s(new FormData,H,x);break}case 6:{if(!H)throw A;c=s(new URLSearchParams,H,x);break}case 0:case 5:c=x;break}if(e)t.endpoint=et(t.endpoint,e);t.queryParams=p,t.headers=E,t.body=c;return}if(V(n)&&o(r)){let e=new Map,p=new URLSearchParams,E=new Headers,c=new URLSearchParams,x=new FormData;const w={};let N=void 0,H;for(let[_,k]of Object.entries(n)){const m=G(k);for(let[F,h]of m.alias){const O=h||_,C=R(r[_],k());switch(await g([...m.validators,...m.asyncValidator],C),F){case 0:{Object.defineProperty(w,O,{value:C,writable:!0,enumerable:!0}),H=0;break}case 1:p=s(p,O,C);break;case 2:e=i(e,O,C);break;case 3:E=s(E,O,C);break;case 4:{x=s(x,O,C),H=4;break}case 6:{c=s(c,O,C),H=6;break}case 5:{N=C,H=5;break}}}}switch(t.endpoint=et(t.endpoint,e),t.queryParams=p,t.headers=E,H){case 5:t.body=N;break;case 4:t.body=x;break;case 6:t.body=c;break;case 0:t.body=w;break}return}throw J}function Nt(t){const n=new URL(t.endpoint,t.host);if(t.queryParams)n.search=t.queryParams.toString();const r=t.headers??new Headers;if(!r.has("Content-Type")){const T=Tt(t.body);if(T)r.set("Content-Type",T)}if(!r.has("Accept"))r.set("Accept","application/json, text/plain, */*");const o=t.withCredentials?"include":void 0;return new Request(n,{headers:r,method:t.method,body:xt(t.body),signal:t.abort,credentials:o})}async function S(t){const n=t.downloadProgress,r=Nt(t),o=t.abort;let T;try{T=await globalThis.fetch(r)}catch(w){if(o?.aborted&&o.reason instanceof Error)switch(!0){case o.reason.name==="AbortError":throw new f({error:K});case o.reason.name==="TimeoutError":throw new f({error:X})}throw new f({error:w})}const{ok:s,headers:i,status:R,statusText:e,url:p}=T,E=q(i),c=l(i);let x=null;if(T.body){const w=[],N=T.body.getReader();let H=0;while(!0){const{done:k,value:m}=await N.read();if(k)break;w.push(m),H+=m.length,n?.({lengthComputable:E>0,loaded:H,total:E})}const _=tt(w,H);try{x=v({request:t,content:_,contentType:c})}catch(k){throw new f({error:k,status:R,statusText:e,headers:i,url:p})}}if(!s)throw new f({status:R,statusText:e,headers:i,url:p,body:x});return M({url:p,status:R,statusText:e,headers:i,body:x})}function ct(t){return typeof t==="object"&&t!==null&&$ in t}function d(t){if(!ct(t))throw j;return t[$]}function st(t){const n={host:t.host,interceptors:t.interceptors??[],handler:t.handler||S};return{[$]:n}}function _t(t,n){const o={...d(t),...n};return{[$]:o}}function z(){if(!B)throw Q;return B}function Ot(t){B=t}function At(){B=void 0}function ht(t){B=st(t)}var $=Symbol("Client"),B;function It(t,n){let r=n?.encode;if(!r){const o=globalThis.btoa;if(typeof o!=="function")throw new Error("BasicAuthInterceptor is not supported in this environment");r=(T)=>o(`${T.username}:${T.password}`)}return(o,T)=>{const s=o.headers||new Headers;return s.set("Authorization",`Basic ${r(t())}`),o.headers=s,T(o)}}var Ft=(t)=>{if(!t)return new Error("required");return null},Ut=(t)=>{if(typeof t!=="boolean"||!t)return new Error("requiredTrue");return null},Bt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length<t)return new Error(`minLength ${t}`);return null}},Dt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length>t)return new Error(`maxLength ${t}`);return null}},Lt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n<t)return new Error(`minLength ${t}`);return null}},yt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n>t)return new Error(`maxLength ${t}`);return null}},Pt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(!t.test(n))return new Error("pattern");return null}};export{Ot as setGlobalClient,At as restGlobalClient,Ut as requiredTrue,Ft as required,Pt as pattern,Bt as minLength,Lt as min,Dt as maxLength,yt as max,wt as makeHttpContextToken,Z as makeHttpContext,P as isHttpContextToken,V as isFieldGroup,U as isField,ct as isClient,z as getGlobalClient,Rt as field,S as fetchHandler,g as doValid,mt as defineRequest,ht as createGlobalClient,st as createClient,_t as cloneClient,It as basicAuthInterceptor,f as HttpErrorResponse,J as ERR_UNSUPPORTED_FIELD_TYPE,Et as ERR_UNKNOWN,X as ERR_TIMEOUT,pt as ERR_OBSERVE,A as ERR_NOT_SET_ALIAS,W as ERR_NOT_FOUND_HANDLER,Q as ERR_NOT_FOUND_GLOBAL_CLIENT,Ht as ERR_NETWORK,y as ERR_INVALID_HTTP_CONTEXT_TOKEN,j as ERR_INVALID_CLIENT,K as ERR_ABORTED};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defjs/core",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "module": "index.js",
6
6
  "typings": "index.d.ts",