@nhost/nhost-js 3.2.8 → 5.0.0-beta.1

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 (108) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +67 -37
  3. package/dist/nhost-js/auth.cjs.js +2 -0
  4. package/dist/nhost-js/auth.cjs.js.map +1 -0
  5. package/dist/nhost-js/auth.es.js +261 -0
  6. package/dist/nhost-js/auth.es.js.map +1 -0
  7. package/dist/nhost-js/fetch.cjs.js +2 -0
  8. package/dist/nhost-js/fetch.cjs.js.map +1 -0
  9. package/dist/nhost-js/fetch.es.js +10 -0
  10. package/dist/nhost-js/fetch.es.js.map +1 -0
  11. package/dist/nhost-js/graphql.cjs.js +2 -0
  12. package/dist/nhost-js/graphql.cjs.js.map +1 -0
  13. package/dist/nhost-js/graphql.es.js +35 -0
  14. package/dist/nhost-js/graphql.es.js.map +1 -0
  15. package/dist/nhost-js/storage.cjs.js +2 -0
  16. package/dist/nhost-js/storage.cjs.js.map +1 -0
  17. package/dist/nhost-js/storage.es.js +205 -0
  18. package/dist/nhost-js/storage.es.js.map +1 -0
  19. package/dist/nhost-js.cjs.js +2 -0
  20. package/dist/nhost-js.cjs.js.map +1 -0
  21. package/dist/nhost-js.es.js +476 -0
  22. package/dist/nhost-js.es.js.map +1 -0
  23. package/dist/nhost-js.umd.js +2 -0
  24. package/dist/nhost-js.umd.js.map +1 -0
  25. package/dist/src/auth/client.d.ts +415 -0
  26. package/dist/src/auth/client.d.ts.map +1 -0
  27. package/dist/src/auth/client.js +330 -0
  28. package/dist/src/auth/client.js.map +1 -0
  29. package/dist/src/auth/index.d.ts +11 -0
  30. package/dist/src/auth/index.d.ts.map +1 -0
  31. package/dist/src/auth/index.js +11 -0
  32. package/dist/src/auth/index.js.map +1 -0
  33. package/dist/src/auth/interface.d.ts +72 -0
  34. package/dist/src/auth/interface.d.ts.map +1 -0
  35. package/dist/src/auth/interface.js +2 -0
  36. package/dist/src/auth/interface.js.map +1 -0
  37. package/dist/src/fetch/index.d.ts +53 -0
  38. package/dist/src/fetch/index.d.ts.map +1 -0
  39. package/dist/src/fetch/index.js +40 -0
  40. package/dist/src/fetch/index.js.map +1 -0
  41. package/dist/src/graphql/client.d.ts +89 -0
  42. package/dist/src/graphql/client.d.ts.map +1 -0
  43. package/dist/src/graphql/client.js +49 -0
  44. package/dist/src/graphql/client.js.map +1 -0
  45. package/dist/src/graphql/index.d.ts +10 -0
  46. package/dist/src/graphql/index.d.ts.map +1 -0
  47. package/dist/src/graphql/index.js +10 -0
  48. package/dist/src/graphql/index.js.map +1 -0
  49. package/dist/src/index.d.ts +169 -0
  50. package/dist/src/index.d.ts.map +1 -0
  51. package/dist/src/index.js +237 -0
  52. package/dist/src/index.js.map +1 -0
  53. package/dist/src/middlewareAttachToken.d.ts +24 -0
  54. package/dist/src/middlewareAttachToken.d.ts.map +1 -0
  55. package/dist/src/middlewareAttachToken.js +60 -0
  56. package/dist/src/middlewareAttachToken.js.map +1 -0
  57. package/dist/src/middlewareRefreshSession.d.ts +43 -0
  58. package/dist/src/middlewareRefreshSession.d.ts.map +1 -0
  59. package/dist/src/middlewareRefreshSession.js +190 -0
  60. package/dist/src/middlewareRefreshSession.js.map +1 -0
  61. package/dist/src/middlewareResponseSession.d.ts +26 -0
  62. package/dist/src/middlewareResponseSession.d.ts.map +1 -0
  63. package/dist/src/middlewareResponseSession.js +83 -0
  64. package/dist/src/middlewareResponseSession.js.map +1 -0
  65. package/dist/src/sessionStorage.d.ts +123 -0
  66. package/dist/src/sessionStorage.d.ts.map +1 -0
  67. package/dist/src/sessionStorage.js +165 -0
  68. package/dist/src/sessionStorage.js.map +1 -0
  69. package/dist/src/storage/client.d.ts +184 -0
  70. package/dist/src/storage/client.d.ts.map +1 -0
  71. package/dist/src/storage/client.js +249 -0
  72. package/dist/src/storage/client.js.map +1 -0
  73. package/dist/src/storage/index.d.ts +11 -0
  74. package/dist/src/storage/index.d.ts.map +1 -0
  75. package/dist/src/storage/index.js +11 -0
  76. package/dist/src/storage/index.js.map +1 -0
  77. package/dist/src/storage/interface.d.ts +52 -0
  78. package/dist/src/storage/interface.d.ts.map +1 -0
  79. package/dist/src/storage/interface.js +2 -0
  80. package/dist/src/storage/interface.js.map +1 -0
  81. package/dist/tsconfig.tsbuildinfo +1 -0
  82. package/package.json +94 -60
  83. package/dist/clients/auth.d.ts +0 -8
  84. package/dist/clients/auth.d.ts.map +0 -1
  85. package/dist/clients/functions/index.d.ts +0 -107
  86. package/dist/clients/functions/index.d.ts.map +0 -1
  87. package/dist/clients/functions/types.d.ts +0 -28
  88. package/dist/clients/functions/types.d.ts.map +0 -1
  89. package/dist/clients/graphql.d.ts +0 -8
  90. package/dist/clients/graphql.d.ts.map +0 -1
  91. package/dist/clients/index.d.ts +0 -6
  92. package/dist/clients/index.d.ts.map +0 -1
  93. package/dist/clients/nhost.d.ts +0 -83
  94. package/dist/clients/nhost.d.ts.map +0 -1
  95. package/dist/clients/storage.d.ts +0 -8
  96. package/dist/clients/storage.d.ts.map +0 -1
  97. package/dist/index.cjs.js +0 -2
  98. package/dist/index.cjs.js.map +0 -1
  99. package/dist/index.d.ts +0 -6
  100. package/dist/index.d.ts.map +0 -1
  101. package/dist/index.esm.js +0 -344
  102. package/dist/index.esm.js.map +0 -1
  103. package/dist/utils/helpers.d.ts +0 -20
  104. package/dist/utils/helpers.d.ts.map +0 -1
  105. package/dist/utils/types.d.ts +0 -57
  106. package/dist/utils/types.d.ts.map +0 -1
  107. package/umd/nhost-js.umd.js +0 -22
  108. package/umd/nhost-js.umd.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graphql.es.js","sources":["../../src/graphql/client.ts"],"sourcesContent":["/**\n * @fileoverview GraphQL client for the Nhost JavaScript SDK.\n *\n * This module provides functionality for executing GraphQL operations against\n * a Hasura GraphQL API, with automatic authentication token handling.\n */\n\nimport { createEnhancedFetch } from \"../fetch\";\nimport type { ChainFunction } from \"../fetch\";\n\n/**\n * Variables object for GraphQL operations.\n * Key-value pairs of variable names and their values.\n */\nexport interface GraphQLVariables {\n [key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any\n}\n\n/**\n * GraphQL request object used for queries and mutations.\n */\nexport interface GraphQLRequest {\n /** The GraphQL query or mutation string */\n query: string;\n /** Optional variables for parameterized queries */\n variables?: GraphQLVariables;\n /** Optional name of the operation to execute */\n operationName?: string;\n}\n\n/**\n * Represents a GraphQL error returned from the server.\n */\nexport interface GraphQLError {\n /** Error message */\n message: string;\n /** Source locations in the GraphQL document where the error occurred */\n locations?: { line: number; column: number }[];\n /** Path in the query where the error occurred */\n path?: string[];\n /** Additional error information specific to the GraphQL implementation */\n extensions?: any; // eslint-disable-line @typescript-eslint/no-explicit-any\n}\n\n/**\n * Standard GraphQL response format as defined by the GraphQL specification.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface GraphQLResponse<T = any> {\n /** The data returned from successful execution */\n data?: T;\n /** Array of errors if execution was unsuccessful or partially successful */\n errors?: GraphQLError[];\n}\n\n/**\n * Response wrapper for GraphQL operations with additional metadata.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface FetchResponse<T = any> {\n /** The parsed response body */\n body: T;\n /** HTTP status code of the response */\n status: number;\n /** HTTP headers from the response */\n headers: Headers;\n}\n\n/**\n * GraphQL client interface providing methods for executing queries and mutations\n */\nexport interface Client {\n /**\n * Execute a GraphQL query operation\n *\n * Queries are used to fetch data and should not modify any data on the server.\n *\n * @param request - GraphQL request object containing query and optional variables\n * @param options - Additional fetch options to apply to the request\n * @returns Promise with the GraphQL response and metadata\n */\n post: (\n request: GraphQLRequest,\n options?: RequestInit,\n ) => Promise<FetchResponse<GraphQLResponse>>;\n}\n\n/**\n * Creates a GraphQL API client for interacting with a GraphQL endpoint.\n *\n * This client provides methods for executing queries and mutations against\n * a GraphQL API, with support for middleware functions to handle authentication,\n * error handling, and other cross-cutting concerns.\n *\n * @param baseURL - Base URL for the GraphQL endpoint\n * @param chainFunctions - Array of middleware functions for the fetch chain\n * @returns GraphQL client with query and mutation methods\n */\nexport const createAPIClient = (\n baseURL: string,\n chainFunctions: ChainFunction[] = [],\n) => {\n const enhancedFetch = createEnhancedFetch(chainFunctions);\n\n const executeOperation = async (\n request: GraphQLRequest,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse>> => {\n const response = await enhancedFetch(`${baseURL}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(request),\n ...options,\n });\n\n const body = await response.text();\n const data: GraphQLResponse = body ? JSON.parse(body) : {};\n\n const resp = {\n body: data,\n status: response.status,\n headers: response.headers,\n };\n\n if (data.errors) {\n throw resp;\n }\n\n return resp;\n };\n\n const post = (\n request: GraphQLRequest,\n options?: RequestInit,\n ): Promise<FetchResponse<GraphQLResponse>> => {\n return executeOperation(request, options);\n };\n\n return {\n post,\n } as Client;\n};\n"],"names":[],"mappings":";AAkGO,MAAM,kBAAkB,CAC7B,SACA,iBAAkC,OAC/B;AACG,QAAA,gBAAgB,oBAAoB,cAAc;AAElD,QAAA,mBAAmB,OACvB,SACA,YAC4C;AAC5C,UAAM,WAAW,MAAM,cAAc,GAAG,OAAO,IAAI;AAAA,MACjD,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,gBAAgB;AAAA,MAClB;AAAA,MACA,MAAM,KAAK,UAAU,OAAO;AAAA,MAC5B,GAAG;AAAA,IAAA,CACJ;AAEK,UAAA,OAAO,MAAM,SAAS,KAAK;AACjC,UAAM,OAAwB,OAAO,KAAK,MAAM,IAAI,IAAI,CAAC;AAEzD,UAAM,OAAO;AAAA,MACX,MAAM;AAAA,MACN,QAAQ,SAAS;AAAA,MACjB,SAAS,SAAS;AAAA,IACpB;AAEA,QAAI,KAAK,QAAQ;AACT,YAAA;AAAA,IAAA;AAGD,WAAA;AAAA,EACT;AAEM,QAAA,OAAO,CACX,SACA,YAC4C;AACrC,WAAA,iBAAiB,SAAS,OAAO;AAAA,EAC1C;AAEO,SAAA;AAAA,IACL;AAAA,EACF;AACF;"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./fetch.cjs.js");exports.createAPIClient=(e,a=[])=>{let s=t.createEnhancedFetch(a);const r=()=>e+"/openapi.yaml",n=()=>e+"/version",i=()=>e+"/files/",o=(t,a)=>{const s=new URLSearchParams;Object.entries(a||{}).forEach((([t,e])=>{void 0!==e&&s.append(t,null===e?"null":e.toString())}));const r=s.toString();return r.length>0?e+`/files/${t}?${r}`:e+`/files/${t}`},d=(t,a)=>{const s=new URLSearchParams;Object.entries(a||{}).forEach((([t,e])=>{void 0!==e&&s.append(t,null===e?"null":e.toString())}));const r=s.toString();return r.length>0?e+`/files/${t}?${r}`:e+`/files/${t}`},c=t=>e+`/files/${t}`,u=t=>e+`/files/${t}`;return{getOpenAPISpec:async t=>{const e=await s(r(),{...t,method:"GET"}),a=[204,205,304,412].includes(e.status)?null:await e.text(),n={body:a?JSON.parse(a):{},status:e.status,headers:Object.fromEntries(Array.from(e.headers.entries()))};if(!e.ok)throw n;return n},getVersion:async t=>{const e=await s(n(),{...t,method:"GET"}),a=[204,205,304,412].includes(e.status)?null:await e.text(),r={body:a?JSON.parse(a):{},status:e.status,headers:Object.fromEntries(Array.from(e.headers.entries()))};if(!e.ok)throw r;return r},uploadFiles:async(t,e)=>{const a=new FormData;void 0!==t["bucket-id"]&&a.append("bucket-id",t["bucket-id"]),void 0!==t["metadata[]"]&&t["metadata[]"].forEach((t=>a.append("metadata[]",JSON.stringify(t)))),void 0!==t["file[]"]&&t["file[]"].forEach((t=>a.append("file[]",t)));const r=await s(i(),{...e,method:"POST",body:a}),n=[204,205,304,412].includes(r.status)?null:await r.text(),o={body:n?JSON.parse(n):{},status:r.status,headers:Object.fromEntries(Array.from(r.headers.entries()))};if(!r.ok)throw o;return o},getFileMetadataHeaders:async(t,e,a)=>{const r=await s(o(t,e),{...a,method:"HEAD"}),n=[204,205,304,412].includes(r.status)?null:await r.text(),i={body:n?JSON.parse(n):{},status:r.status,headers:Object.fromEntries(Array.from(r.headers.entries()))};if(!r.ok)throw i;return i},getFile:async(t,e,a)=>{const r=await s(d(t,e),{...a,method:"GET"}),n={body:await r.blob(),status:r.status,headers:Object.fromEntries(Array.from(r.headers.entries()))};if(!r.ok)throw n;return n},replaceFile:async(t,e,a)=>{const r=new FormData;void 0!==e.metadata&&r.append("metadata",JSON.stringify(e.metadata)),void 0!==e.file&&r.append("file",e.file);const n=await s(c(t),{...a,method:"PUT",body:r}),i=[204,205,304,412].includes(n.status)?null:await n.text(),o={body:i?JSON.parse(i):{},status:n.status,headers:Object.fromEntries(Array.from(n.headers.entries()))};if(!n.ok)throw o;return o},deleteFile:async(t,e)=>{const a=await s(u(t),{...e,method:"DELETE"}),r=[204,205,304,412].includes(a.status)?null:await a.text(),n={body:r?JSON.parse(r):{},status:a.status,headers:Object.fromEntries(Array.from(a.headers.entries()))};if(!a.ok)throw n;return n},pushChainFunction:e=>{a.push(e),s=t.createEnhancedFetch(a)},baseURL:e}};
2
+ //# sourceMappingURL=storage.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.cjs.js","sources":["../../src/storage/client.ts"],"sourcesContent":["/**\n * Generated by orval v7.9.0 🍺\n * Do not edit manually.\n * Nhost Storage API\n * Nhost Storage API - A service for managing and serving files with powerful access control capabilities\n * OpenAPI spec version: 1.0.0\n */\nimport { createEnhancedFetch } from \"../fetch\";\nimport type { ChainFunction } from \"../fetch\";\n\nimport type { Client } from \"./interface\";\n\n/**\n * Contains version information about the storage service.\n */\nexport interface VersionInformation {\n /** The version number of the storage service build. */\n buildVersion?: string;\n}\n\n/**\n * Basic information about a file in storage.\n */\nexport interface FileSummary {\n /** Unique identifier for the file. */\n id?: string;\n /** Name of the file including extension. */\n name?: string;\n /** ID of the bucket containing the file. */\n bucketId?: string;\n /** Whether the file has been successfully uploaded. */\n isUploaded?: boolean;\n}\n\n/**\n * Custom metadata associated with the file.\n */\nexport type FileMetadataMetadata = { [key: string]: unknown };\n\n/**\n * Comprehensive metadata information about a file in storage.\n */\nexport interface FileMetadata {\n /** Unique identifier for the file. */\n id?: string;\n /** Name of the file including extension. */\n name?: string;\n /** Size of the file in bytes. */\n size?: number;\n /** ID of the bucket containing the file. */\n bucketId?: string;\n /** Entity tag for cache validation. */\n etag?: string;\n /** Timestamp when the file was created. */\n createdAt?: string;\n /** Timestamp when the file was last updated. */\n updatedAt?: string;\n /** Whether the file has been successfully uploaded. */\n isUploaded?: boolean;\n /** MIME type of the file. */\n mimeType?: string;\n /** ID of the user who uploaded the file. */\n uploadedByUserId?: string;\n /** Custom metadata associated with the file. */\n metadata?: FileMetadataMetadata;\n}\n\n/**\n * Custom metadata to associate with the file.\n */\nexport type UploadFileMetadataMetadata = { [key: string]: unknown };\n\n/**\n * Metadata provided when uploading a new file.\n */\nexport interface UploadFileMetadata {\n /** Optional custom ID for the file. If not provided, a UUID will be generated. */\n id?: string;\n /** Name to assign to the file. If not provided, the original filename will be used. */\n name?: string;\n /** Custom metadata to associate with the file. */\n metadata?: UploadFileMetadataMetadata;\n}\n\n/**\n * Updated custom metadata to associate with the file.\n */\nexport type UpdateFileMetadataMetadata = { [key: string]: unknown };\n\n/**\n * Metadata that can be updated for an existing file.\n */\nexport interface UpdateFileMetadata {\n /** New name to assign to the file. */\n name?: string;\n /** Updated custom metadata to associate with the file. */\n metadata?: UpdateFileMetadataMetadata;\n}\n\n/**\n * Contains a presigned URL for direct file operations.\n */\nexport interface PresignedURLResponse {\n /** The presigned URL for file operations. */\n url?: string;\n /** The time in seconds until the URL expires. */\n expiration?: number;\n}\n\n/**\n * Error details.\n */\nexport type ErrorError = {\n /** Human-readable error message. */\n message: string;\n};\n\n/**\n * Error information returned by the API.\n */\nexport interface Error {\n /** Error details. */\n error?: ErrorError;\n}\n\nexport type GetOpenAPISpec200 = { [key: string]: unknown };\n\nexport type UploadFilesBody = {\n /** Target bucket identifier where files will be stored. */\n \"bucket-id\"?: string;\n /** Optional custom metadata for each uploaded file. Must match the order of the file[] array. */\n \"metadata[]\"?: UploadFileMetadata[];\n /** Array of files to upload. */\n \"file[]\"?: Blob[];\n};\n\nexport type UploadFiles201 = {\n /** List of successfully processed files with their metadata. */\n processedFiles?: FileMetadata[];\n};\n\nexport type GetFileMetadataHeadersParams = {\n /**\n * Image quality (1-100). Only applies to JPEG, WebP and PNG files\n */\n q?: number;\n /**\n * Maximum height to resize image to while maintaining aspect ratio. Only applies to image files\n */\n h?: number;\n /**\n * Maximum width to resize image to while maintaining aspect ratio. Only applies to image files\n */\n w?: number;\n /**\n * Blur the image using this sigma value. Only applies to image files\n */\n b?: number;\n /**\n * Output format for image files. Use 'auto' for content negotiation based on Accept header\n */\n f?: GetFileMetadataHeadersF;\n};\n\nexport type GetFileMetadataHeadersF =\n | \"auto\"\n | \"same\"\n | \"jpeg\"\n | \"webp\"\n | \"png\"\n | \"avif\";\nexport type GetFileParams = {\n /**\n * Image quality (1-100). Only applies to JPEG, WebP and PNG files\n */\n q?: number;\n /**\n * Maximum height to resize image to while maintaining aspect ratio. Only applies to image files\n */\n h?: number;\n /**\n * Maximum width to resize image to while maintaining aspect ratio. Only applies to image files\n */\n w?: number;\n /**\n * Blur the image using this sigma value. Only applies to image files\n */\n b?: number;\n /**\n * Output format for image files. Use 'auto' for content negotiation based on Accept header\n */\n f?: GetFileF;\n};\n\nexport type GetFileF = \"auto\" | \"same\" | \"jpeg\" | \"webp\" | \"png\" | \"avif\";\nexport type ReplaceFileBody = {\n /** Optional metadata to update for the file */\n metadata?: UpdateFileMetadata;\n /** New file content to replace the existing file */\n file?: Blob;\n};\n\nexport type FetchResponse<T> = {\n body: T;\n status: number;\n headers: Record<string, string>;\n};\n\nexport const createAPIClient = (\n baseURL: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n let fetch = createEnhancedFetch(chainFunctions);\n\n const pushChainFunction = (chainFunction: ChainFunction) => {\n chainFunctions.push(chainFunction);\n fetch = createEnhancedFetch(chainFunctions);\n };\n\n /**\n * Returns the OpenAPI schema definition for this API, allowing clients to understand the available endpoints and models.\n * @summary Get OpenAPI specification\n */\n const getOpenAPISpec = async (\n options?: RequestInit,\n ): Promise<FetchResponse<GetOpenAPISpec200>> => {\n const res = await fetch(getGetOpenAPISpecUrl(), {\n ...options,\n method: \"GET\",\n });\n\n const body = [204, 205, 304, 412].includes(res.status)\n ? null\n : await res.text();\n const payload: GetOpenAPISpec200 = body ? JSON.parse(body) : {};\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<GetOpenAPISpec200>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getGetOpenAPISpecUrl = () => {\n return baseURL + `/openapi.yaml`;\n };\n\n /**\n * Retrieves build and version information about the storage service. Useful for monitoring and debugging.\n * @summary Get service version information\n */\n const getVersion = async (\n options?: RequestInit,\n ): Promise<FetchResponse<VersionInformation>> => {\n const res = await fetch(getGetVersionUrl(), {\n ...options,\n method: \"GET\",\n });\n\n const body = [204, 205, 304, 412].includes(res.status)\n ? null\n : await res.text();\n const payload: VersionInformation = body ? JSON.parse(body) : {};\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<VersionInformation>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getGetVersionUrl = () => {\n return baseURL + `/version`;\n };\n\n /**\n * Upload one or more files to a specified bucket. Supports batch uploading with optional custom metadata for each file. If uploading multiple files, either provide metadata for all files or none.\n * @summary Upload files\n */\n const uploadFiles = async (\n uploadFilesBody: UploadFilesBody,\n options?: RequestInit,\n ): Promise<FetchResponse<UploadFiles201>> => {\n const formData = new FormData();\n if (uploadFilesBody[\"bucket-id\"] !== undefined) {\n formData.append(`bucket-id`, uploadFilesBody[\"bucket-id\"]);\n }\n if (uploadFilesBody[\"metadata[]\"] !== undefined) {\n uploadFilesBody[\"metadata[]\"].forEach((value) =>\n formData.append(`metadata[]`, JSON.stringify(value)),\n );\n }\n if (uploadFilesBody[\"file[]\"] !== undefined) {\n uploadFilesBody[\"file[]\"].forEach((value) =>\n formData.append(`file[]`, value),\n );\n }\n\n const res = await fetch(getUploadFilesUrl(), {\n ...options,\n method: \"POST\",\n body: formData,\n });\n\n const body = [204, 205, 304, 412].includes(res.status)\n ? null\n : await res.text();\n const payload: UploadFiles201 = body ? JSON.parse(body) : {};\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<UploadFiles201>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getUploadFilesUrl = () => {\n return baseURL + `/files/`;\n };\n\n /**\n * Retrieve file metadata headers without downloading the file content. Supports conditional requests and provides caching information.\n * @summary Check file information\n */\n const getFileMetadataHeaders = async (\n id: string,\n params?: GetFileMetadataHeadersParams,\n options?: RequestInit,\n ): Promise<FetchResponse<void>> => {\n const res = await fetch(getGetFileMetadataHeadersUrl(id, params), {\n ...options,\n method: \"HEAD\",\n });\n\n const body = [204, 205, 304, 412].includes(res.status)\n ? null\n : await res.text();\n const payload: void = body ? JSON.parse(body) : {};\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<void>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getGetFileMetadataHeadersUrl = (\n id: string,\n params?: GetFileMetadataHeadersParams,\n ) => {\n const normalizedParams = new URLSearchParams();\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (value !== undefined) {\n normalizedParams.append(\n key,\n value === null ? \"null\" : value.toString(),\n );\n }\n });\n\n const stringifiedParams = normalizedParams.toString();\n\n return stringifiedParams.length > 0\n ? baseURL + `/files/${id}?${stringifiedParams}`\n : baseURL + `/files/${id}`;\n };\n\n /**\n * Retrieve and download the complete file content. Supports conditional requests, image transformations, and range requests for partial downloads.\n * @summary Download file\n */\n const getFile = async (\n id: string,\n params?: GetFileParams,\n options?: RequestInit,\n ): Promise<FetchResponse<Blob>> => {\n const res = await fetch(getGetFileUrl(id, params), {\n ...options,\n method: \"GET\",\n });\n\n const payload: Blob = await res.blob();\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<Blob>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getGetFileUrl = (id: string, params?: GetFileParams) => {\n const normalizedParams = new URLSearchParams();\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (value !== undefined) {\n normalizedParams.append(\n key,\n value === null ? \"null\" : value.toString(),\n );\n }\n });\n\n const stringifiedParams = normalizedParams.toString();\n\n return stringifiedParams.length > 0\n ? baseURL + `/files/${id}?${stringifiedParams}`\n : baseURL + `/files/${id}`;\n };\n\n /**\n * Replace an existing file with new content while preserving the file ID. The operation follows these steps:\n1. The isUploaded flag is set to false to mark the file as being updated\n2. The file content is replaced in the storage backend\n3. File metadata is updated (size, mime-type, isUploaded, etc.)\n\nEach step is atomic, but if a step fails, previous steps will not be automatically rolled back.\n\n * @summary Replace file\n */\n const replaceFile = async (\n id: string,\n replaceFileBody: ReplaceFileBody,\n options?: RequestInit,\n ): Promise<FetchResponse<FileMetadata>> => {\n const formData = new FormData();\n if (replaceFileBody.metadata !== undefined) {\n formData.append(`metadata`, JSON.stringify(replaceFileBody.metadata));\n }\n if (replaceFileBody.file !== undefined) {\n formData.append(`file`, replaceFileBody.file);\n }\n\n const res = await fetch(getReplaceFileUrl(id), {\n ...options,\n method: \"PUT\",\n body: formData,\n });\n\n const body = [204, 205, 304, 412].includes(res.status)\n ? null\n : await res.text();\n const payload: FileMetadata = body ? JSON.parse(body) : {};\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<FileMetadata>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getReplaceFileUrl = (id: string) => {\n return baseURL + `/files/${id}`;\n };\n\n /**\n * Permanently delete a file from storage. This removes both the file content and its associated metadata.\n * @summary Delete file\n */\n const deleteFile = async (\n id: string,\n options?: RequestInit,\n ): Promise<FetchResponse<void>> => {\n const res = await fetch(getDeleteFileUrl(id), {\n ...options,\n method: \"DELETE\",\n });\n\n const body = [204, 205, 304, 412].includes(res.status)\n ? null\n : await res.text();\n const payload: void = body ? JSON.parse(body) : {};\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<void>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getDeleteFileUrl = (id: string) => {\n return baseURL + `/files/${id}`;\n };\n\n return {\n getOpenAPISpec,\n getVersion,\n uploadFiles,\n getFileMetadataHeaders,\n getFile,\n replaceFile,\n deleteFile,\n pushChainFunction,\n baseURL,\n };\n};\n"],"names":["baseURL","chainFunctions","fetch","createEnhancedFetch","getGetOpenAPISpecUrl","getGetVersionUrl","getUploadFilesUrl","getGetFileMetadataHeadersUrl","id","params","normalizedParams","URLSearchParams","Object","entries","forEach","key","value","append","toString","stringifiedParams","length","getGetFileUrl","getReplaceFileUrl","getDeleteFileUrl","getOpenAPISpec","async","options","res","method","body","includes","status","text","response","JSON","parse","headers","fromEntries","Array","from","ok","getVersion","uploadFiles","uploadFilesBody","formData","FormData","stringify","getFileMetadataHeaders","getFile","blob","replaceFile","replaceFileBody","metadata","file","deleteFile","pushChainFunction","chainFunction","push"],"mappings":"0IAgN+B,CAC7BA,EACAC,EAAkC,MAE9B,IAAAC,EAAQC,sBAAoBF,GAE1B,MAmCAG,EAAuB,IACpBJ,EAAU,gBAiCbK,EAAmB,IAChBL,EAAU,WAkDbM,EAAoB,IACjBN,EAAU,UAmCbO,EAA+B,CACnCC,EACAC,KAEM,MAAAC,EAAmB,IAAIC,gBAEtBC,OAAAC,QAAQJ,GAAU,C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BAAoBF,EAAc,EA+T1CD,UACF"}
@@ -0,0 +1,205 @@
1
+ import { createEnhancedFetch } from "./fetch.es.js";
2
+ const createAPIClient = (baseURL, chainFunctions = []) => {
3
+ let fetch = createEnhancedFetch(chainFunctions);
4
+ const pushChainFunction = (chainFunction) => {
5
+ chainFunctions.push(chainFunction);
6
+ fetch = createEnhancedFetch(chainFunctions);
7
+ };
8
+ const getOpenAPISpec = async (options) => {
9
+ const res = await fetch(getGetOpenAPISpecUrl(), {
10
+ ...options,
11
+ method: "GET"
12
+ });
13
+ const body = [204, 205, 304, 412].includes(res.status) ? null : await res.text();
14
+ const payload = body ? JSON.parse(body) : {};
15
+ const response = {
16
+ body: payload,
17
+ status: res.status,
18
+ headers: Object.fromEntries(Array.from(res.headers.entries()))
19
+ };
20
+ if (!res.ok) {
21
+ throw response;
22
+ }
23
+ return response;
24
+ };
25
+ const getGetOpenAPISpecUrl = () => {
26
+ return baseURL + `/openapi.yaml`;
27
+ };
28
+ const getVersion = async (options) => {
29
+ const res = await fetch(getGetVersionUrl(), {
30
+ ...options,
31
+ method: "GET"
32
+ });
33
+ const body = [204, 205, 304, 412].includes(res.status) ? null : await res.text();
34
+ const payload = body ? JSON.parse(body) : {};
35
+ const response = {
36
+ body: payload,
37
+ status: res.status,
38
+ headers: Object.fromEntries(Array.from(res.headers.entries()))
39
+ };
40
+ if (!res.ok) {
41
+ throw response;
42
+ }
43
+ return response;
44
+ };
45
+ const getGetVersionUrl = () => {
46
+ return baseURL + `/version`;
47
+ };
48
+ const uploadFiles = async (uploadFilesBody, options) => {
49
+ const formData = new FormData();
50
+ if (uploadFilesBody["bucket-id"] !== void 0) {
51
+ formData.append(`bucket-id`, uploadFilesBody["bucket-id"]);
52
+ }
53
+ if (uploadFilesBody["metadata[]"] !== void 0) {
54
+ uploadFilesBody["metadata[]"].forEach(
55
+ (value) => formData.append(`metadata[]`, JSON.stringify(value))
56
+ );
57
+ }
58
+ if (uploadFilesBody["file[]"] !== void 0) {
59
+ uploadFilesBody["file[]"].forEach(
60
+ (value) => formData.append(`file[]`, value)
61
+ );
62
+ }
63
+ const res = await fetch(getUploadFilesUrl(), {
64
+ ...options,
65
+ method: "POST",
66
+ body: formData
67
+ });
68
+ const body = [204, 205, 304, 412].includes(res.status) ? null : await res.text();
69
+ const payload = body ? JSON.parse(body) : {};
70
+ const response = {
71
+ body: payload,
72
+ status: res.status,
73
+ headers: Object.fromEntries(Array.from(res.headers.entries()))
74
+ };
75
+ if (!res.ok) {
76
+ throw response;
77
+ }
78
+ return response;
79
+ };
80
+ const getUploadFilesUrl = () => {
81
+ return baseURL + `/files/`;
82
+ };
83
+ const getFileMetadataHeaders = async (id, params, options) => {
84
+ const res = await fetch(getGetFileMetadataHeadersUrl(id, params), {
85
+ ...options,
86
+ method: "HEAD"
87
+ });
88
+ const body = [204, 205, 304, 412].includes(res.status) ? null : await res.text();
89
+ const payload = body ? JSON.parse(body) : {};
90
+ const response = {
91
+ body: payload,
92
+ status: res.status,
93
+ headers: Object.fromEntries(Array.from(res.headers.entries()))
94
+ };
95
+ if (!res.ok) {
96
+ throw response;
97
+ }
98
+ return response;
99
+ };
100
+ const getGetFileMetadataHeadersUrl = (id, params) => {
101
+ const normalizedParams = new URLSearchParams();
102
+ Object.entries(params || {}).forEach(([key, value]) => {
103
+ if (value !== void 0) {
104
+ normalizedParams.append(
105
+ key,
106
+ value === null ? "null" : value.toString()
107
+ );
108
+ }
109
+ });
110
+ const stringifiedParams = normalizedParams.toString();
111
+ return stringifiedParams.length > 0 ? baseURL + `/files/${id}?${stringifiedParams}` : baseURL + `/files/${id}`;
112
+ };
113
+ const getFile = async (id, params, options) => {
114
+ const res = await fetch(getGetFileUrl(id, params), {
115
+ ...options,
116
+ method: "GET"
117
+ });
118
+ const payload = await res.blob();
119
+ const response = {
120
+ body: payload,
121
+ status: res.status,
122
+ headers: Object.fromEntries(Array.from(res.headers.entries()))
123
+ };
124
+ if (!res.ok) {
125
+ throw response;
126
+ }
127
+ return response;
128
+ };
129
+ const getGetFileUrl = (id, params) => {
130
+ const normalizedParams = new URLSearchParams();
131
+ Object.entries(params || {}).forEach(([key, value]) => {
132
+ if (value !== void 0) {
133
+ normalizedParams.append(
134
+ key,
135
+ value === null ? "null" : value.toString()
136
+ );
137
+ }
138
+ });
139
+ const stringifiedParams = normalizedParams.toString();
140
+ return stringifiedParams.length > 0 ? baseURL + `/files/${id}?${stringifiedParams}` : baseURL + `/files/${id}`;
141
+ };
142
+ const replaceFile = async (id, replaceFileBody, options) => {
143
+ const formData = new FormData();
144
+ if (replaceFileBody.metadata !== void 0) {
145
+ formData.append(`metadata`, JSON.stringify(replaceFileBody.metadata));
146
+ }
147
+ if (replaceFileBody.file !== void 0) {
148
+ formData.append(`file`, replaceFileBody.file);
149
+ }
150
+ const res = await fetch(getReplaceFileUrl(id), {
151
+ ...options,
152
+ method: "PUT",
153
+ body: formData
154
+ });
155
+ const body = [204, 205, 304, 412].includes(res.status) ? null : await res.text();
156
+ const payload = body ? JSON.parse(body) : {};
157
+ const response = {
158
+ body: payload,
159
+ status: res.status,
160
+ headers: Object.fromEntries(Array.from(res.headers.entries()))
161
+ };
162
+ if (!res.ok) {
163
+ throw response;
164
+ }
165
+ return response;
166
+ };
167
+ const getReplaceFileUrl = (id) => {
168
+ return baseURL + `/files/${id}`;
169
+ };
170
+ const deleteFile = async (id, options) => {
171
+ const res = await fetch(getDeleteFileUrl(id), {
172
+ ...options,
173
+ method: "DELETE"
174
+ });
175
+ const body = [204, 205, 304, 412].includes(res.status) ? null : await res.text();
176
+ const payload = body ? JSON.parse(body) : {};
177
+ const response = {
178
+ body: payload,
179
+ status: res.status,
180
+ headers: Object.fromEntries(Array.from(res.headers.entries()))
181
+ };
182
+ if (!res.ok) {
183
+ throw response;
184
+ }
185
+ return response;
186
+ };
187
+ const getDeleteFileUrl = (id) => {
188
+ return baseURL + `/files/${id}`;
189
+ };
190
+ return {
191
+ getOpenAPISpec,
192
+ getVersion,
193
+ uploadFiles,
194
+ getFileMetadataHeaders,
195
+ getFile,
196
+ replaceFile,
197
+ deleteFile,
198
+ pushChainFunction,
199
+ baseURL
200
+ };
201
+ };
202
+ export {
203
+ createAPIClient
204
+ };
205
+ //# sourceMappingURL=storage.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.es.js","sources":["../../src/storage/client.ts"],"sourcesContent":["/**\n * Generated by orval v7.9.0 🍺\n * Do not edit manually.\n * Nhost Storage API\n * Nhost Storage API - A service for managing and serving files with powerful access control capabilities\n * OpenAPI spec version: 1.0.0\n */\nimport { createEnhancedFetch } from \"../fetch\";\nimport type { ChainFunction } from \"../fetch\";\n\nimport type { Client } from \"./interface\";\n\n/**\n * Contains version information about the storage service.\n */\nexport interface VersionInformation {\n /** The version number of the storage service build. */\n buildVersion?: string;\n}\n\n/**\n * Basic information about a file in storage.\n */\nexport interface FileSummary {\n /** Unique identifier for the file. */\n id?: string;\n /** Name of the file including extension. */\n name?: string;\n /** ID of the bucket containing the file. */\n bucketId?: string;\n /** Whether the file has been successfully uploaded. */\n isUploaded?: boolean;\n}\n\n/**\n * Custom metadata associated with the file.\n */\nexport type FileMetadataMetadata = { [key: string]: unknown };\n\n/**\n * Comprehensive metadata information about a file in storage.\n */\nexport interface FileMetadata {\n /** Unique identifier for the file. */\n id?: string;\n /** Name of the file including extension. */\n name?: string;\n /** Size of the file in bytes. */\n size?: number;\n /** ID of the bucket containing the file. */\n bucketId?: string;\n /** Entity tag for cache validation. */\n etag?: string;\n /** Timestamp when the file was created. */\n createdAt?: string;\n /** Timestamp when the file was last updated. */\n updatedAt?: string;\n /** Whether the file has been successfully uploaded. */\n isUploaded?: boolean;\n /** MIME type of the file. */\n mimeType?: string;\n /** ID of the user who uploaded the file. */\n uploadedByUserId?: string;\n /** Custom metadata associated with the file. */\n metadata?: FileMetadataMetadata;\n}\n\n/**\n * Custom metadata to associate with the file.\n */\nexport type UploadFileMetadataMetadata = { [key: string]: unknown };\n\n/**\n * Metadata provided when uploading a new file.\n */\nexport interface UploadFileMetadata {\n /** Optional custom ID for the file. If not provided, a UUID will be generated. */\n id?: string;\n /** Name to assign to the file. If not provided, the original filename will be used. */\n name?: string;\n /** Custom metadata to associate with the file. */\n metadata?: UploadFileMetadataMetadata;\n}\n\n/**\n * Updated custom metadata to associate with the file.\n */\nexport type UpdateFileMetadataMetadata = { [key: string]: unknown };\n\n/**\n * Metadata that can be updated for an existing file.\n */\nexport interface UpdateFileMetadata {\n /** New name to assign to the file. */\n name?: string;\n /** Updated custom metadata to associate with the file. */\n metadata?: UpdateFileMetadataMetadata;\n}\n\n/**\n * Contains a presigned URL for direct file operations.\n */\nexport interface PresignedURLResponse {\n /** The presigned URL for file operations. */\n url?: string;\n /** The time in seconds until the URL expires. */\n expiration?: number;\n}\n\n/**\n * Error details.\n */\nexport type ErrorError = {\n /** Human-readable error message. */\n message: string;\n};\n\n/**\n * Error information returned by the API.\n */\nexport interface Error {\n /** Error details. */\n error?: ErrorError;\n}\n\nexport type GetOpenAPISpec200 = { [key: string]: unknown };\n\nexport type UploadFilesBody = {\n /** Target bucket identifier where files will be stored. */\n \"bucket-id\"?: string;\n /** Optional custom metadata for each uploaded file. Must match the order of the file[] array. */\n \"metadata[]\"?: UploadFileMetadata[];\n /** Array of files to upload. */\n \"file[]\"?: Blob[];\n};\n\nexport type UploadFiles201 = {\n /** List of successfully processed files with their metadata. */\n processedFiles?: FileMetadata[];\n};\n\nexport type GetFileMetadataHeadersParams = {\n /**\n * Image quality (1-100). Only applies to JPEG, WebP and PNG files\n */\n q?: number;\n /**\n * Maximum height to resize image to while maintaining aspect ratio. Only applies to image files\n */\n h?: number;\n /**\n * Maximum width to resize image to while maintaining aspect ratio. Only applies to image files\n */\n w?: number;\n /**\n * Blur the image using this sigma value. Only applies to image files\n */\n b?: number;\n /**\n * Output format for image files. Use 'auto' for content negotiation based on Accept header\n */\n f?: GetFileMetadataHeadersF;\n};\n\nexport type GetFileMetadataHeadersF =\n | \"auto\"\n | \"same\"\n | \"jpeg\"\n | \"webp\"\n | \"png\"\n | \"avif\";\nexport type GetFileParams = {\n /**\n * Image quality (1-100). Only applies to JPEG, WebP and PNG files\n */\n q?: number;\n /**\n * Maximum height to resize image to while maintaining aspect ratio. Only applies to image files\n */\n h?: number;\n /**\n * Maximum width to resize image to while maintaining aspect ratio. Only applies to image files\n */\n w?: number;\n /**\n * Blur the image using this sigma value. Only applies to image files\n */\n b?: number;\n /**\n * Output format for image files. Use 'auto' for content negotiation based on Accept header\n */\n f?: GetFileF;\n};\n\nexport type GetFileF = \"auto\" | \"same\" | \"jpeg\" | \"webp\" | \"png\" | \"avif\";\nexport type ReplaceFileBody = {\n /** Optional metadata to update for the file */\n metadata?: UpdateFileMetadata;\n /** New file content to replace the existing file */\n file?: Blob;\n};\n\nexport type FetchResponse<T> = {\n body: T;\n status: number;\n headers: Record<string, string>;\n};\n\nexport const createAPIClient = (\n baseURL: string,\n chainFunctions: ChainFunction[] = [],\n): Client => {\n let fetch = createEnhancedFetch(chainFunctions);\n\n const pushChainFunction = (chainFunction: ChainFunction) => {\n chainFunctions.push(chainFunction);\n fetch = createEnhancedFetch(chainFunctions);\n };\n\n /**\n * Returns the OpenAPI schema definition for this API, allowing clients to understand the available endpoints and models.\n * @summary Get OpenAPI specification\n */\n const getOpenAPISpec = async (\n options?: RequestInit,\n ): Promise<FetchResponse<GetOpenAPISpec200>> => {\n const res = await fetch(getGetOpenAPISpecUrl(), {\n ...options,\n method: \"GET\",\n });\n\n const body = [204, 205, 304, 412].includes(res.status)\n ? null\n : await res.text();\n const payload: GetOpenAPISpec200 = body ? JSON.parse(body) : {};\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<GetOpenAPISpec200>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getGetOpenAPISpecUrl = () => {\n return baseURL + `/openapi.yaml`;\n };\n\n /**\n * Retrieves build and version information about the storage service. Useful for monitoring and debugging.\n * @summary Get service version information\n */\n const getVersion = async (\n options?: RequestInit,\n ): Promise<FetchResponse<VersionInformation>> => {\n const res = await fetch(getGetVersionUrl(), {\n ...options,\n method: \"GET\",\n });\n\n const body = [204, 205, 304, 412].includes(res.status)\n ? null\n : await res.text();\n const payload: VersionInformation = body ? JSON.parse(body) : {};\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<VersionInformation>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getGetVersionUrl = () => {\n return baseURL + `/version`;\n };\n\n /**\n * Upload one or more files to a specified bucket. Supports batch uploading with optional custom metadata for each file. If uploading multiple files, either provide metadata for all files or none.\n * @summary Upload files\n */\n const uploadFiles = async (\n uploadFilesBody: UploadFilesBody,\n options?: RequestInit,\n ): Promise<FetchResponse<UploadFiles201>> => {\n const formData = new FormData();\n if (uploadFilesBody[\"bucket-id\"] !== undefined) {\n formData.append(`bucket-id`, uploadFilesBody[\"bucket-id\"]);\n }\n if (uploadFilesBody[\"metadata[]\"] !== undefined) {\n uploadFilesBody[\"metadata[]\"].forEach((value) =>\n formData.append(`metadata[]`, JSON.stringify(value)),\n );\n }\n if (uploadFilesBody[\"file[]\"] !== undefined) {\n uploadFilesBody[\"file[]\"].forEach((value) =>\n formData.append(`file[]`, value),\n );\n }\n\n const res = await fetch(getUploadFilesUrl(), {\n ...options,\n method: \"POST\",\n body: formData,\n });\n\n const body = [204, 205, 304, 412].includes(res.status)\n ? null\n : await res.text();\n const payload: UploadFiles201 = body ? JSON.parse(body) : {};\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<UploadFiles201>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getUploadFilesUrl = () => {\n return baseURL + `/files/`;\n };\n\n /**\n * Retrieve file metadata headers without downloading the file content. Supports conditional requests and provides caching information.\n * @summary Check file information\n */\n const getFileMetadataHeaders = async (\n id: string,\n params?: GetFileMetadataHeadersParams,\n options?: RequestInit,\n ): Promise<FetchResponse<void>> => {\n const res = await fetch(getGetFileMetadataHeadersUrl(id, params), {\n ...options,\n method: \"HEAD\",\n });\n\n const body = [204, 205, 304, 412].includes(res.status)\n ? null\n : await res.text();\n const payload: void = body ? JSON.parse(body) : {};\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<void>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getGetFileMetadataHeadersUrl = (\n id: string,\n params?: GetFileMetadataHeadersParams,\n ) => {\n const normalizedParams = new URLSearchParams();\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (value !== undefined) {\n normalizedParams.append(\n key,\n value === null ? \"null\" : value.toString(),\n );\n }\n });\n\n const stringifiedParams = normalizedParams.toString();\n\n return stringifiedParams.length > 0\n ? baseURL + `/files/${id}?${stringifiedParams}`\n : baseURL + `/files/${id}`;\n };\n\n /**\n * Retrieve and download the complete file content. Supports conditional requests, image transformations, and range requests for partial downloads.\n * @summary Download file\n */\n const getFile = async (\n id: string,\n params?: GetFileParams,\n options?: RequestInit,\n ): Promise<FetchResponse<Blob>> => {\n const res = await fetch(getGetFileUrl(id, params), {\n ...options,\n method: \"GET\",\n });\n\n const payload: Blob = await res.blob();\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<Blob>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getGetFileUrl = (id: string, params?: GetFileParams) => {\n const normalizedParams = new URLSearchParams();\n\n Object.entries(params || {}).forEach(([key, value]) => {\n if (value !== undefined) {\n normalizedParams.append(\n key,\n value === null ? \"null\" : value.toString(),\n );\n }\n });\n\n const stringifiedParams = normalizedParams.toString();\n\n return stringifiedParams.length > 0\n ? baseURL + `/files/${id}?${stringifiedParams}`\n : baseURL + `/files/${id}`;\n };\n\n /**\n * Replace an existing file with new content while preserving the file ID. The operation follows these steps:\n1. The isUploaded flag is set to false to mark the file as being updated\n2. The file content is replaced in the storage backend\n3. File metadata is updated (size, mime-type, isUploaded, etc.)\n\nEach step is atomic, but if a step fails, previous steps will not be automatically rolled back.\n\n * @summary Replace file\n */\n const replaceFile = async (\n id: string,\n replaceFileBody: ReplaceFileBody,\n options?: RequestInit,\n ): Promise<FetchResponse<FileMetadata>> => {\n const formData = new FormData();\n if (replaceFileBody.metadata !== undefined) {\n formData.append(`metadata`, JSON.stringify(replaceFileBody.metadata));\n }\n if (replaceFileBody.file !== undefined) {\n formData.append(`file`, replaceFileBody.file);\n }\n\n const res = await fetch(getReplaceFileUrl(id), {\n ...options,\n method: \"PUT\",\n body: formData,\n });\n\n const body = [204, 205, 304, 412].includes(res.status)\n ? null\n : await res.text();\n const payload: FileMetadata = body ? JSON.parse(body) : {};\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<FileMetadata>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getReplaceFileUrl = (id: string) => {\n return baseURL + `/files/${id}`;\n };\n\n /**\n * Permanently delete a file from storage. This removes both the file content and its associated metadata.\n * @summary Delete file\n */\n const deleteFile = async (\n id: string,\n options?: RequestInit,\n ): Promise<FetchResponse<void>> => {\n const res = await fetch(getDeleteFileUrl(id), {\n ...options,\n method: \"DELETE\",\n });\n\n const body = [204, 205, 304, 412].includes(res.status)\n ? null\n : await res.text();\n const payload: void = body ? JSON.parse(body) : {};\n\n const response = {\n body: payload,\n status: res.status,\n headers: Object.fromEntries(Array.from((res.headers as any).entries())),\n } as FetchResponse<void>;\n\n if (!res.ok) {\n throw response;\n }\n\n return response;\n };\n\n const getDeleteFileUrl = (id: string) => {\n return baseURL + `/files/${id}`;\n };\n\n return {\n getOpenAPISpec,\n getVersion,\n uploadFiles,\n getFileMetadataHeaders,\n getFile,\n replaceFile,\n deleteFile,\n pushChain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B;AAMM,QAAA,aAAa,OACjB,IACA,YACiC;AACjC,UAAM,MAAM,MAAM,MAAM,iBAAiB,EAAE,GAAG;AAAA,MAC5C,GAAG;AAAA,MACH,QAAQ;AAAA,IAAA,CACT;AAED,UAAM,OAAO,CAAC,KAAK,KAAK,KAAK,GAAG,EAAE,SAAS,IAAI,MAAM,IACjD,OACA,MAAM,IAAI,KAAK;AACnB,UAAM,UAAgB,OAAO,KAAK,MAAM,IAAI,IAAI,CAAC;AAEjD,UAAM,WAAW;AAAA,MACf,MAAM;AAAA,MACN,QAAQ,IAAI;AAAA,MACZ,SAAS,OAAO,YAAY,MAAM,KAAM,IAAI,QAAgB,SAAS,CAAC;AAAA,IACxE;AAEI,QAAA,CAAC,IAAI,IAAI;AACL,YAAA;AAAA,IAAA;AAGD,WAAA;AAAA,EACT;AAEM,QAAA,mBAAmB,CAAC,OAAe;AAChC,WAAA,UAAU,UAAU,EAAE;AAAA,EAC/B;AAEO,SAAA;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./nhost-js/auth.cjs.js"),t=require("./nhost-js/storage.cjs.js"),s=require("./nhost-js/graphql.cjs.js"),r="nhostSession";class o{storageKey;constructor(e=r){this.storageKey=e}get(){try{const e=window.localStorage.getItem(this.storageKey);return e?JSON.parse(e):null}catch{return this.remove(),null}}set(e){window.localStorage.setItem(this.storageKey,JSON.stringify(e))}remove(){window.localStorage.removeItem(this.storageKey)}}class n{session=null;get(){return this.session}set(e){this.session=e}remove(){this.session=null}}const i=()=>{if("undefined"!=typeof window&&"undefined"!=typeof localStorage)try{return localStorage.setItem("__test","__test"),localStorage.removeItem("__test"),new o}catch{console.warn("localStorage is not available, using in-memory storage instead")}return new n},a=e=>{try{const t=e.split(".");if(3!==t.length)return console.warn("Token does not have three parts"),0;const s=t[1];if(!s)return console.warn("Payload part is empty"),0;const r=function(e){try{let t;if("undefined"!=typeof window)t=decodeURIComponent(window.atob(e).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join(""));else{t=Buffer.from(e,"base64").toString("utf8")}return JSON.parse(t)}catch(t){throw console.warn("Error decoding token payload:",t),t}}(s.replace(/-/g,"+").replace(/_/g,"/"));return r.exp?1e3*r.exp:(console.warn("No exp claim found in token"),0)}catch(t){return console.warn("Failed to extract token expiration:",t),0}};const c=(e,t,s)=>{const{marginSeconds:r=60}=s||{};let o=null,n=0;return s=>async(i,c={})=>{if(function(e,t,s){const r=new Headers(t.headers||{});if(r.has("Authorization"))return!0;if(e===`${s}/token`)return!0;return!1}(i,c,e.baseURL))return s(i,c);try{if(o=t.get(),o?.accessToken&&(n=a(o.accessToken)),!o)return s(i,c);if(function(e,t){const s=Date.now();return e-s<1e3*t}(n,r)&&o.refreshToken){const s=await async function(e,t,s){try{const r=await e.refreshToken({refreshToken:s});if(200===r.status){const e=r.body;return t.set(e),e}return null}catch(r){return console.error("Error refreshing token:",r),null}}(e,t,o.refreshToken);s&&(o=s,n=a(s.accessToken),t.set(s))}return s(i,c)}catch(u){return console.error("Error in token refresh chain:",u),s(i,c)}}};const u=e=>t=>async(s,r={})=>{const o=new Headers(r.headers||{});if(o.has("Authorization"))return t(s,r);const n=e.get();if(n?.accessToken){const e={...r,headers:h(o,n)};return t(s,e)}return t(s,r)};function h(e,t){return t.accessToken&&e.set("Authorization",`Bearer ${t.accessToken}`),e}const l=e=>t=>async(s,r)=>{const o=await t(s,r);try{if(s.endsWith("/signout"))return e.remove(),o;if(s.endsWith("/token")||s.includes("/signin/")||s.includes("/signup/")){const t=o.clone(),s=await t.json().catch((()=>null));if(s){const t=function(e){return e?.session||e?.data?.session||e?.accessToken&&e?.refreshToken&&e||null}(s);t&&t.accessToken&&t.refreshToken&&e.set(t)}}}catch(n){console.warn("Error in session response middleware:",n)}return o},g=(e,t,s,r)=>r||(t&&s?`https://${t}.${e}.${s}.nhost.run/v1`:t?`https://${t}.${e}.nhost.run/v1`:`https://local.${e}.local.nhost.run/v1`);class f{auth;storage;graphql;sessionStorage;constructor(e,t,s,r){this.auth=e,this.storage=t,this.graphql=s,this.sessionStorage=r}getUserSession(){return this.sessionStorage.get()}async refreshSession(e=60){try{return await this._refreshSession(e)}catch(t){try{return console.warn("error refreshing session, retrying:",t),await this._refreshSession(e)}catch(s){const e=s;return 401===e?.status&&(console.error("session probably expired"),this.sessionStorage.remove()),null}}}async _refreshSession(e=60){const t=this.sessionStorage.get();if(!t)return null;const s=a(t?.accessToken||""),r=Date.now(),o=s<r;if(s-r>1e3*e)return t;try{const e=await this.auth.refreshToken({refreshToken:t.refreshToken});return this.sessionStorage.set(e.body),e.body}catch(n){if(!o)return t;throw n}}async clearSession(){this.sessionStorage.remove()}}exports.CookieStorage=class{cookieName;expirationDays;secure;sameSite;constructor(e=r,t=30,s=!0,o="lax"){this.cookieName=e,this.expirationDays=t,this.secure=s,this.sameSite=o}get(){const e=document.cookie.split(";");for(const t of e){const[e,s]=t.trim().split("=");if(e===this.cookieName)try{return JSON.parse(decodeURIComponent(s||""))}catch{return this.remove(),null}}return null}set(e){const t=new Date;t.setTime(t.getTime()+24*this.expirationDays*60*60*1e3);const s=encodeURIComponent(JSON.stringify(e)),r=`${this.cookieName}=${s}; expires=${t.toUTCString()}; path=/; ${this.secure?"secure; ":""}SameSite=${this.sameSite}`;document.cookie=r}remove(){document.cookie=`${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; ${this.secure?"secure; ":""}SameSite=${this.sameSite}`}},exports.DEFAULT_SESSION_KEY=r,exports.LocalStorage=o,exports.MemoryStorage=n,exports.NhostClient=f,exports.createAttachAccessTokenMiddleware=u,exports.createClient=function(r={}){const{subdomain:o,region:n,authUrl:a,storageUrl:h,graphqlUrl:p,storage:d=i(),disableAutoRefreshToken:S=!1}=r,m=g("auth",o,n,a),y=g("storage",o,n,h),w=g("graphql",o,n,p),k=e.createAPIClient(m),T=function(e,t,s){const r=[l(t),u(t)];return s&&r.unshift(c(e,t)),r}(k,d,!S);for(const e of T)k.pushChainFunction(e);const x=t.createAPIClient(y,T),v=s.createAPIClient(w,T);return new f(k,x,v,d)},exports.createSessionRefreshMiddleware=c,exports.createSessionResponseMiddleware=l,exports.generateServiceUrl=g;
2
+ //# sourceMappingURL=nhost-js.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nhost-js.cjs.js","sources":["../src/sessionStorage.ts","../src/middlewareRefreshSession.ts","../src/middlewareAttachToken.ts","../src/middlewareResponseSession.ts","../src/index.ts"],"sourcesContent":["/**\n * @fileoverview Storage implementations for session persistence in different environments.\n *\n * This module provides different storage adapters for persisting authentication sessions\n * across page reloads and browser sessions.\n */\n\nimport { type Session } from \"./auth\";\n\n/**\n * Session storage interface for session persistence.\n * This interface can be implemented to provide custom storage solutions.\n */\nexport interface SessionStorageInterface {\n /**\n * Get the current session from storage\n * @returns The stored session or null if not found\n */\n get(): Session | null;\n\n /**\n * Set the session in storage\n * @param value - The session to store\n */\n set(value: Session): void;\n\n /**\n * Remove the session from storage\n */\n remove(): void;\n}\n\n/**\n * Default storage key used for storing the Nhost session\n */\nexport const DEFAULT_SESSION_KEY = \"nhostSession\";\n\n/**\n * Browser localStorage implementation of StorageInterface.\n * Persists the session across page reloads and browser restarts.\n */\nexport class LocalStorage implements SessionStorageInterface {\n private readonly storageKey: string;\n\n /**\n * Creates a new LocalStorage instance\n * @param storageKey - The key to use in localStorage (defaults to \"nhostSession\")\n */\n constructor(storageKey = DEFAULT_SESSION_KEY) {\n this.storageKey = storageKey;\n }\n\n /**\n * Gets the session from localStorage\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n try {\n const value = window.localStorage.getItem(this.storageKey);\n return value ? (JSON.parse(value) as Session) : null;\n } catch {\n this.remove();\n return null;\n }\n }\n\n /**\n * Sets the session in localStorage\n * @param value - The session to store\n */\n set(value: Session): void {\n window.localStorage.setItem(this.storageKey, JSON.stringify(value));\n }\n\n /**\n * Removes the session from localStorage\n */\n remove(): void {\n window.localStorage.removeItem(this.storageKey);\n }\n}\n\n/**\n * In-memory storage implementation for non-browser environments or when\n * persistent storage is not available or desirable.\n */\nexport class MemoryStorage implements SessionStorageInterface {\n private session: Session | null = null;\n\n /**\n * Gets the session from memory\n * @returns The stored session or null if not set\n */\n get(): Session | null {\n return this.session;\n }\n\n /**\n * Sets the session in memory\n * @param value - The session to store\n */\n set(value: Session): void {\n this.session = value;\n }\n\n /**\n * Clears the session from memory\n */\n remove(): void {\n this.session = null;\n }\n}\n\n/**\n * Cookie-based storage implementation.\n * This storage uses web browser cookies to store the session so it's not\n * available in server-side environments. It is useful though for sinchronizing\n * sessions between client and server environments.\n */\nexport class CookieStorage implements SessionStorageInterface {\n private readonly cookieName: string;\n private readonly expirationDays: number;\n private readonly secure: boolean;\n private readonly sameSite: \"strict\" | \"lax\" | \"none\";\n\n /**\n * Creates a new CookieStorage instance\n * @param cookieName - Name of the cookie to use (defaults to \"nhostSession\")\n * @param expirationDays - Number of days until the cookie expires (defaults to 30)\n * @param secure - Whether to set the Secure flag on the cookie (defaults to true)\n * @param sameSite - SameSite policy for the cookie (defaults to \"lax\")\n */\n constructor(\n cookieName = DEFAULT_SESSION_KEY,\n expirationDays = 30,\n secure = true,\n sameSite: \"strict\" | \"lax\" | \"none\" = \"lax\",\n ) {\n this.cookieName = cookieName;\n this.expirationDays = expirationDays;\n this.secure = secure;\n this.sameSite = sameSite;\n }\n\n /**\n * Gets the session from cookies\n * @returns The stored session or null if not found\n */\n get(): Session | null {\n const cookies = document.cookie.split(\";\");\n for (const cookie of cookies) {\n const [name, value] = cookie.trim().split(\"=\");\n if (name === this.cookieName) {\n try {\n return JSON.parse(decodeURIComponent(value || \"\")) as Session;\n } catch {\n this.remove();\n return null;\n }\n }\n }\n return null;\n }\n\n /**\n * Sets the session in a cookie\n * @param value - The session to store\n */\n set(value: Session): void {\n const expires = new Date();\n expires.setTime(\n expires.getTime() + this.expirationDays * 24 * 60 * 60 * 1000,\n );\n\n const cookieValue = encodeURIComponent(JSON.stringify(value));\n const cookieString = `${this.cookieName}=${cookieValue}; expires=${expires.toUTCString()}; path=/; ${this.secure ? \"secure; \" : \"\"}SameSite=${this.sameSite}`;\n\n document.cookie = cookieString;\n }\n\n /**\n * Removes the session cookie\n */\n remove(): void {\n document.cookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; ${this.secure ? \"secure; \" : \"\"}SameSite=${this.sameSite}`;\n }\n}\n\n/**\n * Detects the best available storage implementation for the current environment.\n *\n * The detection process follows this order:\n * 1. Try to use localStorage if we're in a browser environment\n * 2. Fall back to in-memory storage if localStorage isn't available\n *\n * @returns The best available storage implementation for the current environment\n */\nexport const detectStorage = (): SessionStorageInterface => {\n if (typeof window !== \"undefined\" && typeof localStorage !== \"undefined\") {\n try {\n // Test if localStorage is actually available (could be disabled)\n localStorage.setItem(\"__test\", \"__test\");\n localStorage.removeItem(\"__test\");\n return new LocalStorage();\n } catch {\n console.warn(\n `localStorage is not available, using in-memory storage instead`,\n );\n }\n }\n return new MemoryStorage();\n};\n","/**\n * @fileoverview Auth token refresh middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically refresh\n * authentication tokens before they expire, ensuring seamless API access\n * without requiring manual token refresh by the application.\n */\n\nimport type { Client, Session } from \"./auth\";\nimport { type SessionStorageInterface } from \"./sessionStorage\";\nimport { type ChainFunction, type FetchFunction } from \"./fetch\";\n\n/**\n * Extracts the expiration time from a JWT token\n * @param token - JWT token string\n * @returns Expiration timestamp in milliseconds, or 0 if unable to extract\n */\nexport const extractTokenExpiration = (token: string): number => {\n try {\n // JWT tokens are in the format header.payload.signature\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n console.warn(\"Token does not have three parts\");\n return 0;\n }\n\n // At this point, we know parts has exactly 3 elements\n // Use a non-null assertion or check explicitly\n const payloadPart = parts[1];\n if (!payloadPart) {\n console.warn(\"Payload part is empty\");\n return 0;\n }\n\n // Decode the payload (middle part)\n const base64 = payloadPart.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const payload = decodeTokenPayload(base64);\n\n if (payload.exp) {\n // exp claim is in seconds, convert to milliseconds\n return payload.exp * 1000;\n } else {\n console.warn(\"No exp claim found in token\");\n return 0;\n }\n } catch (error) {\n console.warn(\"Failed to extract token expiration:\", error);\n return 0;\n }\n};\n\n/**\n * Decodes a base64-encoded JWT payload\n * @param base64Payload - Base64-encoded payload\n * @returns Decoded payload as an object\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction decodeTokenPayload(base64Payload: string): any {\n try {\n let jsonPayload: string;\n\n if (typeof window !== \"undefined\") {\n // Browser environment\n jsonPayload = decodeURIComponent(\n window\n .atob(base64Payload)\n .split(\"\")\n .map((c) => \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2))\n .join(\"\"),\n );\n } else {\n // Node.js environment\n const buffer = Buffer.from(base64Payload, \"base64\");\n jsonPayload = buffer.toString(\"utf8\");\n }\n\n return JSON.parse(jsonPayload);\n } catch (e) {\n console.warn(\"Error decoding token payload:\", e);\n throw e;\n }\n}\n\n/**\n * Configuration options for the session refresh middleware\n */\nexport type SessionRefreshOptions = {\n /**\n * Number of seconds before token expiration when a refresh should be triggered.\n * Default is 60 seconds (1 minute).\n */\n marginSeconds?: number;\n};\n\n/**\n * Creates a fetch middleware that automatically refreshes authentication tokens.\n *\n * This middleware:\n * 1. Checks if the current token is about to expire\n * 2. If so, uses the refresh token to obtain a new access token\n *\n * The middleware handles token refresh transparently, so the application\n * doesn't need to manually refresh tokens.\n *\n * @param authClient - Auth API client for token refresh operations\n * @param storage - Storage implementation for persisting session data\n * @param options - Configuration options for token refresh behavior\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const createSessionRefreshMiddleware = (\n authClient: Client,\n storage: SessionStorageInterface,\n options?: SessionRefreshOptions,\n): ChainFunction => {\n const { marginSeconds = 60 } = options || {};\n\n // Session state\n let currentSession: Session | null = null;\n let tokenExpiresAt = 0;\n\n // Create and return the chain function\n return (next: FetchFunction): FetchFunction => {\n return async (\n url: string,\n options: RequestInit = {},\n ): Promise<Response> => {\n // Skip token handling for certain requests\n if (shouldSkipTokenHandling(url, options, authClient.baseURL)) {\n return next(url, options);\n }\n\n try {\n // Get current session from storage\n currentSession = storage.get();\n\n if (currentSession?.accessToken) {\n tokenExpiresAt = extractTokenExpiration(currentSession.accessToken);\n }\n\n // If we don't have a session, proceed without authorization\n if (!currentSession) {\n return next(url, options);\n }\n\n // Check if token needs refresh\n if (isTokenExpiringSoon(tokenExpiresAt, marginSeconds)) {\n if (currentSession.refreshToken) {\n // Refresh the token\n const refreshedSession = await refreshToken(\n authClient,\n storage,\n currentSession.refreshToken,\n );\n\n if (refreshedSession) {\n currentSession = refreshedSession;\n tokenExpiresAt = extractTokenExpiration(\n refreshedSession.accessToken,\n );\n storage.set(refreshedSession);\n }\n }\n }\n\n // Continue with the fetch chain\n return next(url, options);\n } catch (error) {\n console.error(\"Error in token refresh chain:\", error);\n // Continue with the request even if token refresh fails\n return next(url, options);\n }\n };\n };\n};\n\n/**\n * Performs the actual token refresh operation using the auth client\n *\n * @param authClient - Auth API client to use for token refresh\n * @param storage - Storage implementation for persisting the new session\n * @param refreshToken - Current refresh token to use\n * @returns A new session if refresh was successful, null otherwise\n */\nasync function refreshToken(\n authClient: Client,\n storage: SessionStorageInterface,\n refreshToken: string,\n): Promise<Session | null> {\n try {\n const refreshResponse = await authClient.refreshToken({ refreshToken });\n\n if (refreshResponse.status === 200) {\n const session = refreshResponse.body;\n storage.set(session);\n return session;\n }\n return null;\n } catch (error) {\n console.error(\"Error refreshing token:\", error);\n return null;\n }\n}\n\n/**\n * Determines if token handling should be skipped for this request\n *\n * @param url - Request URL\n * @param options - Request options\n * @param authApiUrl - Base URL for auth API\n * @returns True if token handling should be skipped, false otherwise\n */\nfunction shouldSkipTokenHandling(\n url: string,\n options: RequestInit,\n authApiUrl: string,\n): boolean {\n const headers = new Headers(options.headers || {});\n\n // If Authorization header is explicitly set, skip token handling\n if (headers.has(\"Authorization\")) {\n return true;\n }\n\n // If calling the token endpoint, skip to avoid infinite loops\n if (url === `${authApiUrl}/token`) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Checks if a token is expiring soon and needs to be refreshed\n *\n * @param expiresAt - Token expiration timestamp in milliseconds\n * @param marginSeconds - Number of seconds before expiration to trigger refresh\n * @returns True if token is expiring soon, false otherwise\n */\nfunction isTokenExpiringSoon(\n expiresAt: number,\n marginSeconds: number,\n): boolean {\n const currentTime = Date.now();\n return expiresAt - currentTime < marginSeconds * 1000;\n}\n","/**\n * @fileoverview Authorization token attachment middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * authorization tokens to outgoing API requests, ensuring the client\n * is properly authenticated.\n */\n\nimport type { Session } from \"./auth\";\nimport { type SessionStorageInterface } from \"./sessionStorage\";\nimport { type ChainFunction, type FetchFunction } from \"./fetch\";\n\n/**\n * Creates a fetch middleware that adds the Authorization header with the current access token.\n *\n * This middleware:\n * 1. Gets the current session from storage\n * 2. Adds the authorization header with the access token to outgoing requests\n *\n * This middleware should be used after the refresh middleware in the chain to\n * ensure the most recent token is used.\n *\n * @param storage - Storage implementation for retrieving session data\n * @returns A middleware function that adds Authorization headers\n */\nexport const createAttachAccessTokenMiddleware = (\n storage: SessionStorageInterface,\n): ChainFunction => {\n return (next: FetchFunction): FetchFunction => {\n return async (\n url: string,\n options: RequestInit = {},\n ): Promise<Response> => {\n const headers = new Headers(options.headers || {});\n\n // Skip if Authorization header is already set\n if (headers.has(\"Authorization\")) {\n return next(url, options);\n }\n\n // Get current session from storage\n const session = storage.get();\n\n if (session?.accessToken) {\n // Add authorization header\n const newOptions = {\n ...options,\n headers: addAuthorizationHeader(headers, session),\n };\n\n // Continue with the fetch chain\n return next(url, newOptions);\n }\n\n // No session or no access token, continue without authorization\n return next(url, options);\n };\n };\n};\n\n/**\n * Adds the Authorization header with the access token to the request headers\n *\n * @param headers - Original request headers\n * @param session - Current session containing the access token\n * @returns Modified headers with Authorization header\n */\nfunction addAuthorizationHeader(headers: Headers, session: Session): Headers {\n if (session.accessToken) {\n headers.set(\"Authorization\", `Bearer ${session.accessToken}`);\n }\n return headers;\n}\n","/**\n * @fileoverview Session response middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically extract\n * and persist session information from authentication responses, ensuring\n * that new sessions are properly stored after sign-in operations.\n */\n\nimport { type Session } from \"./auth\";\nimport { type SessionStorageInterface } from \"./sessionStorage\";\nimport { type ChainFunction } from \"./fetch\";\n\n/**\n * Creates a fetch middleware that automatically extracts and stores session data from API responses.\n *\n * This middleware:\n * 1. Monitors responses from authentication-related endpoints\n * 2. Extracts session information when present\n * 3. Stores the session in the provided storage implementation\n * 4. Handles session removal on sign-out\n *\n * This ensures that session data is always up-to-date in storage after operations\n * that create or invalidate sessions.\n *\n * @param storage - Storage implementation for persisting session data\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const createSessionResponseMiddleware = (\n storage: SessionStorageInterface,\n): ChainFunction => {\n /**\n * Helper function to extract session data from various response formats\n *\n * @param data - Response data to extract session from\n * @returns Session object if found, null otherwise\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const sessionExtractor = function (body: any): Session | null {\n // Look for session in common response patterns\n const session =\n // Pattern: { session: {...} }\n (body?.session as Session) ||\n // Pattern: { data: { session: {...} } }\n (body?.data?.session as Session) ||\n // Pattern: { accessToken, refreshToken, ... } where data itself is the session\n (body?.accessToken && body?.refreshToken && (body as Session)) ||\n null;\n\n return session;\n };\n\n return (next: (url: string, options?: RequestInit) => Promise<Response>) => {\n return async (url: string, options?: RequestInit) => {\n // Call the next middleware in the chain\n const response = await next(url, options);\n\n try {\n // Check if this is a logout request\n if (url.endsWith(\"/signout\")) {\n // Remove session on sign-out\n storage.remove();\n return response;\n }\n\n // Check if this is an auth-related endpoint that might return session data\n if (\n url.endsWith(\"/token\") ||\n url.includes(\"/signin/\") ||\n url.includes(\"/signup/\")\n ) {\n // Clone the response to avoid consuming it\n const clonedResponse = response.clone();\n\n // Parse the JSON data\n const body = await clonedResponse.json().catch(() => null);\n\n if (body) {\n // Extract session data from response using provided extractor\n const session = sessionExtractor(body);\n\n // If session data is found, store it\n if (session && session.accessToken && session.refreshToken) {\n storage.set(session);\n }\n }\n }\n } catch (error) {\n console.warn(\"Error in session response middleware:\", error);\n }\n\n // Return the original response\n return response;\n };\n };\n};\n","/**\n * Main entry point for the Nhost JavaScript SDK.\n *\n * This package provides a unified client for interacting with Nhost services:\n * - Authentication\n * - Storage\n * - GraphQL\n * - Functions\n *\n * @example\n * You can import and use this package with:\n *\n * ```ts\n * import { createClient } from \"@nhost/nhost-js\";\n * ```\n *\n * and use it like:\n *\n * {@includeCode ./__tests__/docstrings.test.ts#mainExample}\n *\n * ## Error handling\n *\n * The SDK will throw errors on most operations if the request returns a non-2xx status code or\n * if the request fails entirely (i.e., due to network errors). A continuation you can see\n * how you can handle errors thrown by the SDK.\n *\n * ### Auth\n *\n * {@includeCode ./__tests__/docstrings-auth.test.ts#errorHandling}\n *\n * ### Storage\n *\n * {@includeCode ./__tests__/docstrings-storage.test.ts#errorHandling}\n *\n * ### GraphQL\n *\n * {@includeCode ./__tests__/docstrings-graphql.test.ts#errorHandling}\n *\n * @packageDocumentation\n */\n\nimport {\n createAPIClient as createAuthClient,\n type Session,\n type FetchResponse,\n type ErrorResponse,\n} from \"./auth\";\nimport { createAPIClient as createStorageClient } from \"./storage\";\nimport { createAPIClient as createGraphQLClient } from \"./graphql\";\nimport { type SessionStorageInterface, detectStorage } from \"./sessionStorage\";\nimport {\n extractTokenExpiration,\n createSessionRefreshMiddleware,\n} from \"./middlewareRefreshSession\";\nimport { createAttachAccessTokenMiddleware } from \"./middlewareAttachToken\";\nimport { createSessionResponseMiddleware } from \"./middlewareResponseSession\";\n\nexport {\n type SessionStorageInterface,\n DEFAULT_SESSION_KEY,\n LocalStorage,\n MemoryStorage,\n CookieStorage,\n} from \"./sessionStorage\";\n\nexport {\n type SessionRefreshOptions,\n createSessionRefreshMiddleware,\n} from \"./middlewareRefreshSession\";\nexport { createAttachAccessTokenMiddleware } from \"./middlewareAttachToken\";\nexport { createSessionResponseMiddleware } from \"./middlewareResponseSession\";\n\n/**\n * Generates a base URL for a Nhost service based on configuration\n *\n * @param serviceType - Type of service (auth, storage, graphql, functions)\n * @param subdomain - Nhost project subdomain\n * @param region - Nhost region\n * @param customUrl - Custom URL override if provided\n * @returns The base URL for the service\n *\n * @internal\n */\nexport const generateServiceUrl = (\n serviceType: \"auth\" | \"storage\" | \"graphql\" | \"functions\",\n subdomain?: string,\n region?: string,\n customUrl?: string,\n): string => {\n if (customUrl) {\n return customUrl;\n } else if (subdomain && region) {\n return `https://${subdomain}.${serviceType}.${region}.nhost.run/v1`;\n } else if (subdomain) {\n return `https://${subdomain}.${serviceType}.nhost.run/v1`;\n } else {\n return `https://local.${serviceType}.local.nhost.run/v1`;\n }\n};\n\n/**\n * Configuration options for creating an Nhost client\n */\nexport interface NhostClientOptions {\n /**\n * Nhost project subdomain (e.g., 'abcdefgh'). Used to construct the base URL for services for the Nhost cloud.\n */\n subdomain?: string;\n\n /**\n * Nhost region (e.g., 'eu-central-1'). Used to construct the base URL for services for the Nhost cloud.\n */\n region?: string;\n\n /**\n * Complete base URL for the auth service (overrides subdomain/region)\n */\n authUrl?: string;\n\n /**\n * Complete base URL for the storage service (overrides subdomain/region)\n */\n storageUrl?: string;\n\n /**\n * Complete base URL for the GraphQL service (overrides subdomain/region)\n */\n graphqlUrl?: string;\n\n /**\n * Storage implementation to use for session persistence. If not provided, the SDK will\n * default to localStorage in the browser or memory in other environments.\n */\n storage?: SessionStorageInterface;\n\n /**\n * Disable automatic session refresh. If set to true, the SDK will not attempt to refresh\n */\n disableAutoRefreshToken?: boolean;\n}\n\n/**\n * Main client class that provides access to all Nhost services\n */\nexport class NhostClient {\n /**\n * Authentication client providing methods for user sign-in, sign-up, and session management\n */\n auth: ReturnType<typeof createAuthClient>;\n\n /**\n * Storage client providing methods for file operations (upload, download, delete)\n */\n storage: ReturnType<typeof createStorageClient>;\n\n /**\n * GraphQL client providing methods for executing GraphQL operations against your Hasura backend\n */\n graphql: ReturnType<typeof createGraphQLClient>;\n\n /**\n * Storage implementation used for persisting session information\n */\n sessionStorage: SessionStorageInterface;\n\n /**\n * Create a new Nhost client. This constructor is reserved for advanced use cases.\n * For typical usage, use [createClient](#createclient) instead.\n *\n * @param auth - Authentication client\n * @param storage - Storage client\n * @param graphql - GraphQL client\n * @param sessionStorage - Storage implementation for session persistence\n */\n constructor(\n auth: ReturnType<typeof createAuthClient>,\n storage: ReturnType<typeof createStorageClient>,\n graphql: ReturnType<typeof createGraphQLClient>,\n sessionStorage: SessionStorageInterface,\n ) {\n this.auth = auth;\n this.storage = storage;\n this.graphql = graphql;\n this.sessionStorage = sessionStorage;\n }\n\n /**\n * Get the current session from storage\n *\n * @returns The current session or null if no session exists\n *\n * @example\n * ```ts\n * const session = nhost.getUserSession();\n * if (session) {\n * console.log('User is authenticated:', session.user.id);\n * } else {\n * console.log('No active session');\n * }\n * ```\n */\n getUserSession(): Session | null {\n return this.sessionStorage.get();\n }\n\n /**\n * Refresh the session using the current refresh token\n * in the storage and update the storage with the new session.\n * @param marginSeconds - The number of seconds before the token expiration to refresh the session. If the token is still valid for this duration, it will not be refreshed. Set to 0 to force the refresh.\n *\n * @returns The new session or null if there is currently no session or if refresh fails\n */\n async refreshSession(marginSeconds: number = 60): Promise<Session | null> {\n try {\n return await this._refreshSession(marginSeconds);\n } catch (error) {\n try {\n // we retry the refresh token in case of transient error\n // or race conditions\n console.warn(\"error refreshing session, retrying:\", error);\n return await this._refreshSession(marginSeconds);\n } catch (error) {\n const errResponse = error as FetchResponse<ErrorResponse>;\n if (errResponse?.status === 401) {\n // this probably means the refresh token is invalid\n console.error(\"session probably expired\");\n this.sessionStorage.remove();\n }\n return null;\n }\n }\n }\n\n private async _refreshSession(\n marginSeconds: number = 60,\n ): Promise<Session | null> {\n const session = this.sessionStorage.get();\n if (!session) {\n return null;\n }\n\n const tokenExpiresAt = extractTokenExpiration(session?.accessToken || \"\");\n const currentTime = Date.now();\n const sessionExpired = tokenExpiresAt < currentTime;\n if (tokenExpiresAt - currentTime > marginSeconds * 1000) {\n return session; // No need to refresh\n }\n\n try {\n const response = await this.auth.refreshToken({\n refreshToken: session.refreshToken,\n });\n this.sessionStorage.set(response.body);\n\n return response.body;\n } catch (error) {\n if (!sessionExpired) {\n // If the session is not expired, we can still use the current session\n // so there is no need to error for now\n return session;\n }\n\n // we throw the error so the caller can handle it\n throw error;\n }\n }\n\n /**\n * Clear the session from storage\n */\n async clearSession(): Promise<void> {\n this.sessionStorage.remove();\n }\n}\n\nfunction getMiddlewareChain(\n auth: ReturnType<typeof createAuthClient>,\n storage: SessionStorageInterface,\n autoRefresh: boolean,\n) {\n const mwChain = [\n createSessionResponseMiddleware(storage),\n createAttachAccessTokenMiddleware(storage),\n ];\n if (autoRefresh) {\n // we need to process this one first to make sure any following middlewares\n // run after the session has been refreshed\n mwChain.unshift(createSessionRefreshMiddleware(auth, storage));\n }\n return mwChain;\n}\n\n/**\n * Creates and configures a new Nhost client instance.\n *\n * This helper method instantiates a fully configured Nhost client by:\n * - Instantiating the various service clients (auth, storage, functions and graphql)\n * - Configuring a session storage if none is provided\n * - Setting up the necessary middleware for automatic session management:\n * - Automatically attaching the authorization token to requests\n * - Refreshing the session when it expires\n *\n * @param options - Configuration options for the client\n * @returns A configured Nhost client\n */\nexport function createClient(options: NhostClientOptions = {}): NhostClient {\n const {\n subdomain,\n region,\n authUrl,\n storageUrl,\n graphqlUrl,\n storage = detectStorage(),\n disableAutoRefreshToken = false,\n } = options;\n\n // Determine base URLs for each service\n const authBaseUrl = generateServiceUrl(\"auth\", subdomain, region, authUrl);\n const storageBaseUrl = generateServiceUrl(\n \"storage\",\n subdomain,\n region,\n storageUrl,\n );\n const graphqlBaseUrl = generateServiceUrl(\n \"graphql\",\n subdomain,\n region,\n graphqlUrl,\n );\n\n // Create auth client\n const auth = createAuthClient(authBaseUrl);\n\n const mwChain = getMiddlewareChain(auth, storage, !disableAutoRefreshToken);\n\n for (const mw of mwChain) {\n auth.pushChainFunction(mw);\n }\n\n // Create storage and graphql clients with the refresh and attach token middlewares\n const storageClient = createStorageClient(storageBaseUrl, mwChain);\n const graphqlClient = createGraphQLClient(graphqlBaseUrl, mwChain);\n\n // Return an initialized NhostClient\n return new NhostClient(auth, storageClient, graphqlClient, storage);\n}\n"],"names":["DEFAULT_SESSION_KEY","LocalStorage","storageKey","constructor","this","get","value","window","localStorage","getItem","JSON","parse","remove","set","setItem","stringify","removeItem","MemoryStorage","session","detectStorage","console","warn","extractTokenExpiration","token","parts","split","length","payloadPart","payload","base64Payload","jsonPayload","decodeURIComponent","atob","map","c","charCodeAt","toString","slice","join","Buffer","from","e","decodeTokenPayload","replace","exp","error","createSessionRefreshMiddleware","authClient","storage","options","marginSeconds","currentSession","tokenExpiresAt","next","async","url","authApiUrl","headers","Headers","has","shouldSkipTokenHandling","baseURL","accessToken","expiresAt","currentTime","Date","now","isTokenExpiringSoon","refreshToken","refreshedSession","refreshResponse","status","body","createAttachAccessTokenMiddleware","newOptions","addAuthorizationHeader","createSessionResponseMiddleware","response","endsWith","includes","clonedResponse","clone","json","catch","data","sessionExtractor","generateServiceUrl","serviceType","subdomain","region","customUrl","NhostClient","auth","graphql","sessionStorage","getUserSession","refreshSession","_refreshSession","errResponse","sessionExpired","clearSession","cookieName","expirationDays","secure","sameSite","cookies","document","cookie","name","trim","expires","setTime","getTime","cookieValue","encodeURIComponent","cookieString","toUTCString","authUrl","storageUrl","graphqlUrl","disableAutoRefreshToken","authBaseUrl","storageBaseUrl","graphqlBaseUrl","createAuthClient","mwChain","autoRefresh","unshift","getMiddlewareChain","mw","pushChainFunction","storageClient","createStorageClient","graphqlClient","createGraphQLClient"],"mapp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