@oazapfts/runtime 1.0.1 → 1.0.3
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/headers.d.ts +7 -3
- package/index.cjs +1 -1
- package/index.cjs.map +1 -1
- package/index.d.ts +212 -67
- package/index.js +46 -46
- package/index.js.map +1 -1
- package/package.json +2 -2
- package/query.d.ts +28 -20
- package/util.d.ts +19 -13
- package/runtime.d.ts +0 -115
package/headers.d.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
-
export type CustomHeaders = Record<string, string | null | boolean | number | undefined>;
|
|
2
|
-
|
|
3
|
-
export declare function
|
|
1
|
+
export declare type CustomHeaders = Record<string, string | null | boolean | number | undefined>;
|
|
2
|
+
|
|
3
|
+
export declare function mergeHeaders(base: HeadersInit | CustomHeaders | undefined, overwrite?: HeadersInit | CustomHeaders): Headers;
|
|
4
|
+
|
|
5
|
+
export declare function normalizeHeaders(headers: HeadersInit | CustomHeaders | undefined): Headers;
|
|
6
|
+
|
|
7
|
+
export { }
|
package/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var D=Object.defineProperty,x=Object.defineProperties;var A=Object.getOwnPropertyDescriptors;var g=Object.getOwnPropertySymbols;var j=Object.prototype.hasOwnProperty,O=Object.prototype.propertyIsEnumerable;var H=(r,e,t)=>e in r?D(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,
|
|
1
|
+
"use strict";var D=Object.defineProperty,x=Object.defineProperties;var A=Object.getOwnPropertyDescriptors;var g=Object.getOwnPropertySymbols;var j=Object.prototype.hasOwnProperty,O=Object.prototype.propertyIsEnumerable;var H=(r,e,t)=>e in r?D(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,h=(r,e)=>{for(var t in e||(e={}))j.call(e,t)&&H(r,t,e[t]);if(g)for(var t of g(e))O.call(e,t)&&H(r,t,e[t]);return r},y=(r,e)=>x(r,A(e));var S=(r,e)=>{var t={};for(var s in r)j.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&g)for(var s of g(r))e.indexOf(s)<0&&O.call(r,s)&&(t[s]=r[s]);return t};var E=(r,e,t)=>(H(r,typeof e!="symbol"?e+"":e,t),t);var m=(r,e,t)=>new Promise((s,f)=>{var n=a=>{try{c(t.next(a))}catch(o){f(o)}},i=a=>{try{c(t.throw(a))}catch(o){f(o)}},c=a=>a.done?s(a.value):Promise.resolve(a.value).then(n,i);c((t=t.apply(r,e)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("./query.cjs"),B=require("./util.cjs"),w=require("./headers.cjs");function F(r={}){function e(n,i){return m(this,null,function*(){const c=yield f(n,i);let a;try{a=yield c.text()}catch(o){}return{status:c.status,headers:c.headers,contentType:c.headers.get("content-type"),data:a}})}function t(c){return m(this,arguments,function*(n,i={}){const{status:a,headers:o,contentType:u,data:p}=yield e(n,y(h({},i),{headers:w.mergeHeaders({Accept:"application/json"},i.headers)}));return(u?u.includes("json"):!1)?{status:a,headers:o,data:p?JSON.parse(p):null}:{status:a,headers:o,data:p}})}function s(c){return m(this,arguments,function*(n,i={}){const a=yield f(n,i);let o;try{o=yield a.blob()}catch(u){}return{status:a.status,headers:a.headers,data:o}})}function f(c){return m(this,arguments,function*(n,i={}){const d=y(h(h({},r),i),{headers:w.mergeHeaders(r.headers,i.headers)}),{baseUrl:a,fetch:o}=d,u=S(d,["baseUrl","fetch"]),p=B.joinUrl(a,n);return yield(o||fetch)(p,u)})}return{ok:b,fetchText:e,fetchJson:t,fetchBlob:s,mergeHeaders:w.mergeHeaders,json(a){var o=a,{body:n,headers:i}=o,c=S(o,["body","headers"]);return y(h(h({},c),n!=null&&{body:JSON.stringify(n)}),{headers:w.mergeHeaders({"Content-Type":"application/json"},i)})},form(a){var o=a,{body:n,headers:i}=o,c=S(o,["body","headers"]);return y(h(h({},c),n!=null&&{body:U.form(n)}),{headers:w.mergeHeaders({"Content-Type":"application/x-www-form-urlencoded"},i)})},multipart(a){var o=a,{body:n,headers:i}=o,c=S(o,["body","headers"]);if(n==null)return y(h({},c),{body:n,headers:w.normalizeHeaders(i)});const u=new(r.formDataConstructor||c.formDataConstructor||FormData),p=(l,d)=>{typeof d=="string"||d instanceof Blob?u.append(l,d):typeof d=="number"?u.append(l,String(d)):u.append(l,new Blob([JSON.stringify(d)],{type:"application/json"}))};return Object.entries(n).forEach(([l,d])=>{Array.isArray(d)?d.forEach(k=>p(l,k)):p(l,d)}),y(h({},c),{body:u,headers:w.normalizeHeaders(i)})}}}function N(r,e){return m(this,null,function*(){const{status:t,data:s,headers:f}=yield r,n=e[t];if(n)return n(s);if(e.default)return e.default(t,s);throw new C(t,s,f)})}const J=[200,201,202,204];function b(r){return m(this,null,function*(){const e=yield r;if(J.some(t=>t==e.status))return e.data;throw new C(e.status,e.data,e.headers)})}function T(r){return(...e)=>b(r(...e))}function z(r){const e={};return Object.entries(r).forEach(([t,s])=>{e[t]=typeof s=="function"?T(s):s}),e}class C extends Error{constructor(t,s,f){super(`Error: ${t}`);E(this,"status");E(this,"data");E(this,"headers");this.status=t,this.data=s,this.headers=f}}exports.HttpError=C;exports.SUCCESS_CODES=J;exports.handle=N;exports.ok=b;exports.okify=T;exports.optimistic=z;exports.runtime=F;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../src/runtime.ts","../src/index.ts"],"sourcesContent":["import * as qs from \"./query\";\nimport { joinUrl } from \"./util\";\nimport { ok } from \"./index\";\nimport { CustomHeaders, mergeHeaders, normalizeHeaders } from \"./headers\";\n\nexport { type CustomHeaders };\n\nexport type RequestOpts = {\n baseUrl?: string;\n fetch?: typeof fetch;\n formDataConstructor?: new () => FormData;\n headers?: HeadersInit | CustomHeaders;\n} & Omit<RequestInit, \"body\" | \"headers\">;\n\nexport type Defaults<Headers extends RequestOpts[\"headers\"] = CustomHeaders> =\n Omit<RequestOpts, \"headers\" | \"baseUrl\"> & {\n baseUrl: string;\n headers: Headers;\n };\n\ntype FetchRequestOpts = RequestOpts & {\n body?: string | FormData | Blob;\n};\n\ntype JsonRequestOpts = RequestOpts & {\n body?: any;\n};\n\ntype FormRequestOpts = RequestOpts & {\n body?: Record<string, any>;\n};\n\nexport type ApiResponse = { status: number; data?: any };\n\nexport type WithHeaders<T extends ApiResponse> = T & { headers: Headers };\n\ntype MultipartRequestOpts = RequestOpts & {\n body?: Record<string, unknown>;\n};\n\nexport function runtime(defaults: RequestOpts = {}) {\n async function fetchText(url: string, req?: FetchRequestOpts) {\n const res = await doFetch(url, req);\n let data;\n try {\n data = await res.text();\n } catch (err) {}\n\n return {\n status: res.status,\n headers: res.headers,\n contentType: res.headers.get(\"content-type\"),\n data,\n };\n }\n\n async function fetchJson<T extends ApiResponse>(\n url: string,\n req: FetchRequestOpts = {},\n ) {\n const { status, headers, contentType, data } = await fetchText(url, {\n ...req,\n headers: mergeHeaders(\n {\n Accept: \"application/json\",\n },\n req.headers,\n ),\n });\n\n const isJson = contentType ? contentType.includes(\"json\") : false;\n\n if (isJson) {\n return {\n status,\n headers,\n data: data ? JSON.parse(data) : null,\n } as WithHeaders<T>;\n }\n\n return { status, headers, data } as WithHeaders<T>;\n }\n\n async function fetchBlob<T extends ApiResponse>(\n url: string,\n req: FetchRequestOpts = {},\n ) {\n const res = await doFetch(url, req);\n let data;\n try {\n data = await res.blob();\n } catch (err) {}\n return { status: res.status, headers: res.headers, data } as WithHeaders<T>;\n }\n\n async function doFetch(url: string, req: FetchRequestOpts = {}) {\n const {\n baseUrl,\n fetch: customFetch,\n ...init\n } = {\n ...defaults,\n ...req,\n headers: mergeHeaders(defaults.headers, req.headers),\n };\n const href = joinUrl(baseUrl, url);\n const res = await (customFetch || fetch)(href, init);\n return res;\n }\n\n return {\n ok,\n fetchText,\n fetchJson,\n fetchBlob,\n mergeHeaders,\n\n json({ body, headers, ...req }: JsonRequestOpts) {\n return {\n ...req,\n ...(body != null && { body: JSON.stringify(body) }),\n headers: mergeHeaders(\n {\n \"Content-Type\": \"application/json\",\n },\n headers,\n ),\n };\n },\n\n form({ body, headers, ...req }: FormRequestOpts) {\n return {\n ...req,\n ...(body != null && { body: qs.form(body) }),\n headers: mergeHeaders(\n {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n headers,\n ),\n };\n },\n\n multipart({ body, headers, ...req }: MultipartRequestOpts) {\n if (body == null)\n return { ...req, body, headers: normalizeHeaders(headers) };\n\n const data = new (defaults.formDataConstructor ||\n req.formDataConstructor ||\n FormData)();\n\n const append = (name: string, value: unknown) => {\n if (typeof value === \"string\" || value instanceof Blob) {\n data.append(name, value);\n } else {\n data.append(\n name,\n new Blob([JSON.stringify(value)], { type: \"application/json\" }),\n );\n }\n };\n\n Object.entries(body).forEach(([name, value]) => {\n if (Array.isArray(value)) {\n value.forEach((v) => append(name, v));\n } else {\n append(name, value);\n }\n });\n\n return {\n ...req,\n body: data,\n headers: normalizeHeaders(headers),\n };\n },\n };\n}\n","import type { ApiResponse, WithHeaders } from \"./runtime\";\n\nexport * from \"./runtime\";\n\n/**\n * Type to access a response's data property for a given status.\n */\nexport type DataType<T extends ApiResponse, S extends number> = T extends {\n status: S;\n}\n ? T[\"data\"]\n : never;\n\n/**\n * Object with methods to handle possible status codes of an ApiResponse.\n */\nexport type ResponseHandler<T extends ApiResponse> = {\n [P in T[\"status\"]]?: (res: DataType<T, P>) => any;\n} & {\n default?: (status: number, data: any) => any;\n};\n\nexport type FunctionReturnType<T> = T extends (...args: any[]) => any\n ? ReturnType<T>\n : never;\n\n/**\n * Utility function to handle different status codes.\n *\n * Example:\n *\n * const userId = await handle(api.register({ email, password }), {\n * 200: (user: User) => user.id,\n * 400: (err: string) => console.log(err),\n * })\n **/\nexport async function handle<\n T extends WithHeaders<ApiResponse>,\n H extends ResponseHandler<T>,\n>(promise: Promise<T>, handler: H): Promise<FunctionReturnType<H[keyof H]>> {\n const { status, data, headers } = await promise;\n const statusHandler = (handler as any)[status];\n if (statusHandler) return statusHandler(data);\n if (handler.default) return handler.default(status, data);\n throw new HttpError(status, data, headers);\n}\n\nexport const SUCCESS_CODES = [200, 201, 202, 204] as const;\nexport type SuccessCodes = (typeof SUCCESS_CODES)[number];\n\nexport type SuccessResponse<T extends ApiResponse> = DataType<T, SuccessCodes>;\n\n/**\n * Utility function to directly return any successful response\n * and throw a HttpError otherwise.\n *\n * Example:\n *\n * try {\n * const userId = await ok(api.register({ email, password }));\n * }\n * catch (err) {\n * console.log(err.status)\n * }\n */\nexport async function ok<T extends WithHeaders<ApiResponse>>(\n promise: Promise<T>,\n): Promise<SuccessResponse<T>> {\n const res = await promise;\n if (SUCCESS_CODES.some((s) => s == res.status)) return res.data;\n throw new HttpError(res.status, res.data, res.headers);\n}\n\nexport type Args<T> = T extends (...args: infer U) => any ? U : any;\nexport type ApiFunction = (...args: any[]) => Promise<WithHeaders<ApiResponse>>;\nexport type AsyncReturnType<T> = T extends (...args: any[]) => Promise<infer V>\n ? V\n : never;\n\nexport type OkResponse<T extends ApiFunction> = SuccessResponse<\n AsyncReturnType<T>\n>;\n\nexport type Okify<T extends ApiFunction> = (\n ...args: Args<T>\n) => Promise<OkResponse<T>>;\n\n/**\n * Utility function to wrap an API function with `ok(...)`.\n */\nexport function okify<T extends ApiFunction>(fn: T): Okify<T> {\n return (...args: Args<T>) => ok(fn(...args));\n}\n\ntype OptimisticApi<T> = {\n [K in keyof T]: T[K] extends ApiFunction ? Okify<T[K]> : T[K];\n};\n\n/**\n * Utility to `okify` each function of an API.\n */\nexport function optimistic<T extends Record<string, ApiFunction | unknown>>(\n api: T,\n): OptimisticApi<T> {\n const okApi: any = {};\n Object.entries(api).forEach(([key, value]) => {\n okApi[key] = typeof value === \"function\" ? okify(value as any) : value;\n });\n return okApi;\n}\n\nexport class HttpError extends Error {\n status: number;\n data?: any;\n headers: Headers;\n\n constructor(status: number, data: any, headers: Headers) {\n super(`Error: ${status}`);\n this.status = status;\n this.data = data;\n this.headers = headers;\n }\n}\n"],"names":["runtime","defaults","fetchText","url","req","__async","res","doFetch","data","err","fetchJson","_0","status","headers","contentType","__spreadProps","__spreadValues","mergeHeaders","fetchBlob","_a","baseUrl","customFetch","init","__objRest","href","joinUrl","ok","_b","body","_c","_d","qs.form","_e","_f","normalizeHeaders","append","name","value","v","handle","promise","handler","statusHandler","HttpError","SUCCESS_CODES","s","okify","fn","args","optimistic","api","okApi","key","__publicField"],"mappings":"k/BAwCgB,SAAAA,EAAQC,EAAwB,GAAI,CACnC,SAAAC,EAAUC,EAAaC,EAAwB,QAAAC,EAAA,sBAC5D,MAAMC,EAAM,MAAMC,EAAQJ,EAAKC,CAAG,EAC9B,IAAAI,EACA,GAAA,CACKA,EAAA,MAAMF,EAAI,aACVG,EAAK,CAAC,CAER,MAAA,CACL,OAAQH,EAAI,OACZ,QAASA,EAAI,QACb,YAAaA,EAAI,QAAQ,IAAI,cAAc,EAC3C,KAAAE,CAAA,CAEJ,GAEA,SAAeE,EACbC,EAEA,QAAAN,EAAA,yBAFAF,EACAC,EAAwB,GACxB,CACM,KAAA,CAAE,OAAAQ,UAAQC,EAAS,YAAAC,EAAa,KAAAN,GAAS,MAAMN,EAAUC,EAAKY,EAAAC,EAAA,GAC/DZ,GAD+D,CAElE,QAASa,EAAA,aACP,CACE,OAAQ,kBACV,EACAb,EAAI,OACN,CAAA,EACD,EAID,OAFeU,EAAcA,EAAY,SAAS,MAAM,EAAI,IAGnD,CACL,OAAAF,EAAA,QACAC,EACA,KAAML,EAAO,KAAK,MAAMA,CAAI,EAAI,IAAA,EAI7B,CAAE,OAAAI,EAAQ,QAAAC,EAAS,KAAAL,EAC5B,GAEA,SAAeU,EACbP,EAEA,QAAAN,EAAA,yBAFAF,EACAC,EAAwB,GACxB,CACA,MAAME,EAAM,MAAMC,EAAQJ,EAAKC,CAAG,EAC9B,IAAAI,EACA,GAAA,CACKA,EAAA,MAAMF,EAAI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,EAAI,OAAO,CACvD,GAmBO,SAASwC,EAA6BC,EAAiB,CAC5D,MAAO,IAAIC,IAAkBtB,EAAGqB,EAAG,GAAGC,CAAI,CAAC,CAC7C,CASO,SAASC,EACdC,EACkB,CAClB,MAAMC,EAAa,CAAA,EACZ,cAAA,QAAQD,CAAG,EAAE,QAAQ,CAAC,CAACE,EAAKf,CAAK,IAAM,CAC5Cc,EAAMC,CAAG,EAAI,OAAOf,GAAU,WAAaS,EAAMT,CAAY,EAAIA,CAAA,CAClE,EACMc,CACT,CAEO,MAAMR,UAAkB,KAAM,CAKnC,YAAY/B,EAAgBJ,EAAWK,EAAkB,CACjD,MAAA,UAAUD,CAAM,EAAE,EAL1ByC,EAAA,eACAA,EAAA,aACAA,EAAA,gBAIE,KAAK,OAASzC,EACd,KAAK,KAAOJ,EACZ,KAAK,QAAUK,CACjB,CACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/runtime.ts","../src/index.ts"],"sourcesContent":["import * as qs from \"./query\";\nimport { joinUrl } from \"./util\";\nimport { ok } from \"./index\";\nimport { CustomHeaders, mergeHeaders, normalizeHeaders } from \"./headers\";\n\nexport { type CustomHeaders };\n\nexport type RequestOpts = {\n baseUrl?: string;\n fetch?: typeof fetch;\n formDataConstructor?: new () => FormData;\n headers?: HeadersInit | CustomHeaders;\n} & Omit<RequestInit, \"body\" | \"headers\">;\n\nexport type Defaults<Headers extends RequestOpts[\"headers\"] = CustomHeaders> =\n Omit<RequestOpts, \"headers\" | \"baseUrl\"> & {\n baseUrl: string;\n headers: Headers;\n };\n\ntype FetchRequestOpts = RequestOpts & {\n body?: string | FormData | Blob;\n};\n\ntype JsonRequestOpts = RequestOpts & {\n body?: any;\n};\n\ntype FormRequestOpts = RequestOpts & {\n body?: Record<string, any>;\n};\n\nexport type ApiResponse = { status: number; data?: any };\n\nexport type WithHeaders<T extends ApiResponse> = T & { headers: Headers };\n\ntype MultipartRequestOpts = RequestOpts & {\n body?: Record<string, unknown>;\n};\n\nexport function runtime(defaults: RequestOpts = {}) {\n async function fetchText(url: string, req?: FetchRequestOpts) {\n const res = await doFetch(url, req);\n let data;\n try {\n data = await res.text();\n } catch (err) {}\n\n return {\n status: res.status,\n headers: res.headers,\n contentType: res.headers.get(\"content-type\"),\n data,\n };\n }\n\n async function fetchJson<T extends ApiResponse>(\n url: string,\n req: FetchRequestOpts = {},\n ) {\n const { status, headers, contentType, data } = await fetchText(url, {\n ...req,\n headers: mergeHeaders(\n {\n Accept: \"application/json\",\n },\n req.headers,\n ),\n });\n\n const isJson = contentType ? contentType.includes(\"json\") : false;\n\n if (isJson) {\n return {\n status,\n headers,\n data: data ? JSON.parse(data) : null,\n } as WithHeaders<T>;\n }\n\n return { status, headers, data } as WithHeaders<T>;\n }\n\n async function fetchBlob<T extends ApiResponse>(\n url: string,\n req: FetchRequestOpts = {},\n ) {\n const res = await doFetch(url, req);\n let data;\n try {\n data = await res.blob();\n } catch (err) {}\n return { status: res.status, headers: res.headers, data } as WithHeaders<T>;\n }\n\n async function doFetch(url: string, req: FetchRequestOpts = {}) {\n const {\n baseUrl,\n fetch: customFetch,\n ...init\n } = {\n ...defaults,\n ...req,\n headers: mergeHeaders(defaults.headers, req.headers),\n };\n const href = joinUrl(baseUrl, url);\n const res = await (customFetch || fetch)(href, init);\n return res;\n }\n\n return {\n ok,\n fetchText,\n fetchJson,\n fetchBlob,\n mergeHeaders,\n\n json({ body, headers, ...req }: JsonRequestOpts) {\n return {\n ...req,\n ...(body != null && { body: JSON.stringify(body) }),\n headers: mergeHeaders(\n {\n \"Content-Type\": \"application/json\",\n },\n headers,\n ),\n };\n },\n\n form({ body, headers, ...req }: FormRequestOpts) {\n return {\n ...req,\n ...(body != null && { body: qs.form(body) }),\n headers: mergeHeaders(\n {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n headers,\n ),\n };\n },\n\n multipart({ body, headers, ...req }: MultipartRequestOpts) {\n if (body == null)\n return { ...req, body, headers: normalizeHeaders(headers) };\n\n const data = new (defaults.formDataConstructor ||\n req.formDataConstructor ||\n FormData)();\n\n const append = (name: string, value: unknown) => {\n if (typeof value === \"string\" || value instanceof Blob) {\n data.append(name, value);\n } else if (typeof value === \"number\") {\n data.append(name, String(value));\n } else {\n data.append(\n name,\n new Blob([JSON.stringify(value)], { type: \"application/json\" }),\n );\n }\n };\n\n Object.entries(body).forEach(([name, value]) => {\n if (Array.isArray(value)) {\n value.forEach((v) => append(name, v));\n } else {\n append(name, value);\n }\n });\n\n return {\n ...req,\n body: data,\n headers: normalizeHeaders(headers),\n };\n },\n };\n}\n","import type { ApiResponse, WithHeaders } from \"./runtime\";\n\nexport * from \"./runtime\";\n\n/**\n * Type to access a response's data property for a given status.\n */\nexport type DataType<T extends ApiResponse, S extends number> = T extends {\n status: S;\n}\n ? T[\"data\"]\n : never;\n\n/**\n * Object with methods to handle possible status codes of an ApiResponse.\n */\nexport type ResponseHandler<T extends ApiResponse> = {\n [P in T[\"status\"]]?: (res: DataType<T, P>) => any;\n} & {\n default?: (status: number, data: any) => any;\n};\n\nexport type FunctionReturnType<T> = T extends (...args: any[]) => any\n ? ReturnType<T>\n : never;\n\n/**\n * Utility function to handle different status codes.\n *\n * Example:\n *\n * const userId = await handle(api.register({ email, password }), {\n * 200: (user: User) => user.id,\n * 400: (err: string) => console.log(err),\n * })\n **/\nexport async function handle<\n T extends WithHeaders<ApiResponse>,\n H extends ResponseHandler<T>,\n>(promise: Promise<T>, handler: H): Promise<FunctionReturnType<H[keyof H]>> {\n const { status, data, headers } = await promise;\n const statusHandler = (handler as any)[status];\n if (statusHandler) return statusHandler(data);\n if (handler.default) return handler.default(status, data);\n throw new HttpError(status, data, headers);\n}\n\nexport const SUCCESS_CODES = [200, 201, 202, 204] as const;\nexport type SuccessCodes = (typeof SUCCESS_CODES)[number];\n\nexport type SuccessResponse<T extends ApiResponse> = DataType<T, SuccessCodes>;\n\n/**\n * Utility function to directly return any successful response\n * and throw a HttpError otherwise.\n *\n * Example:\n *\n * try {\n * const userId = await ok(api.register({ email, password }));\n * }\n * catch (err) {\n * console.log(err.status)\n * }\n */\nexport async function ok<T extends WithHeaders<ApiResponse>>(\n promise: Promise<T>,\n): Promise<SuccessResponse<T>> {\n const res = await promise;\n if (SUCCESS_CODES.some((s) => s == res.status)) return res.data;\n throw new HttpError(res.status, res.data, res.headers);\n}\n\nexport type Args<T> = T extends (...args: infer U) => any ? U : any;\nexport type ApiFunction = (...args: any[]) => Promise<WithHeaders<ApiResponse>>;\nexport type AsyncReturnType<T> = T extends (...args: any[]) => Promise<infer V>\n ? V\n : never;\n\nexport type OkResponse<T extends ApiFunction> = SuccessResponse<\n AsyncReturnType<T>\n>;\n\nexport type Okify<T extends ApiFunction> = (\n ...args: Args<T>\n) => Promise<OkResponse<T>>;\n\n/**\n * Utility function to wrap an API function with `ok(...)`.\n */\nexport function okify<T extends ApiFunction>(fn: T): Okify<T> {\n return (...args: Args<T>) => ok(fn(...args));\n}\n\ntype OptimisticApi<T> = {\n [K in keyof T]: T[K] extends ApiFunction ? Okify<T[K]> : T[K];\n};\n\n/**\n * Utility to `okify` each function of an API.\n */\nexport function optimistic<T extends Record<string, ApiFunction | unknown>>(\n api: T,\n): OptimisticApi<T> {\n const okApi: any = {};\n Object.entries(api).forEach(([key, value]) => {\n okApi[key] = typeof value === \"function\" ? okify(value as any) : value;\n });\n return okApi;\n}\n\nexport class HttpError extends Error {\n status: number;\n data?: any;\n headers: Headers;\n\n constructor(status: number, data: any, headers: Headers) {\n super(`Error: ${status}`);\n this.status = status;\n this.data = data;\n this.headers = headers;\n }\n}\n"],"names":["runtime","defaults","fetchText","url","req","__async","res","doFetch","data","err","fetchJson","_0","status","headers","contentType","__spreadProps","__spreadValues","mergeHeaders","fetchBlob","_a","baseUrl","customFetch","init","__objRest","href","joinUrl","ok","_b","body","_c","_d","qs.form","_e","_f","normalizeHeaders","append","name","value","v","handle","promise","handler","statusHandler","HttpError","SUCCESS_CODES","s","okify","fn","args","optimistic","api","okApi","key","__public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cc,EAAMC,CAAG,EAAI,OAAOf,GAAU,WAAaS,EAAMT,CAAY,EAAIA,CAAA,CAClE,EACMc,CACT,CAEO,MAAMR,UAAkB,KAAM,CAKnC,YAAY/B,EAAgBJ,EAAWK,EAAkB,CACjD,MAAA,UAAUD,CAAM,EAAE,EAL1ByC,EAAA,eACAA,EAAA,aACAA,EAAA,gBAIE,KAAK,OAASzC,EACd,KAAK,KAAOJ,EACZ,KAAK,QAAUK,CACjB,CACF"}
|
package/index.d.ts
CHANGED
|
@@ -1,67 +1,212 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
export type
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
export type
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
export
|
|
47
|
-
|
|
48
|
-
export
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
type
|
|
56
|
-
|
|
57
|
-
};
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
1
|
+
export declare type ApiFunction = (...args: any[]) => Promise<WithHeaders<ApiResponse>>;
|
|
2
|
+
|
|
3
|
+
export declare type ApiResponse = {
|
|
4
|
+
status: number;
|
|
5
|
+
data?: any;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
export declare type Args<T> = T extends (...args: infer U) => any ? U : any;
|
|
9
|
+
|
|
10
|
+
export declare type AsyncReturnType<T> = T extends (...args: any[]) => Promise<infer V> ? V : never;
|
|
11
|
+
|
|
12
|
+
export declare type CustomHeaders = Record<string, string | null | boolean | number | undefined>;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Type to access a response's data property for a given status.
|
|
16
|
+
*/
|
|
17
|
+
export declare type DataType<T extends ApiResponse, S extends number> = T extends {
|
|
18
|
+
status: S;
|
|
19
|
+
} ? T["data"] : never;
|
|
20
|
+
|
|
21
|
+
export declare type Defaults<Headers extends RequestOpts["headers"] = CustomHeaders> = Omit<RequestOpts, "headers" | "baseUrl"> & {
|
|
22
|
+
baseUrl: string;
|
|
23
|
+
headers: Headers;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
declare type FetchRequestOpts = RequestOpts & {
|
|
27
|
+
body?: string | FormData | Blob;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
declare type FormRequestOpts = RequestOpts & {
|
|
31
|
+
body?: Record<string, any>;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export declare type FunctionReturnType<T> = T extends (...args: any[]) => any ? ReturnType<T> : never;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Utility function to handle different status codes.
|
|
38
|
+
*
|
|
39
|
+
* Example:
|
|
40
|
+
*
|
|
41
|
+
* const userId = await handle(api.register({ email, password }), {
|
|
42
|
+
* 200: (user: User) => user.id,
|
|
43
|
+
* 400: (err: string) => console.log(err),
|
|
44
|
+
* })
|
|
45
|
+
**/
|
|
46
|
+
export declare function handle<T extends WithHeaders<ApiResponse>, H extends ResponseHandler<T>>(promise: Promise<T>, handler: H): Promise<FunctionReturnType<H[keyof H]>>;
|
|
47
|
+
|
|
48
|
+
export declare class HttpError extends Error {
|
|
49
|
+
status: number;
|
|
50
|
+
data?: any;
|
|
51
|
+
headers: Headers;
|
|
52
|
+
constructor(status: number, data: any, headers: Headers);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
declare type JsonRequestOpts = RequestOpts & {
|
|
56
|
+
body?: any;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
declare function mergeHeaders(base: HeadersInit | CustomHeaders | undefined, overwrite?: HeadersInit | CustomHeaders): Headers;
|
|
60
|
+
|
|
61
|
+
declare type MultipartRequestOpts = RequestOpts & {
|
|
62
|
+
body?: Record<string, unknown>;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Utility function to directly return any successful response
|
|
67
|
+
* and throw a HttpError otherwise.
|
|
68
|
+
*
|
|
69
|
+
* Example:
|
|
70
|
+
*
|
|
71
|
+
* try {
|
|
72
|
+
* const userId = await ok(api.register({ email, password }));
|
|
73
|
+
* }
|
|
74
|
+
* catch (err) {
|
|
75
|
+
* console.log(err.status)
|
|
76
|
+
* }
|
|
77
|
+
*/
|
|
78
|
+
export declare function ok<T extends WithHeaders<ApiResponse>>(promise: Promise<T>): Promise<SuccessResponse<T>>;
|
|
79
|
+
|
|
80
|
+
export declare type Okify<T extends ApiFunction> = (...args: Args<T>) => Promise<OkResponse<T>>;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Utility function to wrap an API function with `ok(...)`.
|
|
84
|
+
*/
|
|
85
|
+
export declare function okify<T extends ApiFunction>(fn: T): Okify<T>;
|
|
86
|
+
|
|
87
|
+
export declare type OkResponse<T extends ApiFunction> = SuccessResponse<AsyncReturnType<T>>;
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Utility to `okify` each function of an API.
|
|
91
|
+
*/
|
|
92
|
+
export declare function optimistic<T extends Record<string, ApiFunction | unknown>>(api: T): OptimisticApi<T>;
|
|
93
|
+
|
|
94
|
+
declare type OptimisticApi<T> = {
|
|
95
|
+
[K in keyof T]: T[K] extends ApiFunction ? Okify<T[K]> : T[K];
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
export declare type RequestOpts = {
|
|
99
|
+
baseUrl?: string;
|
|
100
|
+
fetch?: typeof fetch;
|
|
101
|
+
formDataConstructor?: new () => FormData;
|
|
102
|
+
headers?: HeadersInit | CustomHeaders;
|
|
103
|
+
} & Omit<RequestInit, "body" | "headers">;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Object with methods to handle possible status codes of an ApiResponse.
|
|
107
|
+
*/
|
|
108
|
+
export declare type ResponseHandler<T extends ApiResponse> = {
|
|
109
|
+
[P in T["status"]]?: (res: DataType<T, P>) => any;
|
|
110
|
+
} & {
|
|
111
|
+
default?: (status: number, data: any) => any;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
export declare function runtime(defaults?: RequestOpts): {
|
|
115
|
+
ok: typeof ok;
|
|
116
|
+
fetchText: (url: string, req?: FetchRequestOpts) => Promise<{
|
|
117
|
+
status: number;
|
|
118
|
+
headers: Headers;
|
|
119
|
+
contentType: string | null;
|
|
120
|
+
data: string | undefined;
|
|
121
|
+
}>;
|
|
122
|
+
fetchJson: <T extends ApiResponse>(url: string, req?: FetchRequestOpts) => Promise<WithHeaders<T>>;
|
|
123
|
+
fetchBlob: <T_1 extends ApiResponse>(url: string, req?: FetchRequestOpts) => Promise<WithHeaders<T_1>>;
|
|
124
|
+
mergeHeaders: typeof mergeHeaders;
|
|
125
|
+
json({ body, headers, ...req }: JsonRequestOpts): {
|
|
126
|
+
headers: Headers;
|
|
127
|
+
body?: string | undefined;
|
|
128
|
+
baseUrl?: string | undefined;
|
|
129
|
+
fetch?: typeof fetch | undefined;
|
|
130
|
+
formDataConstructor?: (new () => FormData) | undefined;
|
|
131
|
+
cache?: RequestCache | undefined;
|
|
132
|
+
credentials?: RequestCredentials | undefined;
|
|
133
|
+
integrity?: string | undefined;
|
|
134
|
+
keepalive?: boolean | undefined;
|
|
135
|
+
method?: string | undefined;
|
|
136
|
+
mode?: RequestMode | undefined;
|
|
137
|
+
priority?: RequestPriority | undefined;
|
|
138
|
+
redirect?: RequestRedirect | undefined;
|
|
139
|
+
referrer?: string | undefined;
|
|
140
|
+
referrerPolicy?: ReferrerPolicy | undefined;
|
|
141
|
+
signal?: AbortSignal | null | undefined;
|
|
142
|
+
window?: null | undefined;
|
|
143
|
+
};
|
|
144
|
+
form({ body, headers, ...req }: FormRequestOpts): {
|
|
145
|
+
headers: Headers;
|
|
146
|
+
body?: string | undefined;
|
|
147
|
+
baseUrl?: string | undefined;
|
|
148
|
+
fetch?: typeof fetch | undefined;
|
|
149
|
+
formDataConstructor?: (new () => FormData) | undefined;
|
|
150
|
+
cache?: RequestCache | undefined;
|
|
151
|
+
credentials?: RequestCredentials | undefined;
|
|
152
|
+
integrity?: string | undefined;
|
|
153
|
+
keepalive?: boolean | undefined;
|
|
154
|
+
method?: string | undefined;
|
|
155
|
+
mode?: RequestMode | undefined;
|
|
156
|
+
priority?: RequestPriority | undefined;
|
|
157
|
+
redirect?: RequestRedirect | undefined;
|
|
158
|
+
referrer?: string | undefined;
|
|
159
|
+
referrerPolicy?: ReferrerPolicy | undefined;
|
|
160
|
+
signal?: AbortSignal | null | undefined;
|
|
161
|
+
window?: null | undefined;
|
|
162
|
+
};
|
|
163
|
+
multipart({ body, headers, ...req }: MultipartRequestOpts): {
|
|
164
|
+
body: undefined;
|
|
165
|
+
headers: Headers;
|
|
166
|
+
baseUrl?: string | undefined;
|
|
167
|
+
fetch?: typeof fetch | undefined;
|
|
168
|
+
formDataConstructor?: (new () => FormData) | undefined;
|
|
169
|
+
cache?: RequestCache | undefined;
|
|
170
|
+
credentials?: RequestCredentials | undefined;
|
|
171
|
+
integrity?: string | undefined;
|
|
172
|
+
keepalive?: boolean | undefined;
|
|
173
|
+
method?: string | undefined;
|
|
174
|
+
mode?: RequestMode | undefined;
|
|
175
|
+
priority?: RequestPriority | undefined;
|
|
176
|
+
redirect?: RequestRedirect | undefined;
|
|
177
|
+
referrer?: string | undefined;
|
|
178
|
+
referrerPolicy?: ReferrerPolicy | undefined;
|
|
179
|
+
signal?: AbortSignal | null | undefined;
|
|
180
|
+
window?: null | undefined;
|
|
181
|
+
} | {
|
|
182
|
+
body: FormData;
|
|
183
|
+
headers: Headers;
|
|
184
|
+
baseUrl?: string | undefined;
|
|
185
|
+
fetch?: typeof fetch | undefined;
|
|
186
|
+
formDataConstructor?: (new () => FormData) | undefined;
|
|
187
|
+
cache?: RequestCache | undefined;
|
|
188
|
+
credentials?: RequestCredentials | undefined;
|
|
189
|
+
integrity?: string | undefined;
|
|
190
|
+
keepalive?: boolean | undefined;
|
|
191
|
+
method?: string | undefined;
|
|
192
|
+
mode?: RequestMode | undefined;
|
|
193
|
+
priority?: RequestPriority | undefined;
|
|
194
|
+
redirect?: RequestRedirect | undefined;
|
|
195
|
+
referrer?: string | undefined;
|
|
196
|
+
referrerPolicy?: ReferrerPolicy | undefined;
|
|
197
|
+
signal?: AbortSignal | null | undefined;
|
|
198
|
+
window?: null | undefined;
|
|
199
|
+
};
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
export declare const SUCCESS_CODES: readonly [200, 201, 202, 204];
|
|
203
|
+
|
|
204
|
+
export declare type SuccessCodes = (typeof SUCCESS_CODES)[number];
|
|
205
|
+
|
|
206
|
+
export declare type SuccessResponse<T extends ApiResponse> = DataType<T, SuccessCodes>;
|
|
207
|
+
|
|
208
|
+
export declare type WithHeaders<T extends ApiResponse> = T & {
|
|
209
|
+
headers: Headers;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
export { }
|
package/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { form as w } from "./query.js";
|
|
2
|
-
import { joinUrl as
|
|
3
|
-
import { mergeHeaders as d, normalizeHeaders as
|
|
4
|
-
function
|
|
2
|
+
import { joinUrl as b } from "./util.js";
|
|
3
|
+
import { mergeHeaders as d, normalizeHeaders as h } from "./headers.js";
|
|
4
|
+
function J(a = {}) {
|
|
5
5
|
async function e(r, n) {
|
|
6
|
-
const t = await
|
|
6
|
+
const t = await p(r, n);
|
|
7
7
|
let s;
|
|
8
8
|
try {
|
|
9
9
|
s = await t.text();
|
|
@@ -16,8 +16,8 @@ function O(a = {}) {
|
|
|
16
16
|
data: s
|
|
17
17
|
};
|
|
18
18
|
}
|
|
19
|
-
async function
|
|
20
|
-
const { status: t, headers: s, contentType: u, data:
|
|
19
|
+
async function i(r, n = {}) {
|
|
20
|
+
const { status: t, headers: s, contentType: u, data: o } = await e(r, {
|
|
21
21
|
...n,
|
|
22
22
|
headers: d(
|
|
23
23
|
{
|
|
@@ -29,11 +29,11 @@ function O(a = {}) {
|
|
|
29
29
|
return (u ? u.includes("json") : !1) ? {
|
|
30
30
|
status: t,
|
|
31
31
|
headers: s,
|
|
32
|
-
data:
|
|
33
|
-
} : { status: t, headers: s, data:
|
|
32
|
+
data: o ? JSON.parse(o) : null
|
|
33
|
+
} : { status: t, headers: s, data: o };
|
|
34
34
|
}
|
|
35
|
-
async function
|
|
36
|
-
const t = await
|
|
35
|
+
async function f(r, n = {}) {
|
|
36
|
+
const t = await p(r, n);
|
|
37
37
|
let s;
|
|
38
38
|
try {
|
|
39
39
|
s = await t.blob();
|
|
@@ -41,7 +41,7 @@ function O(a = {}) {
|
|
|
41
41
|
}
|
|
42
42
|
return { status: t.status, headers: t.headers, data: s };
|
|
43
43
|
}
|
|
44
|
-
async function
|
|
44
|
+
async function p(r, n = {}) {
|
|
45
45
|
const {
|
|
46
46
|
baseUrl: t,
|
|
47
47
|
fetch: s,
|
|
@@ -50,14 +50,14 @@ function O(a = {}) {
|
|
|
50
50
|
...a,
|
|
51
51
|
...n,
|
|
52
52
|
headers: d(a.headers, n.headers)
|
|
53
|
-
},
|
|
54
|
-
return await (s || fetch)(
|
|
53
|
+
}, o = b(t, r);
|
|
54
|
+
return await (s || fetch)(o, u);
|
|
55
55
|
}
|
|
56
56
|
return {
|
|
57
|
-
ok:
|
|
57
|
+
ok: y,
|
|
58
58
|
fetchText: e,
|
|
59
|
-
fetchJson:
|
|
60
|
-
fetchBlob:
|
|
59
|
+
fetchJson: i,
|
|
60
|
+
fetchBlob: f,
|
|
61
61
|
mergeHeaders: d,
|
|
62
62
|
json({ body: r, headers: n, ...t }) {
|
|
63
63
|
return {
|
|
@@ -85,62 +85,62 @@ function O(a = {}) {
|
|
|
85
85
|
},
|
|
86
86
|
multipart({ body: r, headers: n, ...t }) {
|
|
87
87
|
if (r == null)
|
|
88
|
-
return { ...t, body: r, headers:
|
|
89
|
-
const s = new (a.formDataConstructor || t.formDataConstructor || FormData)(), u = (
|
|
90
|
-
typeof
|
|
91
|
-
|
|
92
|
-
new Blob([JSON.stringify(
|
|
88
|
+
return { ...t, body: r, headers: h(n) };
|
|
89
|
+
const s = new (a.formDataConstructor || t.formDataConstructor || FormData)(), u = (o, c) => {
|
|
90
|
+
typeof c == "string" || c instanceof Blob ? s.append(o, c) : typeof c == "number" ? s.append(o, String(c)) : s.append(
|
|
91
|
+
o,
|
|
92
|
+
new Blob([JSON.stringify(c)], { type: "application/json" })
|
|
93
93
|
);
|
|
94
94
|
};
|
|
95
|
-
return Object.entries(r).forEach(([
|
|
96
|
-
Array.isArray(
|
|
95
|
+
return Object.entries(r).forEach(([o, c]) => {
|
|
96
|
+
Array.isArray(c) ? c.forEach((m) => u(o, m)) : u(o, c);
|
|
97
97
|
}), {
|
|
98
98
|
...t,
|
|
99
99
|
body: s,
|
|
100
|
-
headers:
|
|
100
|
+
headers: h(n)
|
|
101
101
|
};
|
|
102
102
|
}
|
|
103
103
|
};
|
|
104
104
|
}
|
|
105
|
-
async function
|
|
106
|
-
const { status:
|
|
105
|
+
async function O(a, e) {
|
|
106
|
+
const { status: i, data: f, headers: p } = await a, r = e[i];
|
|
107
107
|
if (r)
|
|
108
|
-
return r(
|
|
108
|
+
return r(f);
|
|
109
109
|
if (e.default)
|
|
110
|
-
return e.default(
|
|
111
|
-
throw new
|
|
110
|
+
return e.default(i, f);
|
|
111
|
+
throw new l(i, f, p);
|
|
112
112
|
}
|
|
113
|
-
const
|
|
114
|
-
async function
|
|
113
|
+
const j = [200, 201, 202, 204];
|
|
114
|
+
async function y(a) {
|
|
115
115
|
const e = await a;
|
|
116
|
-
if (
|
|
116
|
+
if (j.some((i) => i == e.status))
|
|
117
117
|
return e.data;
|
|
118
|
-
throw new
|
|
118
|
+
throw new l(e.status, e.data, e.headers);
|
|
119
119
|
}
|
|
120
|
-
function
|
|
121
|
-
return (...e) =>
|
|
120
|
+
function E(a) {
|
|
121
|
+
return (...e) => y(a(...e));
|
|
122
122
|
}
|
|
123
123
|
function x(a) {
|
|
124
124
|
const e = {};
|
|
125
|
-
return Object.entries(a).forEach(([
|
|
126
|
-
e[
|
|
125
|
+
return Object.entries(a).forEach(([i, f]) => {
|
|
126
|
+
e[i] = typeof f == "function" ? E(f) : f;
|
|
127
127
|
}), e;
|
|
128
128
|
}
|
|
129
|
-
class
|
|
129
|
+
class l extends Error {
|
|
130
130
|
status;
|
|
131
131
|
data;
|
|
132
132
|
headers;
|
|
133
|
-
constructor(e,
|
|
134
|
-
super(`Error: ${e}`), this.status = e, this.data =
|
|
133
|
+
constructor(e, i, f) {
|
|
134
|
+
super(`Error: ${e}`), this.status = e, this.data = i, this.headers = f;
|
|
135
135
|
}
|
|
136
136
|
}
|
|
137
137
|
export {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
138
|
+
l as HttpError,
|
|
139
|
+
j as SUCCESS_CODES,
|
|
140
|
+
O as handle,
|
|
141
|
+
y as ok,
|
|
142
|
+
E as okify,
|
|
143
143
|
x as optimistic,
|
|
144
|
-
|
|
144
|
+
J as runtime
|
|
145
145
|
};
|
|
146
146
|
//# sourceMappingURL=index.js.map
|
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/runtime.ts","../src/index.ts"],"sourcesContent":["import * as qs from \"./query\";\nimport { joinUrl } from \"./util\";\nimport { ok } from \"./index\";\nimport { CustomHeaders, mergeHeaders, normalizeHeaders } from \"./headers\";\n\nexport { type CustomHeaders };\n\nexport type RequestOpts = {\n baseUrl?: string;\n fetch?: typeof fetch;\n formDataConstructor?: new () => FormData;\n headers?: HeadersInit | CustomHeaders;\n} & Omit<RequestInit, \"body\" | \"headers\">;\n\nexport type Defaults<Headers extends RequestOpts[\"headers\"] = CustomHeaders> =\n Omit<RequestOpts, \"headers\" | \"baseUrl\"> & {\n baseUrl: string;\n headers: Headers;\n };\n\ntype FetchRequestOpts = RequestOpts & {\n body?: string | FormData | Blob;\n};\n\ntype JsonRequestOpts = RequestOpts & {\n body?: any;\n};\n\ntype FormRequestOpts = RequestOpts & {\n body?: Record<string, any>;\n};\n\nexport type ApiResponse = { status: number; data?: any };\n\nexport type WithHeaders<T extends ApiResponse> = T & { headers: Headers };\n\ntype MultipartRequestOpts = RequestOpts & {\n body?: Record<string, unknown>;\n};\n\nexport function runtime(defaults: RequestOpts = {}) {\n async function fetchText(url: string, req?: FetchRequestOpts) {\n const res = await doFetch(url, req);\n let data;\n try {\n data = await res.text();\n } catch (err) {}\n\n return {\n status: res.status,\n headers: res.headers,\n contentType: res.headers.get(\"content-type\"),\n data,\n };\n }\n\n async function fetchJson<T extends ApiResponse>(\n url: string,\n req: FetchRequestOpts = {},\n ) {\n const { status, headers, contentType, data } = await fetchText(url, {\n ...req,\n headers: mergeHeaders(\n {\n Accept: \"application/json\",\n },\n req.headers,\n ),\n });\n\n const isJson = contentType ? contentType.includes(\"json\") : false;\n\n if (isJson) {\n return {\n status,\n headers,\n data: data ? JSON.parse(data) : null,\n } as WithHeaders<T>;\n }\n\n return { status, headers, data } as WithHeaders<T>;\n }\n\n async function fetchBlob<T extends ApiResponse>(\n url: string,\n req: FetchRequestOpts = {},\n ) {\n const res = await doFetch(url, req);\n let data;\n try {\n data = await res.blob();\n } catch (err) {}\n return { status: res.status, headers: res.headers, data } as WithHeaders<T>;\n }\n\n async function doFetch(url: string, req: FetchRequestOpts = {}) {\n const {\n baseUrl,\n fetch: customFetch,\n ...init\n } = {\n ...defaults,\n ...req,\n headers: mergeHeaders(defaults.headers, req.headers),\n };\n const href = joinUrl(baseUrl, url);\n const res = await (customFetch || fetch)(href, init);\n return res;\n }\n\n return {\n ok,\n fetchText,\n fetchJson,\n fetchBlob,\n mergeHeaders,\n\n json({ body, headers, ...req }: JsonRequestOpts) {\n return {\n ...req,\n ...(body != null && { body: JSON.stringify(body) }),\n headers: mergeHeaders(\n {\n \"Content-Type\": \"application/json\",\n },\n headers,\n ),\n };\n },\n\n form({ body, headers, ...req }: FormRequestOpts) {\n return {\n ...req,\n ...(body != null && { body: qs.form(body) }),\n headers: mergeHeaders(\n {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n headers,\n ),\n };\n },\n\n multipart({ body, headers, ...req }: MultipartRequestOpts) {\n if (body == null)\n return { ...req, body, headers: normalizeHeaders(headers) };\n\n const data = new (defaults.formDataConstructor ||\n req.formDataConstructor ||\n FormData)();\n\n const append = (name: string, value: unknown) => {\n if (typeof value === \"string\" || value instanceof Blob) {\n data.append(name, value);\n } else {\n data.append(\n name,\n new Blob([JSON.stringify(value)], { type: \"application/json\" }),\n );\n }\n };\n\n Object.entries(body).forEach(([name, value]) => {\n if (Array.isArray(value)) {\n value.forEach((v) => append(name, v));\n } else {\n append(name, value);\n }\n });\n\n return {\n ...req,\n body: data,\n headers: normalizeHeaders(headers),\n };\n },\n };\n}\n","import type { ApiResponse, WithHeaders } from \"./runtime\";\n\nexport * from \"./runtime\";\n\n/**\n * Type to access a response's data property for a given status.\n */\nexport type DataType<T extends ApiResponse, S extends number> = T extends {\n status: S;\n}\n ? T[\"data\"]\n : never;\n\n/**\n * Object with methods to handle possible status codes of an ApiResponse.\n */\nexport type ResponseHandler<T extends ApiResponse> = {\n [P in T[\"status\"]]?: (res: DataType<T, P>) => any;\n} & {\n default?: (status: number, data: any) => any;\n};\n\nexport type FunctionReturnType<T> = T extends (...args: any[]) => any\n ? ReturnType<T>\n : never;\n\n/**\n * Utility function to handle different status codes.\n *\n * Example:\n *\n * const userId = await handle(api.register({ email, password }), {\n * 200: (user: User) => user.id,\n * 400: (err: string) => console.log(err),\n * })\n **/\nexport async function handle<\n T extends WithHeaders<ApiResponse>,\n H extends ResponseHandler<T>,\n>(promise: Promise<T>, handler: H): Promise<FunctionReturnType<H[keyof H]>> {\n const { status, data, headers } = await promise;\n const statusHandler = (handler as any)[status];\n if (statusHandler) return statusHandler(data);\n if (handler.default) return handler.default(status, data);\n throw new HttpError(status, data, headers);\n}\n\nexport const SUCCESS_CODES = [200, 201, 202, 204] as const;\nexport type SuccessCodes = (typeof SUCCESS_CODES)[number];\n\nexport type SuccessResponse<T extends ApiResponse> = DataType<T, SuccessCodes>;\n\n/**\n * Utility function to directly return any successful response\n * and throw a HttpError otherwise.\n *\n * Example:\n *\n * try {\n * const userId = await ok(api.register({ email, password }));\n * }\n * catch (err) {\n * console.log(err.status)\n * }\n */\nexport async function ok<T extends WithHeaders<ApiResponse>>(\n promise: Promise<T>,\n): Promise<SuccessResponse<T>> {\n const res = await promise;\n if (SUCCESS_CODES.some((s) => s == res.status)) return res.data;\n throw new HttpError(res.status, res.data, res.headers);\n}\n\nexport type Args<T> = T extends (...args: infer U) => any ? U : any;\nexport type ApiFunction = (...args: any[]) => Promise<WithHeaders<ApiResponse>>;\nexport type AsyncReturnType<T> = T extends (...args: any[]) => Promise<infer V>\n ? V\n : never;\n\nexport type OkResponse<T extends ApiFunction> = SuccessResponse<\n AsyncReturnType<T>\n>;\n\nexport type Okify<T extends ApiFunction> = (\n ...args: Args<T>\n) => Promise<OkResponse<T>>;\n\n/**\n * Utility function to wrap an API function with `ok(...)`.\n */\nexport function okify<T extends ApiFunction>(fn: T): Okify<T> {\n return (...args: Args<T>) => ok(fn(...args));\n}\n\ntype OptimisticApi<T> = {\n [K in keyof T]: T[K] extends ApiFunction ? Okify<T[K]> : T[K];\n};\n\n/**\n * Utility to `okify` each function of an API.\n */\nexport function optimistic<T extends Record<string, ApiFunction | unknown>>(\n api: T,\n): OptimisticApi<T> {\n const okApi: any = {};\n Object.entries(api).forEach(([key, value]) => {\n okApi[key] = typeof value === \"function\" ? okify(value as any) : value;\n });\n return okApi;\n}\n\nexport class HttpError extends Error {\n status: number;\n data?: any;\n headers: Headers;\n\n constructor(status: number, data: any, headers: Headers) {\n super(`Error: ${status}`);\n this.status = status;\n this.data = data;\n this.headers = headers;\n }\n}\n"],"names":["runtime","defaults","fetchText","url","req","res","doFetch","data","fetchJson","status","headers","contentType","mergeHeaders","fetchBlob","baseUrl","customFetch","init","href","joinUrl","ok","body","qs.form","normalizeHeaders","append","name","value","v","handle","promise","handler","statusHandler","HttpError","SUCCESS_CODES","s","okify","fn","args","optimistic","api","okApi","key"],"mappings":";;;AAwCgB,SAAAA,EAAQC,IAAwB,IAAI;AACnC,iBAAAC,EAAUC,GAAaC,GAAwB;AAC5D,UAAMC,IAAM,MAAMC,EAAQH,GAAKC,CAAG;AAC9B,QAAAG;AACA,QAAA;AACK,MAAAA,IAAA,MAAMF,EAAI;YACL;AAAA,IAAC;AAER,WAAA;AAAA,MACL,QAAQA,EAAI;AAAA,MACZ,SAASA,EAAI;AAAA,MACb,aAAaA,EAAI,QAAQ,IAAI,cAAc;AAAA,MAC3C,MAAAE;AAAA,IAAA;AAAA,EAEJ;AAEA,iBAAeC,EACbL,GACAC,IAAwB,IACxB;AACM,UAAA,EAAE,QAAAK,GAAQ,SAAAC,GAAS,aAAAC,GAAa,MAAAJ,MAAS,MAAML,EAAUC,GAAK;AAAA,MAClE,GAAGC;AAAA,MACH,SAASQ;AAAA,QACP;AAAA,UACE,QAAQ;AAAA,QACV;AAAA,QACAR,EAAI;AAAA,MACN;AAAA,IAAA,CACD;AAID,YAFeO,IAAcA,EAAY,SAAS,MAAM,IAAI,MAGnD;AAAA,MACL,QAAAF;AAA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;AAkBhD,eAAsBb,EACpBS,GAC6B;AAC7B,QAAMvB,IAAM,MAAMuB;AAClB,MAAII,EAAc,KAAK,CAACC,MAAMA,KAAK5B,EAAI,MAAM;AAAG,WAAOA,EAAI;AAC3D,QAAM,IAAI0B,EAAU1B,EAAI,QAAQA,EAAI,MAAMA,EAAI,OAAO;AACvD;AAmBO,SAAS6B,EAA6BC,GAAiB;AAC5D,SAAO,IAAIC,MAAkBjB,EAAGgB,EAAG,GAAGC,CAAI,CAAC;AAC7C;AASO,SAASC,EACdC,GACkB;AAClB,QAAMC,IAAa,CAAA;AACZ,gBAAA,QAAQD,CAAG,EAAE,QAAQ,CAAC,CAACE,GAAKf,CAAK,MAAM;AAC5C,IAAAc,EAAMC,CAAG,IAAI,OAAOf,KAAU,aAAaS,EAAMT,CAAY,IAAIA;AAAA,EAAA,CAClE,GACMc;AACT;AAEO,MAAMR,UAAkB,MAAM;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAYtB,GAAgBF,GAAWG,GAAkB;AACjD,UAAA,UAAUD,CAAM,EAAE,GACxB,KAAK,SAASA,GACd,KAAK,OAAOF,GACZ,KAAK,UAAUG;AAAA,EACjB;AACF;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/runtime.ts","../src/index.ts"],"sourcesContent":["import * as qs from \"./query\";\nimport { joinUrl } from \"./util\";\nimport { ok } from \"./index\";\nimport { CustomHeaders, mergeHeaders, normalizeHeaders } from \"./headers\";\n\nexport { type CustomHeaders };\n\nexport type RequestOpts = {\n baseUrl?: string;\n fetch?: typeof fetch;\n formDataConstructor?: new () => FormData;\n headers?: HeadersInit | CustomHeaders;\n} & Omit<RequestInit, \"body\" | \"headers\">;\n\nexport type Defaults<Headers extends RequestOpts[\"headers\"] = CustomHeaders> =\n Omit<RequestOpts, \"headers\" | \"baseUrl\"> & {\n baseUrl: string;\n headers: Headers;\n };\n\ntype FetchRequestOpts = RequestOpts & {\n body?: string | FormData | Blob;\n};\n\ntype JsonRequestOpts = RequestOpts & {\n body?: any;\n};\n\ntype FormRequestOpts = RequestOpts & {\n body?: Record<string, any>;\n};\n\nexport type ApiResponse = { status: number; data?: any };\n\nexport type WithHeaders<T extends ApiResponse> = T & { headers: Headers };\n\ntype MultipartRequestOpts = RequestOpts & {\n body?: Record<string, unknown>;\n};\n\nexport function runtime(defaults: RequestOpts = {}) {\n async function fetchText(url: string, req?: FetchRequestOpts) {\n const res = await doFetch(url, req);\n let data;\n try {\n data = await res.text();\n } catch (err) {}\n\n return {\n status: res.status,\n headers: res.headers,\n contentType: res.headers.get(\"content-type\"),\n data,\n };\n }\n\n async function fetchJson<T extends ApiResponse>(\n url: string,\n req: FetchRequestOpts = {},\n ) {\n const { status, headers, contentType, data } = await fetchText(url, {\n ...req,\n headers: mergeHeaders(\n {\n Accept: \"application/json\",\n },\n req.headers,\n ),\n });\n\n const isJson = contentType ? contentType.includes(\"json\") : false;\n\n if (isJson) {\n return {\n status,\n headers,\n data: data ? JSON.parse(data) : null,\n } as WithHeaders<T>;\n }\n\n return { status, headers, data } as WithHeaders<T>;\n }\n\n async function fetchBlob<T extends ApiResponse>(\n url: string,\n req: FetchRequestOpts = {},\n ) {\n const res = await doFetch(url, req);\n let data;\n try {\n data = await res.blob();\n } catch (err) {}\n return { status: res.status, headers: res.headers, data } as WithHeaders<T>;\n }\n\n async function doFetch(url: string, req: FetchRequestOpts = {}) {\n const {\n baseUrl,\n fetch: customFetch,\n ...init\n } = {\n ...defaults,\n ...req,\n headers: mergeHeaders(defaults.headers, req.headers),\n };\n const href = joinUrl(baseUrl, url);\n const res = await (customFetch || fetch)(href, init);\n return res;\n }\n\n return {\n ok,\n fetchText,\n fetchJson,\n fetchBlob,\n mergeHeaders,\n\n json({ body, headers, ...req }: JsonRequestOpts) {\n return {\n ...req,\n ...(body != null && { body: JSON.stringify(body) }),\n headers: mergeHeaders(\n {\n \"Content-Type\": \"application/json\",\n },\n headers,\n ),\n };\n },\n\n form({ body, headers, ...req }: FormRequestOpts) {\n return {\n ...req,\n ...(body != null && { body: qs.form(body) }),\n headers: mergeHeaders(\n {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n },\n headers,\n ),\n };\n },\n\n multipart({ body, headers, ...req }: MultipartRequestOpts) {\n if (body == null)\n return { ...req, body, headers: normalizeHeaders(headers) };\n\n const data = new (defaults.formDataConstructor ||\n req.formDataConstructor ||\n FormData)();\n\n const append = (name: string, value: unknown) => {\n if (typeof value === \"string\" || value instanceof Blob) {\n data.append(name, value);\n } else if (typeof value === \"number\") {\n data.append(name, String(value));\n } else {\n data.append(\n name,\n new Blob([JSON.stringify(value)], { type: \"application/json\" }),\n );\n }\n };\n\n Object.entries(body).forEach(([name, value]) => {\n if (Array.isArray(value)) {\n value.forEach((v) => append(name, v));\n } else {\n append(name, value);\n }\n });\n\n return {\n ...req,\n body: data,\n headers: normalizeHeaders(headers),\n };\n },\n };\n}\n","import type { ApiResponse, WithHeaders } from \"./runtime\";\n\nexport * from \"./runtime\";\n\n/**\n * Type to access a response's data property for a given status.\n */\nexport type DataType<T extends ApiResponse, S extends number> = T extends {\n status: S;\n}\n ? T[\"data\"]\n : never;\n\n/**\n * Object with methods to handle possible status codes of an ApiResponse.\n */\nexport type ResponseHandler<T extends ApiResponse> = {\n [P in T[\"status\"]]?: (res: DataType<T, P>) => any;\n} & {\n default?: (status: number, data: any) => any;\n};\n\nexport type FunctionReturnType<T> = T extends (...args: any[]) => any\n ? ReturnType<T>\n : never;\n\n/**\n * Utility function to handle different status codes.\n *\n * Example:\n *\n * const userId = await handle(api.register({ email, password }), {\n * 200: (user: User) => user.id,\n * 400: (err: string) => console.log(err),\n * })\n **/\nexport async function handle<\n T extends WithHeaders<ApiResponse>,\n H extends ResponseHandler<T>,\n>(promise: Promise<T>, handler: H): Promise<FunctionReturnType<H[keyof H]>> {\n const { status, data, headers } = await promise;\n const statusHandler = (handler as any)[status];\n if (statusHandler) return statusHandler(data);\n if (handler.default) return handler.default(status, data);\n throw new HttpError(status, data, headers);\n}\n\nexport const SUCCESS_CODES = [200, 201, 202, 204] as const;\nexport type SuccessCodes = (typeof SUCCESS_CODES)[number];\n\nexport type SuccessResponse<T extends ApiResponse> = DataType<T, SuccessCodes>;\n\n/**\n * Utility function to directly return any successful response\n * and throw a HttpError otherwise.\n *\n * Example:\n *\n * try {\n * const userId = await ok(api.register({ email, password }));\n * }\n * catch (err) {\n * console.log(err.status)\n * }\n */\nexport async function ok<T extends WithHeaders<ApiResponse>>(\n promise: Promise<T>,\n): Promise<SuccessResponse<T>> {\n const res = await promise;\n if (SUCCESS_CODES.some((s) => s == res.status)) return res.data;\n throw new HttpError(res.status, res.data, res.headers);\n}\n\nexport type Args<T> = T extends (...args: infer U) => any ? U : any;\nexport type ApiFunction = (...args: any[]) => Promise<WithHeaders<ApiResponse>>;\nexport type AsyncReturnType<T> = T extends (...args: any[]) => Promise<infer V>\n ? V\n : never;\n\nexport type OkResponse<T extends ApiFunction> = SuccessResponse<\n AsyncReturnType<T>\n>;\n\nexport type Okify<T extends ApiFunction> = (\n ...args: Args<T>\n) => Promise<OkResponse<T>>;\n\n/**\n * Utility function to wrap an API function with `ok(...)`.\n */\nexport function okify<T extends ApiFunction>(fn: T): Okify<T> {\n return (...args: Args<T>) => ok(fn(...args));\n}\n\ntype OptimisticApi<T> = {\n [K in keyof T]: T[K] extends ApiFunction ? Okify<T[K]> : T[K];\n};\n\n/**\n * Utility to `okify` each function of an API.\n */\nexport function optimistic<T extends Record<string, ApiFunction | unknown>>(\n api: T,\n): OptimisticApi<T> {\n const okApi: any = {};\n Object.entries(api).forEach(([key, value]) => {\n okApi[key] = typeof value === \"function\" ? okify(value as any) : value;\n });\n return okApi;\n}\n\nexport class HttpError extends Error {\n status: number;\n data?: any;\n headers: Headers;\n\n constructor(status: number, data: any, headers: Headers) {\n super(`Error: ${status}`);\n this.status = status;\n this.data = data;\n this.headers = headers;\n }\n}\n"],"names":["runtime","defaults","fetchText","url","req","res","doFetch","data","fetchJson","status","headers","contentType","mergeHeaders","fetchBlob","baseUrl","customFetch","init","href","joinUrl","ok","body","qs.form","normalizeHeaders","append","name","value","v","handle","promise","handler","statusHandler","HttpError","SUCCESS_CODES","s","okify","fn","args","optimistic","api","okApi","key"],"mappings":";;;AAwCgB,SAAAA,EAAQC,IAAwB,IAAI;AACnC,iBAAAC,EAAUC,GAAaC,GAAwB;AAC5D,UAAMC,IAAM,MAAMC,EAAQH,GAAKC,CAAG;AAC9B,QAAAG;AACA,QAAA;AACK,MAAAA,IAAA,MAAMF,EAAI;YACL;AAAA,IAAC;AAER,WAAA;AAAA,MACL,QAAQA,EAAI;AAAA,MACZ,SAASA,EAAI;AAAA,MACb,aAAaA,EAAI,QAAQ,IAAI,cAAc;AAAA,MAC3C,MAAAE;AAAA,IAAA;AAAA,EAEJ;AAEA,iBAAeC,EACbL,GACAC,IAAwB,IACxB;AACM,UAAA,EAAE,QAAAK,GAAQ,SAAAC,GAAS,aAAAC,GAAa,MAAAJ,MAAS,MAAML,EAAUC,GAAK;AAAA,MAClE,GAAGC;AAAA,MACH,SAASQ;AAAA,QACP;AAAA,UACE,QAAQ;AAAA,QACV;AAAA,QACAR,EAAI;AAAA,MACN;AAAA,IAAA,CACD;AAID,YAFeO,IAAcA,EAAY,SAAS,MAAM,IAAI,MAGnD;AAAA,MACL,QAAAF;AAAA,MACA,SAAAC;AAAA,MACA,MAAMH,IAAO,KAAK,MAAMA,CAAI,IAAI;AAAA,IAAA,IAI7B,EAAE,QAAAE,GAAQ,SAAAC,GAAS,MAAAH;EAC5B;AAEA,iBAAeM,EACbV,GACAC,IAAwB,IACxB;AACA,UAAMC,IAAM,MAAMC,EAAQH,GAAKC,CAAG;AAC9B,QAAAG;AACA,QAAA;AACK,MAAAA,IAAA,MAAMF,EAAI;YACL;AAAA,IAAC;AACf,WAAO,EAAE,QAAQA,EAAI,QAAQ,SAASA,EAAI,SAAS,MAAAE;EACrD;AAEA,iBAAeD,EAAQH,GAAaC,IAAwB,IAAI;AACx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kB;AAClB,QAAMC,IAAa,CAAA;AACZ,gBAAA,QAAQD,CAAG,EAAE,QAAQ,CAAC,CAACE,GAAKf,CAAK,MAAM;AAC5C,IAAAc,EAAMC,CAAG,IAAI,OAAOf,KAAU,aAAaS,EAAMT,CAAY,IAAIA;AAAA,EAAA,CAClE,GACMc;AACT;AAEO,MAAMR,UAAkB,MAAM;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAYtB,GAAgBF,GAAWG,GAAkB;AACjD,UAAA,UAAUD,CAAM,EAAE,GACxB,KAAK,SAASA,GACd,KAAK,OAAOF,GACZ,KAAK,UAAUG;AAAA,EACjB;AACF;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oazapfts/runtime",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.3",
|
|
4
4
|
"description": "Runtime for OpenApi TypeScript client generator",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.cjs",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"directory": "packages/runtime"
|
|
35
35
|
},
|
|
36
36
|
"scripts": {
|
|
37
|
-
"build": "rm -rf dist &&
|
|
37
|
+
"build": "rm -rf dist && vite build --mode esm && vite build --mode cjs",
|
|
38
38
|
"prepack": "sed -i 's|||g' package.json && mv * ."
|
|
39
39
|
},
|
|
40
40
|
"release": {
|
package/query.d.ts
CHANGED
|
@@ -1,20 +1,28 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
*
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
export declare function json(params: Record<string, any>, encoders?: (typeof encodeURIComponent)[]): string;
|
|
18
|
-
|
|
19
|
-
export declare const pipe: (params: Record<string, any>, encoders?: (typeof encodeURIComponent)[]) => string;
|
|
20
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Serializes nested objects according to the `deepObject` style specified in
|
|
3
|
+
* https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#style-values
|
|
4
|
+
*/
|
|
5
|
+
export declare function deep(params: Record<string, any>, [k, v]?: (typeof encodeURIComponent)[]): string;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Property values of type array or object generate separate parameters
|
|
9
|
+
* for each value of the array, or key-value-pair of the map.
|
|
10
|
+
* For other types of properties this property has no effect.
|
|
11
|
+
* See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#encoding-object
|
|
12
|
+
*/
|
|
13
|
+
export declare function explode(params: Record<string, any>, encoders?: (typeof encodeURIComponent)[]): string;
|
|
14
|
+
|
|
15
|
+
export declare const form: (params: Record<string, any>, encoders?: (typeof encodeURIComponent)[]) => string;
|
|
16
|
+
|
|
17
|
+
export declare function json(params: Record<string, any>, encoders?: (typeof encodeURIComponent)[]): string;
|
|
18
|
+
|
|
19
|
+
export declare const pipe: (params: Record<string, any>, encoders?: (typeof encodeURIComponent)[]) => string;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Join params using an ampersand and prepends a questionmark if not empty.
|
|
23
|
+
*/
|
|
24
|
+
export declare function query(...params: string[]): string;
|
|
25
|
+
|
|
26
|
+
export declare const space: (params: Record<string, any>, encoders?: (typeof encodeURIComponent)[]) => string;
|
|
27
|
+
|
|
28
|
+
export { }
|
package/util.d.ts
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
*
|
|
10
|
-
*/
|
|
11
|
-
export declare function
|
|
12
|
-
|
|
13
|
-
export
|
|
1
|
+
export declare const allowReserved: (typeof encodeURI)[];
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Separate array values by the given delimiter.
|
|
5
|
+
*/
|
|
6
|
+
export declare function delimited(delimiter?: string): (params: Record<string, any>, encoders?: (typeof encodeURIComponent)[]) => string;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Creates a tag-function to encode template strings with the given encoders.
|
|
10
|
+
*/
|
|
11
|
+
export declare function encode(encoders: Encoders, delimiter?: string): (strings: TemplateStringsArray, ...values: any[]) => string;
|
|
12
|
+
|
|
13
|
+
export declare const encodeReserved: (typeof encodeURIComponent)[];
|
|
14
|
+
|
|
15
|
+
declare type Encoders = Array<(s: string) => string>;
|
|
16
|
+
|
|
17
|
+
export declare function joinUrl(...parts: Array<string | undefined>): string;
|
|
18
|
+
|
|
19
|
+
export { }
|
package/runtime.d.ts
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
import { ok } from "./index";
|
|
2
|
-
import { CustomHeaders, mergeHeaders } from "./headers";
|
|
3
|
-
export { type CustomHeaders };
|
|
4
|
-
export type RequestOpts = {
|
|
5
|
-
baseUrl?: string;
|
|
6
|
-
fetch?: typeof fetch;
|
|
7
|
-
formDataConstructor?: new () => FormData;
|
|
8
|
-
headers?: HeadersInit | CustomHeaders;
|
|
9
|
-
} & Omit<RequestInit, "body" | "headers">;
|
|
10
|
-
export type Defaults<Headers extends RequestOpts["headers"] = CustomHeaders> = Omit<RequestOpts, "headers" | "baseUrl"> & {
|
|
11
|
-
baseUrl: string;
|
|
12
|
-
headers: Headers;
|
|
13
|
-
};
|
|
14
|
-
type FetchRequestOpts = RequestOpts & {
|
|
15
|
-
body?: string | FormData | Blob;
|
|
16
|
-
};
|
|
17
|
-
type JsonRequestOpts = RequestOpts & {
|
|
18
|
-
body?: any;
|
|
19
|
-
};
|
|
20
|
-
type FormRequestOpts = RequestOpts & {
|
|
21
|
-
body?: Record<string, any>;
|
|
22
|
-
};
|
|
23
|
-
export type ApiResponse = {
|
|
24
|
-
status: number;
|
|
25
|
-
data?: any;
|
|
26
|
-
};
|
|
27
|
-
export type WithHeaders<T extends ApiResponse> = T & {
|
|
28
|
-
headers: Headers;
|
|
29
|
-
};
|
|
30
|
-
type MultipartRequestOpts = RequestOpts & {
|
|
31
|
-
body?: Record<string, unknown>;
|
|
32
|
-
};
|
|
33
|
-
export declare function runtime(defaults?: RequestOpts): {
|
|
34
|
-
ok: typeof ok;
|
|
35
|
-
fetchText: (url: string, req?: FetchRequestOpts) => Promise<{
|
|
36
|
-
status: number;
|
|
37
|
-
headers: Headers;
|
|
38
|
-
contentType: string | null;
|
|
39
|
-
data: string | undefined;
|
|
40
|
-
}>;
|
|
41
|
-
fetchJson: <T extends ApiResponse>(url: string, req?: FetchRequestOpts) => Promise<WithHeaders<T>>;
|
|
42
|
-
fetchBlob: <T_1 extends ApiResponse>(url: string, req?: FetchRequestOpts) => Promise<WithHeaders<T_1>>;
|
|
43
|
-
mergeHeaders: typeof mergeHeaders;
|
|
44
|
-
json({ body, headers, ...req }: JsonRequestOpts): {
|
|
45
|
-
headers: Headers;
|
|
46
|
-
body?: string | undefined;
|
|
47
|
-
baseUrl?: string | undefined;
|
|
48
|
-
fetch?: typeof fetch | undefined;
|
|
49
|
-
formDataConstructor?: (new () => FormData) | undefined;
|
|
50
|
-
cache?: RequestCache | undefined;
|
|
51
|
-
credentials?: RequestCredentials | undefined;
|
|
52
|
-
integrity?: string | undefined;
|
|
53
|
-
keepalive?: boolean | undefined;
|
|
54
|
-
method?: string | undefined;
|
|
55
|
-
mode?: RequestMode | undefined;
|
|
56
|
-
redirect?: RequestRedirect | undefined;
|
|
57
|
-
referrer?: string | undefined;
|
|
58
|
-
referrerPolicy?: ReferrerPolicy | undefined;
|
|
59
|
-
signal?: AbortSignal | null | undefined;
|
|
60
|
-
window?: null | undefined;
|
|
61
|
-
};
|
|
62
|
-
form({ body, headers, ...req }: FormRequestOpts): {
|
|
63
|
-
headers: Headers;
|
|
64
|
-
body?: string | undefined;
|
|
65
|
-
baseUrl?: string | undefined;
|
|
66
|
-
fetch?: typeof fetch | undefined;
|
|
67
|
-
formDataConstructor?: (new () => FormData) | undefined;
|
|
68
|
-
cache?: RequestCache | undefined;
|
|
69
|
-
credentials?: RequestCredentials | undefined;
|
|
70
|
-
integrity?: string | undefined;
|
|
71
|
-
keepalive?: boolean | undefined;
|
|
72
|
-
method?: string | undefined;
|
|
73
|
-
mode?: RequestMode | undefined;
|
|
74
|
-
redirect?: RequestRedirect | undefined;
|
|
75
|
-
referrer?: string | undefined;
|
|
76
|
-
referrerPolicy?: ReferrerPolicy | undefined;
|
|
77
|
-
signal?: AbortSignal | null | undefined;
|
|
78
|
-
window?: null | undefined;
|
|
79
|
-
};
|
|
80
|
-
multipart({ body, headers, ...req }: MultipartRequestOpts): {
|
|
81
|
-
body: undefined;
|
|
82
|
-
headers: Headers;
|
|
83
|
-
baseUrl?: string | undefined;
|
|
84
|
-
fetch?: typeof fetch | undefined;
|
|
85
|
-
formDataConstructor?: (new () => FormData) | undefined;
|
|
86
|
-
cache?: RequestCache | undefined;
|
|
87
|
-
credentials?: RequestCredentials | undefined;
|
|
88
|
-
integrity?: string | undefined;
|
|
89
|
-
keepalive?: boolean | undefined;
|
|
90
|
-
method?: string | undefined;
|
|
91
|
-
mode?: RequestMode | undefined;
|
|
92
|
-
redirect?: RequestRedirect | undefined;
|
|
93
|
-
referrer?: string | undefined;
|
|
94
|
-
referrerPolicy?: ReferrerPolicy | undefined;
|
|
95
|
-
signal?: AbortSignal | null | undefined;
|
|
96
|
-
window?: null | undefined;
|
|
97
|
-
} | {
|
|
98
|
-
body: FormData;
|
|
99
|
-
headers: Headers;
|
|
100
|
-
baseUrl?: string | undefined;
|
|
101
|
-
fetch?: typeof fetch | undefined;
|
|
102
|
-
formDataConstructor?: (new () => FormData) | undefined;
|
|
103
|
-
cache?: RequestCache | undefined;
|
|
104
|
-
credentials?: RequestCredentials | undefined;
|
|
105
|
-
integrity?: string | undefined;
|
|
106
|
-
keepalive?: boolean | undefined;
|
|
107
|
-
method?: string | undefined;
|
|
108
|
-
mode?: RequestMode | undefined;
|
|
109
|
-
redirect?: RequestRedirect | undefined;
|
|
110
|
-
referrer?: string | undefined;
|
|
111
|
-
referrerPolicy?: ReferrerPolicy | undefined;
|
|
112
|
-
signal?: AbortSignal | null | undefined;
|
|
113
|
-
window?: null | undefined;
|
|
114
|
-
};
|
|
115
|
-
};
|