tempest-react-sdk 0.47.0 → 0.48.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/components/AIChat/AIChatTurn.cjs +1 -1
- package/dist/components/AIChat/AIChatTurn.js +4 -4
- package/dist/components/AppBar/use-sticky-body-warning.cjs.map +1 -1
- package/dist/components/AppBar/use-sticky-body-warning.js.map +1 -1
- package/dist/components/DataTable/DataTable.cjs +1 -1
- package/dist/components/DataTable/DataTable.js +11 -11
- package/dist/components/DataTable/use-dev-warnings.cjs.map +1 -1
- package/dist/components/DataTable/use-dev-warnings.js.map +1 -1
- package/dist/components/NotificationCenter/NotificationCenter.cjs +1 -1
- package/dist/components/NotificationCenter/NotificationCenter.js +21 -21
- package/dist/components/Sidebar/Sidebar.cjs +1 -1
- package/dist/components/Sidebar/Sidebar.cjs.map +1 -1
- package/dist/components/Sidebar/Sidebar.js +91 -38
- package/dist/components/Sidebar/Sidebar.js.map +1 -1
- package/dist/components/Sidebar/Sidebar.module.cjs +1 -1
- package/dist/components/Sidebar/Sidebar.module.cjs.map +1 -1
- package/dist/components/Sidebar/Sidebar.module.js +12 -8
- package/dist/components/Sidebar/Sidebar.module.js.map +1 -1
- package/dist/forms/masked-inputs.cjs +1 -1
- package/dist/forms/masked-inputs.js +12 -12
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +45 -31
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/describe-api-error.cjs +1 -1
- package/dist/http/describe-api-error.cjs.map +1 -1
- package/dist/http/describe-api-error.js +11 -7
- package/dist/http/describe-api-error.js.map +1 -1
- package/dist/http/errors.cjs +1 -1
- package/dist/http/errors.cjs.map +1 -1
- package/dist/http/errors.js +38 -21
- package/dist/http/errors.js.map +1 -1
- package/dist/http/use-describe-api-error.cjs +1 -1
- package/dist/http/use-describe-api-error.cjs.map +1 -1
- package/dist/http/use-describe-api-error.js +14 -10
- package/dist/http/use-describe-api-error.js.map +1 -1
- package/dist/icons/Icon.cjs +1 -1
- package/dist/icons/Icon.cjs.map +1 -1
- package/dist/icons/Icon.js +15 -14
- package/dist/icons/Icon.js.map +1 -1
- package/dist/icons/IconPicker.cjs +2 -0
- package/dist/icons/IconPicker.cjs.map +1 -0
- package/dist/icons/IconPicker.js +49 -0
- package/dist/icons/IconPicker.js.map +1 -0
- package/dist/icons/IconPicker.module.cjs +2 -0
- package/dist/icons/IconPicker.module.cjs.map +1 -0
- package/dist/icons/IconPicker.module.js +10 -0
- package/dist/icons/IconPicker.module.js.map +1 -0
- package/dist/icons/alias.cjs +2 -0
- package/dist/icons/alias.cjs.map +1 -0
- package/dist/icons/alias.js +9 -0
- package/dist/icons/alias.js.map +1 -0
- package/dist/icons/generated/loaders.cjs +1 -1
- package/dist/icons/generated/loaders.cjs.map +1 -1
- package/dist/icons/generated/loaders.js +273 -28
- package/dist/icons/generated/loaders.js.map +1 -1
- package/dist/icons/generated/shard-00.cjs +2 -0
- package/dist/icons/generated/shard-00.cjs.map +1 -0
- package/dist/icons/generated/shard-00.js +48 -0
- package/dist/icons/generated/shard-00.js.map +1 -0
- package/dist/icons/generated/shard-01.cjs +2 -0
- package/dist/icons/generated/shard-01.cjs.map +1 -0
- package/dist/icons/generated/shard-01.js +48 -0
- package/dist/icons/generated/shard-01.js.map +1 -0
- package/dist/icons/generated/shard-02.cjs +2 -0
- package/dist/icons/generated/shard-02.cjs.map +1 -0
- package/dist/icons/generated/shard-02.js +48 -0
- package/dist/icons/generated/shard-02.js.map +1 -0
- package/dist/icons/generated/shard-03.cjs +2 -0
- package/dist/icons/generated/shard-03.cjs.map +1 -0
- package/dist/icons/generated/shard-03.js +48 -0
- package/dist/icons/generated/shard-03.js.map +1 -0
- package/dist/icons/generated/shard-04.cjs +2 -0
- package/dist/icons/generated/shard-04.cjs.map +1 -0
- package/dist/icons/generated/shard-04.js +48 -0
- package/dist/icons/generated/shard-04.js.map +1 -0
- package/dist/icons/generated/shard-05.cjs +2 -0
- package/dist/icons/generated/shard-05.cjs.map +1 -0
- package/dist/icons/generated/shard-05.js +48 -0
- package/dist/icons/generated/shard-05.js.map +1 -0
- package/dist/icons/generated/shard-06.cjs +2 -0
- package/dist/icons/generated/shard-06.cjs.map +1 -0
- package/dist/icons/generated/shard-06.js +48 -0
- package/dist/icons/generated/shard-06.js.map +1 -0
- package/dist/icons/generated/shard-07.cjs +2 -0
- package/dist/icons/generated/shard-07.cjs.map +1 -0
- package/dist/icons/generated/shard-07.js +48 -0
- package/dist/icons/generated/shard-07.js.map +1 -0
- package/dist/icons/generated/shard-08.cjs +2 -0
- package/dist/icons/generated/shard-08.cjs.map +1 -0
- package/dist/icons/generated/shard-08.js +48 -0
- package/dist/icons/generated/shard-08.js.map +1 -0
- package/dist/icons/generated/shard-09.cjs +2 -0
- package/dist/icons/generated/shard-09.cjs.map +1 -0
- package/dist/icons/generated/shard-09.js +48 -0
- package/dist/icons/generated/shard-09.js.map +1 -0
- package/dist/icons/generated/shard-10.cjs +2 -0
- package/dist/icons/generated/shard-10.cjs.map +1 -0
- package/dist/icons/generated/shard-10.js +48 -0
- package/dist/icons/generated/shard-10.js.map +1 -0
- package/dist/icons/generated/shard-11.cjs +2 -0
- package/dist/icons/generated/shard-11.cjs.map +1 -0
- package/dist/icons/generated/shard-11.js +48 -0
- package/dist/icons/generated/shard-11.js.map +1 -0
- package/dist/icons/generated/shard-12.cjs +2 -0
- package/dist/icons/generated/shard-12.cjs.map +1 -0
- package/dist/icons/generated/shard-12.js +48 -0
- package/dist/icons/generated/shard-12.js.map +1 -0
- package/dist/icons/generated/shard-13.cjs +2 -0
- package/dist/icons/generated/shard-13.cjs.map +1 -0
- package/dist/icons/generated/shard-13.js +48 -0
- package/dist/icons/generated/shard-13.js.map +1 -0
- package/dist/icons/generated/shard-14.cjs +2 -0
- package/dist/icons/generated/shard-14.cjs.map +1 -0
- package/dist/icons/generated/shard-14.js +48 -0
- package/dist/icons/generated/shard-14.js.map +1 -0
- package/dist/icons/generated/shard-15.cjs +2 -0
- package/dist/icons/generated/shard-15.cjs.map +1 -0
- package/dist/icons/generated/shard-15.js +48 -0
- package/dist/icons/generated/shard-15.js.map +1 -0
- package/dist/icons/generated/shard-16.cjs +2 -0
- package/dist/icons/generated/shard-16.cjs.map +1 -0
- package/dist/icons/generated/shard-16.js +48 -0
- package/dist/icons/generated/shard-16.js.map +1 -0
- package/dist/icons/generated/shard-17.cjs +2 -0
- package/dist/icons/generated/shard-17.cjs.map +1 -0
- package/dist/icons/generated/shard-17.js +48 -0
- package/dist/icons/generated/shard-17.js.map +1 -0
- package/dist/icons/generated/shard-18.cjs +2 -0
- package/dist/icons/generated/shard-18.cjs.map +1 -0
- package/dist/icons/generated/shard-18.js +48 -0
- package/dist/icons/generated/shard-18.js.map +1 -0
- package/dist/icons/generated/shard-19.cjs +2 -0
- package/dist/icons/generated/shard-19.cjs.map +1 -0
- package/dist/icons/generated/shard-19.js +48 -0
- package/dist/icons/generated/shard-19.js.map +1 -0
- package/dist/icons/generated/shard-20.cjs +2 -0
- package/dist/icons/generated/shard-20.cjs.map +1 -0
- package/dist/icons/generated/shard-20.js +48 -0
- package/dist/icons/generated/shard-20.js.map +1 -0
- package/dist/icons/generated/shard-21.cjs +2 -0
- package/dist/icons/generated/shard-21.cjs.map +1 -0
- package/dist/icons/generated/shard-21.js +48 -0
- package/dist/icons/generated/shard-21.js.map +1 -0
- package/dist/icons/generated/shard-22.cjs +2 -0
- package/dist/icons/generated/shard-22.cjs.map +1 -0
- package/dist/icons/generated/shard-22.js +48 -0
- package/dist/icons/generated/shard-22.js.map +1 -0
- package/dist/icons/generated/shard-23.cjs +2 -0
- package/dist/icons/generated/shard-23.cjs.map +1 -0
- package/dist/icons/generated/shard-23.js +48 -0
- package/dist/icons/generated/shard-23.js.map +1 -0
- package/dist/icons/generated/shard-24.cjs +2 -0
- package/dist/icons/generated/shard-24.cjs.map +1 -0
- package/dist/icons/generated/shard-24.js +48 -0
- package/dist/icons/generated/shard-24.js.map +1 -0
- package/dist/icons/generated/shard-25.cjs +2 -0
- package/dist/icons/generated/shard-25.cjs.map +1 -0
- package/dist/icons/generated/shard-25.js +48 -0
- package/dist/icons/generated/shard-25.js.map +1 -0
- package/dist/icons/generated/shard-26.cjs +2 -0
- package/dist/icons/generated/shard-26.cjs.map +1 -0
- package/dist/icons/generated/shard-26.js +48 -0
- package/dist/icons/generated/shard-26.js.map +1 -0
- package/dist/icons/generated/shard-27.cjs +2 -0
- package/dist/icons/generated/shard-27.cjs.map +1 -0
- package/dist/icons/generated/shard-27.js +48 -0
- package/dist/icons/generated/shard-27.js.map +1 -0
- package/dist/icons/generated/shard-28.cjs +2 -0
- package/dist/icons/generated/shard-28.cjs.map +1 -0
- package/dist/icons/generated/shard-28.js +48 -0
- package/dist/icons/generated/shard-28.js.map +1 -0
- package/dist/icons/generated/shard-29.cjs +2 -0
- package/dist/icons/generated/shard-29.cjs.map +1 -0
- package/dist/icons/generated/shard-29.js +48 -0
- package/dist/icons/generated/shard-29.js.map +1 -0
- package/dist/icons/generated/shard-30.cjs +2 -0
- package/dist/icons/generated/shard-30.cjs.map +1 -0
- package/dist/icons/generated/shard-30.js +48 -0
- package/dist/icons/generated/shard-30.js.map +1 -0
- package/dist/icons/generated/shard-31.cjs +2 -0
- package/dist/icons/generated/shard-31.cjs.map +1 -0
- package/dist/icons/generated/shard-31.js +48 -0
- package/dist/icons/generated/shard-31.js.map +1 -0
- package/dist/icons/generated/shard-32.cjs +2 -0
- package/dist/icons/generated/shard-32.cjs.map +1 -0
- package/dist/icons/generated/shard-32.js +48 -0
- package/dist/icons/generated/shard-32.js.map +1 -0
- package/dist/icons/generated/shard-33.cjs +2 -0
- package/dist/icons/generated/shard-33.cjs.map +1 -0
- package/dist/icons/generated/shard-33.js +48 -0
- package/dist/icons/generated/shard-33.js.map +1 -0
- package/dist/icons/generated/shard-34.cjs +2 -0
- package/dist/icons/generated/shard-34.cjs.map +1 -0
- package/dist/icons/generated/shard-34.js +48 -0
- package/dist/icons/generated/shard-34.js.map +1 -0
- package/dist/icons/generated/shard-35.cjs +2 -0
- package/dist/icons/generated/shard-35.cjs.map +1 -0
- package/dist/icons/generated/shard-35.js +48 -0
- package/dist/icons/generated/shard-35.js.map +1 -0
- package/dist/icons/generated/shard-36.cjs +2 -0
- package/dist/icons/generated/shard-36.cjs.map +1 -0
- package/dist/icons/generated/shard-36.js +48 -0
- package/dist/icons/generated/shard-36.js.map +1 -0
- package/dist/icons/generated/shard-37.cjs +2 -0
- package/dist/icons/generated/shard-37.cjs.map +1 -0
- package/dist/icons/generated/shard-37.js +48 -0
- package/dist/icons/generated/shard-37.js.map +1 -0
- package/dist/icons/generated/shard-38.cjs +2 -0
- package/dist/icons/generated/shard-38.cjs.map +1 -0
- package/dist/icons/generated/shard-38.js +48 -0
- package/dist/icons/generated/shard-38.js.map +1 -0
- package/dist/icons/generated/shard-39.cjs +2 -0
- package/dist/icons/generated/shard-39.cjs.map +1 -0
- package/dist/icons/generated/shard-39.js +48 -0
- package/dist/icons/generated/shard-39.js.map +1 -0
- package/dist/icons/generated/shard-40.cjs +2 -0
- package/dist/icons/generated/shard-40.cjs.map +1 -0
- package/dist/icons/generated/shard-40.js +48 -0
- package/dist/icons/generated/shard-40.js.map +1 -0
- package/dist/icons/generated/shard-41.cjs +2 -0
- package/dist/icons/generated/shard-41.cjs.map +1 -0
- package/dist/icons/generated/shard-41.js +48 -0
- package/dist/icons/generated/shard-41.js.map +1 -0
- package/dist/icons/generated/shard-42.cjs +2 -0
- package/dist/icons/generated/shard-42.cjs.map +1 -0
- package/dist/icons/generated/shard-42.js +48 -0
- package/dist/icons/generated/shard-42.js.map +1 -0
- package/dist/icons/generated/shard-43.cjs +2 -0
- package/dist/icons/generated/shard-43.cjs.map +1 -0
- package/dist/icons/generated/shard-43.js +48 -0
- package/dist/icons/generated/shard-43.js.map +1 -0
- package/dist/icons/generated/shard-44.cjs +2 -0
- package/dist/icons/generated/shard-44.cjs.map +1 -0
- package/dist/icons/generated/shard-44.js +15 -0
- package/dist/icons/generated/shard-44.js.map +1 -0
- package/dist/icons/material-symbols.cjs +1 -1
- package/dist/icons/material-symbols.cjs.map +1 -1
- package/dist/icons/material-symbols.js +109 -1
- package/dist/icons/material-symbols.js.map +1 -1
- package/dist/icons/normalize-icon-name.cjs +2 -0
- package/dist/icons/normalize-icon-name.cjs.map +1 -0
- package/dist/icons/normalize-icon-name.js +9 -0
- package/dist/icons/normalize-icon-name.js.map +1 -0
- package/dist/icons/shard-cache.cjs +1 -1
- package/dist/icons/shard-cache.cjs.map +1 -1
- package/dist/icons/shard-cache.js +85 -32
- package/dist/icons/shard-cache.js.map +1 -1
- package/dist/icons/validate-icon-name.cjs +2 -0
- package/dist/icons/validate-icon-name.cjs.map +1 -0
- package/dist/icons/validate-icon-name.js +11 -0
- package/dist/icons/validate-icon-name.js.map +1 -0
- package/dist/icons-virtual-id.d.ts +24 -0
- package/dist/icons-virtual.cjs +2 -0
- package/dist/icons-virtual.cjs.map +1 -0
- package/dist/icons-virtual.d.ts +30 -22
- package/dist/icons-virtual.js +6 -0
- package/dist/icons-virtual.js.map +1 -0
- package/dist/icons.cjs +1 -1
- package/dist/icons.d.ts +269 -32
- package/dist/icons.js +11 -7
- package/dist/styles.css +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +95 -64
- package/dist/tempest-react-sdk.js +225 -226
- package/dist/utils/dev-mode.cjs.map +1 -1
- package/dist/utils/dev-mode.js.map +1 -1
- package/dist/vite/tempest-icons.cjs +4 -4
- package/dist/vite/tempest-icons.cjs.map +1 -1
- package/dist/vite/tempest-icons.js +26 -26
- package/dist/vite/tempest-icons.js.map +1 -1
- package/dist/vite.d.ts +1 -1
- package/package.json +5 -2
- package/dist/icons/generated/shard-a.cjs +0 -2
- package/dist/icons/generated/shard-a.cjs.map +0 -1
- package/dist/icons/generated/shard-a.js +0 -114
- package/dist/icons/generated/shard-a.js.map +0 -1
- package/dist/icons/generated/shard-b.cjs +0 -2
- package/dist/icons/generated/shard-b.cjs.map +0 -1
- package/dist/icons/generated/shard-b.js +0 -158
- package/dist/icons/generated/shard-b.js.map +0 -1
- package/dist/icons/generated/shard-c.cjs +0 -2
- package/dist/icons/generated/shard-c.cjs.map +0 -1
- package/dist/icons/generated/shard-c.js +0 -269
- package/dist/icons/generated/shard-c.js.map +0 -1
- package/dist/icons/generated/shard-d.cjs +0 -2
- package/dist/icons/generated/shard-d.cjs.map +0 -1
- package/dist/icons/generated/shard-d.js +0 -62
- package/dist/icons/generated/shard-d.js.map +0 -1
- package/dist/icons/generated/shard-e.cjs +0 -2
- package/dist/icons/generated/shard-e.cjs.map +0 -1
- package/dist/icons/generated/shard-e.js +0 -33
- package/dist/icons/generated/shard-e.js.map +0 -1
- package/dist/icons/generated/shard-f.cjs +0 -2
- package/dist/icons/generated/shard-f.cjs.map +0 -1
- package/dist/icons/generated/shard-f.js +0 -145
- package/dist/icons/generated/shard-f.js.map +0 -1
- package/dist/icons/generated/shard-g.cjs +0 -2
- package/dist/icons/generated/shard-g.cjs.map +0 -1
- package/dist/icons/generated/shard-g.js +0 -61
- package/dist/icons/generated/shard-g.js.map +0 -1
- package/dist/icons/generated/shard-h.cjs +0 -2
- package/dist/icons/generated/shard-h.cjs.map +0 -1
- package/dist/icons/generated/shard-h.js +0 -62
- package/dist/icons/generated/shard-h.js.map +0 -1
- package/dist/icons/generated/shard-i.cjs +0 -2
- package/dist/icons/generated/shard-i.cjs.map +0 -1
- package/dist/icons/generated/shard-i.js +0 -30
- package/dist/icons/generated/shard-i.js.map +0 -1
- package/dist/icons/generated/shard-j.cjs +0 -2
- package/dist/icons/generated/shard-j.cjs.map +0 -1
- package/dist/icons/generated/shard-j.js +0 -10
- package/dist/icons/generated/shard-j.js.map +0 -1
- package/dist/icons/generated/shard-k.cjs +0 -2
- package/dist/icons/generated/shard-k.cjs.map +0 -1
- package/dist/icons/generated/shard-k.js +0 -16
- package/dist/icons/generated/shard-k.js.map +0 -1
- package/dist/icons/generated/shard-l.cjs +0 -2
- package/dist/icons/generated/shard-l.cjs.map +0 -1
- package/dist/icons/generated/shard-l.js +0 -92
- package/dist/icons/generated/shard-l.js.map +0 -1
- package/dist/icons/generated/shard-m.cjs +0 -2
- package/dist/icons/generated/shard-m.cjs.map +0 -1
- package/dist/icons/generated/shard-m.js +0 -143
- package/dist/icons/generated/shard-m.js.map +0 -1
- package/dist/icons/generated/shard-n.cjs +0 -2
- package/dist/icons/generated/shard-n.cjs.map +0 -1
- package/dist/icons/generated/shard-n.js +0 -24
- package/dist/icons/generated/shard-n.js.map +0 -1
- package/dist/icons/generated/shard-o.cjs +0 -2
- package/dist/icons/generated/shard-o.cjs.map +0 -1
- package/dist/icons/generated/shard-o.js +0 -17
- package/dist/icons/generated/shard-o.js.map +0 -1
- package/dist/icons/generated/shard-p.cjs +0 -2
- package/dist/icons/generated/shard-p.cjs.map +0 -1
- package/dist/icons/generated/shard-p.js +0 -114
- package/dist/icons/generated/shard-p.js.map +0 -1
- package/dist/icons/generated/shard-q.cjs +0 -2
- package/dist/icons/generated/shard-q.cjs.map +0 -1
- package/dist/icons/generated/shard-q.js +0 -10
- package/dist/icons/generated/shard-q.js.map +0 -1
- package/dist/icons/generated/shard-r.cjs +0 -2
- package/dist/icons/generated/shard-r.cjs.map +0 -1
- package/dist/icons/generated/shard-r.js +0 -79
- package/dist/icons/generated/shard-r.js.map +0 -1
- package/dist/icons/generated/shard-s.cjs +0 -2
- package/dist/icons/generated/shard-s.cjs.map +0 -1
- package/dist/icons/generated/shard-s.js +0 -256
- package/dist/icons/generated/shard-s.js.map +0 -1
- package/dist/icons/generated/shard-t.cjs +0 -2
- package/dist/icons/generated/shard-t.cjs.map +0 -1
- package/dist/icons/generated/shard-t.js +0 -109
- package/dist/icons/generated/shard-t.js.map +0 -1
- package/dist/icons/generated/shard-u.cjs +0 -2
- package/dist/icons/generated/shard-u.cjs.map +0 -1
- package/dist/icons/generated/shard-u.js +0 -50
- package/dist/icons/generated/shard-u.js.map +0 -1
- package/dist/icons/generated/shard-v.cjs +0 -2
- package/dist/icons/generated/shard-v.cjs.map +0 -1
- package/dist/icons/generated/shard-v.js +0 -30
- package/dist/icons/generated/shard-v.js.map +0 -1
- package/dist/icons/generated/shard-w.cjs +0 -2
- package/dist/icons/generated/shard-w.cjs.map +0 -1
- package/dist/icons/generated/shard-w.js +0 -48
- package/dist/icons/generated/shard-w.js.map +0 -1
- package/dist/icons/generated/shard-x.cjs +0 -2
- package/dist/icons/generated/shard-x.cjs.map +0 -1
- package/dist/icons/generated/shard-x.js +0 -10
- package/dist/icons/generated/shard-x.js.map +0 -1
- package/dist/icons/generated/shard-z.cjs +0 -2
- package/dist/icons/generated/shard-z.cjs.map +0 -1
- package/dist/icons/generated/shard-z.js +0 -25
- package/dist/icons/generated/shard-z.js.map +0 -1
|
@@ -1,17 +1,21 @@
|
|
|
1
1
|
//#region src/components/Sidebar/Sidebar.module.css
|
|
2
|
-
var e = "tempest_sidebar_UB1qz", t = "tempest_header_zupoS", n = "tempest_nav_aLYuL", r = "
|
|
2
|
+
var e = "tempest_sidebar_UB1qz", t = "tempest_header_zupoS", n = "tempest_nav_aLYuL", r = "tempest_group_YRfYm", i = "tempest_collapsed_ZbZYA", a = "tempest_section_lefYR", o = "tempest_sectionCollapsed_iBtFO", s = "tempest_separator_Ql9Hr", c = "tempest_item_IAjHb", l = "tempest_active_BgcFy", u = "tempest_icon_UQswn", d = "tempest_label_TPvJ9", f = "tempest_badge_xwEZv", p = "tempest_footer_TyRyi", m = {
|
|
3
3
|
sidebar: e,
|
|
4
4
|
header: t,
|
|
5
5
|
nav: n,
|
|
6
|
-
|
|
6
|
+
group: r,
|
|
7
7
|
collapsed: i,
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
8
|
+
section: a,
|
|
9
|
+
sectionCollapsed: o,
|
|
10
|
+
separator: s,
|
|
11
|
+
item: c,
|
|
12
|
+
active: l,
|
|
13
|
+
icon: u,
|
|
14
|
+
label: d,
|
|
15
|
+
badge: f,
|
|
16
|
+
footer: p
|
|
13
17
|
};
|
|
14
18
|
//#endregion
|
|
15
|
-
export {
|
|
19
|
+
export { l as active, f as badge, i as collapsed, m as default, p as footer, r as group, t as header, u as icon, c as item, d as label, n as nav, a as section, o as sectionCollapsed, s as separator, e as sidebar };
|
|
16
20
|
|
|
17
21
|
//# sourceMappingURL=Sidebar.module.js.map
|
|
@@ -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.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: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":""}
|
|
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 {\n text-decoration: none;\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":""}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../
|
|
1
|
+
const e=require("../components/Input/Input.cjs"),t=require("../utils/format.cjs"),n=require("./br-validators.cjs");let r=require("react"),i=require("react/jsx-runtime");function a(t,n=`numeric`){return(0,r.forwardRef)(function({value:r,onChange:a,...o},s){return(0,i.jsx)(e.Input,{...o,ref:s,value:t(r??``),inputMode:n,onChange:e=>a?.(t(e.target.value))})})}var o=a(t.formatCPF),s=a(n.formatCNPJ),c=a(t.formatPhone,`tel`),l=a(n.formatCEP);function u(e,t,n){return new Intl.NumberFormat(t,{style:`currency`,currency:n}).format(e/100)}function d(e){let t=e.replace(/\D/g,``);return t?Number.parseInt(t,10):0}var f=(0,r.forwardRef)(function({value:t,onChange:n,currency:r=`BRL`,locale:a=`pt-BR`,...o},s){return(0,i.jsx)(e.Input,{...o,ref:s,type:`text`,inputMode:`numeric`,value:u(t||0,a,r),onChange:e=>n(d(e.target.value))})});exports.CEPInput=l,exports.CNPJInput=s,exports.CPFInput=o,exports.MoneyInput=f,exports.PhoneInput=c;
|
|
2
2
|
//# sourceMappingURL=masked-inputs.cjs.map
|
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { Input as e } from "../components/Input/Input.js";
|
|
2
|
+
import { formatCPF as t, formatPhone as n } from "../utils/format.js";
|
|
3
3
|
import { formatCEP as r, formatCNPJ as i } from "./br-validators.js";
|
|
4
4
|
import { forwardRef as a } from "react";
|
|
5
5
|
import { jsx as o } from "react/jsx-runtime";
|
|
6
6
|
//#region src/forms/masked-inputs.tsx
|
|
7
|
-
function s(
|
|
7
|
+
function s(t, n = "numeric") {
|
|
8
8
|
return a(function({ value: r, onChange: i, ...a }, s) {
|
|
9
|
-
return /* @__PURE__ */ o(
|
|
9
|
+
return /* @__PURE__ */ o(e, {
|
|
10
10
|
...a,
|
|
11
11
|
ref: s,
|
|
12
|
-
value:
|
|
13
|
-
inputMode:
|
|
14
|
-
onChange: (
|
|
12
|
+
value: t(r ?? ""),
|
|
13
|
+
inputMode: n,
|
|
14
|
+
onChange: (e) => i?.(t(e.target.value))
|
|
15
15
|
});
|
|
16
16
|
});
|
|
17
17
|
}
|
|
18
|
-
var c = s(
|
|
18
|
+
var c = s(t), l = s(i), u = s(n, "tel"), d = s(r);
|
|
19
19
|
function f(e, t, n) {
|
|
20
20
|
return new Intl.NumberFormat(t, {
|
|
21
21
|
style: "currency",
|
|
@@ -26,14 +26,14 @@ function p(e) {
|
|
|
26
26
|
let t = e.replace(/\D/g, "");
|
|
27
27
|
return t ? Number.parseInt(t, 10) : 0;
|
|
28
28
|
}
|
|
29
|
-
var m = a(function({ value:
|
|
30
|
-
return /* @__PURE__ */ o(
|
|
29
|
+
var m = a(function({ value: t, onChange: n, currency: r = "BRL", locale: i = "pt-BR", ...a }, s) {
|
|
30
|
+
return /* @__PURE__ */ o(e, {
|
|
31
31
|
...a,
|
|
32
32
|
ref: s,
|
|
33
33
|
type: "text",
|
|
34
34
|
inputMode: "numeric",
|
|
35
|
-
value: f(
|
|
36
|
-
onChange: (e) =>
|
|
35
|
+
value: f(t || 0, i, r),
|
|
36
|
+
onChange: (e) => n(p(e.target.value))
|
|
37
37
|
});
|
|
38
38
|
});
|
|
39
39
|
//#endregion
|
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 i=new Set([`GET`,`HEAD`,`OPTIONS`]),a=new Set([0,408,425,429]);function o(e,t){return!i.has(t)||!(e instanceof n.TempestApiError)?!1:a.has(e.status)||e.status>=500}function s(e){return e?e===!0?{}:e:null}function c(e){return typeof FormData<`u`&&e instanceof FormData}async function
|
|
1
|
+
const e=require("../utils/ids.cjs"),t=require("./build-url.cjs"),n=require("./errors.cjs"),r=require("./retry.cjs");var i=new Set([`GET`,`HEAD`,`OPTIONS`]),a=new Set([0,408,425,429]);function o(e,t){return!i.has(t)||!(e instanceof n.TempestApiError)?!1:a.has(e.status)||e.status>=500}function s(e){return e?e===!0?{}:e:null}function c(e){return typeof FormData<`u`&&e instanceof FormData}function l(e){return Math.round(performance.now()-e)}async function u(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 d(n){let i=n.fetcher??globalThis.fetch.bind(globalThis);function a(){let e=n.getToken?.();return e?{Authorization:`Bearer ${e}`}:{}}async function d(e,r,o){let{body:s,params:l,headers:u,...d}=r,f=c(s),p={...f?{}:{"Content-Type":`application/json`},...o?{"X-Request-ID":o}:{},...n.headers,...a(),...u},m={...d,headers:p,credentials:n.withCredentials?`include`:d.credentials,body:s==null?void 0:f?s:JSON.stringify(s)};return i(t.buildApiUrl(n.baseURL,e,{prefix:n.prefix,params:l}),m)}async function f(e,t,r,i){let a=n.logger;if(!a)return d(e,t,r);let o=performance.now();try{let n=await d(e,t,r),s={requestId:r,status:n.status,ms:l(o)},c=`${i} ${e} → ${n.status}`;return n.status>=400?a.warn(c,s):a.debug(c,s),n}catch(t){throw a.warn(`${i} ${e} → no response`,{requestId:r,ms:l(o),error:t}),t}}async function p(e,t){if(n.onUnauthorized){n.logger?.warn(`unauthorized — calling onUnauthorized`,{requestId:t,status:e.status});try{await n.onUnauthorized(e)}catch(r){n.logger?.warn(`onUnauthorized threw — keeping the original response error`,{requestId:t,status:e.status,error:r})}}}async function m(t,r){let i=n.requestId?n.requestId():e.randomId(),a=(r.method??`GET`).toUpperCase(),o=await f(t,r,i,a);if(o.status===401){if(n.refresh){try{await n.refresh(),o=await f(t,r,i,a)}catch{throw await p(o,i),await u(o,i)}o.status===401&&await p(o,i)}else await p(o,i)}if(!o.ok)throw await u(o,i);if(o.status!==204)return(o.headers.get(`content-type`)??``).includes(`application/json`)?await o.json():await o.text()}async function h(e,t={}){let i=s(n.retry);if(!i)return m(e,t);let a=(t.method??`GET`).toUpperCase();return r.retry(()=>m(e,t),{...i,shouldRetry:i.shouldRetry??(e=>o(e,a))})}async function g(e,t,n=`POST`){return h(e,{method:n,body:t})}return{request:h,get:(e,t)=>h(e,{...t,method:`GET`}),post:(e,t)=>h(e,{...t,method:`POST`}),put:(e,t)=>h(e,{...t,method:`PUT`}),patch:(e,t)=>h(e,{...t,method:`PATCH`}),delete:(e,t)=>h(e,{...t,method:`DELETE`}),upload:g}}exports.createApiClient=d;
|
|
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 } 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 */\nconst RETRIABLE_STATUSES: ReadonlySet<number> = new Set([0, 408, 425, 429]);\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 RETRIABLE_STATUSES.has(error.status) || error.status >= 500;\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\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 = Date.now();\n try {\n const response = await rawRequest(path, options, requestId);\n const entry = { requestId, status: response.status, ms: Date.now() - 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: Date.now() - startedAt,\n error,\n });\n throw error;\n }\n }\n\n async function endSession(response: Response, requestId: string): Promise<void> {\n config.logger?.warn(`unauthorized — calling onUnauthorized`, {\n requestId,\n status: response.status,\n });\n await config.onUnauthorized?.(response);\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 endSession(response, requestId);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await endSession(response, requestId);\n }\n } else {\n await endSession(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,EAO5E,EAA0C,IAAI,IAAI,CAAC,EAAG,IAAK,IAAK,GAAG,CAAC,EAc1E,SAAS,EAAmB,EAAgB,EAAyB,CAGjE,MAFI,CAAC,EAAmB,IAAI,CAAM,GAC9B,EAAE,aAAiB,EAAA,iBAAyB,GACzC,EAAmB,IAAI,EAAM,MAAM,GAAK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xB,OAJoB,EAAS,QAAQ,IAAI,cAAc,GAAK,GAAA,CAC5C,SAAS,kBAAkB,EAC/B,MAAM,EAAS,KAAK,EAExB,MAAM,EAAS,KAAK,CAChC,CAEA,eAAe,EAAW,EAAc,EAA0B,CAAC,EAAe,CAC9E,IAAM,EAAe,EAAa,EAAO,KAAK,EAC9C,GAAI,CAAC,EAAc,OAAO,EAAW,EAAM,CAAO,EAElD,IAAM,GAAU,EAAQ,QAAU,MAAA,CAAO,YAAY,EACrD,OAAO,EAAA,UAAuB,EAAW,EAAM,CAAO,EAAG,CACrD,GAAG,EACH,YACI,EAAa,cAAiB,GAAmB,EAAmB,EAAO,CAAM,EACzF,CAAC,CACL,CAEA,eAAe,EACX,EACA,EACA,EAAmC,OACzB,CACV,OAAO,EAAW,EAAM,CAAE,SAAQ,KAAM,CAAS,CAAC,CACtD,CAEA,MAAO,CACH,UACA,KAAS,EAAc,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 } 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 */\nconst RETRIABLE_STATUSES: ReadonlySet<number> = new Set([0, 408, 425, 429]);\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 RETRIABLE_STATUSES.has(error.status) || error.status >= 500;\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,EAO5E,EAA0C,IAAI,IAAI,CAAC,EAAG,IAAK,IAAK,GAAG,CAAC,EAc1E,SAAS,EAAmB,EAAgB,EAAyB,CAGjE,MAFI,CAAC,EAAmB,IAAI,CAAM,GAC9B,EAAE,aAAiB,EAAA,iBAAyB,GACzC,EAAmB,IAAI,EAAM,MAAM,GAAK,EAAM,QAAU,GACnE,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
24
24
|
}
|
|
25
|
-
|
|
25
|
+
function u(e) {
|
|
26
|
+
return Math.round(performance.now() - e);
|
|
27
|
+
}
|
|
28
|
+
async function d(e, t) {
|
|
26
29
|
let i;
|
|
27
30
|
try {
|
|
28
31
|
i = await e.clone().json();
|
|
@@ -35,7 +38,7 @@ async function u(e, t) {
|
|
|
35
38
|
}
|
|
36
39
|
return new n(r(e.status, i, e.headers, t));
|
|
37
40
|
}
|
|
38
|
-
function
|
|
41
|
+
function f(n) {
|
|
39
42
|
let r = n.fetcher ?? globalThis.fetch.bind(globalThis);
|
|
40
43
|
function a() {
|
|
41
44
|
let e = n.getToken?.();
|
|
@@ -59,87 +62,98 @@ function d(n) {
|
|
|
59
62
|
params: c
|
|
60
63
|
}), m);
|
|
61
64
|
}
|
|
62
|
-
async function
|
|
65
|
+
async function f(e, t, r, i) {
|
|
63
66
|
let a = n.logger;
|
|
64
67
|
if (!a) return o(e, t, r);
|
|
65
|
-
let s =
|
|
68
|
+
let s = performance.now();
|
|
66
69
|
try {
|
|
67
70
|
let n = await o(e, t, r), c = {
|
|
68
71
|
requestId: r,
|
|
69
72
|
status: n.status,
|
|
70
|
-
ms:
|
|
73
|
+
ms: u(s)
|
|
71
74
|
}, l = `${i} ${e} → ${n.status}`;
|
|
72
75
|
return n.status >= 400 ? a.warn(l, c) : a.debug(l, c), n;
|
|
73
76
|
} catch (t) {
|
|
74
77
|
throw a.warn(`${i} ${e} → no response`, {
|
|
75
78
|
requestId: r,
|
|
76
|
-
ms:
|
|
79
|
+
ms: u(s),
|
|
77
80
|
error: t
|
|
78
81
|
}), t;
|
|
79
82
|
}
|
|
80
83
|
}
|
|
81
|
-
async function
|
|
82
|
-
n.
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
84
|
+
async function p(e, t) {
|
|
85
|
+
if (n.onUnauthorized) {
|
|
86
|
+
n.logger?.warn("unauthorized — calling onUnauthorized", {
|
|
87
|
+
requestId: t,
|
|
88
|
+
status: e.status
|
|
89
|
+
});
|
|
90
|
+
try {
|
|
91
|
+
await n.onUnauthorized(e);
|
|
92
|
+
} catch (r) {
|
|
93
|
+
n.logger?.warn("onUnauthorized threw — keeping the original response error", {
|
|
94
|
+
requestId: t,
|
|
95
|
+
status: e.status,
|
|
96
|
+
error: r
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
86
100
|
}
|
|
87
|
-
async function
|
|
88
|
-
let i = n.requestId ? n.requestId() : e(), a = (r.method ?? "GET").toUpperCase(), o = await
|
|
101
|
+
async function m(t, r) {
|
|
102
|
+
let i = n.requestId ? n.requestId() : e(), a = (r.method ?? "GET").toUpperCase(), o = await f(t, r, i, a);
|
|
89
103
|
if (o.status === 401) {
|
|
90
104
|
if (n.refresh) {
|
|
91
105
|
try {
|
|
92
|
-
await n.refresh(), o = await
|
|
106
|
+
await n.refresh(), o = await f(t, r, i, a);
|
|
93
107
|
} catch {
|
|
94
|
-
throw await
|
|
108
|
+
throw await p(o, i), await d(o, i);
|
|
95
109
|
}
|
|
96
|
-
o.status === 401 && await
|
|
97
|
-
} else await
|
|
110
|
+
o.status === 401 && await p(o, i);
|
|
111
|
+
} else await p(o, i);
|
|
98
112
|
}
|
|
99
|
-
if (!o.ok) throw await
|
|
113
|
+
if (!o.ok) throw await d(o, i);
|
|
100
114
|
if (o.status !== 204) return (o.headers.get("content-type") ?? "").includes("application/json") ? await o.json() : await o.text();
|
|
101
115
|
}
|
|
102
|
-
async function
|
|
116
|
+
async function h(e, t = {}) {
|
|
103
117
|
let r = c(n.retry);
|
|
104
|
-
if (!r) return
|
|
118
|
+
if (!r) return m(e, t);
|
|
105
119
|
let a = (t.method ?? "GET").toUpperCase();
|
|
106
|
-
return i(() =>
|
|
120
|
+
return i(() => m(e, t), {
|
|
107
121
|
...r,
|
|
108
122
|
shouldRetry: r.shouldRetry ?? ((e) => s(e, a))
|
|
109
123
|
});
|
|
110
124
|
}
|
|
111
|
-
async function
|
|
112
|
-
return
|
|
125
|
+
async function g(e, t, n = "POST") {
|
|
126
|
+
return h(e, {
|
|
113
127
|
method: n,
|
|
114
128
|
body: t
|
|
115
129
|
});
|
|
116
130
|
}
|
|
117
131
|
return {
|
|
118
|
-
request:
|
|
119
|
-
get: (e, t) =>
|
|
132
|
+
request: h,
|
|
133
|
+
get: (e, t) => h(e, {
|
|
120
134
|
...t,
|
|
121
135
|
method: "GET"
|
|
122
136
|
}),
|
|
123
|
-
post: (e, t) =>
|
|
137
|
+
post: (e, t) => h(e, {
|
|
124
138
|
...t,
|
|
125
139
|
method: "POST"
|
|
126
140
|
}),
|
|
127
|
-
put: (e, t) =>
|
|
141
|
+
put: (e, t) => h(e, {
|
|
128
142
|
...t,
|
|
129
143
|
method: "PUT"
|
|
130
144
|
}),
|
|
131
|
-
patch: (e, t) =>
|
|
145
|
+
patch: (e, t) => h(e, {
|
|
132
146
|
...t,
|
|
133
147
|
method: "PATCH"
|
|
134
148
|
}),
|
|
135
|
-
delete: (e, t) =>
|
|
149
|
+
delete: (e, t) => h(e, {
|
|
136
150
|
...t,
|
|
137
151
|
method: "DELETE"
|
|
138
152
|
}),
|
|
139
|
-
upload:
|
|
153
|
+
upload: g
|
|
140
154
|
};
|
|
141
155
|
}
|
|
142
156
|
//#endregion
|
|
143
|
-
export {
|
|
157
|
+
export { f as createApiClient };
|
|
144
158
|
|
|
145
159
|
//# 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 } 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 */\nconst RETRIABLE_STATUSES: ReadonlySet<number> = new Set([0, 408, 425, 429]);\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 RETRIABLE_STATUSES.has(error.status) || error.status >= 500;\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\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 = Date.now();\n try {\n const response = await rawRequest(path, options, requestId);\n const entry = { requestId, status: response.status, ms: Date.now() - 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: Date.now() - startedAt,\n error,\n });\n throw error;\n }\n }\n\n async function endSession(response: Response, requestId: string): Promise<void> {\n config.logger?.warn(`unauthorized — calling onUnauthorized`, {\n requestId,\n status: response.status,\n });\n await config.onUnauthorized?.(response);\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 endSession(response, requestId);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await endSession(response, requestId);\n }\n } else {\n await endSession(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,GAO5E,oBAA0C,IAAI,IAAI;CAAC;CAAG;CAAK;CAAK;AAAG,CAAC;AAc1E,SAAS,EAAmB,GAAgB,GAAyB;CAGjE,OAFI,CAAC,EAAmB,IAAI,CAAM,KAC9B,EAAE,aAAiB,KAAyB,KACzC,EAAmB,IAAI,EAAM,MAAM,KAAK,EAAM,UAAU;AACnE;AAQA,SAAS,EAAa,GAAiE;CAEnF,OADK,IACE,MAAW,KAAO,CAAC,IAAI,IADV;AAExB;AAEA,SAAS,EAAW,GAAiC;CACjD,OAAO,OAAO,WAAa,OAAe,aAAgB;AAC9D;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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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 } 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 */\nconst RETRIABLE_STATUSES: ReadonlySet<number> = new Set([0, 408, 425, 429]);\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 RETRIABLE_STATUSES.has(error.status) || error.status >= 500;\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,GAO5E,oBAA0C,IAAI,IAAI;CAAC;CAAG;CAAK;CAAK;AAAG,CAAC;AAc1E,SAAS,EAAmB,GAAgB,GAAyB;CAGjE,OAFI,CAAC,EAAmB,IAAI,CAAM,KAC9B,EAAE,aAAiB,KAAyB,KACzC,EAAmB,IAAI,EAAM,MAAM,KAAK,EAAM,UAAU;AACnE;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,CACx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AW,GAAM,CAAO,GAAG;GACrD,GAAG;GACH,aACI,EAAa,iBAAiB,MAAmB,EAAmB,GAAO,CAAM;EACzF,CAAC;CACL;CAEA,eAAe,EACX,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,2 +1,2 @@
|
|
|
1
|
-
const e=require("./errors.cjs");var t={offline:`Sem conexão com o servidor. Verifique sua internet e tente de novo.`},n=`tempest.error.offline`;function
|
|
1
|
+
const e=require("./errors.cjs");var t={offline:`Sem conexão com o servidor. Verifique sua internet e tente de novo.`,validation:`Confira os campos destacados e tente de novo.`},n=`tempest.error.offline`,r=`tempest.error.validation`;function i(e){return`Erro ${e}`}function a(){return typeof navigator<`u`&&navigator.onLine===!1}function o(n,r,o){let s=o?.offline??t.offline;if(e.isApiError(n)){if(n.status===0)return s;if(n.fields&&Object.keys(n.fields).length>0)return o?.validation??t.validation;let e=n.detail.trim();return e!==``&&e!==i(n.status)?e:`${r} (HTTP ${n.status})`}return a()?s:r}exports.API_ERROR_OFFLINE_KEY=n,exports.API_ERROR_VALIDATION_KEY=r,exports.DEFAULT_API_ERROR_STRINGS=t,exports.describeApiError=o;
|
|
2
2
|
//# sourceMappingURL=describe-api-error.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"describe-api-error.cjs","names":[],"sources":["../../src/http/describe-api-error.ts"],"sourcesContent":["// The last mile of error handling: a typed error is what code reads, a sentence\n// is what a person reads, and every app was writing the funnel between the two.\n// The case everyone forgets is the request that never reached the server, which\n// without special handling renders as the nonsense \"erro 0\".\n\nimport { isApiError } from \"./errors\";\n\n/** The
|
|
1
|
+
{"version":3,"file":"describe-api-error.cjs","names":[],"sources":["../../src/http/describe-api-error.ts"],"sourcesContent":["// The last mile of error handling: a typed error is what code reads, a sentence\n// is what a person reads, and every app was writing the funnel between the two.\n// The case everyone forgets is the request that never reached the server, which\n// without special handling renders as the nonsense \"erro 0\".\n\nimport { isApiError } from \"./errors\";\n\n/** The fixed sentences {@link describeApiError} may need. */\nexport interface ApiErrorStrings {\n /** Shown when the request never reached the server. */\n offline: string;\n /**\n * Shown when the backend rejected the payload field by field.\n *\n * The per-field messages are on `error.fields`, to be attached to the inputs\n * themselves; this sentence is what the toast says.\n */\n validation: string;\n}\n\n/**\n * PT-BR defaults, used when no strings are supplied and no catalog answers.\n *\n * The SDK's copy is pt-BR everywhere else (`FilterBar`, `DataTable`, `Chat`), so\n * the default here matches rather than introducing an English string that only\n * shows up on a network failure.\n */\nexport const DEFAULT_API_ERROR_STRINGS: ApiErrorStrings = {\n offline: \"Sem conexão com o servidor. Verifique sua internet e tente de novo.\",\n validation: \"Confira os campos destacados e tente de novo.\",\n};\n\n/**\n * Translation key the {@link useDescribeApiError} hook looks up.\n *\n * A catalog that does not define it falls back to\n * {@link DEFAULT_API_ERROR_STRINGS}, because `t` returns the key itself when the\n * lookup misses and printing `tempest.error.offline` at the user would be worse\n * than printing pt-BR at them.\n */\nexport const API_ERROR_OFFLINE_KEY = \"tempest.error.offline\";\n\n/**\n * Translation key for the validation sentence, looked up the same way as\n * {@link API_ERROR_OFFLINE_KEY}.\n */\nexport const API_ERROR_VALIDATION_KEY = \"tempest.error.validation\";\n\n/**\n * Detail text `buildApiError` synthesises when the response body carries none.\n *\n * Ported from `buildApiError` in `errors.ts`, which falls back to `Erro ${status}`.\n * Recognising it here is what lets the caller's `fallback` win: \"Erro 500\" says\n * strictly less than \"Não foi possível carregar os pedidos\".\n *\n * @param status - The HTTP status of the error.\n * @returns The synthetic detail for that status.\n */\nfunction syntheticDetail(status: number): string {\n return `Erro ${status}`;\n}\n\n/**\n * Whether the browser currently reports itself as offline.\n *\n * `fetch` rejects a network failure with a plain `TypeError` whose message\n * differs per browser (\"Failed to fetch\", \"NetworkError when attempting to fetch\n * resource.\", \"Load failed\"), so sniffing the message is not portable. The online\n * flag is, and it is the signal that matters for the sentence being chosen.\n *\n * @returns `true` only when the environment positively says it is offline.\n */\nfunction browserIsOffline(): boolean {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n}\n\n/**\n * Turn any caught value into a sentence worth showing.\n *\n * The funnel, in order:\n *\n * 1. A request that never reached the server — `status === 0`, or a non-API\n * error thrown while the browser reports itself offline — produces the\n * offline sentence. This is the step apps skip, and skipping it renders\n * \"erro 0\" or a raw `TypeError` at the user.\n * 2. A validation rejection — `error.fields` is set — produces the validation\n * sentence, **not** `detail`. On a `422` the `detail` line is assembled from\n * the backend's field paths and the validator's own wording\n * (`\"items.0.price: Input should be greater than 0\"`), which is right for a\n * log and wrong for a person: it is half English in a pt-BR screen and it\n * names internals. The per-field messages stay on `fields`, where a form can\n * attach them to the inputs that failed.\n * 3. The backend's own `detail`, which is the most specific thing available and\n * is already written for a person.\n * 4. `fallback`, with `(HTTP <status>)` appended when a status is known, so the\n * screenshot in the support ticket carries the one fact a developer needs.\n *\n * Pure on purpose: it works in an interceptor, in a logger and anywhere outside\n * the React tree. {@link useDescribeApiError} is the same funnel with the\n * sentences resolved through `I18nProvider`.\n *\n * @example\n * catch (error) {\n * toast(describeApiError(error, \"Não foi possível salvar o pedido\"));\n * }\n *\n * @param error - The caught value, of any shape.\n * @param fallback - What to say when the error carries nothing better.\n * @param strings - Overrides for the fixed sentences.\n * @returns A sentence to show the user.\n */\nexport function describeApiError(\n error: unknown,\n fallback: string,\n strings?: Partial<ApiErrorStrings>,\n): string {\n const offline = strings?.offline ?? DEFAULT_API_ERROR_STRINGS.offline;\n\n if (isApiError(error)) {\n if (error.status === 0) return offline;\n if (error.fields && Object.keys(error.fields).length > 0) {\n return strings?.validation ?? DEFAULT_API_ERROR_STRINGS.validation;\n }\n const detail = error.detail.trim();\n if (detail !== \"\" && detail !== syntheticDetail(error.status)) return detail;\n return `${fallback} (HTTP ${error.status})`;\n }\n\n if (browserIsOffline()) return offline;\n\n return fallback;\n}\n"],"mappings":"gCA2BA,IAAa,EAA6C,CACtD,QAAS,sEACT,WAAY,+CAChB,EAUa,EAAwB,wBAMxB,EAA2B,2BAYxC,SAAS,EAAgB,EAAwB,CAC7C,MAAO,QAAQ,GACnB,CAYA,SAAS,GAA4B,CACjC,OAAO,OAAO,UAAc,KAAe,UAAU,SAAW,EACpE,CAqCA,SAAgB,EACZ,EACA,EACA,EACM,CACN,IAAM,EAAU,GAAS,SAAW,EAA0B,QAE9D,GAAI,EAAA,WAAW,CAAK,EAAG,CACnB,GAAI,EAAM,SAAW,EAAG,OAAO,EAC/B,GAAI,EAAM,QAAU,OAAO,KAAK,EAAM,MAAM,CAAC,CAAC,OAAS,EACnD,OAAO,GAAS,YAAc,EAA0B,WAE5D,IAAM,EAAS,EAAM,OAAO,KAAK,EAEjC,OADI,IAAW,IAAM,IAAW,EAAgB,EAAM,MAAM,EAAU,EAC/D,GAAG,EAAS,SAAS,EAAM,OAAO,EAC7C,CAIA,OAFI,EAAiB,EAAU,EAExB,CACX"}
|
|
@@ -1,22 +1,26 @@
|
|
|
1
1
|
import { isApiError as e } from "./errors.js";
|
|
2
2
|
//#region src/http/describe-api-error.ts
|
|
3
|
-
var t = {
|
|
4
|
-
|
|
3
|
+
var t = {
|
|
4
|
+
offline: "Sem conexão com o servidor. Verifique sua internet e tente de novo.",
|
|
5
|
+
validation: "Confira os campos destacados e tente de novo."
|
|
6
|
+
}, n = "tempest.error.offline", r = "tempest.error.validation";
|
|
7
|
+
function i(e) {
|
|
5
8
|
return `Erro ${e}`;
|
|
6
9
|
}
|
|
7
|
-
function
|
|
10
|
+
function a() {
|
|
8
11
|
return typeof navigator < "u" && navigator.onLine === !1;
|
|
9
12
|
}
|
|
10
|
-
function
|
|
13
|
+
function o(n, r, o) {
|
|
11
14
|
let s = o?.offline ?? t.offline;
|
|
12
15
|
if (e(n)) {
|
|
13
16
|
if (n.status === 0) return s;
|
|
17
|
+
if (n.fields && Object.keys(n.fields).length > 0) return o?.validation ?? t.validation;
|
|
14
18
|
let e = n.detail.trim();
|
|
15
|
-
return e !== "" && e !==
|
|
19
|
+
return e !== "" && e !== i(n.status) ? e : `${r} (HTTP ${n.status})`;
|
|
16
20
|
}
|
|
17
|
-
return
|
|
21
|
+
return a() ? s : r;
|
|
18
22
|
}
|
|
19
23
|
//#endregion
|
|
20
|
-
export { n as API_ERROR_OFFLINE_KEY, t as DEFAULT_API_ERROR_STRINGS,
|
|
24
|
+
export { n as API_ERROR_OFFLINE_KEY, r as API_ERROR_VALIDATION_KEY, t as DEFAULT_API_ERROR_STRINGS, o as describeApiError };
|
|
21
25
|
|
|
22
26
|
//# sourceMappingURL=describe-api-error.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"describe-api-error.js","names":[],"sources":["../../src/http/describe-api-error.ts"],"sourcesContent":["// The last mile of error handling: a typed error is what code reads, a sentence\n// is what a person reads, and every app was writing the funnel between the two.\n// The case everyone forgets is the request that never reached the server, which\n// without special handling renders as the nonsense \"erro 0\".\n\nimport { isApiError } from \"./errors\";\n\n/** The
|
|
1
|
+
{"version":3,"file":"describe-api-error.js","names":[],"sources":["../../src/http/describe-api-error.ts"],"sourcesContent":["// The last mile of error handling: a typed error is what code reads, a sentence\n// is what a person reads, and every app was writing the funnel between the two.\n// The case everyone forgets is the request that never reached the server, which\n// without special handling renders as the nonsense \"erro 0\".\n\nimport { isApiError } from \"./errors\";\n\n/** The fixed sentences {@link describeApiError} may need. */\nexport interface ApiErrorStrings {\n /** Shown when the request never reached the server. */\n offline: string;\n /**\n * Shown when the backend rejected the payload field by field.\n *\n * The per-field messages are on `error.fields`, to be attached to the inputs\n * themselves; this sentence is what the toast says.\n */\n validation: string;\n}\n\n/**\n * PT-BR defaults, used when no strings are supplied and no catalog answers.\n *\n * The SDK's copy is pt-BR everywhere else (`FilterBar`, `DataTable`, `Chat`), so\n * the default here matches rather than introducing an English string that only\n * shows up on a network failure.\n */\nexport const DEFAULT_API_ERROR_STRINGS: ApiErrorStrings = {\n offline: \"Sem conexão com o servidor. Verifique sua internet e tente de novo.\",\n validation: \"Confira os campos destacados e tente de novo.\",\n};\n\n/**\n * Translation key the {@link useDescribeApiError} hook looks up.\n *\n * A catalog that does not define it falls back to\n * {@link DEFAULT_API_ERROR_STRINGS}, because `t` returns the key itself when the\n * lookup misses and printing `tempest.error.offline` at the user would be worse\n * than printing pt-BR at them.\n */\nexport const API_ERROR_OFFLINE_KEY = \"tempest.error.offline\";\n\n/**\n * Translation key for the validation sentence, looked up the same way as\n * {@link API_ERROR_OFFLINE_KEY}.\n */\nexport const API_ERROR_VALIDATION_KEY = \"tempest.error.validation\";\n\n/**\n * Detail text `buildApiError` synthesises when the response body carries none.\n *\n * Ported from `buildApiError` in `errors.ts`, which falls back to `Erro ${status}`.\n * Recognising it here is what lets the caller's `fallback` win: \"Erro 500\" says\n * strictly less than \"Não foi possível carregar os pedidos\".\n *\n * @param status - The HTTP status of the error.\n * @returns The synthetic detail for that status.\n */\nfunction syntheticDetail(status: number): string {\n return `Erro ${status}`;\n}\n\n/**\n * Whether the browser currently reports itself as offline.\n *\n * `fetch` rejects a network failure with a plain `TypeError` whose message\n * differs per browser (\"Failed to fetch\", \"NetworkError when attempting to fetch\n * resource.\", \"Load failed\"), so sniffing the message is not portable. The online\n * flag is, and it is the signal that matters for the sentence being chosen.\n *\n * @returns `true` only when the environment positively says it is offline.\n */\nfunction browserIsOffline(): boolean {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n}\n\n/**\n * Turn any caught value into a sentence worth showing.\n *\n * The funnel, in order:\n *\n * 1. A request that never reached the server — `status === 0`, or a non-API\n * error thrown while the browser reports itself offline — produces the\n * offline sentence. This is the step apps skip, and skipping it renders\n * \"erro 0\" or a raw `TypeError` at the user.\n * 2. A validation rejection — `error.fields` is set — produces the validation\n * sentence, **not** `detail`. On a `422` the `detail` line is assembled from\n * the backend's field paths and the validator's own wording\n * (`\"items.0.price: Input should be greater than 0\"`), which is right for a\n * log and wrong for a person: it is half English in a pt-BR screen and it\n * names internals. The per-field messages stay on `fields`, where a form can\n * attach them to the inputs that failed.\n * 3. The backend's own `detail`, which is the most specific thing available and\n * is already written for a person.\n * 4. `fallback`, with `(HTTP <status>)` appended when a status is known, so the\n * screenshot in the support ticket carries the one fact a developer needs.\n *\n * Pure on purpose: it works in an interceptor, in a logger and anywhere outside\n * the React tree. {@link useDescribeApiError} is the same funnel with the\n * sentences resolved through `I18nProvider`.\n *\n * @example\n * catch (error) {\n * toast(describeApiError(error, \"Não foi possível salvar o pedido\"));\n * }\n *\n * @param error - The caught value, of any shape.\n * @param fallback - What to say when the error carries nothing better.\n * @param strings - Overrides for the fixed sentences.\n * @returns A sentence to show the user.\n */\nexport function describeApiError(\n error: unknown,\n fallback: string,\n strings?: Partial<ApiErrorStrings>,\n): string {\n const offline = strings?.offline ?? DEFAULT_API_ERROR_STRINGS.offline;\n\n if (isApiError(error)) {\n if (error.status === 0) return offline;\n if (error.fields && Object.keys(error.fields).length > 0) {\n return strings?.validation ?? DEFAULT_API_ERROR_STRINGS.validation;\n }\n const detail = error.detail.trim();\n if (detail !== \"\" && detail !== syntheticDetail(error.status)) return detail;\n return `${fallback} (HTTP ${error.status})`;\n }\n\n if (browserIsOffline()) return offline;\n\n return fallback;\n}\n"],"mappings":";;AA2BA,IAAa,IAA6C;CACtD,SAAS;CACT,YAAY;AAChB,GAUa,IAAwB,yBAMxB,IAA2B;AAYxC,SAAS,EAAgB,GAAwB;CAC7C,OAAO,QAAQ;AACnB;AAYA,SAAS,IAA4B;CACjC,OAAO,OAAO,YAAc,OAAe,UAAU,WAAW;AACpE;AAqCA,SAAgB,EACZ,GACA,GACA,GACM;CACN,IAAM,IAAU,GAAS,WAAW,EAA0B;CAE9D,IAAI,EAAW,CAAK,GAAG;EACnB,IAAI,EAAM,WAAW,GAAG,OAAO;EAC/B,IAAI,EAAM,UAAU,OAAO,KAAK,EAAM,MAAM,CAAC,CAAC,SAAS,GACnD,OAAO,GAAS,cAAc,EAA0B;EAE5D,IAAM,IAAS,EAAM,OAAO,KAAK;EAEjC,OADI,MAAW,MAAM,MAAW,EAAgB,EAAM,MAAM,IAAU,IAC/D,GAAG,EAAS,SAAS,EAAM,OAAO;CAC7C;CAIA,OAFI,EAAiB,IAAU,IAExB;AACX"}
|
package/dist/http/errors.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=class extends Error{status;detail;code;requestId;body;constructor(e){super(e.detail),this.name=`TempestApiError`,this.status=e.status,this.detail=e.detail,this.code=e.code,this.requestId=e.requestId,this.body=e.body}};function t(e){return typeof e==`object`&&!!e&&typeof e.status==`number`&&typeof e.detail==`string`}var n=new Set([`body`,`query`,`path`,`header`,`cookie`]);function r(e){if(!Array.isArray(e))return;let t=e.filter(e=>typeof e==`string`||typeof e==`number`).filter((e,t)=>!(t===0&&n.has(String(e))));return t.length>0?t.join(`.`):void 0}function i(e){if(e!=null){if(typeof e==`string`)return e===``?void 0:e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e)){let
|
|
1
|
+
var e=class extends Error{status;detail;code;requestId;fields;body;constructor(e){super(e.detail),this.name=`TempestApiError`,this.status=e.status,this.detail=e.detail,this.code=e.code,this.requestId=e.requestId,this.fields=e.fields,this.body=e.body}};function t(e){return typeof e==`object`&&!!e&&typeof e.status==`number`&&typeof e.detail==`string`}var n=new Set([`body`,`query`,`path`,`header`,`cookie`]);function r(e){if(!Array.isArray(e))return;let t=e.filter(e=>typeof e==`string`||typeof e==`number`).filter((e,t)=>!(t===0&&n.has(String(e))));return t.length>0?t.join(`.`):void 0}var i=4;function a(e){if(!Array.isArray(e))return;let t={};for(let n of e){if(typeof n!=`object`||!n)continue;let e=n,i=r(e.loc);if(i===void 0||i in t)continue;let a=o(e.msg)??o(e.message);a!==void 0&&(t[i]=a)}return Object.keys(t).length>0?t:void 0}function o(e,t=0){if(e!=null){if(typeof e==`string`)return e===``?void 0:e;if(typeof e==`number`||typeof e==`boolean`)return String(e);if(!(t>=i)){if(Array.isArray(e)){let n=e.map(e=>{let n=o(e,t+1);if(n===void 0)return;let i=typeof e==`object`&&e?r(e.loc):void 0;return i===void 0?n:`${i}: ${n}`}).filter(e=>e!==void 0);return n.length>0?n.join(`; `):void 0}if(typeof e==`object`){let n=e;return o(n.msg,t+1)??o(n.message,t+1)??o(n.detail,t+1)}}}}function s(e,t,n,r){let i=typeof t==`object`&&t?t:null,s=o(i?.detail)??o(i?.message)??`Erro ${e}`,l=typeof i?.code==`string`?i.code:void 0,u=typeof i?.details==`object`&&i.details!==null?i.details:null;return{status:e,detail:s,code:l,requestId:(typeof u?.request_id==`string`?u.request_id:void 0)??n?.get(`X-Request-ID`)??r??void 0??void 0,retryAfter:c(n?.get(`Retry-After`)),fields:a(i?.detail),body:t}}function c(e){if(!e)return;let t=e.trim();if(/^\d+$/.test(t))return Number(t);let n=Date.parse(t);if(!Number.isNaN(n))return Math.max(0,Math.round((n-Date.now())/1e3))}exports.TempestApiError=e,exports.buildApiError=s,exports.isApiError=t,exports.parseRetryAfter=c;
|
|
2
2
|
//# sourceMappingURL=errors.cjs.map
|
package/dist/http/errors.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.cjs","names":[],"sources":["../../src/http/errors.ts"],"sourcesContent":["import type { ApiError } from \"./types\";\n\n/**\n * Error thrown by {@link createApiClient} / {@link uploadWithProgress} on a\n * non-2xx response. Mirrors the Tempest FastAPI SDK error envelope\n * (`{ detail, code, details.request_id }`) so callers get a typed `code` and a\n * `requestId` for log correlation, while still being a real `Error` (stack\n * trace, `instanceof Error`).\n *\n * @example\n * try {\n * await api.post(\"/users\", { body });\n * } catch (err) {\n * if (isApiError(err) && err.code === \"EMAIL_TAKEN\") {\n * showFieldError(\"email\", err.detail);\n * }\n * }\n */\nexport class TempestApiError extends Error implements ApiError {\n readonly status: number;\n readonly detail: string;\n readonly code?: string;\n readonly requestId?: string;\n readonly body?: unknown;\n\n constructor(init: ApiError) {\n super(init.detail);\n this.name = \"TempestApiError\";\n this.status = init.status;\n this.detail = init.detail;\n this.code = init.code;\n this.requestId = init.requestId;\n this.body = init.body;\n }\n}\n\n/**\n * Type guard for the {@link ApiError} shape. Matches both {@link TempestApiError}\n * instances and plain objects carrying `status` + `detail`.\n *\n * @param error - The unknown value (typically a caught error).\n * @returns Whether `error` conforms to the `ApiError` contract.\n */\nexport function isApiError(error: unknown): error is ApiError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n typeof (error as ApiError).status === \"number\" &&\n typeof (error as ApiError).detail === \"string\"\n );\n}\n\n/**\n * Location prefixes FastAPI puts at the head of a validation error's `loc`,\n * naming the part of the request rather than the field. Dropped from the\n * rendered path, so `[\"body\", \"email\"]` reads as `email`.\n */\nconst LOC_ROOTS: ReadonlySet<string> = new Set([\"body\", \"query\", \"path\", \"header\", \"cookie\"]);\n\n/**\n * Render a FastAPI validation error's `loc` tuple as a dotted field path.\n *\n * @param loc - The raw `loc` value from one validation error entry.\n * @returns The dotted path (`\"items.0.price\"`), or undefined when `loc` carries\n * nothing addressable.\n */\nfunction formatLoc(loc: unknown): string | undefined {\n if (!Array.isArray(loc)) return undefined;\n const parts = loc\n .filter(\n (part): part is string | number => typeof part === \"string\" || typeof part === \"number\",\n )\n .filter((part, index) => !(index === 0 && LOC_ROOTS.has(String(part))));\n return parts.length > 0 ? parts.join(\".\") : undefined;\n}\n\n/**\n * Collapse a backend `detail` of any shape into a single readable line.\n *\n * FastAPI answers a `422` with `detail` as a **list** of\n * `{ loc, msg, type }` entries, not a string. Passing that through `String()`\n * yields `\"[object Object]\"` — an error message that tells the user nothing and\n * hides which field failed. Each entry becomes `\"<field>: <msg>\"` and the\n * entries are joined with `\"; \"`; a nested object is read through its\n * `msg`/`message`/`detail` string.\n *\n * @param raw - The `detail` (or `message`) value from the error body.\n * @returns The rendered message, or undefined when nothing readable is there —\n * letting the caller fall back to the synthetic `Erro <status>`.\n */\nfunction normalizeDetail(raw: unknown): string | undefined {\n if (raw === null || raw === undefined) return undefined;\n if (typeof raw === \"string\") return raw === \"\" ? undefined : raw;\n if (typeof raw === \"number\" || typeof raw === \"boolean\") return String(raw);\n\n if (Array.isArray(raw)) {\n const lines = raw\n .map((entry) => {\n const message = normalizeDetail(entry);\n if (message === undefined) return undefined;\n const field =\n typeof entry === \"object\" && entry !== null\n ? formatLoc((entry as Record<string, unknown>).loc)\n : undefined;\n return field === undefined ? message : `${field}: ${message}`;\n })\n .filter((line): line is string => line !== undefined);\n return lines.length > 0 ? lines.join(\"; \") : undefined;\n }\n\n if (typeof raw === \"object\") {\n const entry = raw as Record<string, unknown>;\n return (\n normalizeDetail(entry.msg) ??\n normalizeDetail(entry.message) ??\n normalizeDetail(entry.detail)\n );\n }\n\n return undefined;\n}\n\n/**\n * Parse an error body + response into the Tempest {@link ApiError} envelope.\n *\n * Reads `detail`/`message`, the programmatic `code`, and the correlation id\n * from `details.request_id` (falling back to the `X-Request-ID` header, then\n * the id the client sent).\n *\n * A `422` from FastAPI carries `detail` as a list of `{ loc, msg, type }`\n * entries, so it is flattened to `\"<field>: <msg>; <field>: <msg>\"` instead of\n * being stringified into `\"[object Object]\"`. The untouched list stays on\n * `body` for callers that map errors onto form fields.\n *\n * @param status - HTTP status code.\n * @param body - The parsed error body (object, string, or null).\n * @param headers - The response headers (for the `X-Request-ID` fallback).\n * @param sentRequestId - The id the client sent on the request, if any.\n * @returns A fully-populated `ApiError`.\n *\n * @tempest-limits param-count — the arguments are the response as it arrives\n * (`status`, `body`, `headers`) plus the id the request was sent with, and they are\n * passed at exactly one place: the client's response path. Exported from the package\n * root, so the rewrite would be breaking for callers that build their own errors.\n */\nexport function buildApiError(\n status: number,\n body: unknown,\n headers?: Headers | { get(name: string): string | null },\n sentRequestId?: string,\n): ApiError {\n const obj =\n typeof body === \"object\" && body !== null ? (body as Record<string, unknown>) : null;\n const detail =\n normalizeDetail(obj?.detail) ?? normalizeDetail(obj?.message) ?? `Erro ${status}`;\n const code = typeof obj?.code === \"string\" ? obj.code : undefined;\n const details =\n typeof obj?.details === \"object\" && obj.details !== null\n ? (obj.details as Record<string, unknown>)\n : null;\n const requestId =\n (typeof details?.request_id === \"string\" ? details.request_id : undefined) ??\n headers?.get(\"X-Request-ID\") ??\n sentRequestId ??\n undefined;\n\n return {\n status,\n detail,\n code,\n requestId: requestId ?? undefined,\n retryAfter: parseRetryAfter(headers?.get(\"Retry-After\")),\n body,\n };\n}\n\n/**\n * Parse a `Retry-After` header into seconds. Accepts a delta-seconds integer\n * (`\"120\"`) or an HTTP-date (`\"Wed, 21 Oct 2015 07:28:00 GMT\"`).\n *\n * @param value - The raw header value, or null.\n * @returns The delay in seconds (>= 0), or undefined when absent/unparseable.\n */\nexport function parseRetryAfter(value: string | null | undefined): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const when = Date.parse(trimmed);\n if (Number.isNaN(when)) return undefined;\n return Math.max(0, Math.round((when - Date.now()) / 1000));\n}\n"],"mappings":"AAkBA,IAAa,EAAb,cAAqC,KAA0B,CAC3D,OACA,OACA,KACA,UACA,KAEA,YAAY,EAAgB,CACxB,MAAM,EAAK,MAAM,EACjB,KAAK,KAAO,kBACZ,KAAK,OAAS,EAAK,OACnB,KAAK,OAAS,EAAK,OACnB,KAAK,KAAO,EAAK,KACjB,KAAK,UAAY,EAAK,UACtB,KAAK,KAAO,EA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,EACA,EACA,EACA,EACQ,CACR,IAAM,EACF,OAAO,GAAS,UAAY,EAAiB,EAAmC,KAC9E,EACF,EAAgB,GAAK,MAAM,GAAK,EAAgB,GAAK,OAAO,GAAK,QAAQ,IACvE,EAAO,OAAO,GAAK,MAAS,SAAW,EAAI,KAAO,IAAA,GAClD,EACF,OAAO,GAAK,SAAY,UAAY,EAAI,UAAY,KAC7C,EAAI,QACL,KAOV,MAAO,CACH,SACA,SACA,OACA,WATC,OAAO,GAAS,YAAe,SAAW,EAAQ,WAAa,IAAA,KAChE,GAAS,IAAI,cAAc,GAC3B,GACA,IAAA,IAMwB,IAAA,GACxB,WAAY,EAAgB,GAAS,IAAI,aAAa,CAAC,EACvD,MACJ,CACJ,CASA,SAAgB,EAAgB,EAAsD,CAClF,GAAI,CAAC,EAAO,OACZ,IAAM,EAAU,EAAM,KAAK,EAC3B,GAAI,QAAQ,KAAK,CAAO,EAAG,OAAO,OAAO,CAAO,EAChD,IAAM,EAAO,KAAK,MAAM,CAAO,EAC3B,WAAO,MAAM,CAAI,EACrB,OAAO,KAAK,IAAI,EAAG,KAAK,OAAO,EAAO,KAAK,IAAI,GAAK,GAAI,CAAC,CAC7D"}
|
|
1
|
+
{"version":3,"file":"errors.cjs","names":[],"sources":["../../src/http/errors.ts"],"sourcesContent":["import type { ApiError } from \"./types\";\n\n/**\n * Error thrown by {@link createApiClient} / {@link uploadWithProgress} on a\n * non-2xx response. Mirrors the Tempest FastAPI SDK error envelope\n * (`{ detail, code, details.request_id }`) so callers get a typed `code` and a\n * `requestId` for log correlation, while still being a real `Error` (stack\n * trace, `instanceof Error`).\n *\n * @example\n * try {\n * await api.post(\"/users\", { body });\n * } catch (err) {\n * if (isApiError(err) && err.code === \"EMAIL_TAKEN\") {\n * showFieldError(\"email\", err.detail);\n * }\n * }\n */\nexport class TempestApiError extends Error implements ApiError {\n readonly status: number;\n readonly detail: string;\n readonly code?: string;\n readonly requestId?: string;\n readonly fields?: Record<string, string>;\n readonly body?: unknown;\n\n constructor(init: ApiError) {\n super(init.detail);\n this.name = \"TempestApiError\";\n this.status = init.status;\n this.detail = init.detail;\n this.code = init.code;\n this.requestId = init.requestId;\n this.fields = init.fields;\n this.body = init.body;\n }\n}\n\n/**\n * Type guard for the {@link ApiError} shape. Matches both {@link TempestApiError}\n * instances and plain objects carrying `status` + `detail`.\n *\n * @param error - The unknown value (typically a caught error).\n * @returns Whether `error` conforms to the `ApiError` contract.\n */\nexport function isApiError(error: unknown): error is ApiError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n typeof (error as ApiError).status === \"number\" &&\n typeof (error as ApiError).detail === \"string\"\n );\n}\n\n/**\n * Location prefixes FastAPI puts at the head of a validation error's `loc`,\n * naming the part of the request rather than the field. Dropped from the\n * rendered path, so `[\"body\", \"email\"]` reads as `email`.\n */\nconst LOC_ROOTS: ReadonlySet<string> = new Set([\"body\", \"query\", \"path\", \"header\", \"cookie\"]);\n\n/**\n * Render a FastAPI validation error's `loc` tuple as a dotted field path.\n *\n * @param loc - The raw `loc` value from one validation error entry.\n * @returns The dotted path (`\"items.0.price\"`), or undefined when `loc` carries\n * nothing addressable.\n */\nfunction formatLoc(loc: unknown): string | undefined {\n if (!Array.isArray(loc)) return undefined;\n const parts = loc\n .filter(\n (part): part is string | number => typeof part === \"string\" || typeof part === \"number\",\n )\n .filter((part, index) => !(index === 0 && LOC_ROOTS.has(String(part))));\n return parts.length > 0 ? parts.join(\".\") : undefined;\n}\n\n/**\n * How deep {@link normalizeDetail} follows a nested `detail` before giving up.\n *\n * A real envelope needs two or three levels: the list, an entry, the entry's\n * own `detail`. The cap exists because the body is untrusted input arriving on\n * the error path — a response nesting `{\"detail\":{\"detail\":…}}` twenty thousand\n * deep (a 220 KB body) overflowed the stack, and a `RangeError` thrown while\n * *building* the error is worse than the error: the caller's `catch` stops\n * receiving a `TempestApiError`, so `isApiError` is false, `describeApiError`\n * has nothing to read and the `401` handling never runs.\n */\nconst MAX_DETAIL_DEPTH = 4;\n\n/**\n * Pull field-level messages out of a validation `detail` list.\n *\n * FastAPI's `422` body is `detail: [{ loc, msg, type }]`, which is exactly what\n * a form needs and exactly what the flattened `detail` string destroys. Only the\n * top level is read: a validation error names one field per entry, and following\n * nesting here would invent paths the backend never sent.\n *\n * @param raw - The `detail` value from the error body.\n * @returns Field path to message, or undefined when the body is not a\n * validation list (or carries no entry naming a field).\n */\nfunction collectFields(raw: unknown): Record<string, string> | undefined {\n if (!Array.isArray(raw)) return undefined;\n\n const fields: Record<string, string> = {};\n for (const entry of raw) {\n if (typeof entry !== \"object\" || entry === null) continue;\n const record = entry as Record<string, unknown>;\n const field = formatLoc(record.loc);\n if (field === undefined || field in fields) continue;\n const message = normalizeDetail(record.msg) ?? normalizeDetail(record.message);\n if (message === undefined) continue;\n fields[field] = message;\n }\n\n return Object.keys(fields).length > 0 ? fields : undefined;\n}\n\n/**\n * Collapse a backend `detail` of any shape into a single readable line.\n *\n * FastAPI answers a `422` with `detail` as a **list** of\n * `{ loc, msg, type }` entries, not a string. Passing that through `String()`\n * yields `\"[object Object]\"` — an error message that tells the user nothing and\n * hides which field failed. Each entry becomes `\"<field>: <msg>\"` and the\n * entries are joined with `\"; \"`; a nested object is read through its\n * `msg`/`message`/`detail` string.\n *\n * @param raw - The `detail` (or `message`) value from the error body.\n * @param depth - Current nesting level. Past {@link MAX_DETAIL_DEPTH} the value\n * is treated as unreadable instead of followed further.\n * @returns The rendered message, or undefined when nothing readable is there —\n * letting the caller fall back to the synthetic `Erro <status>`.\n */\nfunction normalizeDetail(raw: unknown, depth: number = 0): string | undefined {\n if (raw === null || raw === undefined) return undefined;\n if (typeof raw === \"string\") return raw === \"\" ? undefined : raw;\n if (typeof raw === \"number\" || typeof raw === \"boolean\") return String(raw);\n if (depth >= MAX_DETAIL_DEPTH) return undefined;\n\n if (Array.isArray(raw)) {\n const lines = raw\n .map((entry) => {\n const message = normalizeDetail(entry, depth + 1);\n if (message === undefined) return undefined;\n const field =\n typeof entry === \"object\" && entry !== null\n ? formatLoc((entry as Record<string, unknown>).loc)\n : undefined;\n return field === undefined ? message : `${field}: ${message}`;\n })\n .filter((line): line is string => line !== undefined);\n return lines.length > 0 ? lines.join(\"; \") : undefined;\n }\n\n if (typeof raw === \"object\") {\n const entry = raw as Record<string, unknown>;\n return (\n normalizeDetail(entry.msg, depth + 1) ??\n normalizeDetail(entry.message, depth + 1) ??\n normalizeDetail(entry.detail, depth + 1)\n );\n }\n\n return undefined;\n}\n\n/**\n * Parse an error body + response into the Tempest {@link ApiError} envelope.\n *\n * Reads `detail`/`message`, the programmatic `code`, and the correlation id\n * from `details.request_id` (falling back to the `X-Request-ID` header, then\n * the id the client sent).\n *\n * A `422` from FastAPI carries `detail` as a list of `{ loc, msg, type }`\n * entries, so it is flattened to `\"<field>: <msg>; <field>: <msg>\"` instead of\n * being stringified into `\"[object Object]\"`, and the same entries are indexed\n * on `fields` (`{ email: \"Field required\" }`) for a form to consume without\n * parsing that line back apart. The untouched body stays on `body`.\n *\n * That flattened `detail` is developer-facing: it carries the backend's field\n * paths and the validator's own wording. `describeApiError` knows not to show it\n * to a person when `fields` is set.\n *\n * @param status - HTTP status code.\n * @param body - The parsed error body (object, string, or null).\n * @param headers - The response headers (for the `X-Request-ID` fallback).\n * @param sentRequestId - The id the client sent on the request, if any.\n * @returns A fully-populated `ApiError`.\n *\n * @tempest-limits param-count — the arguments are the response as it arrives\n * (`status`, `body`, `headers`) plus the id the request was sent with, and they are\n * passed at exactly one place: the client's response path. Exported from the package\n * root, so the rewrite would be breaking for callers that build their own errors.\n */\nexport function buildApiError(\n status: number,\n body: unknown,\n headers?: Headers | { get(name: string): string | null },\n sentRequestId?: string,\n): ApiError {\n const obj =\n typeof body === \"object\" && body !== null ? (body as Record<string, unknown>) : null;\n const detail =\n normalizeDetail(obj?.detail) ?? normalizeDetail(obj?.message) ?? `Erro ${status}`;\n const code = typeof obj?.code === \"string\" ? obj.code : undefined;\n const details =\n typeof obj?.details === \"object\" && obj.details !== null\n ? (obj.details as Record<string, unknown>)\n : null;\n const requestId =\n (typeof details?.request_id === \"string\" ? details.request_id : undefined) ??\n headers?.get(\"X-Request-ID\") ??\n sentRequestId ??\n undefined;\n\n return {\n status,\n detail,\n code,\n requestId: requestId ?? undefined,\n retryAfter: parseRetryAfter(headers?.get(\"Retry-After\")),\n fields: collectFields(obj?.detail),\n body,\n };\n}\n\n/**\n * Parse a `Retry-After` header into seconds. Accepts a delta-seconds integer\n * (`\"120\"`) or an HTTP-date (`\"Wed, 21 Oct 2015 07:28:00 GMT\"`).\n *\n * @param value - The raw header value, or null.\n * @returns The delay in seconds (>= 0), or undefined when absent/unparseable.\n */\nexport function parseRetryAfter(value: string | null | undefined): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const when = Date.parse(trimmed);\n if (Number.isNaN(when)) return undefined;\n return Math.max(0, Math.round((when - Date.now()) / 1000));\n}\n"],"mappings":"AAkBA,IAAa,EAAb,cAAqC,KAA0B,CAC3D,OACA,OACA,KACA,UACA,OACA,KAEA,YAAY,EAAgB,CACxB,MAAM,EAAK,MAAM,EACjB,KAAK,KAAO,kBACZ,KAAK,OAAS,EAAK,OACnB,KAAK,OAAS,EAAK,OACnB,KAAK,KAAO,EAAK,KACjB,KAAK,UAAY,EAAK,UACtB,KAAK,OAAS,EAAK,OACnB,KAAK,KAAO,EAAK,IACrB,CACJ,EASA,SAAgB,EAAW,EAAmC,CAC1D,OACI,OAAO,GAAU,YACjB,GACA,OAAQ,EAAmB,QAAW,UACtC,OAAQ,EAAmB,QAAW,QAE9C,CAOA,IAAM,EAAiC,IAAI,IAAI,CAAC,OAAQ,QAAS,OAAQ,SAAU,QAAQ,CAAC,EAS5F,SAAS,EAAU,EAAkC,CACjD,GAAI,CAAC,MAAM,QAAQ,CAAG,EAAG,OACzB,IAAM,EAAQ,EACT,OACI,GAAkC,OAAO,GAAS,UAAY,OAAO,GAAS,QACnF,CAAC,CACA,QAAQ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