tempest-react-sdk 0.49.0 → 0.51.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/dist/audio/sfx-pool.cjs +1 -1
- package/dist/audio/sfx-pool.cjs.map +1 -1
- package/dist/audio/sfx-pool.js +36 -36
- package/dist/audio/sfx-pool.js.map +1 -1
- package/dist/components/BarList/BarList.cjs +1 -1
- package/dist/components/BarList/BarList.cjs.map +1 -1
- package/dist/components/BarList/BarList.js +6 -1
- package/dist/components/BarList/BarList.js.map +1 -1
- package/dist/components/BarList/bar-list-model.cjs +1 -1
- package/dist/components/BarList/bar-list-model.cjs.map +1 -1
- package/dist/components/BarList/bar-list-model.js +8 -8
- package/dist/components/BarList/bar-list-model.js.map +1 -1
- package/dist/components/DataTable/DataTable.cjs +1 -1
- package/dist/components/DataTable/DataTable.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.js +112 -110
- package/dist/components/DataTable/DataTable.js.map +1 -1
- package/dist/components/DataTable/use-dev-warnings.cjs +1 -1
- package/dist/components/DataTable/use-dev-warnings.cjs.map +1 -1
- package/dist/components/DataTable/use-dev-warnings.js +5 -3
- package/dist/components/DataTable/use-dev-warnings.js.map +1 -1
- package/dist/components/Markdown/markdown-parse.cjs +5 -5
- package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
- package/dist/components/Markdown/markdown-parse.js +66 -63
- package/dist/components/Markdown/markdown-parse.js.map +1 -1
- package/dist/components/Sidebar/Sidebar.cjs +1 -1
- package/dist/components/Sidebar/Sidebar.cjs.map +1 -1
- package/dist/components/Sidebar/Sidebar.js +25 -45
- package/dist/components/Sidebar/Sidebar.js.map +1 -1
- package/dist/components/Sidebar/Sidebar.module.cjs.map +1 -1
- package/dist/components/Sidebar/Sidebar.module.js.map +1 -1
- package/dist/components/Sidebar/SidebarEntry.cjs +2 -0
- package/dist/components/Sidebar/SidebarEntry.cjs.map +1 -0
- package/dist/components/Sidebar/SidebarEntry.js +40 -0
- package/dist/components/Sidebar/SidebarEntry.js.map +1 -0
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +84 -71
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +112 -104
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/timeout.cjs +2 -0
- package/dist/http/timeout.cjs.map +1 -0
- package/dist/http/timeout.js +22 -0
- package/dist/http/timeout.js.map +1 -0
- package/dist/icons/material-symbols.cjs.map +1 -1
- package/dist/icons/material-symbols.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/tempest-react-sdk.d.ts +104 -18
- package/dist/utils/csv.cjs.map +1 -1
- package/dist/utils/csv.js.map +1 -1
- package/dist/vite/tempest-pwa-dev-sw.cjs +1 -1
- package/dist/vite/tempest-pwa-dev-sw.cjs.map +1 -1
- package/dist/vite/tempest-pwa-dev-sw.js +49 -41
- package/dist/vite/tempest-pwa-dev-sw.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Sidebar.module.js","names":[],"sources":["../../../src/components/Sidebar/Sidebar.module.css"],"sourcesContent":[".sidebar {\n display: flex;\n flex-direction: column;\n height: 100%;\n background: var(--tempest-surface);\n border-right: 1px solid var(--tempest-border);\n font-family: var(--tempest-font-sans);\n transition: width var(--tempest-duration-base, 200ms) var(--tempest-ease-out, ease-out);\n overflow: hidden;\n}\n\n.header {\n padding: var(--tempest-space-3) var(--tempest-space-4);\n border-bottom: 1px solid var(--tempest-border);\n min-height: 56px;\n display: flex;\n align-items: center;\n}\n\n.nav {\n flex: 1 1 auto;\n overflow-y: auto;\n padding: var(--tempest-space-2);\n display: flex;\n flex-direction: column;\n gap: 2px;\n}\n\n.group {\n display: flex;\n flex-direction: column;\n gap: 2px;\n}\n\n.group + .group {\n margin-top: var(--tempest-space-3);\n}\n\n.collapsed .group + .group {\n margin-top: var(--tempest-space-2);\n padding-top: var(--tempest-space-2);\n border-top: 1px solid var(--tempest-border);\n}\n\n.section {\n padding: var(--tempest-space-2) var(--tempest-space-3) var(--tempest-space-1);\n color: var(--tempest-text-muted);\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-semibold);\n letter-spacing: 0.04em;\n text-transform: uppercase;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.sectionCollapsed {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip-path: inset(50%);\n white-space: nowrap;\n border: 0;\n}\n\n.separator {\n flex: 0 0 auto;\n margin: var(--tempest-space-2) var(--tempest-space-1);\n border: 0;\n border-top: 1px solid var(--tempest-border);\n}\n\n.item {\n display: flex;\n align-items: center;\n gap: var(--tempest-space-3);\n padding: var(--tempest-space-2) var(--tempest-space-3);\n background: none;\n border: 0;\n border-radius: var(--tempest-radius-md);\n color: var(--tempest-text);\n font-size: var(--tempest-text-sm);\n text-align: left;\n cursor: pointer;\n transition: background var(--tempest-duration-fast, 120ms);\n min-height: 36px;\n width: 100%;\n}\n\n.collapsed .item {\n justify-content: center;\n padding-left: 0;\n padding-right: 0;\n}\n\n.item
|
|
1
|
+
{"version":3,"file":"Sidebar.module.js","names":[],"sources":["../../../src/components/Sidebar/Sidebar.module.css"],"sourcesContent":[".sidebar {\n display: flex;\n flex-direction: column;\n height: 100%;\n background: var(--tempest-surface);\n border-right: 1px solid var(--tempest-border);\n font-family: var(--tempest-font-sans);\n transition: width var(--tempest-duration-base, 200ms) var(--tempest-ease-out, ease-out);\n overflow: hidden;\n}\n\n.header {\n padding: var(--tempest-space-3) var(--tempest-space-4);\n border-bottom: 1px solid var(--tempest-border);\n min-height: 56px;\n display: flex;\n align-items: center;\n}\n\n.nav {\n flex: 1 1 auto;\n overflow-y: auto;\n padding: var(--tempest-space-2);\n display: flex;\n flex-direction: column;\n gap: 2px;\n}\n\n.group {\n display: flex;\n flex-direction: column;\n gap: 2px;\n}\n\n.group + .group {\n margin-top: var(--tempest-space-3);\n}\n\n.collapsed .group + .group {\n margin-top: var(--tempest-space-2);\n padding-top: var(--tempest-space-2);\n border-top: 1px solid var(--tempest-border);\n}\n\n.section {\n padding: var(--tempest-space-2) var(--tempest-space-3) var(--tempest-space-1);\n color: var(--tempest-text-muted);\n font-size: var(--tempest-text-xs);\n font-weight: var(--tempest-weight-semibold);\n letter-spacing: 0.04em;\n text-transform: uppercase;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.sectionCollapsed {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip-path: inset(50%);\n white-space: nowrap;\n border: 0;\n}\n\n.separator {\n flex: 0 0 auto;\n margin: var(--tempest-space-2) var(--tempest-space-1);\n border: 0;\n border-top: 1px solid var(--tempest-border);\n}\n\n.item {\n display: flex;\n align-items: center;\n gap: var(--tempest-space-3);\n padding: var(--tempest-space-2) var(--tempest-space-3);\n background: none;\n border: 0;\n border-radius: var(--tempest-radius-md);\n color: var(--tempest-text);\n font-size: var(--tempest-text-sm);\n text-align: left;\n cursor: pointer;\n transition: background var(--tempest-duration-fast, 120ms);\n min-height: 36px;\n width: 100%;\n text-decoration: none;\n}\n\n.collapsed .item {\n justify-content: center;\n padding-left: 0;\n padding-right: 0;\n}\n\n.item:hover {\n background: var(--tempest-gray-100);\n}\n\n.item.active {\n background: var(--tempest-primary-100);\n color: var(--tempest-primary-700);\n font-weight: var(--tempest-weight-medium);\n}\n\n.item:disabled {\n opacity: 0.4;\n cursor: not-allowed;\n}\n\n.icon {\n display: inline-flex;\n align-items: center;\n font-size: 18px;\n line-height: 1;\n flex: 0 0 auto;\n}\n\n.label {\n flex: 1 1 auto;\n min-width: 0;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n.badge {\n flex: 0 0 auto;\n min-width: 18px;\n height: 18px;\n padding: 0 6px;\n border-radius: var(--tempest-radius-full);\n background: var(--tempest-gray-200);\n color: var(--tempest-text);\n font-size: 10px;\n line-height: 18px;\n text-align: center;\n}\n\n.footer {\n padding: var(--tempest-space-3) var(--tempest-space-4);\n border-top: 1px solid var(--tempest-border);\n}\n"],"mappings":""}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../utils/cn.cjs"),t=require("./Sidebar.module.cjs");let n=require("react/jsx-runtime");function r({item:r,active:i,collapsed:a,onSelect:o}){let s=a&&typeof r.label==`string`?r.label:void 0,c=(0,n.jsxs)(n.Fragment,{children:[r.icon&&(0,n.jsx)(`span`,{className:t.default.icon,children:r.icon}),!a&&(0,n.jsx)(`span`,{className:t.default.label,children:r.label}),!a&&r.badge!==void 0&&(0,n.jsx)(`span`,{className:t.default.badge,children:r.badge})]});return r.href&&!r.disabled?(0,n.jsx)(`a`,{href:r.href,className:e.cn(t.default.item,i&&t.default.active),"aria-current":i?`page`:void 0,onClick:()=>o?.(r.key),title:s,children:c}):(0,n.jsx)(`button`,{type:`button`,className:e.cn(t.default.item,i&&t.default.active),"aria-current":i?`page`:void 0,disabled:r.disabled,onClick:()=>o?.(r.key),title:s,children:c})}exports.SidebarEntry=r;
|
|
2
|
+
//# sourceMappingURL=SidebarEntry.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SidebarEntry.cjs","names":[],"sources":["../../../src/components/Sidebar/SidebarEntry.tsx"],"sourcesContent":["import { cn } from \"@/utils/cn\";\n\nimport type { SidebarItem } from \"./Sidebar\";\nimport styles from \"./Sidebar.module.css\";\n\n/**\n * One navigation entry: an anchor when it carries an `href`, a button otherwise.\n *\n * A link that navigates has to be a link — middle-click, \"open in new tab\" and\n * the status bar preview all come from the element, not from the handler. A\n * disabled entry falls back to the button, because a disabled anchor does not\n * exist in HTML.\n */\nexport function SidebarEntry({\n item,\n active,\n collapsed,\n onSelect,\n}: {\n item: SidebarItem;\n active: boolean;\n collapsed: boolean;\n onSelect?: (key: string) => void;\n}) {\n const title = collapsed && typeof item.label === \"string\" ? item.label : undefined;\n const body = (\n <>\n {item.icon && <span className={styles.icon}>{item.icon}</span>}\n {!collapsed && <span className={styles.label}>{item.label}</span>}\n {!collapsed && item.badge !== undefined && (\n <span className={styles.badge}>{item.badge}</span>\n )}\n </>\n );\n\n if (item.href && !item.disabled) {\n return (\n <a\n href={item.href}\n className={cn(styles.item, active && styles.active)}\n aria-current={active ? \"page\" : undefined}\n onClick={() => onSelect?.(item.key)}\n title={title}\n >\n {body}\n </a>\n );\n }\n\n return (\n <button\n type=\"button\"\n className={cn(styles.item, active && styles.active)}\n aria-current={active ? \"page\" : undefined}\n disabled={item.disabled}\n onClick={() => onSelect?.(item.key)}\n title={title}\n >\n {body}\n </button>\n );\n}\n"],"mappings":"2GAaA,SAAgB,EAAa,CACzB,OACA,SACA,YACA,YAMD,CACC,IAAM,EAAQ,GAAa,OAAO,EAAK,OAAU,SAAW,EAAK,MAAQ,IAAA,GACnE,GACF,EAAA,EAAA,KAAA,CAAA,EAAA,SAAA,CAAA,SAAA,CACK,EAAK,OAAQ,EAAA,EAAA,IAAA,CAAC,OAAD,CAAM,UAAW,EAAA,QAAO,KAAO,SAAA,EAAK,IAAW,CAAA,EAC5D,CAAC,IAAa,EAAA,EAAA,IAAA,CAAC,OAAD,CAAM,UAAW,EAAA,QAAO,MAAQ,SAAA,EAAK,KAAY,CAAA,EAC/D,CAAC,GAAa,EAAK,QAAU,IAAA,KAC1B,EAAA,EAAA,IAAA,CAAC,OAAD,CAAM,UAAW,EAAA,QAAO,MAAQ,SAAA,EAAK,KAAY,CAAA,CAEvD,CAAA,CAAA,EAiBN,OAdI,EAAK,MAAQ,CAAC,EAAK,UAEf,EAAA,EAAA,IAAA,CAAC,IAAD,CACI,KAAM,EAAK,KACX,UAAW,EAAA,GAAG,EAAA,QAAO,KAAM,GAAU,EAAA,QAAO,MAAM,EAClD,eAAc,EAAS,OAAS,IAAA,GAChC,YAAe,IAAW,EAAK,GAAG,EAC3B,QAEN,SAAA,CACF,CAAA,GAKP,EAAA,EAAA,IAAA,CAAC,SAAD,CACI,KAAK,SACL,UAAW,EAAA,GAAG,EAAA,QAAO,KAAM,GAAU,EAAA,QAAO,MAAM,EAClD,eAAc,EAAS,OAAS,IAAA,GAChC,SAAU,EAAK,SACf,YAAe,IAAW,EAAK,GAAG,EAC3B,QAEN,SAAA,CACG,CAAA,CAEhB"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { cn as e } from "../../utils/cn.js";
|
|
2
|
+
import t from "./Sidebar.module.js";
|
|
3
|
+
import { Fragment as n, jsx as r, jsxs as i } from "react/jsx-runtime";
|
|
4
|
+
//#region src/components/Sidebar/SidebarEntry.tsx
|
|
5
|
+
function a({ item: a, active: o, collapsed: s, onSelect: c }) {
|
|
6
|
+
let l = s && typeof a.label == "string" ? a.label : void 0, u = /* @__PURE__ */ i(n, { children: [
|
|
7
|
+
a.icon && /* @__PURE__ */ r("span", {
|
|
8
|
+
className: t.icon,
|
|
9
|
+
children: a.icon
|
|
10
|
+
}),
|
|
11
|
+
!s && /* @__PURE__ */ r("span", {
|
|
12
|
+
className: t.label,
|
|
13
|
+
children: a.label
|
|
14
|
+
}),
|
|
15
|
+
!s && a.badge !== void 0 && /* @__PURE__ */ r("span", {
|
|
16
|
+
className: t.badge,
|
|
17
|
+
children: a.badge
|
|
18
|
+
})
|
|
19
|
+
] });
|
|
20
|
+
return a.href && !a.disabled ? /* @__PURE__ */ r("a", {
|
|
21
|
+
href: a.href,
|
|
22
|
+
className: e(t.item, o && t.active),
|
|
23
|
+
"aria-current": o ? "page" : void 0,
|
|
24
|
+
onClick: () => c?.(a.key),
|
|
25
|
+
title: l,
|
|
26
|
+
children: u
|
|
27
|
+
}) : /* @__PURE__ */ r("button", {
|
|
28
|
+
type: "button",
|
|
29
|
+
className: e(t.item, o && t.active),
|
|
30
|
+
"aria-current": o ? "page" : void 0,
|
|
31
|
+
disabled: a.disabled,
|
|
32
|
+
onClick: () => c?.(a.key),
|
|
33
|
+
title: l,
|
|
34
|
+
children: u
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
export { a as SidebarEntry };
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=SidebarEntry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SidebarEntry.js","names":[],"sources":["../../../src/components/Sidebar/SidebarEntry.tsx"],"sourcesContent":["import { cn } from \"@/utils/cn\";\n\nimport type { SidebarItem } from \"./Sidebar\";\nimport styles from \"./Sidebar.module.css\";\n\n/**\n * One navigation entry: an anchor when it carries an `href`, a button otherwise.\n *\n * A link that navigates has to be a link — middle-click, \"open in new tab\" and\n * the status bar preview all come from the element, not from the handler. A\n * disabled entry falls back to the button, because a disabled anchor does not\n * exist in HTML.\n */\nexport function SidebarEntry({\n item,\n active,\n collapsed,\n onSelect,\n}: {\n item: SidebarItem;\n active: boolean;\n collapsed: boolean;\n onSelect?: (key: string) => void;\n}) {\n const title = collapsed && typeof item.label === \"string\" ? item.label : undefined;\n const body = (\n <>\n {item.icon && <span className={styles.icon}>{item.icon}</span>}\n {!collapsed && <span className={styles.label}>{item.label}</span>}\n {!collapsed && item.badge !== undefined && (\n <span className={styles.badge}>{item.badge}</span>\n )}\n </>\n );\n\n if (item.href && !item.disabled) {\n return (\n <a\n href={item.href}\n className={cn(styles.item, active && styles.active)}\n aria-current={active ? \"page\" : undefined}\n onClick={() => onSelect?.(item.key)}\n title={title}\n >\n {body}\n </a>\n );\n }\n\n return (\n <button\n type=\"button\"\n className={cn(styles.item, active && styles.active)}\n aria-current={active ? \"page\" : undefined}\n disabled={item.disabled}\n onClick={() => onSelect?.(item.key)}\n title={title}\n >\n {body}\n </button>\n );\n}\n"],"mappings":";;;;AAaA,SAAgB,EAAa,EACzB,SACA,WACA,cACA,eAMD;CACC,IAAM,IAAQ,KAAa,OAAO,EAAK,SAAU,WAAW,EAAK,QAAQ,KAAA,GACnE,IACF,kBAAA,GAAA,EAAA,UAAA;EACK,EAAK,QAAQ,kBAAC,QAAD;GAAM,WAAW,EAAO;GAAO,UAAA,EAAK;EAAW,CAAA;EAC5D,CAAC,KAAa,kBAAC,QAAD;GAAM,WAAW,EAAO;GAAQ,UAAA,EAAK;EAAY,CAAA;EAC/D,CAAC,KAAa,EAAK,UAAU,KAAA,KAC1B,kBAAC,QAAD;GAAM,WAAW,EAAO;GAAQ,UAAA,EAAK;EAAY,CAAA;CAEvD,EAAA,CAAA;CAiBN,OAdI,EAAK,QAAQ,CAAC,EAAK,WAEf,kBAAC,KAAD;EACI,MAAM,EAAK;EACX,WAAW,EAAG,EAAO,MAAM,KAAU,EAAO,MAAM;EAClD,gBAAc,IAAS,SAAS,KAAA;EAChC,eAAe,IAAW,EAAK,GAAG;EAC3B;EAEN,UAAA;CACF,CAAA,IAKP,kBAAC,UAAD;EACI,MAAK;EACL,WAAW,EAAG,EAAO,MAAM,KAAU,EAAO,MAAM;EAClD,gBAAc,IAAS,SAAS,KAAA;EAChC,UAAU,EAAK;EACf,eAAe,IAAW,EAAK,GAAG;EAC3B;EAEN,UAAA;CACG,CAAA;AAEhB"}
|
package/dist/http/api-client.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../utils/ids.cjs"),t=require("./build-url.cjs"),n=require("./errors.cjs"),r=require("./retry.cjs");var
|
|
1
|
+
const e=require("../utils/ids.cjs"),t=require("./build-url.cjs"),n=require("./errors.cjs"),r=require("./retry.cjs"),i=require("./timeout.cjs");var a=new Set([`GET`,`HEAD`,`OPTIONS`]);function o(e,t){return!a.has(t)||!(e instanceof n.TempestApiError)?!1:n.isRetriableStatus(e.status)}function s(e){return e?e===!0?{}:e:null}var c=15e3,l=3e5;function u(e){return typeof FormData<`u`&&e instanceof FormData}function d(e){return Math.round(performance.now()-e)}async function f(e,t){let r;try{r=await e.clone().json()}catch{try{r=await e.text()}catch{r=null}}return new n.TempestApiError(n.buildApiError(e.status,r,e.headers,t))}function p(a){let p=a.fetcher??globalThis.fetch.bind(globalThis);function m(){let e=a.getToken?.();return e?{Authorization:`Bearer ${e}`}:{}}async function h(e,r,o){let{body:s,params:d,headers:f,signal:h,timeout:g,..._}=r,v=u(s),y=v?a.uploadTimeout:a.timeout,b=g===void 0?y===void 0?v?l:c:y:g,x={...v?{}:{"Content-Type":`application/json`},...o?{"X-Request-ID":o}:{},...a.headers,...m(),...f},S=i.withTimeout(h,b),C={..._,signal:S.signal,headers:x,credentials:a.withCredentials?`include`:_.credentials,body:s==null?void 0:v?s:JSON.stringify(s)},w=t.buildApiUrl(a.baseURL,e,{prefix:a.prefix,params:d});try{return await p(w,C)}catch(e){throw S.timedOut()?new n.TempestApiError({status:0,detail:`A requisição excedeu ${b}ms e foi abandonada.`}):e}finally{S.dispose()}}async function g(e,t,n,r){let i=a.logger;if(!i)return h(e,t,n);let o=performance.now();try{let a=await h(e,t,n),s={requestId:n,status:a.status,ms:d(o)},c=`${r} ${e} → ${a.status}`;return a.status>=400?i.warn(c,s):i.debug(c,s),a}catch(t){throw i.warn(`${r} ${e} → no response`,{requestId:n,ms:d(o),error:t}),t}}async function _(e,t){if(a.onUnauthorized){a.logger?.warn(`unauthorized — calling onUnauthorized`,{requestId:t,status:e.status});try{await a.onUnauthorized(e)}catch(n){a.logger?.warn(`onUnauthorized threw — keeping the original response error`,{requestId:t,status:e.status,error:n})}}}async function v(t,n){let r=a.requestId?a.requestId():e.randomId(),i=(n.method??`GET`).toUpperCase(),o=await g(t,n,r,i);if(o.status===401){if(a.refresh){try{await a.refresh(),o=await g(t,n,r,i)}catch{throw await _(o,r),await f(o,r)}o.status===401&&await _(o,r)}else await _(o,r)}if(!o.ok)throw await f(o,r);if(o.status!==204)return(o.headers.get(`content-type`)??``).includes(`application/json`)?await o.json():await o.text()}async function y(e,t={}){let n=s(a.retry);if(!n)return v(e,t);let i=(t.method??`GET`).toUpperCase();return r.retry(()=>v(e,t),{...n,shouldRetry:n.shouldRetry??(e=>o(e,i))})}async function b(e,t,n=`POST`,r){return y(e,{...r,method:n,body:t})}return{request:y,get:(e,t)=>y(e,{...t,method:`GET`}),post:(e,t)=>y(e,{...t,method:`POST`}),put:(e,t)=>y(e,{...t,method:`PUT`}),patch:(e,t)=>y(e,{...t,method:`PATCH`}),delete:(e,t)=>y(e,{...t,method:`DELETE`}),upload:b}}exports.createApiClient=p;
|
|
2
2
|
//# sourceMappingURL=api-client.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-client.cjs","names":[],"sources":["../../src/http/api-client.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — createApiClient is over the limit and every line\n * is a request-lifecycle concern the client cannot delegate: base URL joining, the\n * auth header, the 401 refresh-and-replay, the opt-in retry wrapper and the response\n * parsing that turns a failure into a typed error.\n */\nimport { randomId } from \"../utils\";\nimport { buildApiUrl } from \"./build-url\";\nimport { buildApiError, TempestApiError, isRetriableStatus } from \"./errors\";\nimport { retry as retryWithBackoff } from \"./retry\";\nimport type { RetryOptions } from \"./retry\";\nimport type { ApiClient, ApiClientConfig, RequestOptions } from \"./types\";\n\n/**\n * Methods the built-in retry policy will replay.\n *\n * `PUT` and `DELETE` are idempotent on paper but stay out: a backend that logs,\n * bills, or fires a webhook per call still sees two, so replaying them is a\n * decision the caller makes through `shouldRetry`, not a default.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Sub-500 statuses worth a second attempt: a network failure (status `0`), a\n * request timeout, a too-early replay, and a rate limit — which usually carries\n * the `Retry-After` the backoff already honours.\n */\n\n/**\n * The built-in retry policy, used when `retry` is `true` or is options carrying\n * no `shouldRetry` of their own.\n *\n * Conservative on purpose. Replaying a write can duplicate it, and replaying a\n * `400` or a `403` cannot fix a bad payload or a permission the caller does not\n * have — it only spends the user's time before showing the same error.\n *\n * @param error - Whatever the attempt threw.\n * @param method - The upper-cased HTTP method of the request.\n * @returns Whether the client should try again.\n */\nfunction isRetriableFailure(error: unknown, method: string): boolean {\n if (!IDEMPOTENT_METHODS.has(method)) return false;\n if (!(error instanceof TempestApiError)) return false;\n return isRetriableStatus(error.status);\n}\n\n/**\n * Normalize the `retry` config into options, or `null` when retrying is off.\n *\n * @param config - The `retry` field as the caller wrote it.\n * @returns Retry options to use, or `null` to run a single attempt.\n */\nfunction resolveRetry(config: boolean | RetryOptions | undefined): RetryOptions | null {\n if (!config) return null;\n return config === true ? {} : config;\n}\n\nfunction isFormData(body: unknown): body is FormData {\n return typeof FormData !== \"undefined\" && body instanceof FormData;\n}\n\n/**\n * Milliseconds since a `performance.now()` reading, rounded.\n *\n * `performance.now()` rather than `Date.now()` because this measures a\n * duration: the wall clock can step sideways mid-request (an NTP correction, a\n * VM resuming, the user changing the clock) and turn a 40 ms call into a\n * negative number. The monotonic clock cannot.\n *\n * @param startedAt - The reading taken before the work started.\n * @returns Whole milliseconds elapsed.\n */\nfunction elapsedMs(startedAt: number): number {\n return Math.round(performance.now() - startedAt);\n}\n\nasync function parseError(response: Response, sentRequestId?: string): Promise<TempestApiError> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n try {\n body = await response.text();\n } catch {\n body = null;\n }\n }\n return new TempestApiError(\n buildApiError(response.status, body, response.headers, sentRequestId),\n );\n}\n\n/**\n * Create a typed HTTP client backed by `fetch`.\n *\n * Handles JSON serialization, query params, bearer auth via `getToken`, uploads\n * via `FormData`, and throws a typed `ApiError` on any non-2xx response.\n *\n * **Expired sessions.** A `401` with `refresh` configured awaits the refresh and\n * replays the request once. `onUnauthorized` fires whenever that path ends\n * unauthorized anyway — the refresh threw, or the replay came back `401` — which\n * is the signal to clear the session. Without `refresh`, the first `401` calls\n * it directly.\n *\n * **Retries** are off unless you set `retry`. See {@link ApiClientConfig.retry}\n * for the built-in policy; it never replays a write.\n *\n * **Logging** is off unless you pass a `logger`. With one, every finished attempt\n * writes a line — `debug` under 400, `warn` from 400 up, plus a `warn` when\n * `onUnauthorized` fires — carrying `requestId`, `status` and elapsed `ms`, and\n * never a body, header or query string. The level and the destination belong to\n * the logger, not to a boolean here.\n *\n * @example\n * const api = createApiClient({\n * baseURL: import.meta.env.VITE_API_URL,\n * getToken: () => useAuthStore.getState().token,\n * refresh,\n * onUnauthorized: () => useAuthStore.getState().logout(),\n * logger: createLogger({ level: import.meta.env.DEV ? \"debug\" : \"warn\" }).child(\"http\"),\n * retry: true,\n * });\n *\n * @param config - Base URL plus the optional auth, retry and fetch hooks.\n * @returns A client with `request`/`get`/`post`/`put`/`patch`/`delete`/`upload`.\n */\nexport function createApiClient(config: ApiClientConfig): ApiClient {\n const fetcher = config.fetcher ?? globalThis.fetch.bind(globalThis);\n\n function authHeaders(): Record<string, string> {\n const token = config.getToken?.();\n return token ? { Authorization: `Bearer ${token}` } : {};\n }\n\n async function rawRequest(\n path: string,\n options: RequestOptions,\n requestId?: string,\n ): Promise<Response> {\n const { body, params, headers, ...rest } = options;\n const isForm = isFormData(body);\n\n const finalHeaders: Record<string, string> = {\n ...(isForm ? {} : { \"Content-Type\": \"application/json\" }),\n ...(requestId ? { \"X-Request-ID\": requestId } : {}),\n ...config.headers,\n ...authHeaders(),\n ...(headers as Record<string, string> | undefined),\n };\n\n const init: RequestInit = {\n ...rest,\n headers: finalHeaders,\n credentials: config.withCredentials ? \"include\" : rest.credentials,\n body:\n body === undefined || body === null\n ? undefined\n : isForm\n ? (body as FormData)\n : JSON.stringify(body),\n };\n\n return fetcher(buildApiUrl(config.baseURL, path, { prefix: config.prefix, params }), init);\n }\n\n async function send(\n path: string,\n options: RequestOptions,\n requestId: string,\n method: string,\n ): Promise<Response> {\n const log = config.logger;\n if (!log) return rawRequest(path, options, requestId);\n\n const startedAt = performance.now();\n try {\n const response = await rawRequest(path, options, requestId);\n const entry = { requestId, status: response.status, ms: elapsedMs(startedAt) };\n const line = `${method} ${path} → ${response.status}`;\n if (response.status >= 400) log.warn(line, entry);\n else log.debug(line, entry);\n return response;\n } catch (error) {\n log.warn(`${method} ${path} → no response`, {\n requestId,\n ms: elapsedMs(startedAt),\n error,\n });\n throw error;\n }\n }\n\n async function notifyUnauthorized(response: Response, requestId: string): Promise<void> {\n if (!config.onUnauthorized) return;\n config.logger?.warn(`unauthorized — calling onUnauthorized`, {\n requestId,\n status: response.status,\n });\n try {\n await config.onUnauthorized(response);\n } catch (error) {\n config.logger?.warn(`onUnauthorized threw — keeping the original response error`, {\n requestId,\n status: response.status,\n error,\n });\n }\n }\n\n async function attempt<T>(path: string, options: RequestOptions): Promise<T> {\n const requestId = config.requestId ? config.requestId() : randomId();\n const method = (options.method ?? \"GET\").toUpperCase();\n let response = await send(path, options, requestId, method);\n\n if (response.status === 401) {\n if (config.refresh) {\n try {\n await config.refresh();\n response = await send(path, options, requestId, method);\n } catch {\n await notifyUnauthorized(response, requestId);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await notifyUnauthorized(response, requestId);\n }\n } else {\n await notifyUnauthorized(response, requestId);\n }\n }\n\n if (!response.ok) {\n throw await parseError(response, requestId);\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n return (await response.json()) as T;\n }\n return (await response.text()) as unknown as T;\n }\n\n async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n const retryOptions = resolveRetry(config.retry);\n if (!retryOptions) return attempt<T>(path, options);\n\n const method = (options.method ?? \"GET\").toUpperCase();\n return retryWithBackoff(() => attempt<T>(path, options), {\n ...retryOptions,\n shouldRetry:\n retryOptions.shouldRetry ?? ((error: unknown) => isRetriableFailure(error, method)),\n });\n }\n\n async function upload<T>(\n path: string,\n formData: FormData,\n method: \"POST\" | \"PUT\" | \"PATCH\" = \"POST\",\n ): Promise<T> {\n return request<T>(path, { method, body: formData });\n }\n\n return {\n request,\n get: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"GET\" }),\n post: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"POST\" }),\n put: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PUT\" }),\n patch: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PATCH\" }),\n delete: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"DELETE\" }),\n upload,\n };\n}\n"],"mappings":"oHAoBA,IAAM,EAA0C,IAAI,IAAI,CAAC,MAAO,OAAQ,SAAS,CAAC,EAoBlF,SAAS,EAAmB,EAAgB,EAAyB,CAGjE,MAFI,CAAC,EAAmB,IAAI,CAAM,GAC9B,EAAE,aAAiB,EAAA,iBAAyB,GACzC,EAAA,kBAAkB,EAAM,MAAM,CACzC,CAQA,SAAS,EAAa,EAAiE,CAEnF,OADK,EACE,IAAW,GAAO,CAAC,EAAI,EADV,IAExB,CAEA,SAAS,EAAW,EAAiC,CACjD,OAAO,OAAO,SAAa,KAAe,aAAgB,QAC9D,CAaA,SAAS,EAAU,EAA2B,CAC1C,OAAO,KAAK,MAAM,YAAY,IAAI,EAAI,CAAS,CACnD,CAEA,eAAe,EAAW,EAAoB,EAAkD,CAC5F,IAAI,EACJ,GAAI,CACA,EAAO,MAAM,EAAS,MAAM,CAAC,CAAC,KAAK,CACvC,MAAQ,CACJ,GAAI,CACA,EAAO,MAAM,EAAS,KAAK,CAC/B,MAAQ,CACJ,EAAO,IACX,CACJ,CACA,OAAO,IAAI,EAAA,gBACP,EAAA,cAAc,EAAS,OAAQ,EAAM,EAAS,QAAS,CAAa,CACxE,CACJ,CAoCA,SAAgB,EAAgB,EAAoC,CAChE,IAAM,EAAU,EAAO,SAAW,WAAW,MAAM,KAAK,UAAU,EAElE,SAAS,GAAsC,CAC3C,IAAM,EAAQ,EAAO,WAAW,EAChC,OAAO,EAAQ,CAAE,cAAe,UAAU,GAAQ,EAAI,CAAC,CAC3D,CAEA,eAAe,EACX,EACA,EACA,EAC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IACnB,EAAW,EAAM,CAAE,GAAG,EAAS,OAAQ,KAAM,CAAC,EAClD,MAAU,EAAc,IACpB,EAAW,EAAM,CAAE,GAAG,EAAS,OAAQ,MAAO,CAAC,EACnD,KAAS,EAAc,IACnB,EAAW,EAAM,CAAE,GAAG,EAAS,OAAQ,KAAM,CAAC,EAClD,OAAW,EAAc,IACrB,EAAW,EAAM,CAAE,GAAG,EAAS,OAAQ,OAAQ,CAAC,EACpD,QAAY,EAAc,IACtB,EAAW,EAAM,CAAE,GAAG,EAAS,OAAQ,QAAS,CAAC,EACrD,QACJ,CACJ"}
|
|
1
|
+
{"version":3,"file":"api-client.cjs","names":[],"sources":["../../src/http/api-client.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — createApiClient is over the limit and every line\n * is a request-lifecycle concern the client cannot delegate: base URL joining, the\n * auth header, the 401 refresh-and-replay, the opt-in retry wrapper and the response\n * parsing that turns a failure into a typed error.\n */\nimport { randomId } from \"../utils\";\nimport { buildApiUrl } from \"./build-url\";\nimport { buildApiError, TempestApiError, isRetriableStatus } from \"./errors\";\nimport { retry as retryWithBackoff } from \"./retry\";\nimport type { RetryOptions } from \"./retry\";\nimport { withTimeout } from \"./timeout\";\nimport type { ApiClient, ApiClientConfig, RequestOptions } from \"./types\";\n\n/**\n * Methods the built-in retry policy will replay.\n *\n * `PUT` and `DELETE` are idempotent on paper but stay out: a backend that logs,\n * bills, or fires a webhook per call still sees two, so replaying them is a\n * decision the caller makes through `shouldRetry`, not a default.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Sub-500 statuses worth a second attempt: a network failure (status `0`), a\n * request timeout, a too-early replay, and a rate limit — which usually carries\n * the `Retry-After` the backoff already honours.\n */\n\n/**\n * The built-in retry policy, used when `retry` is `true` or is options carrying\n * no `shouldRetry` of their own.\n *\n * Conservative on purpose. Replaying a write can duplicate it, and replaying a\n * `400` or a `403` cannot fix a bad payload or a permission the caller does not\n * have — it only spends the user's time before showing the same error.\n *\n * @param error - Whatever the attempt threw.\n * @param method - The upper-cased HTTP method of the request.\n * @returns Whether the client should try again.\n */\nfunction isRetriableFailure(error: unknown, method: string): boolean {\n if (!IDEMPOTENT_METHODS.has(method)) return false;\n if (!(error instanceof TempestApiError)) return false;\n return isRetriableStatus(error.status);\n}\n\n/**\n * Normalize the `retry` config into options, or `null` when retrying is off.\n *\n * @param config - The `retry` field as the caller wrote it.\n * @returns Retry options to use, or `null` to run a single attempt.\n */\nfunction resolveRetry(config: boolean | RetryOptions | undefined): RetryOptions | null {\n if (!config) return null;\n return config === true ? {} : config;\n}\n\n/** Default milliseconds before a request is abandoned. */\nconst DEFAULT_TIMEOUT = 15_000;\n\n/** Default milliseconds before a `FormData` request is abandoned. */\nconst DEFAULT_UPLOAD_TIMEOUT = 300_000;\n\nfunction isFormData(body: unknown): body is FormData {\n return typeof FormData !== \"undefined\" && body instanceof FormData;\n}\n\n/**\n * Milliseconds since a `performance.now()` reading, rounded.\n *\n * `performance.now()` rather than `Date.now()` because this measures a\n * duration: the wall clock can step sideways mid-request (an NTP correction, a\n * VM resuming, the user changing the clock) and turn a 40 ms call into a\n * negative number. The monotonic clock cannot.\n *\n * @param startedAt - The reading taken before the work started.\n * @returns Whole milliseconds elapsed.\n */\nfunction elapsedMs(startedAt: number): number {\n return Math.round(performance.now() - startedAt);\n}\n\nasync function parseError(response: Response, sentRequestId?: string): Promise<TempestApiError> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n try {\n body = await response.text();\n } catch {\n body = null;\n }\n }\n return new TempestApiError(\n buildApiError(response.status, body, response.headers, sentRequestId),\n );\n}\n\n/**\n * Create a typed HTTP client backed by `fetch`.\n *\n * Handles JSON serialization, query params, bearer auth via `getToken`, uploads\n * via `FormData`, and throws a typed `ApiError` on any non-2xx response.\n *\n * **Expired sessions.** A `401` with `refresh` configured awaits the refresh and\n * replays the request once. `onUnauthorized` fires whenever that path ends\n * unauthorized anyway — the refresh threw, or the replay came back `401` — which\n * is the signal to clear the session. Without `refresh`, the first `401` calls\n * it directly.\n *\n * **Retries** are off unless you set `retry`. See {@link ApiClientConfig.retry}\n * for the built-in policy; it never replays a write.\n *\n * **Logging** is off unless you pass a `logger`. With one, every finished attempt\n * writes a line — `debug` under 400, `warn` from 400 up, plus a `warn` when\n * `onUnauthorized` fires — carrying `requestId`, `status` and elapsed `ms`, and\n * never a body, header or query string. The level and the destination belong to\n * the logger, not to a boolean here.\n *\n * @example\n * const api = createApiClient({\n * baseURL: import.meta.env.VITE_API_URL,\n * getToken: () => useAuthStore.getState().token,\n * refresh,\n * onUnauthorized: () => useAuthStore.getState().logout(),\n * logger: createLogger({ level: import.meta.env.DEV ? \"debug\" : \"warn\" }).child(\"http\"),\n * retry: true,\n * });\n *\n * @param config - Base URL plus the optional auth, retry and fetch hooks.\n * @returns A client with `request`/`get`/`post`/`put`/`patch`/`delete`/`upload`.\n */\nexport function createApiClient(config: ApiClientConfig): ApiClient {\n const fetcher = config.fetcher ?? globalThis.fetch.bind(globalThis);\n\n function authHeaders(): Record<string, string> {\n const token = config.getToken?.();\n return token ? { Authorization: `Bearer ${token}` } : {};\n }\n\n async function rawRequest(\n path: string,\n options: RequestOptions,\n requestId?: string,\n ): Promise<Response> {\n const { body, params, headers, signal, timeout, ...rest } = options;\n const isForm = isFormData(body);\n const configured = isForm ? config.uploadTimeout : config.timeout;\n const fallback = isForm ? DEFAULT_UPLOAD_TIMEOUT : DEFAULT_TIMEOUT;\n const limit =\n timeout !== undefined ? timeout : configured !== undefined ? configured : fallback;\n\n const finalHeaders: Record<string, string> = {\n ...(isForm ? {} : { \"Content-Type\": \"application/json\" }),\n ...(requestId ? { \"X-Request-ID\": requestId } : {}),\n ...config.headers,\n ...authHeaders(),\n ...(headers as Record<string, string> | undefined),\n };\n\n const timed = withTimeout(signal, limit);\n const init: RequestInit = {\n ...rest,\n signal: timed.signal,\n headers: finalHeaders,\n credentials: config.withCredentials ? \"include\" : rest.credentials,\n body:\n body === undefined || body === null\n ? undefined\n : isForm\n ? (body as FormData)\n : JSON.stringify(body),\n };\n\n const url = buildApiUrl(config.baseURL, path, { prefix: config.prefix, params });\n try {\n return await fetcher(url, init);\n } catch (cause) {\n if (timed.timedOut()) {\n throw new TempestApiError({\n status: 0,\n detail: `A requisição excedeu ${limit}ms e foi abandonada.`,\n });\n }\n throw cause;\n } finally {\n timed.dispose();\n }\n }\n\n async function send(\n path: string,\n options: RequestOptions,\n requestId: string,\n method: string,\n ): Promise<Response> {\n const log = config.logger;\n if (!log) return rawRequest(path, options, requestId);\n\n const startedAt = performance.now();\n try {\n const response = await rawRequest(path, options, requestId);\n const entry = { requestId, status: response.status, ms: elapsedMs(startedAt) };\n const line = `${method} ${path} → ${response.status}`;\n if (response.status >= 400) log.warn(line, entry);\n else log.debug(line, entry);\n return response;\n } catch (error) {\n log.warn(`${method} ${path} → no response`, {\n requestId,\n ms: elapsedMs(startedAt),\n error,\n });\n throw error;\n }\n }\n\n async function notifyUnauthorized(response: Response, requestId: string): Promise<void> {\n if (!config.onUnauthorized) return;\n config.logger?.warn(`unauthorized — calling onUnauthorized`, {\n requestId,\n status: response.status,\n });\n try {\n await config.onUnauthorized(response);\n } catch (error) {\n config.logger?.warn(`onUnauthorized threw — keeping the original response error`, {\n requestId,\n status: response.status,\n error,\n });\n }\n }\n\n async function attempt<T>(path: string, options: RequestOptions): Promise<T> {\n const requestId = config.requestId ? config.requestId() : randomId();\n const method = (options.method ?? \"GET\").toUpperCase();\n let response = await send(path, options, requestId, method);\n\n if (response.status === 401) {\n if (config.refresh) {\n try {\n await config.refresh();\n response = await send(path, options, requestId, method);\n } catch {\n await notifyUnauthorized(response, requestId);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await notifyUnauthorized(response, requestId);\n }\n } else {\n await notifyUnauthorized(response, requestId);\n }\n }\n\n if (!response.ok) {\n throw await parseError(response, requestId);\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n return (await response.json()) as T;\n }\n return (await response.text()) as unknown as T;\n }\n\n async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n const retryOptions = resolveRetry(config.retry);\n if (!retryOptions) return attempt<T>(path, options);\n\n const method = (options.method ?? \"GET\").toUpperCase();\n return retryWithBackoff(() => attempt<T>(path, options), {\n ...retryOptions,\n shouldRetry:\n retryOptions.shouldRetry ?? ((error: unknown) => isRetriableFailure(error, method)),\n });\n }\n\n async function upload<T>(\n path: string,\n formData: FormData,\n method: \"POST\" | \"PUT\" | \"PATCH\" = \"POST\",\n options?: Omit<RequestOptions, \"body\" | \"method\">,\n ): Promise<T> {\n return request<T>(path, { ...options, method, body: formData });\n }\n\n return {\n request,\n get: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"GET\" }),\n post: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"POST\" }),\n put: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PUT\" }),\n patch: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PATCH\" }),\n delete: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"DELETE\" }),\n upload,\n };\n}\n"],"mappings":"+IAqBA,IAAM,EAA0C,IAAI,IAAI,CAAC,MAAO,OAAQ,SAAS,CAAC,EAoBlF,SAAS,EAAmB,EAAgB,EAAyB,CAGjE,MAFI,CAAC,EAAmB,IAAI,CAAM,GAC9B,EAAE,aAAiB,EAAA,iBAAyB,GACzC,EAAA,kBAAkB,EAAM,MAAM,CACzC,CAQA,SAAS,EAAa,EAAiE,CAEnF,OADK,EACE,IAAW,GAAO,CAAC,EAAI,EADV,IAExB,CAGA,IAAM,EAAkB,KAGlB,EAAyB,IAE/B,SAAS,EAAW,EAAiC,CACjD,OAAO,OAAO,SAAa,KAAe,aAAgB,QAC9D,CAaA,SAAS,EA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Q,OAAQ,CAAC,EACpD,QAAY,EAAc,IACtB,EAAW,EAAM,CAAE,GAAG,EAAS,OAAQ,QAAS,CAAC,EACrD,QACJ,CACJ"}
|
package/dist/http/api-client.js
CHANGED
|
@@ -2,25 +2,27 @@ import { randomId as e } from "../utils/ids.js";
|
|
|
2
2
|
import { buildApiUrl as t } from "./build-url.js";
|
|
3
3
|
import { TempestApiError as n, buildApiError as r, isRetriableStatus as i } from "./errors.js";
|
|
4
4
|
import { retry as a } from "./retry.js";
|
|
5
|
+
import { withTimeout as o } from "./timeout.js";
|
|
5
6
|
//#region src/http/api-client.ts
|
|
6
|
-
var
|
|
7
|
+
var s = /* @__PURE__ */ new Set([
|
|
7
8
|
"GET",
|
|
8
9
|
"HEAD",
|
|
9
10
|
"OPTIONS"
|
|
10
11
|
]);
|
|
11
|
-
function
|
|
12
|
-
return !
|
|
12
|
+
function c(e, t) {
|
|
13
|
+
return !s.has(t) || !(e instanceof n) ? !1 : i(e.status);
|
|
13
14
|
}
|
|
14
|
-
function
|
|
15
|
+
function l(e) {
|
|
15
16
|
return e ? e === !0 ? {} : e : null;
|
|
16
17
|
}
|
|
17
|
-
|
|
18
|
+
var u = 15e3, d = 3e5;
|
|
19
|
+
function f(e) {
|
|
18
20
|
return typeof FormData < "u" && e instanceof FormData;
|
|
19
21
|
}
|
|
20
|
-
function
|
|
22
|
+
function p(e) {
|
|
21
23
|
return Math.round(performance.now() - e);
|
|
22
24
|
}
|
|
23
|
-
async function
|
|
25
|
+
async function m(e, t) {
|
|
24
26
|
let i;
|
|
25
27
|
try {
|
|
26
28
|
i = await e.clone().json();
|
|
@@ -33,122 +35,133 @@ async function d(e, t) {
|
|
|
33
35
|
}
|
|
34
36
|
return new n(r(e.status, i, e.headers, t));
|
|
35
37
|
}
|
|
36
|
-
function
|
|
37
|
-
let
|
|
38
|
-
function
|
|
39
|
-
let e =
|
|
38
|
+
function h(r) {
|
|
39
|
+
let i = r.fetcher ?? globalThis.fetch.bind(globalThis);
|
|
40
|
+
function s() {
|
|
41
|
+
let e = r.getToken?.();
|
|
40
42
|
return e ? { Authorization: `Bearer ${e}` } : {};
|
|
41
43
|
}
|
|
42
|
-
async function
|
|
43
|
-
let { body:
|
|
44
|
-
...
|
|
45
|
-
...
|
|
46
|
-
...
|
|
47
|
-
...
|
|
48
|
-
...
|
|
49
|
-
},
|
|
50
|
-
...
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
prefix:
|
|
57
|
-
params:
|
|
58
|
-
})
|
|
44
|
+
async function h(e, a, c) {
|
|
45
|
+
let { body: l, params: p, headers: m, signal: h, timeout: g, ..._ } = a, v = f(l), y = v ? r.uploadTimeout : r.timeout, b = g === void 0 ? y === void 0 ? v ? d : u : y : g, x = {
|
|
46
|
+
...v ? {} : { "Content-Type": "application/json" },
|
|
47
|
+
...c ? { "X-Request-ID": c } : {},
|
|
48
|
+
...r.headers,
|
|
49
|
+
...s(),
|
|
50
|
+
...m
|
|
51
|
+
}, S = o(h, b), C = {
|
|
52
|
+
..._,
|
|
53
|
+
signal: S.signal,
|
|
54
|
+
headers: x,
|
|
55
|
+
credentials: r.withCredentials ? "include" : _.credentials,
|
|
56
|
+
body: l == null ? void 0 : v ? l : JSON.stringify(l)
|
|
57
|
+
}, w = t(r.baseURL, e, {
|
|
58
|
+
prefix: r.prefix,
|
|
59
|
+
params: p
|
|
60
|
+
});
|
|
61
|
+
try {
|
|
62
|
+
return await i(w, C);
|
|
63
|
+
} catch (e) {
|
|
64
|
+
throw S.timedOut() ? new n({
|
|
65
|
+
status: 0,
|
|
66
|
+
detail: `A requisição excedeu ${b}ms e foi abandonada.`
|
|
67
|
+
}) : e;
|
|
68
|
+
} finally {
|
|
69
|
+
S.dispose();
|
|
70
|
+
}
|
|
59
71
|
}
|
|
60
|
-
async function
|
|
61
|
-
let a =
|
|
62
|
-
if (!a) return
|
|
63
|
-
let
|
|
72
|
+
async function g(e, t, n, i) {
|
|
73
|
+
let a = r.logger;
|
|
74
|
+
if (!a) return h(e, t, n);
|
|
75
|
+
let o = performance.now();
|
|
64
76
|
try {
|
|
65
|
-
let
|
|
66
|
-
requestId:
|
|
67
|
-
status:
|
|
68
|
-
ms:
|
|
69
|
-
},
|
|
70
|
-
return
|
|
77
|
+
let r = await h(e, t, n), s = {
|
|
78
|
+
requestId: n,
|
|
79
|
+
status: r.status,
|
|
80
|
+
ms: p(o)
|
|
81
|
+
}, c = `${i} ${e} → ${r.status}`;
|
|
82
|
+
return r.status >= 400 ? a.warn(c, s) : a.debug(c, s), r;
|
|
71
83
|
} catch (t) {
|
|
72
84
|
throw a.warn(`${i} ${e} → no response`, {
|
|
73
|
-
requestId:
|
|
74
|
-
ms:
|
|
85
|
+
requestId: n,
|
|
86
|
+
ms: p(o),
|
|
75
87
|
error: t
|
|
76
88
|
}), t;
|
|
77
89
|
}
|
|
78
90
|
}
|
|
79
|
-
async function
|
|
80
|
-
if (
|
|
81
|
-
|
|
91
|
+
async function _(e, t) {
|
|
92
|
+
if (r.onUnauthorized) {
|
|
93
|
+
r.logger?.warn("unauthorized — calling onUnauthorized", {
|
|
82
94
|
requestId: t,
|
|
83
95
|
status: e.status
|
|
84
96
|
});
|
|
85
97
|
try {
|
|
86
|
-
await
|
|
87
|
-
} catch (
|
|
88
|
-
|
|
98
|
+
await r.onUnauthorized(e);
|
|
99
|
+
} catch (n) {
|
|
100
|
+
r.logger?.warn("onUnauthorized threw — keeping the original response error", {
|
|
89
101
|
requestId: t,
|
|
90
102
|
status: e.status,
|
|
91
|
-
error:
|
|
103
|
+
error: n
|
|
92
104
|
});
|
|
93
105
|
}
|
|
94
106
|
}
|
|
95
107
|
}
|
|
96
|
-
async function
|
|
97
|
-
let i =
|
|
108
|
+
async function v(t, n) {
|
|
109
|
+
let i = r.requestId ? r.requestId() : e(), a = (n.method ?? "GET").toUpperCase(), o = await g(t, n, i, a);
|
|
98
110
|
if (o.status === 401) {
|
|
99
|
-
if (
|
|
111
|
+
if (r.refresh) {
|
|
100
112
|
try {
|
|
101
|
-
await
|
|
113
|
+
await r.refresh(), o = await g(t, n, i, a);
|
|
102
114
|
} catch {
|
|
103
|
-
throw await
|
|
115
|
+
throw await _(o, i), await m(o, i);
|
|
104
116
|
}
|
|
105
|
-
o.status === 401 && await
|
|
106
|
-
} else await
|
|
117
|
+
o.status === 401 && await _(o, i);
|
|
118
|
+
} else await _(o, i);
|
|
107
119
|
}
|
|
108
|
-
if (!o.ok) throw await
|
|
120
|
+
if (!o.ok) throw await m(o, i);
|
|
109
121
|
if (o.status !== 204) return (o.headers.get("content-type") ?? "").includes("application/json") ? await o.json() : await o.text();
|
|
110
122
|
}
|
|
111
|
-
async function
|
|
112
|
-
let
|
|
113
|
-
if (!
|
|
123
|
+
async function y(e, t = {}) {
|
|
124
|
+
let n = l(r.retry);
|
|
125
|
+
if (!n) return v(e, t);
|
|
114
126
|
let i = (t.method ?? "GET").toUpperCase();
|
|
115
|
-
return a(() =>
|
|
116
|
-
...
|
|
117
|
-
shouldRetry:
|
|
127
|
+
return a(() => v(e, t), {
|
|
128
|
+
...n,
|
|
129
|
+
shouldRetry: n.shouldRetry ?? ((e) => c(e, i))
|
|
118
130
|
});
|
|
119
131
|
}
|
|
120
|
-
async function
|
|
121
|
-
return
|
|
132
|
+
async function b(e, t, n = "POST", r) {
|
|
133
|
+
return y(e, {
|
|
134
|
+
...r,
|
|
122
135
|
method: n,
|
|
123
136
|
body: t
|
|
124
137
|
});
|
|
125
138
|
}
|
|
126
139
|
return {
|
|
127
|
-
request:
|
|
128
|
-
get: (e, t) =>
|
|
140
|
+
request: y,
|
|
141
|
+
get: (e, t) => y(e, {
|
|
129
142
|
...t,
|
|
130
143
|
method: "GET"
|
|
131
144
|
}),
|
|
132
|
-
post: (e, t) =>
|
|
145
|
+
post: (e, t) => y(e, {
|
|
133
146
|
...t,
|
|
134
147
|
method: "POST"
|
|
135
148
|
}),
|
|
136
|
-
put: (e, t) =>
|
|
149
|
+
put: (e, t) => y(e, {
|
|
137
150
|
...t,
|
|
138
151
|
method: "PUT"
|
|
139
152
|
}),
|
|
140
|
-
patch: (e, t) =>
|
|
153
|
+
patch: (e, t) => y(e, {
|
|
141
154
|
...t,
|
|
142
155
|
method: "PATCH"
|
|
143
156
|
}),
|
|
144
|
-
delete: (e, t) =>
|
|
157
|
+
delete: (e, t) => y(e, {
|
|
145
158
|
...t,
|
|
146
159
|
method: "DELETE"
|
|
147
160
|
}),
|
|
148
|
-
upload:
|
|
161
|
+
upload: b
|
|
149
162
|
};
|
|
150
163
|
}
|
|
151
164
|
//#endregion
|
|
152
|
-
export {
|
|
165
|
+
export { h as createApiClient };
|
|
153
166
|
|
|
154
167
|
//# sourceMappingURL=api-client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-client.js","names":[],"sources":["../../src/http/api-client.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — createApiClient is over the limit and every line\n * is a request-lifecycle concern the client cannot delegate: base URL joining, the\n * auth header, the 401 refresh-and-replay, the opt-in retry wrapper and the response\n * parsing that turns a failure into a typed error.\n */\nimport { randomId } from \"../utils\";\nimport { buildApiUrl } from \"./build-url\";\nimport { buildApiError, TempestApiError, isRetriableStatus } from \"./errors\";\nimport { retry as retryWithBackoff } from \"./retry\";\nimport type { RetryOptions } from \"./retry\";\nimport type { ApiClient, ApiClientConfig, RequestOptions } from \"./types\";\n\n/**\n * Methods the built-in retry policy will replay.\n *\n * `PUT` and `DELETE` are idempotent on paper but stay out: a backend that logs,\n * bills, or fires a webhook per call still sees two, so replaying them is a\n * decision the caller makes through `shouldRetry`, not a default.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Sub-500 statuses worth a second attempt: a network failure (status `0`), a\n * request timeout, a too-early replay, and a rate limit — which usually carries\n * the `Retry-After` the backoff already honours.\n */\n\n/**\n * The built-in retry policy, used when `retry` is `true` or is options carrying\n * no `shouldRetry` of their own.\n *\n * Conservative on purpose. Replaying a write can duplicate it, and replaying a\n * `400` or a `403` cannot fix a bad payload or a permission the caller does not\n * have — it only spends the user's time before showing the same error.\n *\n * @param error - Whatever the attempt threw.\n * @param method - The upper-cased HTTP method of the request.\n * @returns Whether the client should try again.\n */\nfunction isRetriableFailure(error: unknown, method: string): boolean {\n if (!IDEMPOTENT_METHODS.has(method)) return false;\n if (!(error instanceof TempestApiError)) return false;\n return isRetriableStatus(error.status);\n}\n\n/**\n * Normalize the `retry` config into options, or `null` when retrying is off.\n *\n * @param config - The `retry` field as the caller wrote it.\n * @returns Retry options to use, or `null` to run a single attempt.\n */\nfunction resolveRetry(config: boolean | RetryOptions | undefined): RetryOptions | null {\n if (!config) return null;\n return config === true ? {} : config;\n}\n\nfunction isFormData(body: unknown): body is FormData {\n return typeof FormData !== \"undefined\" && body instanceof FormData;\n}\n\n/**\n * Milliseconds since a `performance.now()` reading, rounded.\n *\n * `performance.now()` rather than `Date.now()` because this measures a\n * duration: the wall clock can step sideways mid-request (an NTP correction, a\n * VM resuming, the user changing the clock) and turn a 40 ms call into a\n * negative number. The monotonic clock cannot.\n *\n * @param startedAt - The reading taken before the work started.\n * @returns Whole milliseconds elapsed.\n */\nfunction elapsedMs(startedAt: number): number {\n return Math.round(performance.now() - startedAt);\n}\n\nasync function parseError(response: Response, sentRequestId?: string): Promise<TempestApiError> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n try {\n body = await response.text();\n } catch {\n body = null;\n }\n }\n return new TempestApiError(\n buildApiError(response.status, body, response.headers, sentRequestId),\n );\n}\n\n/**\n * Create a typed HTTP client backed by `fetch`.\n *\n * Handles JSON serialization, query params, bearer auth via `getToken`, uploads\n * via `FormData`, and throws a typed `ApiError` on any non-2xx response.\n *\n * **Expired sessions.** A `401` with `refresh` configured awaits the refresh and\n * replays the request once. `onUnauthorized` fires whenever that path ends\n * unauthorized anyway — the refresh threw, or the replay came back `401` — which\n * is the signal to clear the session. Without `refresh`, the first `401` calls\n * it directly.\n *\n * **Retries** are off unless you set `retry`. See {@link ApiClientConfig.retry}\n * for the built-in policy; it never replays a write.\n *\n * **Logging** is off unless you pass a `logger`. With one, every finished attempt\n * writes a line — `debug` under 400, `warn` from 400 up, plus a `warn` when\n * `onUnauthorized` fires — carrying `requestId`, `status` and elapsed `ms`, and\n * never a body, header or query string. The level and the destination belong to\n * the logger, not to a boolean here.\n *\n * @example\n * const api = createApiClient({\n * baseURL: import.meta.env.VITE_API_URL,\n * getToken: () => useAuthStore.getState().token,\n * refresh,\n * onUnauthorized: () => useAuthStore.getState().logout(),\n * logger: createLogger({ level: import.meta.env.DEV ? \"debug\" : \"warn\" }).child(\"http\"),\n * retry: true,\n * });\n *\n * @param config - Base URL plus the optional auth, retry and fetch hooks.\n * @returns A client with `request`/`get`/`post`/`put`/`patch`/`delete`/`upload`.\n */\nexport function createApiClient(config: ApiClientConfig): ApiClient {\n const fetcher = config.fetcher ?? globalThis.fetch.bind(globalThis);\n\n function authHeaders(): Record<string, string> {\n const token = config.getToken?.();\n return token ? { Authorization: `Bearer ${token}` } : {};\n }\n\n async function rawRequest(\n path: string,\n options: RequestOptions,\n requestId?: string,\n ): Promise<Response> {\n const { body, params, headers, ...rest } = options;\n const isForm = isFormData(body);\n\n const finalHeaders: Record<string, string> = {\n ...(isForm ? {} : { \"Content-Type\": \"application/json\" }),\n ...(requestId ? { \"X-Request-ID\": requestId } : {}),\n ...config.headers,\n ...authHeaders(),\n ...(headers as Record<string, string> | undefined),\n };\n\n const init: RequestInit = {\n ...rest,\n headers: finalHeaders,\n credentials: config.withCredentials ? \"include\" : rest.credentials,\n body:\n body === undefined || body === null\n ? undefined\n : isForm\n ? (body as FormData)\n : JSON.stringify(body),\n };\n\n return fetcher(buildApiUrl(config.baseURL, path, { prefix: config.prefix, params }), init);\n }\n\n async function send(\n path: string,\n options: RequestOptions,\n requestId: string,\n method: string,\n ): Promise<Response> {\n const log = config.logger;\n if (!log) return rawRequest(path, options, requestId);\n\n const startedAt = performance.now();\n try {\n const response = await rawRequest(path, options, requestId);\n const entry = { requestId, status: response.status, ms: elapsedMs(startedAt) };\n const line = `${method} ${path} → ${response.status}`;\n if (response.status >= 400) log.warn(line, entry);\n else log.debug(line, entry);\n return response;\n } catch (error) {\n log.warn(`${method} ${path} → no response`, {\n requestId,\n ms: elapsedMs(startedAt),\n error,\n });\n throw error;\n }\n }\n\n async function notifyUnauthorized(response: Response, requestId: string): Promise<void> {\n if (!config.onUnauthorized) return;\n config.logger?.warn(`unauthorized — calling onUnauthorized`, {\n requestId,\n status: response.status,\n });\n try {\n await config.onUnauthorized(response);\n } catch (error) {\n config.logger?.warn(`onUnauthorized threw — keeping the original response error`, {\n requestId,\n status: response.status,\n error,\n });\n }\n }\n\n async function attempt<T>(path: string, options: RequestOptions): Promise<T> {\n const requestId = config.requestId ? config.requestId() : randomId();\n const method = (options.method ?? \"GET\").toUpperCase();\n let response = await send(path, options, requestId, method);\n\n if (response.status === 401) {\n if (config.refresh) {\n try {\n await config.refresh();\n response = await send(path, options, requestId, method);\n } catch {\n await notifyUnauthorized(response, requestId);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await notifyUnauthorized(response, requestId);\n }\n } else {\n await notifyUnauthorized(response, requestId);\n }\n }\n\n if (!response.ok) {\n throw await parseError(response, requestId);\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n return (await response.json()) as T;\n }\n return (await response.text()) as unknown as T;\n }\n\n async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n const retryOptions = resolveRetry(config.retry);\n if (!retryOptions) return attempt<T>(path, options);\n\n const method = (options.method ?? \"GET\").toUpperCase();\n return retryWithBackoff(() => attempt<T>(path, options), {\n ...retryOptions,\n shouldRetry:\n retryOptions.shouldRetry ?? ((error: unknown) => isRetriableFailure(error, method)),\n });\n }\n\n async function upload<T>(\n path: string,\n formData: FormData,\n method: \"POST\" | \"PUT\" | \"PATCH\" = \"POST\",\n ): Promise<T> {\n return request<T>(path, { method, body: formData });\n }\n\n return {\n request,\n get: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"GET\" }),\n post: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"POST\" }),\n put: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PUT\" }),\n patch: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PATCH\" }),\n delete: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"DELETE\" }),\n upload,\n };\n}\n"],"mappings":";;;;;AAoBA,IAAM,oBAA0C,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;AAoBlF,SAAS,EAAmB,GAAgB,GAAyB;CAGjE,OAFI,CAAC,EAAmB,IAAI,CAAM,KAC9B,EAAE,aAAiB,KAAyB,KACzC,EAAkB,EAAM,MAAM;AACzC;AAQA,SAAS,EAAa,GAAiE;CAEnF,OADK,IACE,MAAW,KAAO,CAAC,IAAI,IADV;AAExB;AAEA,SAAS,EAAW,GAAiC;CACjD,OAAO,OAAO,WAAa,OAAe,aAAgB;AAC9D;AAaA,SAAS,EAAU,GAA2B;CAC1C,OAAO,KAAK,MAAM,YAAY,IAAI,IAAI,CAAS;AACnD;AAEA,eAAe,EAAW,GAAoB,GAAkD;CAC5F,IAAI;CACJ,IAAI;EACA,IAAO,MAAM,EAAS,MAAM,CAAC,CAAC,KAAK;CACvC,QAAQ;EACJ,IAAI;GACA,IAAO,MAAM,EAAS,KAAK;EAC/B,QAAQ;GACJ,IAAO;EACX;CACJ;CACA,OAAO,IAAI,EACP,EAAc,EAAS,QAAQ,GAAM,EAAS,SAAS,CAAa,CACxE;AACJ;AAoCA,SAAgB,EAAgB,GAAoC;CAChE,IAAM,IAAU,EAAO,WAAW,WAAW,MAAM,KAAK,UAAU;CAElE,SAAS,IAAsC;EAC3C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,GACA,GACA,IAAmC,QACzB;EACV,OAAO,EAAW,GAAM;GAAE;GAAQ,MAAM;EAAS,CAAC;CACtD;CAEA,OAAO;EACH;EACA,MAAS,GAAc,MACnB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAM,CAAC;EAClD,OAAU,GAAc,MACpB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAO,CAAC;EACnD,MAAS,GAAc,MACnB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAM,CAAC;EAClD,QAAW,GAAc,MACrB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAQ,CAAC;EACpD,SAAY,GAAc,MACtB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAS,CAAC;EACrD;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"api-client.js","names":[],"sources":["../../src/http/api-client.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — createApiClient is over the limit and every line\n * is a request-lifecycle concern the client cannot delegate: base URL joining, the\n * auth header, the 401 refresh-and-replay, the opt-in retry wrapper and the response\n * parsing that turns a failure into a typed error.\n */\nimport { randomId } from \"../utils\";\nimport { buildApiUrl } from \"./build-url\";\nimport { buildApiError, TempestApiError, isRetriableStatus } from \"./errors\";\nimport { retry as retryWithBackoff } from \"./retry\";\nimport type { RetryOptions } from \"./retry\";\nimport { withTimeout } from \"./timeout\";\nimport type { ApiClient, ApiClientConfig, RequestOptions } from \"./types\";\n\n/**\n * Methods the built-in retry policy will replay.\n *\n * `PUT` and `DELETE` are idempotent on paper but stay out: a backend that logs,\n * bills, or fires a webhook per call still sees two, so replaying them is a\n * decision the caller makes through `shouldRetry`, not a default.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Sub-500 statuses worth a second attempt: a network failure (status `0`), a\n * request timeout, a too-early replay, and a rate limit — which usually carries\n * the `Retry-After` the backoff already honours.\n */\n\n/**\n * The built-in retry policy, used when `retry` is `true` or is options carrying\n * no `shouldRetry` of their own.\n *\n * Conservative on purpose. Replaying a write can duplicate it, and replaying a\n * `400` or a `403` cannot fix a bad payload or a permission the caller does not\n * have — it only spends the user's time before showing the same error.\n *\n * @param error - Whatever the attempt threw.\n * @param method - The upper-cased HTTP method of the request.\n * @returns Whether the client should try again.\n */\nfunction isRetriableFailure(error: unknown, method: string): boolean {\n if (!IDEMPOTENT_METHODS.has(method)) return false;\n if (!(error instanceof TempestApiError)) return false;\n return isRetriableStatus(error.status);\n}\n\n/**\n * Normalize the `retry` config into options, or `null` when retrying is off.\n *\n * @param config - The `retry` field as the caller wrote it.\n * @returns Retry options to use, or `null` to run a single attempt.\n */\nfunction resolveRetry(config: boolean | RetryOptions | undefined): RetryOptions | null {\n if (!config) return null;\n return config === true ? {} : config;\n}\n\n/** Default milliseconds before a request is abandoned. */\nconst DEFAULT_TIMEOUT = 15_000;\n\n/** Default milliseconds before a `FormData` request is abandoned. */\nconst DEFAULT_UPLOAD_TIMEOUT = 300_000;\n\nfunction isFormData(body: unknown): body is FormData {\n return typeof FormData !== \"undefined\" && body instanceof FormData;\n}\n\n/**\n * Milliseconds since a `performance.now()` reading, rounded.\n *\n * `performance.now()` rather than `Date.now()` because this measures a\n * duration: the wall clock can step sideways mid-request (an NTP correction, a\n * VM resuming, the user changing the clock) and turn a 40 ms call into a\n * negative number. The monotonic clock cannot.\n *\n * @param startedAt - The reading taken before the work started.\n * @returns Whole milliseconds elapsed.\n */\nfunction elapsedMs(startedAt: number): number {\n return Math.round(performance.now() - startedAt);\n}\n\nasync function parseError(response: Response, sentRequestId?: string): Promise<TempestApiError> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n try {\n body = await response.text();\n } catch {\n body = null;\n }\n }\n return new TempestApiError(\n buildApiError(response.status, body, response.headers, sentRequestId),\n );\n}\n\n/**\n * Create a typed HTTP client backed by `fetch`.\n *\n * Handles JSON serialization, query params, bearer auth via `getToken`, uploads\n * via `FormData`, and throws a typed `ApiError` on any non-2xx response.\n *\n * **Expired sessions.** A `401` with `refresh` configured awaits the refresh and\n * replays the request once. `onUnauthorized` fires whenever that path ends\n * unauthorized anyway — the refresh threw, or the replay came back `401` — which\n * is the signal to clear the session. Without `refresh`, the first `401` calls\n * it directly.\n *\n * **Retries** are off unless you set `retry`. See {@link ApiClientConfig.retry}\n * for the built-in policy; it never replays a write.\n *\n * **Logging** is off unless you pass a `logger`. With one, every finished attempt\n * writes a line — `debug` under 400, `warn` from 400 up, plus a `warn` when\n * `onUnauthorized` fires — carrying `requestId`, `status` and elapsed `ms`, and\n * never a body, header or query string. The level and the destination belong to\n * the logger, not to a boolean here.\n *\n * @example\n * const api = createApiClient({\n * baseURL: import.meta.env.VITE_API_URL,\n * getToken: () => useAuthStore.getState().token,\n * refresh,\n * onUnauthorized: () => useAuthStore.getState().logout(),\n * logger: createLogger({ level: import.meta.env.DEV ? \"debug\" : \"warn\" }).child(\"http\"),\n * retry: true,\n * });\n *\n * @param config - Base URL plus the optional auth, retry and fetch hooks.\n * @returns A client with `request`/`get`/`post`/`put`/`patch`/`delete`/`upload`.\n */\nexport function createApiClient(config: ApiClientConfig): ApiClient {\n const fetcher = config.fetcher ?? globalThis.fetch.bind(globalThis);\n\n function authHeaders(): Record<string, string> {\n const token = config.getToken?.();\n return token ? { Authorization: `Bearer ${token}` } : {};\n }\n\n async function rawRequest(\n path: string,\n options: RequestOptions,\n requestId?: string,\n ): Promise<Response> {\n const { body, params, headers, signal, timeout, ...rest } = options;\n const isForm = isFormData(body);\n const configured = isForm ? config.uploadTimeout : config.timeout;\n const fallback = isForm ? DEFAULT_UPLOAD_TIMEOUT : DEFAULT_TIMEOUT;\n const limit =\n timeout !== undefined ? timeout : configured !== undefined ? configured : fallback;\n\n const finalHeaders: Record<string, string> = {\n ...(isForm ? {} : { \"Content-Type\": \"application/json\" }),\n ...(requestId ? { \"X-Request-ID\": requestId } : {}),\n ...config.headers,\n ...authHeaders(),\n ...(headers as Record<string, string> | undefined),\n };\n\n const timed = withTimeout(signal, limit);\n const init: RequestInit = {\n ...rest,\n signal: timed.signal,\n headers: finalHeaders,\n credentials: config.withCredentials ? \"include\" : rest.credentials,\n body:\n body === undefined || body === null\n ? undefined\n : isForm\n ? (body as FormData)\n : JSON.stringify(body),\n };\n\n const url = buildApiUrl(config.baseURL, path, { prefix: config.prefix, params });\n try {\n return await fetcher(url, init);\n } catch (cause) {\n if (timed.timedOut()) {\n throw new TempestApiError({\n status: 0,\n detail: `A requisição excedeu ${limit}ms e foi abandonada.`,\n });\n }\n throw cause;\n } finally {\n timed.dispose();\n }\n }\n\n async function send(\n path: string,\n options: RequestOptions,\n requestId: string,\n method: string,\n ): Promise<Response> {\n const log = config.logger;\n if (!log) return rawRequest(path, options, requestId);\n\n const startedAt = performance.now();\n try {\n const response = await rawRequest(path, options, requestId);\n const entry = { requestId, status: response.status, ms: elapsedMs(startedAt) };\n const line = `${method} ${path} → ${response.status}`;\n if (response.status >= 400) log.warn(line, entry);\n else log.debug(line, entry);\n return response;\n } catch (error) {\n log.warn(`${method} ${path} → no response`, {\n requestId,\n ms: elapsedMs(startedAt),\n error,\n });\n throw error;\n }\n }\n\n async function notifyUnauthorized(response: Response, requestId: string): Promise<void> {\n if (!config.onUnauthorized) return;\n config.logger?.warn(`unauthorized — calling onUnauthorized`, {\n requestId,\n status: response.status,\n });\n try {\n await config.onUnauthorized(response);\n } catch (error) {\n config.logger?.warn(`onUnauthorized threw — keeping the original response error`, {\n requestId,\n status: response.status,\n error,\n });\n }\n }\n\n async function attempt<T>(path: string, options: RequestOptions): Promise<T> {\n const requestId = config.requestId ? config.requestId() : randomId();\n const method = (options.method ?? \"GET\").toUpperCase();\n let response = await send(path, options, requestId, method);\n\n if (response.status === 401) {\n if (config.refresh) {\n try {\n await config.refresh();\n response = await send(path, options, requestId, method);\n } catch {\n await notifyUnauthorized(response, requestId);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await notifyUnauthorized(response, requestId);\n }\n } else {\n await notifyUnauthorized(response, requestId);\n }\n }\n\n if (!response.ok) {\n throw await parseError(response, requestId);\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"application/json\")) {\n return (await response.json()) as T;\n }\n return (await response.text()) as unknown as T;\n }\n\n async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n const retryOptions = resolveRetry(config.retry);\n if (!retryOptions) return attempt<T>(path, options);\n\n const method = (options.method ?? \"GET\").toUpperCase();\n return retryWithBackoff(() => attempt<T>(path, options), {\n ...retryOptions,\n shouldRetry:\n retryOptions.shouldRetry ?? ((error: unknown) => isRetriableFailure(error, method)),\n });\n }\n\n async function upload<T>(\n path: string,\n formData: FormData,\n method: \"POST\" | \"PUT\" | \"PATCH\" = \"POST\",\n options?: Omit<RequestOptions, \"body\" | \"method\">,\n ): Promise<T> {\n return request<T>(path, { ...options, method, body: formData });\n }\n\n return {\n request,\n get: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"GET\" }),\n post: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"POST\" }),\n put: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PUT\" }),\n patch: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PATCH\" }),\n delete: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"DELETE\" }),\n upload,\n };\n}\n"],"mappings":";;;;;;AAqBA,IAAM,oBAA0C,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;AAoBlF,SAAS,EAAmB,GAAgB,GAAyB;CAGjE,OAFI,CAAC,EAAmB,IAAI,CAAM,KAC9B,EAAE,aAAiB,KAAyB,KACzC,EAAkB,EAAM,MAAM;AACzC;AAQA,SAAS,EAAa,GAAiE;CAEnF,OADK,IACE,MAAW,KAAO,CAAC,IAAI,IADV;AAExB;AAGA,IAAM,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S,QAAQ;EAAM,CAAC;EAClD,QAAW,GAAc,MACrB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAQ,CAAC;EACpD,SAAY,GAAc,MACtB,EAAW,GAAM;GAAE,GAAG;GAAS,QAAQ;EAAS,CAAC;EACrD;CACJ;AACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../utils/base64.cjs"),t=require("./errors.cjs"),n=require("./retry.cjs"),r=require("./idempotency.cjs");var i=`1.0.0`,a=5242880;function o(t){return e.bytesToBase64(new TextEncoder().encode(t))}function s(e){if(!e)return null;let t=Object.entries(e).map(([e,t])=>`${e} ${o(t)}`);return t.length>0?t.join(`,`):null}function c(e,t){let n=t,r=typeof n.name==`string`?n.name:`blob`,i=typeof n.lastModified==`number`?n.lastModified:0;return`${e}|${r}|${t.size}|${t.type}|${i}`}function l(e=`tempest-upload:`){function t(){try{return typeof localStorage>`u`?null:localStorage}catch{return null}}return{get(n){let r=t()?.getItem(e+n);if(!r)return null;try{return JSON.parse(r)}catch{return null}},set(n,r){t()?.setItem(e+n,JSON.stringify(r))},delete(n){t()?.removeItem(e+n)}}}function u(e){return new Promise((n,r)=>{let i=new XMLHttpRequest;i.open(e.method,e.url),i.withCredentials=e.withCredentials;for(let[t,n]of Object.entries(e.headers))i.setRequestHeader(t,n);if(e.onProgress){let t=e.onProgress;i.upload.onprogress=e=>t(e.loaded)}i.onload=()=>n({status:i.status,text:i.responseText,header:e=>i.getResponseHeader(e)}),i.onerror=()=>r(new t.TempestApiError({status:0,detail:`Falha de rede no upload resumível.`})),i.onabort=()=>r(new DOMException(`Aborted`,`AbortError`)),e.register(i),i.send(e.body)})}function d(e){let t=e.header(`Upload-Offset`);if(t===null)return null;let n=Number(t);return Number.isFinite(n)&&n>=0?n:null}function f(e){if(!e)return null;try{return JSON.parse(e)}catch{return e}}function p(e,n){let r=f(e.text),i=t.buildApiError(e.status,r,{get:e.header}),a=typeof r==`object`&&!!r&&(`detail`in r||`message`in r);return new t.TempestApiError({...i,detail:a?i.detail:n})}function
|
|
1
|
+
const e=require("../utils/base64.cjs"),t=require("./errors.cjs"),n=require("./retry.cjs"),r=require("./idempotency.cjs");var i=`1.0.0`,a=5242880;function o(t){return e.bytesToBase64(new TextEncoder().encode(t))}function s(e){if(!e)return null;let t=Object.entries(e).map(([e,t])=>`${e} ${o(t)}`);return t.length>0?t.join(`,`):null}function c(e,t){let n=t,r=typeof n.name==`string`?n.name:`blob`,i=typeof n.lastModified==`number`?n.lastModified:0;return`${e}|${r}|${t.size}|${t.type}|${i}`}function l(e=`tempest-upload:`){function t(){try{return typeof localStorage>`u`?null:localStorage}catch{return null}}return{get(n){let r=t()?.getItem(e+n);if(!r)return null;try{return JSON.parse(r)}catch{return null}},set(n,r){t()?.setItem(e+n,JSON.stringify(r))},delete(n){t()?.removeItem(e+n)}}}function u(e){return new Promise((n,r)=>{let i=new XMLHttpRequest;i.open(e.method,e.url),i.withCredentials=e.withCredentials;for(let[t,n]of Object.entries(e.headers))i.setRequestHeader(t,n);if(e.onProgress){let t=e.onProgress;i.upload.onprogress=e=>t(e.loaded)}i.onload=()=>n({status:i.status,text:i.responseText,header:e=>i.getResponseHeader(e)}),i.onerror=()=>r(new t.TempestApiError({status:0,detail:`Falha de rede no upload resumível.`})),i.onabort=()=>r(new DOMException(`Aborted`,`AbortError`)),e.register(i),i.send(e.body)})}function d(e){let t=e.header(`Upload-Offset`);if(t===null)return null;let n=Number(t);return Number.isFinite(n)&&n>=0?n:null}function f(e){if(!e)return null;try{return JSON.parse(e)}catch{return e}}var p=new Set([409,412]);function m(e){return!t.isApiError(e)||p.has(e.status)?!0:t.isRetriableStatus(e.status)}function h(e,n){let r=f(e.text),i=t.buildApiError(e.status,r,{get:e.header}),a=typeof r==`object`&&!!r&&(`detail`in r||`message`in r);return new t.TempestApiError({...i,detail:a?i.detail:n})}function g(e){let t=typeof window>`u`?void 0:window.location.href;try{return new URL(e,t).href}catch{return e}}function _(e){let{endpoint:o,file:f,chunkSize:p=a,metadata:_,headers:v={},getToken:y,withCredentials:b=!1,key:x=c(o,f),storage:S=l(),retry:C,onProgress:w,onStateChange:T}=e,E=`idle`,D=0,O=null,k=null,A=null,j=null,M=0;function N(e){E!==e&&(E=e,T?.(e))}function P(e){w?.({loaded:e,total:f.size,fraction:f.size===0?1:e/f.size,resumedFrom:M})}function F(){let e={...v,"Tus-Resumable":i},t=y?.();return t&&!(`Authorization`in e)&&(e.Authorization=`Bearer ${t}`),e}function I(e){j=e}async function L(){!S||!O||!k||await S.set(x,{url:O,offset:D,size:f.size,idempotencyKey:k,updatedAt:Date.now()})}async function R(e){let n=await u({method:`HEAD`,url:e,headers:F(),withCredentials:b,register:I});if(n.status===404||n.status===410)throw new t.TempestApiError({status:n.status,detail:`O upload expirou no servidor. Comece de novo.`});let r=d(n);if(r===null)throw h(n,`HEAD sem Upload-Offset.`);return r}async function z(){let e=S?await S.get(x):null;if(e&&e.size===f.size&&(k=e.idempotencyKey,e.url))try{return D=await R(e.url),O=e.url,e.url}catch{D=0}N(`creating`),k??=r.generateIdempotencyKey(),O=null,D=0,S&&await S.set(x,{url:``,offset:0,size:f.size,idempotencyKey:k,updatedAt:Date.now()});let t={...F(),"Upload-Length":String(f.size),"Idempotency-Key":k},n=s(_);n&&(t[`Upload-Metadata`]=n);let i=await u({method:`POST`,url:o,headers:t,withCredentials:b,register:I});if(i.status!==201)throw h(i,`Criação do upload recusada.`);let a=i.header(`Location`);if(!a)throw h(i,`Criação do upload sem cabeçalho Location.`);return O=g(a),await L(),O}async function B(e,t){if(t.needed&&(D=await R(e),t.needed=!1,P(D),await L(),D>=f.size))return;let n=Math.min(D+p,f.size),r=D,i=await u({method:`PATCH`,url:e,headers:{...F(),"Content-Type":`application/offset+octet-stream`,"Upload-Offset":String(r)},body:f.slice(r,n),withCredentials:b,onProgress:e=>P(Math.min(r+e,f.size)),register:I});if(i.status===409||i.status===412)throw t.needed=!0,h(i,`Offset divergente — o servidor já tinha esses bytes.`);if(i.status!==204&&i.status!==200)throw h(i,`Chunk recusado pelo servidor.`);D=d(i)??n,P(D),await L()}async function V(){A=null;let e=await z();M=D,N(`uploading`),P(D);let t={needed:!1};for(;D<f.size&&!A;)await n.retry(()=>B(e,t),{retries:5,...C,shouldRetry:(e,n)=>{if(A||e instanceof DOMException&&e.name===`AbortError`)return!1;let r=C?.shouldRetry?.(e,n)??m(e);return r&&(t.needed=!0),r}});return A===`pause`?(N(`paused`),null):A===`abort`?(N(`aborted`),null):(N(`done`),S&&await S.delete(x),{url:e,size:f.size})}async function H(){try{return await V()}catch(e){if(A!==null||e instanceof DOMException&&e.name===`AbortError`)return N(A===`abort`?`aborted`:`paused`),null;throw N(`error`),e}finally{j=null}}function U(e){A=e,j?.abort(),j=null}return{start:H,resume:H,pause:()=>U(`pause`),abort:async({discard:e=!1}={})=>{U(`abort`),N(`aborted`),e&&(O&&await u({method:`DELETE`,url:O,headers:F(),withCredentials:b,register:()=>void 0}).catch(()=>void 0),S&&await S.delete(x))},get state(){return E},get offset(){return D},get url(){return O},key:x}}exports.DEFAULT_CHUNK_SIZE=a,exports.TUS_VERSION=i,exports.createLocalUploadStorage=l,exports.createResumableUpload=_,exports.uploadFingerprint=c;
|
|
2
2
|
//# sourceMappingURL=resumable-upload.cjs.map
|