tempest-react-sdk 0.75.0 → 0.77.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.
Files changed (147) hide show
  1. package/README.md +4 -2
  2. package/bin/create-tempest-app.e2e.test.mjs +112 -0
  3. package/bin/create-tempest-app.mjs +69 -28
  4. package/bin/lib/component/generate.mjs +191 -0
  5. package/bin/lib/component/generate.test.mjs +336 -0
  6. package/bin/lib/openapi/escape.mjs +210 -0
  7. package/bin/lib/openapi/generate.hostile.test.mjs +592 -0
  8. package/bin/lib/openapi/generate.mjs +93 -17
  9. package/bin/lib/openapi/schema-to-zod.mjs +41 -4
  10. package/bin/tempest.mjs +184 -3
  11. package/dist/auth/create-tempest-auth.cjs +1 -1
  12. package/dist/auth/create-tempest-auth.cjs.map +1 -1
  13. package/dist/auth/create-tempest-auth.js +127 -55
  14. package/dist/auth/create-tempest-auth.js.map +1 -1
  15. package/dist/auth/refresh-queue.cjs +1 -1
  16. package/dist/auth/refresh-queue.cjs.map +1 -1
  17. package/dist/auth/refresh-queue.js +13 -6
  18. package/dist/auth/refresh-queue.js.map +1 -1
  19. package/dist/br/pix.cjs +1 -1
  20. package/dist/br/pix.cjs.map +1 -1
  21. package/dist/br/pix.js +72 -62
  22. package/dist/br/pix.js.map +1 -1
  23. package/dist/br.d.ts +12 -4
  24. package/dist/components/Chat/ChatAttachments.cjs +1 -1
  25. package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
  26. package/dist/components/Chat/ChatAttachments.js +46 -38
  27. package/dist/components/Chat/ChatAttachments.js.map +1 -1
  28. package/dist/components/Markdown/markdown-parse.cjs +7 -5
  29. package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
  30. package/dist/components/Markdown/markdown-parse.js +151 -87
  31. package/dist/components/Markdown/markdown-parse.js.map +1 -1
  32. package/dist/components/Toast/Toast.module.cjs +1 -1
  33. package/dist/components/Toast/Toast.module.cjs.map +1 -1
  34. package/dist/components/Toast/Toast.module.js +7 -3
  35. package/dist/components/Toast/Toast.module.js.map +1 -1
  36. package/dist/components/Toast/ToastProvider.cjs +1 -1
  37. package/dist/components/Toast/ToastProvider.cjs.map +1 -1
  38. package/dist/components/Toast/ToastProvider.js +77 -51
  39. package/dist/components/Toast/ToastProvider.js.map +1 -1
  40. package/dist/data/create-data-provider.cjs +1 -1
  41. package/dist/data/create-data-provider.cjs.map +1 -1
  42. package/dist/data/create-data-provider.js +32 -21
  43. package/dist/data/create-data-provider.js.map +1 -1
  44. package/dist/http/api-client.cjs +1 -1
  45. package/dist/http/api-client.cjs.map +1 -1
  46. package/dist/http/api-client.js +81 -73
  47. package/dist/http/api-client.js.map +1 -1
  48. package/dist/http/errors.cjs +1 -1
  49. package/dist/http/errors.cjs.map +1 -1
  50. package/dist/http/errors.js +39 -35
  51. package/dist/http/errors.js.map +1 -1
  52. package/dist/neural.cjs +2 -0
  53. package/dist/neural.cjs.map +1 -0
  54. package/dist/neural.d.ts +110 -0
  55. package/dist/neural.js +48 -0
  56. package/dist/neural.js.map +1 -0
  57. package/dist/oauth/callback.cjs +2 -0
  58. package/dist/oauth/callback.cjs.map +1 -0
  59. package/dist/oauth/callback.js +42 -0
  60. package/dist/oauth/callback.js.map +1 -0
  61. package/dist/oauth/use-oauth-callback.cjs +1 -1
  62. package/dist/oauth/use-oauth-callback.cjs.map +1 -1
  63. package/dist/oauth/use-oauth-callback.js +13 -20
  64. package/dist/oauth/use-oauth-callback.js.map +1 -1
  65. package/dist/push/use-push-subscription.cjs +1 -1
  66. package/dist/push/use-push-subscription.cjs.map +1 -1
  67. package/dist/push/use-push-subscription.js +42 -42
  68. package/dist/push/use-push-subscription.js.map +1 -1
  69. package/dist/push/web-push-client.cjs +1 -1
  70. package/dist/push/web-push-client.cjs.map +1 -1
  71. package/dist/push/web-push-client.js +23 -3
  72. package/dist/push/web-push-client.js.map +1 -1
  73. package/dist/query/offline-persistence.cjs +1 -1
  74. package/dist/query/offline-persistence.cjs.map +1 -1
  75. package/dist/query/offline-persistence.js +68 -23
  76. package/dist/query/offline-persistence.js.map +1 -1
  77. package/dist/styles/component/Toast.css +6 -1
  78. package/dist/styles/feedback.css +6 -1
  79. package/dist/styles.css +1 -1
  80. package/dist/sw/background-sync.cjs +1 -1
  81. package/dist/sw/background-sync.cjs.map +1 -1
  82. package/dist/sw/background-sync.js +271 -60
  83. package/dist/sw/background-sync.js.map +1 -1
  84. package/dist/sw/cache-inspect.cjs.map +1 -1
  85. package/dist/sw/cache-inspect.js.map +1 -1
  86. package/dist/sw/cache.cjs +1 -1
  87. package/dist/sw/cache.cjs.map +1 -1
  88. package/dist/sw/cache.js +91 -64
  89. package/dist/sw/cache.js.map +1 -1
  90. package/dist/sw/credential-headers.cjs +2 -0
  91. package/dist/sw/credential-headers.cjs.map +1 -0
  92. package/dist/sw/credential-headers.js +17 -0
  93. package/dist/sw/credential-headers.js.map +1 -0
  94. package/dist/sw/session-data.cjs +2 -0
  95. package/dist/sw/session-data.cjs.map +1 -0
  96. package/dist/sw/session-data.js +17 -0
  97. package/dist/sw/session-data.js.map +1 -0
  98. package/dist/sw.cjs +1 -1
  99. package/dist/sw.d.ts +271 -23
  100. package/dist/sw.js +7 -5
  101. package/dist/telemetry/app-error-owner.cjs +2 -0
  102. package/dist/telemetry/app-error-owner.cjs.map +1 -0
  103. package/dist/telemetry/app-error-owner.js +18 -0
  104. package/dist/telemetry/app-error-owner.js.map +1 -0
  105. package/dist/telemetry/app-error-queue.cjs +1 -1
  106. package/dist/telemetry/app-error-queue.cjs.map +1 -1
  107. package/dist/telemetry/app-error-queue.js +19 -14
  108. package/dist/telemetry/app-error-queue.js.map +1 -1
  109. package/dist/telemetry/app-error-reporter.cjs +1 -1
  110. package/dist/telemetry/app-error-reporter.cjs.map +1 -1
  111. package/dist/telemetry/app-error-reporter.js +75 -34
  112. package/dist/telemetry/app-error-reporter.js.map +1 -1
  113. package/dist/telemetry/app-error-transport.cjs +1 -1
  114. package/dist/telemetry/app-error-transport.cjs.map +1 -1
  115. package/dist/telemetry/app-error-transport.js +16 -3
  116. package/dist/telemetry/app-error-transport.js.map +1 -1
  117. package/dist/tempest-react-sdk.cjs +1 -1
  118. package/dist/tempest-react-sdk.d.ts +979 -62
  119. package/dist/tempest-react-sdk.js +160 -156
  120. package/dist/utils/csv.cjs +3 -3
  121. package/dist/utils/csv.cjs.map +1 -1
  122. package/dist/utils/csv.js +16 -13
  123. package/dist/utils/csv.js.map +1 -1
  124. package/dist/utils/safe-url.cjs +2 -0
  125. package/dist/utils/safe-url.cjs.map +1 -0
  126. package/dist/utils/safe-url.js +39 -0
  127. package/dist/utils/safe-url.js.map +1 -0
  128. package/dist/vite/tempest-csp.cjs +2 -2
  129. package/dist/vite/tempest-csp.cjs.map +1 -1
  130. package/dist/vite/tempest-csp.js +118 -63
  131. package/dist/vite/tempest-csp.js.map +1 -1
  132. package/dist/vite.d.ts +21 -5
  133. package/dist/webrtc/peer-link.cjs +1 -1
  134. package/dist/webrtc/peer-link.cjs.map +1 -1
  135. package/dist/webrtc/peer-link.js +2 -10
  136. package/dist/webrtc/peer-link.js.map +1 -1
  137. package/dist/webrtc/peer-mesh.cjs +1 -1
  138. package/dist/webrtc/peer-mesh.cjs.map +1 -1
  139. package/dist/webrtc/peer-mesh.js +110 -72
  140. package/dist/webrtc/peer-mesh.js.map +1 -1
  141. package/package.json +11 -1
  142. package/template-pwa/src/pwa.tsx +22 -0
  143. package/template-pwa/src/sw.ts +27 -14
  144. package/dist/components/Markdown/markdown-url.cjs +0 -2
  145. package/dist/components/Markdown/markdown-url.cjs.map +0 -1
  146. package/dist/components/Markdown/markdown-url.js +0 -28
  147. package/dist/components/Markdown/markdown-url.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"create-data-provider.cjs","names":[],"sources":["../../src/data/create-data-provider.ts"],"sourcesContent":["import type { ApiClient, RequestOptions } from \"@/http/types\";\nimport type { OffsetPage } from \"@/query/pagination\";\n\n/** Query-param values accepted by the API client for a list request. */\ntype ParamValue = string | number | boolean | undefined | null;\n\n/** Filters passed to {@link DataProvider.getList}, spread verbatim into the query string. */\nexport type DataFilters = Record<string, ParamValue>;\n\n/** Parameters for a paginated, sorted, filtered list request. */\nexport interface GetListParams {\n /** Offset pagination — 1-based `page` and `pageSize`. */\n pagination?: { page?: number; pageSize?: number };\n /** Single-field sort. `order` defaults to `\"asc\"`. */\n sort?: { field: string; order?: \"asc\" | \"desc\" };\n /** Arbitrary filter query params, spread onto the request. */\n filters?: DataFilters;\n}\n\n/**\n * Refine-style data provider over the Tempest FastAPI SDK CRUD/pagination\n * conventions. Implementations are stateless wrappers around an {@link ApiClient}.\n */\nexport interface DataProvider {\n /**\n * Fetch a paginated list of a resource.\n *\n * @param resource - The resource name (e.g. `\"users\"`).\n * @param params - Pagination, sort and filter parameters.\n * @returns The offset-paginated envelope.\n */\n getList<T>(resource: string, params?: GetListParams): Promise<OffsetPage<T>>;\n /**\n * Fetch a single record by id.\n *\n * @param resource - The resource name.\n * @param id - The record id.\n * @returns The record.\n */\n getOne<T>(resource: string, id: string | number): Promise<T>;\n /**\n * Fetch many records by id (default: parallel {@link DataProvider.getOne}).\n *\n * @param resource - The resource name.\n * @param ids - The record ids.\n * @returns The records, in the same order as `ids`.\n */\n getMany<T>(resource: string, ids: (string | number)[]): Promise<T[]>;\n /**\n * Create a record.\n *\n * @param resource - The resource name.\n * @param data - The creation payload.\n * @returns The created record.\n */\n create<T>(resource: string, data: unknown): Promise<T>;\n /**\n * Update a record (PATCH by default, PUT when configured).\n *\n * @param resource - The resource name.\n * @param id - The record id.\n * @param data - The update payload.\n * @returns The updated record.\n */\n update<T>(resource: string, id: string | number, data: unknown): Promise<T>;\n /**\n * Delete a record by id.\n *\n * @param resource - The resource name.\n * @param id - The record id.\n * @returns The delete response (often the deleted record).\n */\n deleteOne<T>(resource: string, id: string | number): Promise<T>;\n}\n\n/** Options to tailor {@link createDataProvider} to a backend's conventions. */\nexport interface DataProviderOptions {\n /** Query-param name for the page number. Default: `\"page\"`. */\n pageParam?: string;\n /** Query-param name for the page size. Default: `\"size\"`. */\n sizeParam?: string;\n /** Query-param name for the sort field. Default: `\"order_by\"`. */\n sortFieldParam?: string;\n /** Query-param name for the sort order. Default: `\"ascending\"`. */\n sortOrderParam?: string;\n /**\n * When `true` (default), emit the sort order as a boolean\n * (`order:\"asc\"` → `true`). When `false`, emit the literal `\"asc\"`/`\"desc\"`.\n */\n sortOrderAsBoolean?: boolean;\n /** HTTP method used by {@link DataProvider.update}. Default: `\"patch\"`. */\n updateMethod?: \"patch\" | \"put\";\n /**\n * Build the request path for a resource (and optional id).\n * Default: `id == null ? \"/\" + resource : \"/\" + resource + \"/\" + id`.\n */\n buildPath?: (resource: string, id?: string | number) => string;\n}\n\nconst defaultBuildPath = (resource: string, id?: string | number): string =>\n id == null ? `/${resource}` : `/${resource}/${id}`;\n\n/**\n * Create a {@link DataProvider} bound to an {@link ApiClient}.\n *\n * Maps Refine-style calls to the Tempest FastAPI SDK conventions: list →\n * `GET /{resource}?page=&size=&order_by=&ascending=&...filters`, one →\n * `GET /{resource}/{id}`, create → `POST`, update → `PATCH`/`PUT`,\n * delete → `DELETE`.\n *\n * @param client - The HTTP client created by `createApiClient`.\n * @param options - Optional overrides for param names, sort encoding,\n * update method and path building.\n * @returns A stateless data provider.\n *\n * @example\n * const dataProvider = createDataProvider(apiClient);\n * const page = await dataProvider.getList<User>(\"users\", {\n * pagination: { page: 1, pageSize: 20 },\n * sort: { field: \"created_at\", order: \"desc\" },\n * filters: { active: true },\n * });\n */\nexport function createDataProvider(\n client: ApiClient,\n options: DataProviderOptions = {},\n): DataProvider {\n const {\n pageParam = \"page\",\n sizeParam = \"size\",\n sortFieldParam = \"order_by\",\n sortOrderParam = \"ascending\",\n sortOrderAsBoolean = true,\n updateMethod = \"patch\",\n buildPath = defaultBuildPath,\n } = options;\n\n const provider: DataProvider = {\n getList<T>(resource: string, params: GetListParams = {}): Promise<OffsetPage<T>> {\n const { pagination, sort, filters } = params;\n const query: Record<string, ParamValue> = {};\n\n if (pagination?.page != null) query[pageParam] = pagination.page;\n if (pagination?.pageSize != null) query[sizeParam] = pagination.pageSize;\n\n if (sort?.field) {\n const order = sort.order ?? \"asc\";\n query[sortFieldParam] = sort.field;\n query[sortOrderParam] = sortOrderAsBoolean ? order === \"asc\" : order;\n }\n\n if (filters) {\n for (const [key, value] of Object.entries(filters)) {\n query[key] = value;\n }\n }\n\n const requestOptions: RequestOptions = { params: query };\n return client.get<OffsetPage<T>>(buildPath(resource), requestOptions);\n },\n\n getOne<T>(resource: string, id: string | number): Promise<T> {\n return client.get<T>(buildPath(resource, id));\n },\n\n getMany<T>(resource: string, ids: (string | number)[]): Promise<T[]> {\n return Promise.all(ids.map((id) => provider.getOne<T>(resource, id)));\n },\n\n create<T>(resource: string, data: unknown): Promise<T> {\n return client.post<T>(buildPath(resource), { body: data });\n },\n\n update<T>(resource: string, id: string | number, data: unknown): Promise<T> {\n const path = buildPath(resource, id);\n return updateMethod === \"put\"\n ? client.put<T>(path, { body: data })\n : client.patch<T>(path, { body: data });\n },\n\n deleteOne<T>(resource: string, id: string | number): Promise<T> {\n return client.delete<T>(buildPath(resource, id));\n },\n };\n\n return provider;\n}\n"],"mappings":"AAmGA,IAAM,GAAoB,EAAkB,IACxC,GAAM,KAAO,IAAI,IAAa,IAAI,EAAS,GAAG,IAuBlD,SAAgB,EACZ,EACA,EAA+B,CAAC,EACpB,CACZ,GAAM,CACF,YAAY,OACZ,YAAY,OACZ,iBAAiB,WACjB,iBAAiB,YACjB,qBAAqB,GACrB,eAAe,QACf,YAAY,GACZ,EAEE,EAAyB,CAC3B,QAAW,EAAkB,EAAwB,CAAC,EAA2B,CAC7E,GAAM,CAAE,aAAY,OAAM,WAAY,EAChC,EAAoC,CAAC,EAK3C,GAHI,GAAY,MAAQ,OAAM,EAAM,GAAa,EAAW,MACxD,GAAY,UAAY,OAAM,EAAM,GAAa,EAAW,UAE5D,GAAM,MAAO,CACb,IAAM,EAAQ,EAAK,OAAS,MAC5B,EAAM,GAAkB,EAAK,MAC7B,EAAM,GAAkB,EAAqB,IAAU,MAAQ,CACnE,CAEA,GAAI,EACA,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAO,EAC7C,EAAM,GAAO,EAIrB,IAAM,EAAiC,CAAE,OAAQ,CAAM,EACvD,OAAO,EAAO,IAAmB,EAAU,CAAQ,EAAG,CAAc,CACxE,EAEA,OAAU,EAAkB,EAAiC,CACzD,OAAO,EAAO,IAAO,EAAU,EAAU,CAAE,CAAC,CAChD,EAEA,QAAW,EAAkB,EAAwC,CACjE,OAAO,QAAQ,IAAI,EAAI,IAAK,GAAO,EAAS,OAAU,EAAU,CAAE,CAAC,CAAC,CACxE,EAEA,OAAU,EAAkB,EAA2B,CACnD,OAAO,EAAO,KAAQ,EAAU,CAAQ,EAAG,CAAE,KAAM,CAAK,CAAC,CAC7D,EAEA,OAAU,EAAkB,EAAqB,EAA2B,CACxE,IAAM,EAAO,EAAU,EAAU,CAAE,EACnC,OAAO,IAAiB,MAClB,EAAO,IAAO,EAAM,CAAE,KAAM,CAAK,CAAC,EAClC,EAAO,MAAS,EAAM,CAAE,KAAM,CAAK,CAAC,CAC9C,EAEA,UAAa,EAAkB,EAAiC,CAC5D,OAAO,EAAO,OAAU,EAAU,EAAU,CAAE,CAAC,CACnD,CACJ,EAEA,OAAO,CACX"}
1
+ {"version":3,"file":"create-data-provider.cjs","names":[],"sources":["../../src/data/create-data-provider.ts"],"sourcesContent":["import type { ApiClient, RequestOptions } from \"@/http/types\";\nimport type { OffsetPage } from \"@/query/pagination\";\n\n/** Query-param values accepted by the API client for a list request. */\ntype ParamValue = string | number | boolean | undefined | null;\n\n/** Filters passed to {@link DataProvider.getList}, spread verbatim into the query string. */\nexport type DataFilters = Record<string, ParamValue>;\n\n/** Parameters for a paginated, sorted, filtered list request. */\nexport interface GetListParams {\n /** Offset pagination — 1-based `page` and `pageSize`. */\n pagination?: { page?: number; pageSize?: number };\n /** Single-field sort. `order` defaults to `\"asc\"`. */\n sort?: { field: string; order?: \"asc\" | \"desc\" };\n /** Arbitrary filter query params, spread onto the request. */\n filters?: DataFilters;\n}\n\n/**\n * Refine-style data provider over the Tempest FastAPI SDK CRUD/pagination\n * conventions. Implementations are stateless wrappers around an {@link ApiClient}.\n */\nexport interface DataProvider {\n /**\n * Fetch a paginated list of a resource.\n *\n * @param resource - The resource name (e.g. `\"users\"`).\n * @param params - Pagination, sort and filter parameters.\n * @returns The offset-paginated envelope.\n */\n getList<T>(resource: string, params?: GetListParams): Promise<OffsetPage<T>>;\n /**\n * Fetch a single record by id.\n *\n * @param resource - The resource name.\n * @param id - The record id.\n * @returns The record.\n */\n getOne<T>(resource: string, id: string | number): Promise<T>;\n /**\n * Fetch many records by id (default: parallel {@link DataProvider.getOne}).\n *\n * @param resource - The resource name.\n * @param ids - The record ids.\n * @returns The records, in the same order as `ids`.\n */\n getMany<T>(resource: string, ids: (string | number)[]): Promise<T[]>;\n /**\n * Create a record.\n *\n * @param resource - The resource name.\n * @param data - The creation payload.\n * @returns The created record.\n */\n create<T>(resource: string, data: unknown): Promise<T>;\n /**\n * Update a record (PATCH by default, PUT when configured).\n *\n * @param resource - The resource name.\n * @param id - The record id.\n * @param data - The update payload.\n * @returns The updated record.\n */\n update<T>(resource: string, id: string | number, data: unknown): Promise<T>;\n /**\n * Delete a record by id.\n *\n * @param resource - The resource name.\n * @param id - The record id.\n * @returns The delete response (often the deleted record).\n */\n deleteOne<T>(resource: string, id: string | number): Promise<T>;\n}\n\n/** Options to tailor {@link createDataProvider} to a backend's conventions. */\nexport interface DataProviderOptions {\n /** Query-param name for the page number. Default: `\"page\"`. */\n pageParam?: string;\n /** Query-param name for the page size. Default: `\"size\"`. */\n sizeParam?: string;\n /** Query-param name for the sort field. Default: `\"order_by\"`. */\n sortFieldParam?: string;\n /** Query-param name for the sort order. Default: `\"ascending\"`. */\n sortOrderParam?: string;\n /**\n * When `true` (default), emit the sort order as a boolean\n * (`order:\"asc\"` → `true`). When `false`, emit the literal `\"asc\"`/`\"desc\"`.\n */\n sortOrderAsBoolean?: boolean;\n /** HTTP method used by {@link DataProvider.update}. Default: `\"patch\"`. */\n updateMethod?: \"patch\" | \"put\";\n /**\n * Build the request path for a resource (and optional id).\n * Default: `id == null ? \"/\" + resource : \"/\" + resource + \"/\" + id`.\n *\n * Since 0.77.0 `id` arrives already passed through {@link encodeIdSegment}:\n * percent-encoded as one path segment, and never `\"\"`, `\".\"` or `\"..\"`. An\n * override therefore interpolates it as-is — encoding it again would turn\n * `%2F` into `%252F`.\n */\n buildPath?: (resource: string, id?: string | number) => string;\n}\n\nconst DOT_SEGMENTS: ReadonlySet<string> = new Set([\"\", \".\", \"..\"]);\n\n/**\n * Encode a record id as exactly one URL path segment.\n *\n * The data provider calls this on every id before building a path, because the\n * id is the one part of the URL that may come from outside the app — a search\n * param, a hash, a decoded route param, a value another user stored. Left raw,\n * `\"../../admin/users\"` walks the authenticated request out of the resource,\n * `\"7?role=admin\"` injects query params and `\"7#x\"` truncates the path, all\n * while the request still carries the bearer token (#438).\n *\n * `encodeURIComponent` neutralises `/`, `?`, `#` and `%`. It leaves `.` alone,\n * so `\"\"`, `\".\"` and `\"..\"` are rejected instead: the URL parser resolves them\n * as dot-segments whatever the encoding, and none of them names a record.\n * `null` and `undefined` — what an untyped caller or a not-yet-loaded route\n * param hands over — are rejected too, since `String()` would turn them into\n * the literal segments `\"null\"` and `\"undefined\"`.\n *\n * @param id - The record id, as handed to the provider.\n * @returns The percent-encoded segment, safe to interpolate between two `/`.\n * @throws {TypeError} When the id is `null`, `undefined`, `\"\"`, `\".\"` or `\"..\"`.\n *\n * @example\n * encodeIdSegment(7); // \"7\"\n * encodeIdSegment(\"a/b?x=1\"); // \"a%2Fb%3Fx%3D1\"\n * encodeIdSegment(\"..\"); // throws TypeError\n */\nexport function encodeIdSegment(id: string | number): string {\n if (id == null) {\n throw new TypeError(`Invalid record id ${String(id)}: a record id is required.`);\n }\n const raw = String(id);\n if (DOT_SEGMENTS.has(raw)) {\n throw new TypeError(\n `Invalid record id ${JSON.stringify(raw)}: it would resolve as a path dot-segment.`,\n );\n }\n return encodeURIComponent(raw);\n}\n\nconst defaultBuildPath = (resource: string, id?: string | number): string =>\n id == null ? `/${resource}` : `/${resource}/${id}`;\n\n/**\n * Create a {@link DataProvider} bound to an {@link ApiClient}.\n *\n * Maps Refine-style calls to the Tempest FastAPI SDK conventions: list →\n * `GET /{resource}?page=&size=&order_by=&ascending=&...filters`, one →\n * `GET /{resource}/{id}`, create → `POST`, update → `PATCH`/`PUT`,\n * delete → `DELETE`.\n *\n * Every id goes through {@link encodeIdSegment} before reaching `buildPath`, so\n * an id can never leave its own path segment — not with the default builder,\n * and not with an override that interpolates it.\n *\n * @param client - The HTTP client created by `createApiClient`.\n * @param options - Optional overrides for param names, sort encoding,\n * update method and path building.\n * @returns A stateless data provider.\n *\n * @example\n * const dataProvider = createDataProvider(apiClient);\n * const page = await dataProvider.getList<User>(\"users\", {\n * pagination: { page: 1, pageSize: 20 },\n * sort: { field: \"created_at\", order: \"desc\" },\n * filters: { active: true },\n * });\n */\nexport function createDataProvider(\n client: ApiClient,\n options: DataProviderOptions = {},\n): DataProvider {\n const {\n pageParam = \"page\",\n sizeParam = \"size\",\n sortFieldParam = \"order_by\",\n sortOrderParam = \"ascending\",\n sortOrderAsBoolean = true,\n updateMethod = \"patch\",\n buildPath = defaultBuildPath,\n } = options;\n\n const provider: DataProvider = {\n getList<T>(resource: string, params: GetListParams = {}): Promise<OffsetPage<T>> {\n const { pagination, sort, filters } = params;\n const query: Record<string, ParamValue> = {};\n\n if (pagination?.page != null) query[pageParam] = pagination.page;\n if (pagination?.pageSize != null) query[sizeParam] = pagination.pageSize;\n\n if (sort?.field) {\n const order = sort.order ?? \"asc\";\n query[sortFieldParam] = sort.field;\n query[sortOrderParam] = sortOrderAsBoolean ? order === \"asc\" : order;\n }\n\n if (filters) {\n for (const [key, value] of Object.entries(filters)) {\n query[key] = value;\n }\n }\n\n const requestOptions: RequestOptions = { params: query };\n return client.get<OffsetPage<T>>(buildPath(resource), requestOptions);\n },\n\n async getOne<T>(resource: string, id: string | number): Promise<T> {\n return client.get<T>(buildPath(resource, encodeIdSegment(id)));\n },\n\n getMany<T>(resource: string, ids: (string | number)[]): Promise<T[]> {\n return Promise.all(ids.map((id) => provider.getOne<T>(resource, id)));\n },\n\n create<T>(resource: string, data: unknown): Promise<T> {\n return client.post<T>(buildPath(resource), { body: data });\n },\n\n async update<T>(resource: string, id: string | number, data: unknown): Promise<T> {\n const path = buildPath(resource, encodeIdSegment(id));\n return updateMethod === \"put\"\n ? client.put<T>(path, { body: data })\n : client.patch<T>(path, { body: data });\n },\n\n async deleteOne<T>(resource: string, id: string | number): Promise<T> {\n return client.delete<T>(buildPath(resource, encodeIdSegment(id)));\n },\n };\n\n return provider;\n}\n"],"mappings":"AAwGA,IAAM,EAAoC,IAAI,IAAI,CAAC,GAAI,IAAK,IAAI,CAAC,EA4BjE,SAAgB,EAAgB,EAA6B,CACzD,GAAI,GAAM,KACN,MAAU,UAAU,qBAAqB,OAAO,CAAE,EAAE,2BAA2B,EAEnF,IAAM,EAAM,OAAO,CAAE,EACrB,GAAI,EAAa,IAAI,CAAG,EACpB,MAAU,UACN,qBAAqB,KAAK,UAAU,CAAG,EAAE,0CAC7C,EAEJ,OAAO,mBAAmB,CAAG,CACjC,CAEA,IAAM,GAAoB,EAAkB,IACxC,GAAM,KAAO,IAAI,IAAa,IAAI,EAAS,GAAG,IA2BlD,SAAgB,EACZ,EACA,EAA+B,CAAC,EACpB,CACZ,GAAM,CACF,YAAY,OACZ,YAAY,OACZ,iBAAiB,WACjB,iBAAiB,YACjB,qBAAqB,GACrB,eAAe,QACf,YAAY,GACZ,EAEE,EAAyB,CAC3B,QAAW,EAAkB,EAAwB,CAAC,EAA2B,CAC7E,GAAM,CAAE,aAAY,OAAM,WAAY,EAChC,EAAoC,CAAC,EAK3C,GAHI,GAAY,MAAQ,OAAM,EAAM,GAAa,EAAW,MACxD,GAAY,UAAY,OAAM,EAAM,GAAa,EAAW,UAE5D,GAAM,MAAO,CACb,IAAM,EAAQ,EAAK,OAAS,MAC5B,EAAM,GAAkB,EAAK,MAC7B,EAAM,GAAkB,EAAqB,IAAU,MAAQ,CACnE,CAEA,GAAI,EACA,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAO,EAC7C,EAAM,GAAO,EAIrB,IAAM,EAAiC,CAAE,OAAQ,CAAM,EACvD,OAAO,EAAO,IAAmB,EAAU,CAAQ,EAAG,CAAc,CACxE,EAEA,MAAM,OAAU,EAAkB,EAAiC,CAC/D,OAAO,EAAO,IAAO,EAAU,EAAU,EAAgB,CAAE,CAAC,CAAC,CACjE,EAEA,QAAW,EAAkB,EAAwC,CACjE,OAAO,QAAQ,IAAI,EAAI,IAAK,GAAO,EAAS,OAAU,EAAU,CAAE,CAAC,CAAC,CACxE,EAEA,OAAU,EAAkB,EAA2B,CACnD,OAAO,EAAO,KAAQ,EAAU,CAAQ,EAAG,CAAE,KAAM,CAAK,CAAC,CAC7D,EAEA,MAAM,OAAU,EAAkB,EAAqB,EAA2B,CAC9E,IAAM,EAAO,EAAU,EAAU,EAAgB,CAAE,CAAC,EACpD,OAAO,IAAiB,MAClB,EAAO,IAAO,EAAM,CAAE,KAAM,CAAK,CAAC,EAClC,EAAO,MAAS,EAAM,CAAE,KAAM,CAAK,CAAC,CAC9C,EAEA,MAAM,UAAa,EAAkB,EAAiC,CAClE,OAAO,EAAO,OAAU,EAAU,EAAU,EAAgB,CAAE,CAAC,CAAC,CACpE,CACJ,EAEA,OAAO,CACX"}
@@ -1,37 +1,48 @@
1
1
  //#region src/data/create-data-provider.ts
2
- var e = (e, t) => t == null ? `/${e}` : `/${e}/${t}`;
3
- function t(t, n = {}) {
4
- let { pageParam: r = "page", sizeParam: i = "size", sortFieldParam: a = "order_by", sortOrderParam: o = "ascending", sortOrderAsBoolean: s = !0, updateMethod: c = "patch", buildPath: l = e } = n, u = {
5
- getList(e, n = {}) {
6
- let { pagination: c, sort: u, filters: d } = n, f = {};
7
- if (c?.page != null && (f[r] = c.page), c?.pageSize != null && (f[i] = c.pageSize), u?.field) {
8
- let e = u.order ?? "asc";
9
- f[a] = u.field, f[o] = s ? e === "asc" : e;
2
+ var e = /* @__PURE__ */ new Set([
3
+ "",
4
+ ".",
5
+ ".."
6
+ ]);
7
+ function t(t) {
8
+ if (t == null) throw TypeError(`Invalid record id ${String(t)}: a record id is required.`);
9
+ let n = String(t);
10
+ if (e.has(n)) throw TypeError(`Invalid record id ${JSON.stringify(n)}: it would resolve as a path dot-segment.`);
11
+ return encodeURIComponent(n);
12
+ }
13
+ var n = (e, t) => t == null ? `/${e}` : `/${e}/${t}`;
14
+ function r(e, r = {}) {
15
+ let { pageParam: i = "page", sizeParam: a = "size", sortFieldParam: o = "order_by", sortOrderParam: s = "ascending", sortOrderAsBoolean: c = !0, updateMethod: l = "patch", buildPath: u = n } = r, d = {
16
+ getList(t, n = {}) {
17
+ let { pagination: r, sort: l, filters: d } = n, f = {};
18
+ if (r?.page != null && (f[i] = r.page), r?.pageSize != null && (f[a] = r.pageSize), l?.field) {
19
+ let e = l.order ?? "asc";
20
+ f[o] = l.field, f[s] = c ? e === "asc" : e;
10
21
  }
11
22
  if (d) for (let [e, t] of Object.entries(d)) f[e] = t;
12
23
  let p = { params: f };
13
- return t.get(l(e), p);
24
+ return e.get(u(t), p);
14
25
  },
15
- getOne(e, n) {
16
- return t.get(l(e, n));
26
+ async getOne(n, r) {
27
+ return e.get(u(n, t(r)));
17
28
  },
18
29
  getMany(e, t) {
19
- return Promise.all(t.map((t) => u.getOne(e, t)));
30
+ return Promise.all(t.map((t) => d.getOne(e, t)));
20
31
  },
21
- create(e, n) {
22
- return t.post(l(e), { body: n });
32
+ create(t, n) {
33
+ return e.post(u(t), { body: n });
23
34
  },
24
- update(e, n, r) {
25
- let i = l(e, n);
26
- return c === "put" ? t.put(i, { body: r }) : t.patch(i, { body: r });
35
+ async update(n, r, i) {
36
+ let a = u(n, t(r));
37
+ return l === "put" ? e.put(a, { body: i }) : e.patch(a, { body: i });
27
38
  },
28
- deleteOne(e, n) {
29
- return t.delete(l(e, n));
39
+ async deleteOne(n, r) {
40
+ return e.delete(u(n, t(r)));
30
41
  }
31
42
  };
32
- return u;
43
+ return d;
33
44
  }
34
45
  //#endregion
35
- export { t as createDataProvider };
46
+ export { r as createDataProvider, t as encodeIdSegment };
36
47
 
37
48
  //# sourceMappingURL=create-data-provider.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-data-provider.js","names":[],"sources":["../../src/data/create-data-provider.ts"],"sourcesContent":["import type { ApiClient, RequestOptions } from \"@/http/types\";\nimport type { OffsetPage } from \"@/query/pagination\";\n\n/** Query-param values accepted by the API client for a list request. */\ntype ParamValue = string | number | boolean | undefined | null;\n\n/** Filters passed to {@link DataProvider.getList}, spread verbatim into the query string. */\nexport type DataFilters = Record<string, ParamValue>;\n\n/** Parameters for a paginated, sorted, filtered list request. */\nexport interface GetListParams {\n /** Offset pagination — 1-based `page` and `pageSize`. */\n pagination?: { page?: number; pageSize?: number };\n /** Single-field sort. `order` defaults to `\"asc\"`. */\n sort?: { field: string; order?: \"asc\" | \"desc\" };\n /** Arbitrary filter query params, spread onto the request. */\n filters?: DataFilters;\n}\n\n/**\n * Refine-style data provider over the Tempest FastAPI SDK CRUD/pagination\n * conventions. Implementations are stateless wrappers around an {@link ApiClient}.\n */\nexport interface DataProvider {\n /**\n * Fetch a paginated list of a resource.\n *\n * @param resource - The resource name (e.g. `\"users\"`).\n * @param params - Pagination, sort and filter parameters.\n * @returns The offset-paginated envelope.\n */\n getList<T>(resource: string, params?: GetListParams): Promise<OffsetPage<T>>;\n /**\n * Fetch a single record by id.\n *\n * @param resource - The resource name.\n * @param id - The record id.\n * @returns The record.\n */\n getOne<T>(resource: string, id: string | number): Promise<T>;\n /**\n * Fetch many records by id (default: parallel {@link DataProvider.getOne}).\n *\n * @param resource - The resource name.\n * @param ids - The record ids.\n * @returns The records, in the same order as `ids`.\n */\n getMany<T>(resource: string, ids: (string | number)[]): Promise<T[]>;\n /**\n * Create a record.\n *\n * @param resource - The resource name.\n * @param data - The creation payload.\n * @returns The created record.\n */\n create<T>(resource: string, data: unknown): Promise<T>;\n /**\n * Update a record (PATCH by default, PUT when configured).\n *\n * @param resource - The resource name.\n * @param id - The record id.\n * @param data - The update payload.\n * @returns The updated record.\n */\n update<T>(resource: string, id: string | number, data: unknown): Promise<T>;\n /**\n * Delete a record by id.\n *\n * @param resource - The resource name.\n * @param id - The record id.\n * @returns The delete response (often the deleted record).\n */\n deleteOne<T>(resource: string, id: string | number): Promise<T>;\n}\n\n/** Options to tailor {@link createDataProvider} to a backend's conventions. */\nexport interface DataProviderOptions {\n /** Query-param name for the page number. Default: `\"page\"`. */\n pageParam?: string;\n /** Query-param name for the page size. Default: `\"size\"`. */\n sizeParam?: string;\n /** Query-param name for the sort field. Default: `\"order_by\"`. */\n sortFieldParam?: string;\n /** Query-param name for the sort order. Default: `\"ascending\"`. */\n sortOrderParam?: string;\n /**\n * When `true` (default), emit the sort order as a boolean\n * (`order:\"asc\"` → `true`). When `false`, emit the literal `\"asc\"`/`\"desc\"`.\n */\n sortOrderAsBoolean?: boolean;\n /** HTTP method used by {@link DataProvider.update}. Default: `\"patch\"`. */\n updateMethod?: \"patch\" | \"put\";\n /**\n * Build the request path for a resource (and optional id).\n * Default: `id == null ? \"/\" + resource : \"/\" + resource + \"/\" + id`.\n */\n buildPath?: (resource: string, id?: string | number) => string;\n}\n\nconst defaultBuildPath = (resource: string, id?: string | number): string =>\n id == null ? `/${resource}` : `/${resource}/${id}`;\n\n/**\n * Create a {@link DataProvider} bound to an {@link ApiClient}.\n *\n * Maps Refine-style calls to the Tempest FastAPI SDK conventions: list →\n * `GET /{resource}?page=&size=&order_by=&ascending=&...filters`, one →\n * `GET /{resource}/{id}`, create → `POST`, update → `PATCH`/`PUT`,\n * delete → `DELETE`.\n *\n * @param client - The HTTP client created by `createApiClient`.\n * @param options - Optional overrides for param names, sort encoding,\n * update method and path building.\n * @returns A stateless data provider.\n *\n * @example\n * const dataProvider = createDataProvider(apiClient);\n * const page = await dataProvider.getList<User>(\"users\", {\n * pagination: { page: 1, pageSize: 20 },\n * sort: { field: \"created_at\", order: \"desc\" },\n * filters: { active: true },\n * });\n */\nexport function createDataProvider(\n client: ApiClient,\n options: DataProviderOptions = {},\n): DataProvider {\n const {\n pageParam = \"page\",\n sizeParam = \"size\",\n sortFieldParam = \"order_by\",\n sortOrderParam = \"ascending\",\n sortOrderAsBoolean = true,\n updateMethod = \"patch\",\n buildPath = defaultBuildPath,\n } = options;\n\n const provider: DataProvider = {\n getList<T>(resource: string, params: GetListParams = {}): Promise<OffsetPage<T>> {\n const { pagination, sort, filters } = params;\n const query: Record<string, ParamValue> = {};\n\n if (pagination?.page != null) query[pageParam] = pagination.page;\n if (pagination?.pageSize != null) query[sizeParam] = pagination.pageSize;\n\n if (sort?.field) {\n const order = sort.order ?? \"asc\";\n query[sortFieldParam] = sort.field;\n query[sortOrderParam] = sortOrderAsBoolean ? order === \"asc\" : order;\n }\n\n if (filters) {\n for (const [key, value] of Object.entries(filters)) {\n query[key] = value;\n }\n }\n\n const requestOptions: RequestOptions = { params: query };\n return client.get<OffsetPage<T>>(buildPath(resource), requestOptions);\n },\n\n getOne<T>(resource: string, id: string | number): Promise<T> {\n return client.get<T>(buildPath(resource, id));\n },\n\n getMany<T>(resource: string, ids: (string | number)[]): Promise<T[]> {\n return Promise.all(ids.map((id) => provider.getOne<T>(resource, id)));\n },\n\n create<T>(resource: string, data: unknown): Promise<T> {\n return client.post<T>(buildPath(resource), { body: data });\n },\n\n update<T>(resource: string, id: string | number, data: unknown): Promise<T> {\n const path = buildPath(resource, id);\n return updateMethod === \"put\"\n ? client.put<T>(path, { body: data })\n : client.patch<T>(path, { body: data });\n },\n\n deleteOne<T>(resource: string, id: string | number): Promise<T> {\n return client.delete<T>(buildPath(resource, id));\n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E,MAAM,EAAK,CAAC;EAC9C;EAEA,UAAa,GAAkB,GAAiC;GAC5D,OAAO,EAAO,OAAU,EAAU,GAAU,CAAE,CAAC;EACnD;CACJ;CAEA,OAAO;AACX"}
1
+ {"version":3,"file":"create-data-provider.js","names":[],"sources":["../../src/data/create-data-provider.ts"],"sourcesContent":["import type { ApiClient, RequestOptions } from \"@/http/types\";\nimport type { OffsetPage } from \"@/query/pagination\";\n\n/** Query-param values accepted by the API client for a list request. */\ntype ParamValue = string | number | boolean | undefined | null;\n\n/** Filters passed to {@link DataProvider.getList}, spread verbatim into the query string. */\nexport type DataFilters = Record<string, ParamValue>;\n\n/** Parameters for a paginated, sorted, filtered list request. */\nexport interface GetListParams {\n /** Offset pagination — 1-based `page` and `pageSize`. */\n pagination?: { page?: number; pageSize?: number };\n /** Single-field sort. `order` defaults to `\"asc\"`. */\n sort?: { field: string; order?: \"asc\" | \"desc\" };\n /** Arbitrary filter query params, spread onto the request. */\n filters?: DataFilters;\n}\n\n/**\n * Refine-style data provider over the Tempest FastAPI SDK CRUD/pagination\n * conventions. Implementations are stateless wrappers around an {@link ApiClient}.\n */\nexport interface DataProvider {\n /**\n * Fetch a paginated list of a resource.\n *\n * @param resource - The resource name (e.g. `\"users\"`).\n * @param params - Pagination, sort and filter parameters.\n * @returns The offset-paginated envelope.\n */\n getList<T>(resource: string, params?: GetListParams): Promise<OffsetPage<T>>;\n /**\n * Fetch a single record by id.\n *\n * @param resource - The resource name.\n * @param id - The record id.\n * @returns The record.\n */\n getOne<T>(resource: string, id: string | number): Promise<T>;\n /**\n * Fetch many records by id (default: parallel {@link DataProvider.getOne}).\n *\n * @param resource - The resource name.\n * @param ids - The record ids.\n * @returns The records, in the same order as `ids`.\n */\n getMany<T>(resource: string, ids: (string | number)[]): Promise<T[]>;\n /**\n * Create a record.\n *\n * @param resource - The resource name.\n * @param data - The creation payload.\n * @returns The created record.\n */\n create<T>(resource: string, data: unknown): Promise<T>;\n /**\n * Update a record (PATCH by default, PUT when configured).\n *\n * @param resource - The resource name.\n * @param id - The record id.\n * @param data - The update payload.\n * @returns The updated record.\n */\n update<T>(resource: string, id: string | number, data: unknown): Promise<T>;\n /**\n * Delete a record by id.\n *\n * @param resource - The resource name.\n * @param id - The record id.\n * @returns The delete response (often the deleted record).\n */\n deleteOne<T>(resource: string, id: string | number): Promise<T>;\n}\n\n/** Options to tailor {@link createDataProvider} to a backend's conventions. */\nexport interface DataProviderOptions {\n /** Query-param name for the page number. Default: `\"page\"`. */\n pageParam?: string;\n /** Query-param name for the page size. Default: `\"size\"`. */\n sizeParam?: string;\n /** Query-param name for the sort field. Default: `\"order_by\"`. */\n sortFieldParam?: string;\n /** Query-param name for the sort order. Default: `\"ascending\"`. */\n sortOrderParam?: string;\n /**\n * When `true` (default), emit the sort order as a boolean\n * (`order:\"asc\"` → `true`). When `false`, emit the literal `\"asc\"`/`\"desc\"`.\n */\n sortOrderAsBoolean?: boolean;\n /** HTTP method used by {@link DataProvider.update}. Default: `\"patch\"`. */\n updateMethod?: \"patch\" | \"put\";\n /**\n * Build the request path for a resource (and optional id).\n * Default: `id == null ? \"/\" + resource : \"/\" + resource + \"/\" + id`.\n *\n * Since 0.77.0 `id` arrives already passed through {@link encodeIdSegment}:\n * percent-encoded as one path segment, and never `\"\"`, `\".\"` or `\"..\"`. An\n * override therefore interpolates it as-is — encoding it again would turn\n * `%2F` into `%252F`.\n */\n buildPath?: (resource: string, id?: string | number) => string;\n}\n\nconst DOT_SEGMENTS: ReadonlySet<string> = new Set([\"\", \".\", \"..\"]);\n\n/**\n * Encode a record id as exactly one URL path segment.\n *\n * The data provider calls this on every id before building a path, because the\n * id is the one part of the URL that may come from outside the app — a search\n * param, a hash, a decoded route param, a value another user stored. Left raw,\n * `\"../../admin/users\"` walks the authenticated request out of the resource,\n * `\"7?role=admin\"` injects query params and `\"7#x\"` truncates the path, all\n * while the request still carries the bearer token (#438).\n *\n * `encodeURIComponent` neutralises `/`, `?`, `#` and `%`. It leaves `.` alone,\n * so `\"\"`, `\".\"` and `\"..\"` are rejected instead: the URL parser resolves them\n * as dot-segments whatever the encoding, and none of them names a record.\n * `null` and `undefined` — what an untyped caller or a not-yet-loaded route\n * param hands over — are rejected too, since `String()` would turn them into\n * the literal segments `\"null\"` and `\"undefined\"`.\n *\n * @param id - The record id, as handed to the provider.\n * @returns The percent-encoded segment, safe to interpolate between two `/`.\n * @throws {TypeError} When the id is `null`, `undefined`, `\"\"`, `\".\"` or `\"..\"`.\n *\n * @example\n * encodeIdSegment(7); // \"7\"\n * encodeIdSegment(\"a/b?x=1\"); // \"a%2Fb%3Fx%3D1\"\n * encodeIdSegment(\"..\"); // throws TypeError\n */\nexport function encodeIdSegment(id: string | number): string {\n if (id == null) {\n throw new TypeError(`Invalid record id ${String(id)}: a record id is required.`);\n }\n const raw = String(id);\n if (DOT_SEGMENTS.has(raw)) {\n throw new TypeError(\n `Invalid record id ${JSON.stringify(raw)}: it would resolve as a path dot-segment.`,\n );\n }\n return encodeURIComponent(raw);\n}\n\nconst defaultBuildPath = (resource: string, id?: string | number): string =>\n id == null ? `/${resource}` : `/${resource}/${id}`;\n\n/**\n * Create a {@link DataProvider} bound to an {@link ApiClient}.\n *\n * Maps Refine-style calls to the Tempest FastAPI SDK conventions: list →\n * `GET /{resource}?page=&size=&order_by=&ascending=&...filters`, one →\n * `GET /{resource}/{id}`, create → `POST`, update → `PATCH`/`PUT`,\n * delete → `DELETE`.\n *\n * Every id goes through {@link encodeIdSegment} before reaching `buildPath`, so\n * an id can never leave its own path segment — not with the default builder,\n * and not with an override that interpolates it.\n *\n * @param client - The HTTP client created by `createApiClient`.\n * @param options - Optional overrides for param names, sort encoding,\n * update method and path building.\n * @returns A stateless data provider.\n *\n * @example\n * const dataProvider = createDataProvider(apiClient);\n * const page = await dataProvider.getList<User>(\"users\", {\n * pagination: { page: 1, pageSize: 20 },\n * sort: { field: \"created_at\", order: \"desc\" },\n * filters: { active: true },\n * });\n */\nexport function createDataProvider(\n client: ApiClient,\n options: DataProviderOptions = {},\n): DataProvider {\n const {\n pageParam = \"page\",\n sizeParam = \"size\",\n sortFieldParam = \"order_by\",\n sortOrderParam = \"ascending\",\n sortOrderAsBoolean = true,\n updateMethod = \"patch\",\n buildPath = defaultBuildPath,\n } = options;\n\n const provider: DataProvider = {\n getList<T>(resource: string, params: GetListParams = {}): Promise<OffsetPage<T>> {\n const { pagination, sort, filters } = params;\n const query: Record<string, ParamValue> = {};\n\n if (pagination?.page != null) query[pageParam] = pagination.page;\n if (pagination?.pageSize != null) query[sizeParam] = pagination.pageSize;\n\n if (sort?.field) {\n const order = sort.order ?? \"asc\";\n query[sortFieldParam] = sort.field;\n query[sortOrderParam] = sortOrderAsBoolean ? order === \"asc\" : order;\n }\n\n if (filters) {\n for (const [key, value] of Object.entries(filters)) {\n query[key] = value;\n }\n }\n\n const requestOptions: RequestOptions = { params: query };\n return client.get<OffsetPage<T>>(buildPath(resource), requestOptions);\n },\n\n async getOne<T>(resource: string, id: string | number): Promise<T> {\n return client.get<T>(buildPath(resource, encodeIdSegment(id)));\n },\n\n getMany<T>(resource: string, ids: (string | number)[]): Promise<T[]> {\n return Promise.all(ids.map((id) => provider.getOne<T>(resource, id)));\n },\n\n create<T>(resource: string, data: unknown): Promise<T> {\n return client.post<T>(buildPath(resource), { body: data });\n },\n\n async update<T>(resource: string, id: string | number, data: unknown): Promise<T> {\n const path = buildPath(resource, encodeIdSegment(id));\n return updateMethod === \"put\"\n ? client.put<T>(path, { body: data })\n : client.patch<T>(path, { body: data });\n },\n\n async deleteOne<T>(resource: string, id: string | number): Promise<T> {\n return client.delete<T>(buildPath(resource, encodeIdSegment(id)));\n },\n };\n\n return provider;\n}\n"],"mappings":";AAwGA,IAAM,oBAAoC,IAAI,IAAI;CAAC;CAAI;CAAK;AAAI,CAAC;AA4BjE,SAAgB,EAAgB,GAA6B;CACzD,IAAI,KAAM,MACN,MAAU,UAAU,qBAAqB,OAAO,CAAE,EAAE,2BAA2B;CAEnF,IAAM,IA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;GAC9E,IAAM,IAAO,EAAU,GAAU,EAAgB,CAAE,CAAC;GACpD,OAAO,MAAiB,QAClB,EAAO,IAAO,GAAM,EAAE,MAAM,EAAK,CAAC,IAClC,EAAO,MAAS,GAAM,EAAE,MAAM,EAAK,CAAC;EAC9C;EAEA,MAAM,UAAa,GAAkB,GAAiC;GAClE,OAAO,EAAO,OAAU,EAAU,GAAU,EAAgB,CAAE,CAAC,CAAC;EACpE;CACJ;CAEA,OAAO;AACX"}
@@ -1,2 +1,2 @@
1
- const e=require("../utils/ids.cjs"),t=require("./build-url.cjs"),n=require("./credential-scope.cjs"),r=require("./csrf.cjs"),i=require("./decode-response.cjs"),a=require("./errors.cjs"),o=require("./retry.cjs"),s=require("./timeout.cjs");var c=new Set([`GET`,`HEAD`,`OPTIONS`]);function l(e,t){return!c.has(t)||!(e instanceof a.TempestApiError)?!1:a.isRetriableStatus(e.status)}function u(e){return e?e===!0?{}:e:null}var d=15e3,f=3e5;function p(e){return typeof FormData<`u`&&e instanceof FormData}function m(e){return Math.round(performance.now()-e)}async function h(e,t){let n;try{n=await e.clone().json()}catch{try{n=await e.text()}catch{n=null}}return new a.TempestApiError(a.buildApiError(e.status,n,e.headers,t))}function g(c){let g=c.fetcher??globalThis.fetch.bind(globalThis);function _(e,t){if(t)return{};let r=c.getToken?.();return r?n.isTrustedCredentialTarget(e,c.baseURL,c.trustedOrigins)?{Authorization:`Bearer ${r}`}:(n.reportSuppressedCredential(e,c.baseURL),{}):{}}async function v(e,n,i,o){let{body:l,params:u,headers:m,signal:h,timeout:v,...y}=n,b=p(l),x=b?c.uploadTimeout:c.timeout,S=v===void 0?x===void 0?b?f:d:x:v,C=t.buildApiUrl(c.baseURL,e,{prefix:c.prefix,params:u}),w=m,T={...b?{}:{"Content-Type":`application/json`},...i?{"X-Request-ID":i}:{},...c.headers,..._(C,o),...r.csrfHeaders({method:y.method??`GET`,url:C,reference:c.baseURL,csrf:c.csrf,trustedOrigins:c.trustedOrigins,headers:{...c.headers,...w}}),...w},E=s.withTimeout(h,S),D={...y,signal:E.signal,headers:T,credentials:c.withCredentials?`include`:y.credentials,body:l==null?void 0:b?l:JSON.stringify(l)};try{return await g(C,D)}catch(e){throw E.timedOut()?new a.TempestApiError({status:0,detail:`A requisição excedeu ${S}ms e foi abandonada.`}):e}finally{E.dispose()}}async function y(e,t,n,r,i){let a=c.logger;if(!a)return v(e,t,n,i);let o=performance.now();try{let s=await v(e,t,n,i),c={requestId:n,status:s.status,ms:m(o)},l=`${r} ${e} → ${s.status}`;return s.status>=400?a.warn(l,c):a.debug(l,c),s}catch(t){throw a.warn(`${r} ${e} → no response`,{requestId:n,ms:m(o),error:t}),t}}async function b(e,t){if(c.onUnauthorized){c.logger?.warn(`unauthorized — calling onUnauthorized`,{requestId:t,status:e.status});try{await c.onUnauthorized(e)}catch(n){c.logger?.warn(`onUnauthorized threw — keeping the original response error`,{requestId:t,status:e.status,error:n})}}}async function x(t,n,r){let{skipAuth:i=!1,skipAuthRetry:a=!1,...o}=n,s=c.requestId?c.requestId():e.randomId(),l=(o.method??`GET`).toUpperCase(),u=await y(t,o,s,l,i);if(u.status===401&&!i&&!a){if(c.refresh){try{await c.refresh(),u=await y(t,o,s,l,i)}catch{throw await b(u,s),await h(u,s)}u.status===401&&await b(u,s)}else await b(u,s)}if(!u.ok)throw await h(u,s);return r(u)}async function S(e,t,n){let{retry:r,...i}=t,a=u(r===void 0?c.retry:r);if(!a)return x(e,i,n);let s=(i.method??`GET`).toUpperCase();return o.retry(()=>x(e,i,n),{...a,shouldRetry:a.shouldRetry??(e=>l(e,s))})}async function C(e,t={}){return S(e,t,i.decodeByContentType)}async function w(e,t,n=`POST`,r){return C(e,{...r,method:n,body:t})}return{request:C,get:(e,t)=>C(e,{...t,method:`GET`}),post:(e,t)=>C(e,{...t,method:`POST`}),put:(e,t)=>C(e,{...t,method:`PUT`}),patch:(e,t)=>C(e,{...t,method:`PATCH`}),delete:(e,t)=>C(e,{...t,method:`DELETE`}),blob:(e,t)=>S(e,{...t},e=>e.blob()),arrayBuffer:(e,t)=>S(e,{...t},e=>e.arrayBuffer()),upload:w}}exports.createApiClient=g;
1
+ const e=require("../utils/ids.cjs"),t=require("./build-url.cjs"),n=require("./credential-scope.cjs"),r=require("./csrf.cjs"),i=require("./decode-response.cjs"),a=require("./errors.cjs"),o=require("./retry.cjs"),s=require("./timeout.cjs");var c=new Set([`GET`,`HEAD`,`OPTIONS`]);function l(e,t){return!c.has(t)||!(e instanceof a.TempestApiError)?!1:a.isRetriableStatus(e.status)}function u(e){return e?e===!0?{}:e:null}var d=15e3,f=3e5;function p(e){return typeof FormData<`u`&&e instanceof FormData}function m(e){return Math.round(performance.now()-e)}async function h(e,t){let n;try{n=await e.clone().json()}catch{try{n=await e.text()}catch{n=null}}return new a.TempestApiError(a.buildApiError(e.status,n,e.headers,t))}function g(c){let g=c.fetcher??globalThis.fetch.bind(globalThis);function _(e,t){if(t)return{};let r=c.getToken?.();return r?n.isTrustedCredentialTarget(e,c.baseURL,c.trustedOrigins)?{Authorization:`Bearer ${r}`}:(n.reportSuppressedCredential(e,c.baseURL),{}):{}}async function v(e,n,i,o){let{body:l,params:u,headers:m,signal:h,timeout:v,...y}=n,b=p(l),x=b?c.uploadTimeout:c.timeout,S=v===void 0?x===void 0?b?f:d:x:v,C=t.buildApiUrl(c.baseURL,e,{prefix:c.prefix,params:u}),w=m,T={...b?{}:{"Content-Type":`application/json`},...i?{"X-Request-ID":i}:{},...c.headers,..._(C,o),...r.csrfHeaders({method:y.method??`GET`,url:C,reference:c.baseURL,csrf:c.csrf,trustedOrigins:c.trustedOrigins,headers:{...c.headers,...w}}),...w},E=s.withTimeout(h,S),D={...y,signal:E.signal,headers:T,credentials:c.withCredentials?`include`:y.credentials,body:l==null?void 0:b?l:JSON.stringify(l)};try{return await g(C,D)}catch(e){throw E.timedOut()?new a.TempestApiError({status:0,detail:`A requisição excedeu ${S}ms e foi abandonada.`}):e}finally{E.dispose()}}async function y(e,t,n,r,i){let a=c.logger;if(!a)return v(e,t,n,i);let o=performance.now();try{let s=await v(e,t,n,i),c={requestId:n,status:s.status,ms:m(o)},l=`${r} ${e} → ${s.status}`;return s.status>=400?a.warn(l,c):a.debug(l,c),s}catch(t){throw a.warn(`${r} ${e} → no response`,{requestId:n,ms:m(o),error:t}),t}}async function b(e,t,n){if(c.onUnauthorized){c.logger?.warn(`unauthorized — calling onUnauthorized`,{requestId:t,status:e.status});try{await c.onUnauthorized(e,n)}catch(n){if(n instanceof a.SessionSupersededError)throw n;c.logger?.warn(`onUnauthorized threw — keeping the original response error`,{requestId:t,status:e.status,error:n})}}}function x(e){return{token:e?null:c.getToken?.()??null,epoch:c.getSessionEpoch?.()??null}}async function S(t,n,r){let{skipAuth:i=!1,skipAuthRetry:o=!1,...s}=n,l=c.requestId?c.requestId():e.randomId(),u=(s.method??`GET`).toUpperCase(),d=x(i),f=await y(t,s,l,u,i);if(f.status===401&&!i&&!o){if(c.refresh){let e;try{await c.refresh(d),e=x(i),f=await y(t,s,l,u,i)}catch(e){throw e instanceof a.SessionSupersededError?e:(await b(f,l,d),await h(f,l))}f.status===401&&await b(f,l,e)}else await b(f,l,d)}if(!f.ok)throw await h(f,l);return r(f)}async function C(e,t,n){let{retry:r,...i}=t,a=u(r===void 0?c.retry:r);if(!a)return S(e,i,n);let s=(i.method??`GET`).toUpperCase();return o.retry(()=>S(e,i,n),{...a,shouldRetry:a.shouldRetry??(e=>l(e,s))})}async function w(e,t={}){return C(e,t,i.decodeByContentType)}async function T(e,t,n=`POST`,r){return w(e,{...r,method:n,body:t})}return{request:w,get:(e,t)=>w(e,{...t,method:`GET`}),post:(e,t)=>w(e,{...t,method:`POST`}),put:(e,t)=>w(e,{...t,method:`PUT`}),patch:(e,t)=>w(e,{...t,method:`PATCH`}),delete:(e,t)=>w(e,{...t,method:`DELETE`}),blob:(e,t)=>C(e,{...t},e=>e.blob()),arrayBuffer:(e,t)=>C(e,{...t},e=>e.arrayBuffer()),upload:T}}exports.createApiClient=g;
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 { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\nimport { csrfHeaders } from \"./csrf\";\nimport { decodeByContentType } from \"./decode-response\";\nimport type { ResponseDecoder } from \"./decode-response\";\nimport { buildApiError, TempestApiError, isRetriableStatus } from \"./errors\";\nimport { retry as retryWithBackoff } from \"./retry\";\nimport type { RetryOptions } from \"./retry\";\nimport { withTimeout } from \"./timeout\";\nimport type { ApiClient, ApiClientConfig, RequestOptions } from \"./types\";\n\n/**\n * Methods the built-in retry policy will replay.\n *\n * `PUT` and `DELETE` are idempotent on paper but stay out: a backend that logs,\n * bills, or fires a webhook per call still sees two, so replaying them is a\n * decision the caller makes through `shouldRetry`, not a default.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Sub-500 statuses worth a second attempt: a network failure (status `0`), a\n * request timeout, a too-early replay, and a rate limit — which usually carries\n * the `Retry-After` the backoff already honours.\n */\n\n/**\n * The built-in retry policy, used when `retry` is `true` or is options carrying\n * no `shouldRetry` of their own.\n *\n * Conservative on purpose. Replaying a write can duplicate it, and replaying a\n * `400` or a `403` cannot fix a bad payload or a permission the caller does not\n * have — it only spends the user's time before showing the same error.\n *\n * @param error - Whatever the attempt threw.\n * @param method - The upper-cased HTTP method of the request.\n * @returns Whether the client should try again.\n */\nfunction isRetriableFailure(error: unknown, method: string): boolean {\n if (!IDEMPOTENT_METHODS.has(method)) return false;\n if (!(error instanceof TempestApiError)) return false;\n return isRetriableStatus(error.status);\n}\n\n/**\n * Normalize the `retry` config into options, or `null` when retrying is off.\n *\n * @param config - The `retry` field as the caller wrote it.\n * @returns Retry options to use, or `null` to run a single attempt.\n */\nfunction resolveRetry(config: boolean | RetryOptions | undefined): RetryOptions | null {\n if (!config) return null;\n return config === true ? {} : config;\n}\n\n/** Default milliseconds before a request is abandoned. */\nconst DEFAULT_TIMEOUT = 15_000;\n\n/** Default milliseconds before a `FormData` request is abandoned. */\nconst DEFAULT_UPLOAD_TIMEOUT = 300_000;\n\nfunction isFormData(body: unknown): body is FormData {\n return typeof FormData !== \"undefined\" && body instanceof FormData;\n}\n\n/**\n * Milliseconds since a `performance.now()` reading, rounded.\n *\n * `performance.now()` rather than `Date.now()` because this measures a\n * duration: the wall clock can step sideways mid-request (an NTP correction, a\n * VM resuming, the user changing the clock) and turn a 40 ms call into a\n * negative number. The monotonic clock cannot.\n *\n * @param startedAt - The reading taken before the work started.\n * @returns Whole milliseconds elapsed.\n */\nfunction elapsedMs(startedAt: number): number {\n return Math.round(performance.now() - startedAt);\n}\n\nasync function parseError(response: Response, sentRequestId?: string): Promise<TempestApiError> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n try {\n body = await response.text();\n } catch {\n body = null;\n }\n }\n return new TempestApiError(\n buildApiError(response.status, body, response.headers, sentRequestId),\n );\n}\n\n/**\n * Create a typed HTTP client backed by `fetch`.\n *\n * Handles JSON serialization, query params, bearer auth via `getToken`, uploads\n * via `FormData`, and throws a typed `ApiError` on any non-2xx response.\n *\n * **Expired sessions.** A `401` with `refresh` configured awaits the refresh and\n * replays the request once. `onUnauthorized` fires whenever that path ends\n * unauthorized anyway — the refresh threw, or the replay came back `401` — which\n * is the signal to clear the session. Without `refresh`, the first `401` calls\n * it directly.\n *\n * **Binary bodies** have their own methods — `blob()` and `arrayBuffer()` — which\n * run the same pipeline and skip the parse. `request()` no longer decodes an\n * unknown `Content-Type` as text either: it returns a `Blob` and says so once in\n * a development build, because reading `image/jpeg` as UTF-8 destroyed the bytes\n * on the way in.\n *\n * **The bearer token is scoped to `baseURL`'s origin** since 0.66.0. A path may\n * be an absolute URL, which overrides the base entirely, so without a scope the\n * destination of a credentialed request could come from a value read off the\n * network. A request to another origin still goes out; it goes without the\n * header, and a development build says so once. Declare the exceptions in\n * {@link ApiClientConfig.trustedOrigins}.\n *\n * **CSRF** is off unless you set `csrf`. With it, every unsafe request (anything\n * but `GET`/`HEAD`/`OPTIONS`/`TRACE`) echoes the `csrf_token` cookie in an\n * `X-CSRF-Token` header — the double-submit contract of `tempest-fastapi-sdk`'s\n * `CSRFMiddleware` — scoped to the same origins as the bearer token and sent on\n * `skipAuth` requests too. See {@link ApiClientConfig.csrf}.\n *\n * **Retries** are off unless you set `retry`. See {@link ApiClientConfig.retry}\n * for the built-in policy; it never replays a write. A single call overrides it\n * with {@link RequestOptions.retry}, and opts out of auth entirely with\n * {@link RequestOptions.skipAuth}.\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`/`blob`/\n * `arrayBuffer`/`upload`.\n */\nexport function createApiClient(config: ApiClientConfig): ApiClient {\n const fetcher = config.fetcher ?? globalThis.fetch.bind(globalThis);\n\n /**\n * The `Authorization` header for a request, or nothing.\n *\n * Takes the resolved URL rather than reading `config.baseURL`, because an\n * absolute path overrides the base entirely (see `buildApiUrl`) and the\n * credential is scoped to an origin, not to a client.\n *\n * @param url - The absolute URL the request is going to.\n * @param skipAuth - Whether the caller opted this request out of auth.\n * @returns The header, or an empty object.\n */\n function authHeaders(url: string, skipAuth: boolean): Record<string, string> {\n if (skipAuth) return {};\n const token = config.getToken?.();\n if (!token) return {};\n if (!isTrustedCredentialTarget(url, config.baseURL, config.trustedOrigins)) {\n reportSuppressedCredential(url, config.baseURL);\n return {};\n }\n return { Authorization: `Bearer ${token}` };\n }\n\n async function rawRequest(\n path: string,\n options: RequestOptions,\n requestId: string | undefined,\n skipAuth: boolean,\n ): Promise<Response> {\n const { body, params, headers, signal, timeout, ...rest } = options;\n const isForm = isFormData(body);\n const configured = isForm ? config.uploadTimeout : config.timeout;\n const fallback = isForm ? DEFAULT_UPLOAD_TIMEOUT : DEFAULT_TIMEOUT;\n const limit =\n timeout !== undefined ? timeout : configured !== undefined ? configured : fallback;\n\n const url = buildApiUrl(config.baseURL, path, { prefix: config.prefix, params });\n\n const callerHeaders = headers as Record<string, string> | undefined;\n const finalHeaders: Record<string, string> = {\n ...(isForm ? {} : { \"Content-Type\": \"application/json\" }),\n ...(requestId ? { \"X-Request-ID\": requestId } : {}),\n ...config.headers,\n ...authHeaders(url, skipAuth),\n ...csrfHeaders({\n method: rest.method ?? \"GET\",\n url,\n reference: config.baseURL,\n csrf: config.csrf,\n trustedOrigins: config.trustedOrigins,\n headers: { ...config.headers, ...callerHeaders },\n }),\n ...callerHeaders,\n };\n\n const timed = withTimeout(signal, limit);\n const init: RequestInit = {\n ...rest,\n signal: timed.signal,\n headers: finalHeaders,\n credentials: config.withCredentials ? \"include\" : rest.credentials,\n body:\n body === undefined || body === null\n ? undefined\n : isForm\n ? (body as FormData)\n : JSON.stringify(body),\n };\n\n try {\n return await fetcher(url, init);\n } catch (cause) {\n if (timed.timedOut()) {\n throw new TempestApiError({\n status: 0,\n detail: `A requisição excedeu ${limit}ms e foi abandonada.`,\n });\n }\n throw cause;\n } finally {\n timed.dispose();\n }\n }\n\n async function send(\n path: string,\n options: RequestOptions,\n requestId: string,\n method: string,\n skipAuth: boolean,\n ): Promise<Response> {\n const log = config.logger;\n if (!log) return rawRequest(path, options, requestId, skipAuth);\n\n const startedAt = performance.now();\n try {\n const response = await rawRequest(path, options, requestId, skipAuth);\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>(\n path: string,\n options: RequestOptions,\n decode: ResponseDecoder<T>,\n ): Promise<T> {\n const { skipAuth = false, skipAuthRetry = false, ...init } = options;\n const requestId = config.requestId ? config.requestId() : randomId();\n const method = (init.method ?? \"GET\").toUpperCase();\n let response = await send(path, init, requestId, method, skipAuth);\n\n if (response.status === 401 && !skipAuth && !skipAuthRetry) {\n if (config.refresh) {\n try {\n await config.refresh();\n response = await send(path, init, requestId, method, skipAuth);\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 return decode(response);\n }\n\n async function run<T>(\n path: string,\n options: RequestOptions,\n decode: ResponseDecoder<T>,\n ): Promise<T> {\n const { retry: perRequest, ...rest } = options;\n const retryOptions = resolveRetry(perRequest !== undefined ? perRequest : config.retry);\n if (!retryOptions) return attempt<T>(path, rest, decode);\n\n const method = (rest.method ?? \"GET\").toUpperCase();\n return retryWithBackoff(() => attempt<T>(path, rest, decode), {\n ...retryOptions,\n shouldRetry:\n retryOptions.shouldRetry ?? ((error: unknown) => isRetriableFailure(error, method)),\n });\n }\n\n async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return run<T>(path, options, decodeByContentType);\n }\n\n async function upload<T>(\n path: string,\n formData: FormData,\n method: \"POST\" | \"PUT\" | \"PATCH\" = \"POST\",\n options?: Omit<RequestOptions, \"body\" | \"method\">,\n ): Promise<T> {\n return request<T>(path, { ...options, method, body: formData });\n }\n\n return {\n request,\n get: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"GET\" }),\n post: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"POST\" }),\n put: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PUT\" }),\n patch: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PATCH\" }),\n delete: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"DELETE\" }),\n blob: (path: string, options?: RequestOptions) =>\n run<Blob>(path, { ...options }, (response) => response.blob()),\n arrayBuffer: (path: string, options?: RequestOptions) =>\n run<ArrayBuffer>(path, { ...options }, (response) => response.arrayBuffer()),\n upload,\n };\n}\n"],"mappings":"8OAyBA,IAAM,EAA0C,IAAI,IAAI,CAAC,MAAO,OAAQ,SAAS,CAAC,EAoBlF,SAAS,EAAmB,EAAgB,EAAyB,CAGjE,MAFI,CAAC,EAAmB,IAAI,CAAM,GAC9B,EAAE,aAAiB,EAAA,iBAAyB,GACzC,EAAA,kBAAkB,EAAM,MAAM,CACzC,CAQA,SAAS,EAAa,EAAiE,CAEnF,OADK,EACE,IAAW,GAAO,CAAC,EAAI,EADV,IAExB,CAGA,IAAM,EAAkB,KAGlB,EAAyB,IAE/B,SAAS,EAAW,EAAiC,CACjD,OAAO,OAAO,SAAa,KAAe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EACzF,CAAC,CACL,CAEA,eAAe,EAAW,EAAc,EAA0B,CAAC,EAAe,CAC9E,OAAO,EAAO,EAAM,EAAS,EAAA,mBAAmB,CACpD,CAEA,eAAe,EACX,EACA,EACA,EAAmC,OACnC,EACU,CACV,OAAO,EAAW,EAAM,CAAE,GAAG,EAAS,SAAQ,KAAM,CAAS,CAAC,CAClE,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,MAAO,EAAc,IACjB,EAAU,EAAM,CAAE,GAAG,CAAQ,EAAI,GAAa,EAAS,KAAK,CAAC,EACjE,aAAc,EAAc,IACxB,EAAiB,EAAM,CAAE,GAAG,CAAQ,EAAI,GAAa,EAAS,YAAY,CAAC,EAC/E,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 { isTrustedCredentialTarget, reportSuppressedCredential } from \"./credential-scope\";\nimport { csrfHeaders } from \"./csrf\";\nimport { decodeByContentType } from \"./decode-response\";\nimport type { ResponseDecoder } from \"./decode-response\";\nimport {\n buildApiError,\n SessionSupersededError,\n TempestApiError,\n isRetriableStatus,\n} from \"./errors\";\nimport { retry as retryWithBackoff } from \"./retry\";\nimport type { RetryOptions } from \"./retry\";\nimport { withTimeout } from \"./timeout\";\nimport type { ApiClient, ApiClientConfig, RequestAuthContext, RequestOptions } from \"./types\";\n\n/**\n * Methods the built-in retry policy will replay.\n *\n * `PUT` and `DELETE` are idempotent on paper but stay out: a backend that logs,\n * bills, or fires a webhook per call still sees two, so replaying them is a\n * decision the caller makes through `shouldRetry`, not a default.\n */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Sub-500 statuses worth a second attempt: a network failure (status `0`), a\n * request timeout, a too-early replay, and a rate limit — which usually carries\n * the `Retry-After` the backoff already honours.\n */\n\n/**\n * The built-in retry policy, used when `retry` is `true` or is options carrying\n * no `shouldRetry` of their own.\n *\n * Conservative on purpose. Replaying a write can duplicate it, and replaying a\n * `400` or a `403` cannot fix a bad payload or a permission the caller does not\n * have — it only spends the user's time before showing the same error.\n *\n * @param error - Whatever the attempt threw.\n * @param method - The upper-cased HTTP method of the request.\n * @returns Whether the client should try again.\n */\nfunction isRetriableFailure(error: unknown, method: string): boolean {\n if (!IDEMPOTENT_METHODS.has(method)) return false;\n if (!(error instanceof TempestApiError)) return false;\n return isRetriableStatus(error.status);\n}\n\n/**\n * Normalize the `retry` config into options, or `null` when retrying is off.\n *\n * @param config - The `retry` field as the caller wrote it.\n * @returns Retry options to use, or `null` to run a single attempt.\n */\nfunction resolveRetry(config: boolean | RetryOptions | undefined): RetryOptions | null {\n if (!config) return null;\n return config === true ? {} : config;\n}\n\n/** Default milliseconds before a request is abandoned. */\nconst DEFAULT_TIMEOUT = 15_000;\n\n/** Default milliseconds before a `FormData` request is abandoned. */\nconst DEFAULT_UPLOAD_TIMEOUT = 300_000;\n\nfunction isFormData(body: unknown): body is FormData {\n return typeof FormData !== \"undefined\" && body instanceof FormData;\n}\n\n/**\n * Milliseconds since a `performance.now()` reading, rounded.\n *\n * `performance.now()` rather than `Date.now()` because this measures a\n * duration: the wall clock can step sideways mid-request (an NTP correction, a\n * VM resuming, the user changing the clock) and turn a 40 ms call into a\n * negative number. The monotonic clock cannot.\n *\n * @param startedAt - The reading taken before the work started.\n * @returns Whole milliseconds elapsed.\n */\nfunction elapsedMs(startedAt: number): number {\n return Math.round(performance.now() - startedAt);\n}\n\nasync function parseError(response: Response, sentRequestId?: string): Promise<TempestApiError> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n try {\n body = await response.text();\n } catch {\n body = null;\n }\n }\n return new TempestApiError(\n buildApiError(response.status, body, response.headers, sentRequestId),\n );\n}\n\n/**\n * Create a typed HTTP client backed by `fetch`.\n *\n * Handles JSON serialization, query params, bearer auth via `getToken`, uploads\n * via `FormData`, and throws a typed `ApiError` on any non-2xx response.\n *\n * **Expired sessions.** A `401` with `refresh` configured awaits the refresh and\n * replays the request once. `onUnauthorized` fires whenever that path ends\n * unauthorized anyway — the refresh threw, or the replay came back `401` — which\n * is the signal to clear the session. Without `refresh`, the first `401` calls\n * it directly.\n *\n * **Binary bodies** have their own methods — `blob()` and `arrayBuffer()` — which\n * run the same pipeline and skip the parse. `request()` no longer decodes an\n * unknown `Content-Type` as text either: it returns a `Blob` and says so once in\n * a development build, because reading `image/jpeg` as UTF-8 destroyed the bytes\n * on the way in.\n *\n * **The bearer token is scoped to `baseURL`'s origin** since 0.66.0. A path may\n * be an absolute URL, which overrides the base entirely, so without a scope the\n * destination of a credentialed request could come from a value read off the\n * network. A request to another origin still goes out; it goes without the\n * header, and a development build says so once. Declare the exceptions in\n * {@link ApiClientConfig.trustedOrigins}.\n *\n * **CSRF** is off unless you set `csrf`. With it, every unsafe request (anything\n * but `GET`/`HEAD`/`OPTIONS`/`TRACE`) echoes the `csrf_token` cookie in an\n * `X-CSRF-Token` header — the double-submit contract of `tempest-fastapi-sdk`'s\n * `CSRFMiddleware` — scoped to the same origins as the bearer token and sent on\n * `skipAuth` requests too. See {@link ApiClientConfig.csrf}.\n *\n * **Retries** are off unless you set `retry`. See {@link ApiClientConfig.retry}\n * for the built-in policy; it never replays a write. A single call overrides it\n * with {@link RequestOptions.retry}, and opts out of auth entirely with\n * {@link RequestOptions.skipAuth}.\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`/`blob`/\n * `arrayBuffer`/`upload`.\n */\nexport function createApiClient(config: ApiClientConfig): ApiClient {\n const fetcher = config.fetcher ?? globalThis.fetch.bind(globalThis);\n\n /**\n * The `Authorization` header for a request, or nothing.\n *\n * Takes the resolved URL rather than reading `config.baseURL`, because an\n * absolute path overrides the base entirely (see `buildApiUrl`) and the\n * credential is scoped to an origin, not to a client.\n *\n * @param url - The absolute URL the request is going to.\n * @param skipAuth - Whether the caller opted this request out of auth.\n * @returns The header, or an empty object.\n */\n function authHeaders(url: string, skipAuth: boolean): Record<string, string> {\n if (skipAuth) return {};\n const token = config.getToken?.();\n if (!token) return {};\n if (!isTrustedCredentialTarget(url, config.baseURL, config.trustedOrigins)) {\n reportSuppressedCredential(url, config.baseURL);\n return {};\n }\n return { Authorization: `Bearer ${token}` };\n }\n\n async function rawRequest(\n path: string,\n options: RequestOptions,\n requestId: string | undefined,\n skipAuth: boolean,\n ): Promise<Response> {\n const { body, params, headers, signal, timeout, ...rest } = options;\n const isForm = isFormData(body);\n const configured = isForm ? config.uploadTimeout : config.timeout;\n const fallback = isForm ? DEFAULT_UPLOAD_TIMEOUT : DEFAULT_TIMEOUT;\n const limit =\n timeout !== undefined ? timeout : configured !== undefined ? configured : fallback;\n\n const url = buildApiUrl(config.baseURL, path, { prefix: config.prefix, params });\n\n const callerHeaders = headers as Record<string, string> | undefined;\n const finalHeaders: Record<string, string> = {\n ...(isForm ? {} : { \"Content-Type\": \"application/json\" }),\n ...(requestId ? { \"X-Request-ID\": requestId } : {}),\n ...config.headers,\n ...authHeaders(url, skipAuth),\n ...csrfHeaders({\n method: rest.method ?? \"GET\",\n url,\n reference: config.baseURL,\n csrf: config.csrf,\n trustedOrigins: config.trustedOrigins,\n headers: { ...config.headers, ...callerHeaders },\n }),\n ...callerHeaders,\n };\n\n const timed = withTimeout(signal, limit);\n const init: RequestInit = {\n ...rest,\n signal: timed.signal,\n headers: finalHeaders,\n credentials: config.withCredentials ? \"include\" : rest.credentials,\n body:\n body === undefined || body === null\n ? undefined\n : isForm\n ? (body as FormData)\n : JSON.stringify(body),\n };\n\n try {\n return await fetcher(url, init);\n } catch (cause) {\n if (timed.timedOut()) {\n throw new TempestApiError({\n status: 0,\n detail: `A requisição excedeu ${limit}ms e foi abandonada.`,\n });\n }\n throw cause;\n } finally {\n timed.dispose();\n }\n }\n\n async function send(\n path: string,\n options: RequestOptions,\n requestId: string,\n method: string,\n skipAuth: boolean,\n ): Promise<Response> {\n const log = config.logger;\n if (!log) return rawRequest(path, options, requestId, skipAuth);\n\n const startedAt = performance.now();\n try {\n const response = await rawRequest(path, options, requestId, skipAuth);\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 /**\n * Call `onUnauthorized`, keeping the request's own error unless the hook\n * says the attempt belongs to an ended session.\n *\n * @param response - The `401` that ended the attempt.\n * @param requestId - Correlation id for the log.\n * @param context - The credential and session the attempt left with.\n * @throws {SessionSupersededError} When `onUnauthorized` threw it.\n */\n async function notifyUnauthorized(\n response: Response,\n requestId: string,\n context: RequestAuthContext,\n ): 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, context);\n } catch (error) {\n if (error instanceof SessionSupersededError) throw 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 /**\n * The credential and session an attempt leaves with, read just before it is\n * sent.\n *\n * @param skipAuth - Whether the attempt goes out without credentials.\n * @returns The context handed to `refresh` and `onUnauthorized`.\n */\n function authContext(skipAuth: boolean): RequestAuthContext {\n return {\n token: skipAuth ? null : (config.getToken?.() ?? null),\n epoch: config.getSessionEpoch?.() ?? null,\n };\n }\n\n async function attempt<T>(\n path: string,\n options: RequestOptions,\n decode: ResponseDecoder<T>,\n ): Promise<T> {\n const { skipAuth = false, skipAuthRetry = false, ...init } = options;\n const requestId = config.requestId ? config.requestId() : randomId();\n const method = (init.method ?? \"GET\").toUpperCase();\n const sent = authContext(skipAuth);\n let response = await send(path, init, requestId, method, skipAuth);\n\n if (response.status === 401 && !skipAuth && !skipAuthRetry) {\n if (config.refresh) {\n let replayed: RequestAuthContext;\n try {\n await config.refresh(sent);\n replayed = authContext(skipAuth);\n response = await send(path, init, requestId, method, skipAuth);\n } catch (error) {\n if (error instanceof SessionSupersededError) throw error;\n await notifyUnauthorized(response, requestId, sent);\n throw await parseError(response, requestId);\n }\n if (response.status === 401) {\n await notifyUnauthorized(response, requestId, replayed);\n }\n } else {\n await notifyUnauthorized(response, requestId, sent);\n }\n }\n\n if (!response.ok) {\n throw await parseError(response, requestId);\n }\n\n return decode(response);\n }\n\n async function run<T>(\n path: string,\n options: RequestOptions,\n decode: ResponseDecoder<T>,\n ): Promise<T> {\n const { retry: perRequest, ...rest } = options;\n const retryOptions = resolveRetry(perRequest !== undefined ? perRequest : config.retry);\n if (!retryOptions) return attempt<T>(path, rest, decode);\n\n const method = (rest.method ?? \"GET\").toUpperCase();\n return retryWithBackoff(() => attempt<T>(path, rest, decode), {\n ...retryOptions,\n shouldRetry:\n retryOptions.shouldRetry ?? ((error: unknown) => isRetriableFailure(error, method)),\n });\n }\n\n async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return run<T>(path, options, decodeByContentType);\n }\n\n async function upload<T>(\n path: string,\n formData: FormData,\n method: \"POST\" | \"PUT\" | \"PATCH\" = \"POST\",\n options?: Omit<RequestOptions, \"body\" | \"method\">,\n ): Promise<T> {\n return request<T>(path, { ...options, method, body: formData });\n }\n\n return {\n request,\n get: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"GET\" }),\n post: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"POST\" }),\n put: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PUT\" }),\n patch: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"PATCH\" }),\n delete: <T>(path: string, options?: RequestOptions) =>\n request<T>(path, { ...options, method: \"DELETE\" }),\n blob: (path: string, options?: RequestOptions) =>\n run<Blob>(path, { ...options }, (response) => response.blob()),\n arrayBuffer: (path: string, options?: RequestOptions) =>\n run<ArrayBuffer>(path, { ...options }, (response) => response.arrayBuffer()),\n upload,\n };\n}\n"],"mappings":"8OA8BA,IAAM,EAA0C,IAAI,IAAI,CAAC,MAAO,OAAQ,SAAS,CAAC,EAoBlF,SAAS,EAAmB,EAAgB,EAAyB,CAGjE,MAFI,CAAC,EAAmB,IAAI,CAAM,GAC9B,EAAE,aAAiB,EAAA,iBAAyB,GACzC,EAAA,kBAAkB,EAAM,MAAM,CACzC,CAQA,SAAS,EAAa,EAAiE,CAEnF,OADK,EACE,IAAW,GAAO,CAAC,EA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from "./build-url.js";
3
3
  import { isTrustedCredentialTarget as n, reportSuppressedCredential as r } from "./credential-scope.js";
4
4
  import { csrfHeaders as i } from "./csrf.js";
5
5
  import { decodeByContentType as a } from "./decode-response.js";
6
- import { TempestApiError as o, buildApiError as s, isRetriableStatus as c } from "./errors.js";
7
- import { retry as l } from "./retry.js";
8
- import { withTimeout as u } from "./timeout.js";
6
+ import { SessionSupersededError as o, TempestApiError as s, buildApiError as c, isRetriableStatus as l } from "./errors.js";
7
+ import { retry as u } from "./retry.js";
8
+ import { withTimeout as d } from "./timeout.js";
9
9
  //#region src/http/api-client.ts
10
- var d = /* @__PURE__ */ new Set([
10
+ var f = /* @__PURE__ */ new Set([
11
11
  "GET",
12
12
  "HEAD",
13
13
  "OPTIONS"
14
14
  ]);
15
- function f(e, t) {
16
- return !d.has(t) || !(e instanceof o) ? !1 : c(e.status);
15
+ function p(e, t) {
16
+ return !f.has(t) || !(e instanceof s) ? !1 : l(e.status);
17
17
  }
18
- function p(e) {
18
+ function m(e) {
19
19
  return e ? e === !0 ? {} : e : null;
20
20
  }
21
- var m = 15e3, h = 3e5;
22
- function g(e) {
21
+ var h = 15e3, g = 3e5;
22
+ function _(e) {
23
23
  return typeof FormData < "u" && e instanceof FormData;
24
24
  }
25
- function _(e) {
25
+ function v(e) {
26
26
  return Math.round(performance.now() - e);
27
27
  }
28
- async function v(e, t) {
28
+ async function y(e, t) {
29
29
  let n;
30
30
  try {
31
31
  n = await e.clone().json();
@@ -36,47 +36,47 @@ async function v(e, t) {
36
36
  n = null;
37
37
  }
38
38
  }
39
- return new o(s(e.status, n, e.headers, t));
39
+ return new s(c(e.status, n, e.headers, t));
40
40
  }
41
- function y(s) {
42
- let c = s.fetcher ?? globalThis.fetch.bind(globalThis);
43
- function d(e, t) {
41
+ function b(c) {
42
+ let l = c.fetcher ?? globalThis.fetch.bind(globalThis);
43
+ function f(e, t) {
44
44
  if (t) return {};
45
- let i = s.getToken?.();
46
- return i ? n(e, s.baseURL, s.trustedOrigins) ? { Authorization: `Bearer ${i}` } : (r(e, s.baseURL), {}) : {};
45
+ let i = c.getToken?.();
46
+ return i ? n(e, c.baseURL, c.trustedOrigins) ? { Authorization: `Bearer ${i}` } : (r(e, c.baseURL), {}) : {};
47
47
  }
48
- async function y(e, n, r, a) {
49
- let { body: l, params: f, headers: p, signal: _, timeout: v, ...y } = n, b = g(l), x = b ? s.uploadTimeout : s.timeout, S = v === void 0 ? x === void 0 ? b ? h : m : x : v, C = t(s.baseURL, e, {
50
- prefix: s.prefix,
51
- params: f
48
+ async function b(e, n, r, a) {
49
+ let { body: o, params: u, headers: p, signal: m, timeout: v, ...y } = n, b = _(o), x = b ? c.uploadTimeout : c.timeout, S = v === void 0 ? x === void 0 ? b ? g : h : x : v, C = t(c.baseURL, e, {
50
+ prefix: c.prefix,
51
+ params: u
52
52
  }), w = p, T = {
53
53
  ...b ? {} : { "Content-Type": "application/json" },
54
54
  ...r ? { "X-Request-ID": r } : {},
55
- ...s.headers,
56
- ...d(C, a),
55
+ ...c.headers,
56
+ ...f(C, a),
57
57
  ...i({
58
58
  method: y.method ?? "GET",
59
59
  url: C,
60
- reference: s.baseURL,
61
- csrf: s.csrf,
62
- trustedOrigins: s.trustedOrigins,
60
+ reference: c.baseURL,
61
+ csrf: c.csrf,
62
+ trustedOrigins: c.trustedOrigins,
63
63
  headers: {
64
- ...s.headers,
64
+ ...c.headers,
65
65
  ...w
66
66
  }
67
67
  }),
68
68
  ...w
69
- }, E = u(_, S), D = {
69
+ }, E = d(m, S), D = {
70
70
  ...y,
71
71
  signal: E.signal,
72
72
  headers: T,
73
- credentials: s.withCredentials ? "include" : y.credentials,
74
- body: l == null ? void 0 : b ? l : JSON.stringify(l)
73
+ credentials: c.withCredentials ? "include" : y.credentials,
74
+ body: o == null ? void 0 : b ? o : JSON.stringify(o)
75
75
  };
76
76
  try {
77
- return await c(C, D);
77
+ return await l(C, D);
78
78
  } catch (e) {
79
- throw E.timedOut() ? new o({
79
+ throw E.timedOut() ? new s({
80
80
  status: 0,
81
81
  detail: `A requisição excedeu ${S}ms e foi abandonada.`
82
82
  }) : e;
@@ -84,35 +84,36 @@ function y(s) {
84
84
  E.dispose();
85
85
  }
86
86
  }
87
- async function b(e, t, n, r, i) {
88
- let a = s.logger;
89
- if (!a) return y(e, t, n, i);
87
+ async function x(e, t, n, r, i) {
88
+ let a = c.logger;
89
+ if (!a) return b(e, t, n, i);
90
90
  let o = performance.now();
91
91
  try {
92
- let s = await y(e, t, n, i), c = {
92
+ let s = await b(e, t, n, i), c = {
93
93
  requestId: n,
94
94
  status: s.status,
95
- ms: _(o)
95
+ ms: v(o)
96
96
  }, l = `${r} ${e} → ${s.status}`;
97
97
  return s.status >= 400 ? a.warn(l, c) : a.debug(l, c), s;
98
98
  } catch (t) {
99
99
  throw a.warn(`${r} ${e} → no response`, {
100
100
  requestId: n,
101
- ms: _(o),
101
+ ms: v(o),
102
102
  error: t
103
103
  }), t;
104
104
  }
105
105
  }
106
- async function x(e, t) {
107
- if (s.onUnauthorized) {
108
- s.logger?.warn("unauthorized — calling onUnauthorized", {
106
+ async function S(e, t, n) {
107
+ if (c.onUnauthorized) {
108
+ c.logger?.warn("unauthorized — calling onUnauthorized", {
109
109
  requestId: t,
110
110
  status: e.status
111
111
  });
112
112
  try {
113
- await s.onUnauthorized(e);
113
+ await c.onUnauthorized(e, n);
114
114
  } catch (n) {
115
- s.logger?.warn("onUnauthorized threw — keeping the original response error", {
115
+ if (n instanceof o) throw n;
116
+ c.logger?.warn("onUnauthorized threw — keeping the original response error", {
116
117
  requestId: t,
117
118
  status: e.status,
118
119
  error: n
@@ -120,68 +121,75 @@ function y(s) {
120
121
  }
121
122
  }
122
123
  }
123
- async function S(t, n, r) {
124
- let { skipAuth: i = !1, skipAuthRetry: a = !1, ...o } = n, c = s.requestId ? s.requestId() : e(), l = (o.method ?? "GET").toUpperCase(), u = await b(t, o, c, l, i);
125
- if (u.status === 401 && !i && !a) {
126
- if (s.refresh) {
124
+ function C(e) {
125
+ return {
126
+ token: e ? null : c.getToken?.() ?? null,
127
+ epoch: c.getSessionEpoch?.() ?? null
128
+ };
129
+ }
130
+ async function w(t, n, r) {
131
+ let { skipAuth: i = !1, skipAuthRetry: a = !1, ...s } = n, l = c.requestId ? c.requestId() : e(), u = (s.method ?? "GET").toUpperCase(), d = C(i), f = await x(t, s, l, u, i);
132
+ if (f.status === 401 && !i && !a) {
133
+ if (c.refresh) {
134
+ let e;
127
135
  try {
128
- await s.refresh(), u = await b(t, o, c, l, i);
129
- } catch {
130
- throw await x(u, c), await v(u, c);
136
+ await c.refresh(d), e = C(i), f = await x(t, s, l, u, i);
137
+ } catch (e) {
138
+ throw e instanceof o ? e : (await S(f, l, d), await y(f, l));
131
139
  }
132
- u.status === 401 && await x(u, c);
133
- } else await x(u, c);
140
+ f.status === 401 && await S(f, l, e);
141
+ } else await S(f, l, d);
134
142
  }
135
- if (!u.ok) throw await v(u, c);
136
- return r(u);
143
+ if (!f.ok) throw await y(f, l);
144
+ return r(f);
137
145
  }
138
- async function C(e, t, n) {
139
- let { retry: r, ...i } = t, a = p(r === void 0 ? s.retry : r);
140
- if (!a) return S(e, i, n);
146
+ async function T(e, t, n) {
147
+ let { retry: r, ...i } = t, a = m(r === void 0 ? c.retry : r);
148
+ if (!a) return w(e, i, n);
141
149
  let o = (i.method ?? "GET").toUpperCase();
142
- return l(() => S(e, i, n), {
150
+ return u(() => w(e, i, n), {
143
151
  ...a,
144
- shouldRetry: a.shouldRetry ?? ((e) => f(e, o))
152
+ shouldRetry: a.shouldRetry ?? ((e) => p(e, o))
145
153
  });
146
154
  }
147
- async function w(e, t = {}) {
148
- return C(e, t, a);
155
+ async function E(e, t = {}) {
156
+ return T(e, t, a);
149
157
  }
150
- async function T(e, t, n = "POST", r) {
151
- return w(e, {
158
+ async function D(e, t, n = "POST", r) {
159
+ return E(e, {
152
160
  ...r,
153
161
  method: n,
154
162
  body: t
155
163
  });
156
164
  }
157
165
  return {
158
- request: w,
159
- get: (e, t) => w(e, {
166
+ request: E,
167
+ get: (e, t) => E(e, {
160
168
  ...t,
161
169
  method: "GET"
162
170
  }),
163
- post: (e, t) => w(e, {
171
+ post: (e, t) => E(e, {
164
172
  ...t,
165
173
  method: "POST"
166
174
  }),
167
- put: (e, t) => w(e, {
175
+ put: (e, t) => E(e, {
168
176
  ...t,
169
177
  method: "PUT"
170
178
  }),
171
- patch: (e, t) => w(e, {
179
+ patch: (e, t) => E(e, {
172
180
  ...t,
173
181
  method: "PATCH"
174
182
  }),
175
- delete: (e, t) => w(e, {
183
+ delete: (e, t) => E(e, {
176
184
  ...t,
177
185
  method: "DELETE"
178
186
  }),
179
- blob: (e, t) => C(e, { ...t }, (e) => e.blob()),
180
- arrayBuffer: (e, t) => C(e, { ...t }, (e) => e.arrayBuffer()),
181
- upload: T
187
+ blob: (e, t) => T(e, { ...t }, (e) => e.blob()),
188
+ arrayBuffer: (e, t) => T(e, { ...t }, (e) => e.arrayBuffer()),
189
+ upload: D
182
190
  };
183
191
  }
184
192
  //#endregion
185
- export { y as createApiClient };
193
+ export { b as createApiClient };
186
194
 
187
195
  //# sourceMappingURL=api-client.js.map