@nhost/nhost-js 4.2.1 → 4.2.2

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 (63) hide show
  1. package/dist/{fetch-2PHmQBIJ.mjs → fetch-2PHmQBIJ.js} +1 -1
  2. package/dist/{fetch-DWXwEnoe.js.map → fetch-2PHmQBIJ.js.map} +1 -1
  3. package/dist/{fetch-DWXwEnoe.js → fetch-DWXwEnoe.cjs} +1 -1
  4. package/dist/{fetch-2PHmQBIJ.mjs.map → fetch-DWXwEnoe.cjs.map} +1 -1
  5. package/dist/middlewareWithAdminSession-DDApoLkL.cjs +2 -0
  6. package/dist/{middlewareWithAdminSession-w7fkl0J9.mjs.map → middlewareWithAdminSession-DDApoLkL.cjs.map} +1 -1
  7. package/dist/{middlewareWithAdminSession-w7fkl0J9.mjs → middlewareWithAdminSession-DLqDQUbW.js} +2 -2
  8. package/dist/{middlewareWithAdminSession-BtFo6WUj.js.map → middlewareWithAdminSession-DLqDQUbW.js.map} +1 -1
  9. package/dist/nhost-js/auth.cjs +2 -0
  10. package/dist/nhost-js/auth.cjs.map +1 -0
  11. package/dist/nhost-js/{auth.es.js → auth.js} +2 -2
  12. package/dist/nhost-js/auth.js.map +1 -0
  13. package/dist/nhost-js/fetch.cjs +2 -0
  14. package/dist/nhost-js/fetch.cjs.map +1 -0
  15. package/dist/nhost-js/{fetch.es.js → fetch.js} +3 -3
  16. package/dist/nhost-js/fetch.js.map +1 -0
  17. package/dist/nhost-js/functions.cjs +2 -0
  18. package/dist/nhost-js/functions.cjs.map +1 -0
  19. package/dist/nhost-js/{functions.es.js → functions.js} +2 -2
  20. package/dist/nhost-js/functions.js.map +1 -0
  21. package/dist/nhost-js/graphql.cjs +2 -0
  22. package/dist/nhost-js/graphql.cjs.map +1 -0
  23. package/dist/nhost-js/{graphql.es.js → graphql.js} +2 -2
  24. package/dist/nhost-js/graphql.js.map +1 -0
  25. package/dist/nhost-js/session.cjs +2 -0
  26. package/dist/nhost-js/session.cjs.map +1 -0
  27. package/dist/nhost-js/{session.es.js → session.js} +2 -2
  28. package/dist/nhost-js/session.js.map +1 -0
  29. package/dist/nhost-js/storage.cjs +2 -0
  30. package/dist/nhost-js/storage.cjs.map +1 -0
  31. package/dist/nhost-js/{storage.es.js → storage.js} +2 -2
  32. package/dist/nhost-js/storage.js.map +1 -0
  33. package/dist/nhost-js.cjs +2 -0
  34. package/dist/nhost-js.cjs.map +1 -0
  35. package/dist/{nhost-js.es.js → nhost-js.js} +8 -8
  36. package/dist/nhost-js.js.map +1 -0
  37. package/dist/{refreshSession-Bw715ZmX.js → refreshSession-Bw715ZmX.cjs} +1 -1
  38. package/dist/{refreshSession-CG8GIEun.mjs.map → refreshSession-Bw715ZmX.cjs.map} +1 -1
  39. package/dist/{refreshSession-CG8GIEun.mjs → refreshSession-CG8GIEun.js} +1 -1
  40. package/dist/{refreshSession-Bw715ZmX.js.map → refreshSession-CG8GIEun.js.map} +1 -1
  41. package/package.json +18 -17
  42. package/dist/middlewareWithAdminSession-BtFo6WUj.js +0 -2
  43. package/dist/nhost-js/auth.cjs.js +0 -2
  44. package/dist/nhost-js/auth.cjs.js.map +0 -1
  45. package/dist/nhost-js/auth.es.js.map +0 -1
  46. package/dist/nhost-js/fetch.cjs.js +0 -2
  47. package/dist/nhost-js/fetch.cjs.js.map +0 -1
  48. package/dist/nhost-js/fetch.es.js.map +0 -1
  49. package/dist/nhost-js/functions.cjs.js +0 -2
  50. package/dist/nhost-js/functions.cjs.js.map +0 -1
  51. package/dist/nhost-js/functions.es.js.map +0 -1
  52. package/dist/nhost-js/graphql.cjs.js +0 -2
  53. package/dist/nhost-js/graphql.cjs.js.map +0 -1
  54. package/dist/nhost-js/graphql.es.js.map +0 -1
  55. package/dist/nhost-js/session.cjs.js +0 -2
  56. package/dist/nhost-js/session.cjs.js.map +0 -1
  57. package/dist/nhost-js/session.es.js.map +0 -1
  58. package/dist/nhost-js/storage.cjs.js +0 -2
  59. package/dist/nhost-js/storage.cjs.js.map +0 -1
  60. package/dist/nhost-js/storage.es.js.map +0 -1
  61. package/dist/nhost-js.cjs.js +0 -2
  62. package/dist/nhost-js.cjs.js.map +0 -1
  63. package/dist/nhost-js.es.js.map +0 -1
@@ -58,4 +58,4 @@ export {
58
58
  FetchError as F,
59
59
  createEnhancedFetch as c
60
60
  };
61
- //# sourceMappingURL=fetch-2PHmQBIJ.mjs.map
61
+ //# sourceMappingURL=fetch-2PHmQBIJ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-DWXwEnoe.js","sources":["../src/fetch/fetch.ts"],"sourcesContent":["/**\n * Type definition for a fetch-like function.\n * Takes the same parameters as fetch and returns the same type.\n * This allows middleware to intercept and modify requests and responses.\n */\nexport type FetchFunction = (\n url: string,\n options?: RequestInit,\n) => Promise<Response>;\n\n/**\n * Type definition for a chain function (middleware).\n * Takes a fetch-like function and returns another fetch-like function.\n *\n * Chain functions can be used to implement:\n * - Authentication token handling\n * - Error handling and retry logic\n * - Request and response transformations\n * - Logging and metrics\n */\nexport type ChainFunction = (next: FetchFunction) => FetchFunction;\n\n/**\n * Creates an enhanced fetch function using a chain of middleware functions.\n *\n * The fetch chain executes in the order of the array, with each middleware\n * wrapping the next one in the chain. This allows each middleware to\n * intercept both the request (before calling next) and the response\n * (after calling next).\n *\n * @example\n * ```typescript\n * // Simple logging middleware\n * const loggingMiddleware: ChainFunction = (next) => {\n * return async (url, options) => {\n * console.log(`Request to ${url}`);\n * const response = await next(url, options);\n * console.log(`Response from ${url}: ${response.status}`);\n * return response;\n * };\n * };\n *\n * const enhancedFetch = createEnhancedFetch([loggingMiddleware]);\n * const response = await enhancedFetch('https://api.example.com/data');\n * ```\n *\n * @param chainFunctions - Array of chain functions to apply in order\n * @returns Enhanced fetch function with all middleware applied\n */\nexport function createEnhancedFetch(\n chainFunctions: ChainFunction[] = [],\n): FetchFunction {\n // Build the chain starting with vanilla fetch, but apply functions in reverse\n // to achieve the desired execution order\n return chainFunctions.reduceRight(\n (nextInChain, chainFunction) => chainFunction(nextInChain),\n fetch as FetchFunction,\n );\n}\n\n/**\n * Interface representing a structured API response.\n *\n * This interface provides a consistent structure for responses across the SDK,\n * offering access to the parsed response body along with status and headers.\n *\n * @template T - The type of the response body\n */\nexport interface FetchResponse<T> {\n /** The parsed response body */\n body: T;\n /** HTTP status code of the response */\n status: number;\n /** Response headers */\n headers: Headers;\n}\n\nfunction extractMessage(body: unknown): string {\n if (body && typeof body === \"string\") {\n return body;\n }\n\n if (body && typeof body === \"object\") {\n const typedBody = body as Record<string, unknown>;\n\n if (\"message\" in typedBody && typeof typedBody[\"message\"] === \"string\") {\n return typedBody[\"message\"];\n }\n\n if (\"error\" in typedBody && typeof typedBody[\"error\"] === \"string\") {\n return typedBody[\"error\"];\n }\n\n if (\n \"error\" in typedBody &&\n typedBody[\"error\"] &&\n typeof typedBody[\"error\"] === \"object\"\n ) {\n const error = typedBody[\"error\"] as Record<string, unknown>;\n if (\"message\" in error && typeof error[\"message\"] === \"string\") {\n return error[\"message\"];\n }\n }\n\n if (\"errors\" in typedBody && Array.isArray(typedBody[\"errors\"])) {\n const messages = (typedBody[\"errors\"] as unknown[])\n .filter(\n (error): error is { message: string } =>\n typeof error === \"object\" &&\n error !== null &&\n \"message\" in error &&\n typeof (error as { message: unknown })[\"message\"] === \"string\",\n )\n .map((error) => error[\"message\"]);\n\n if (messages.length > 0) {\n return messages.join(\", \");\n }\n }\n }\n\n return \"An unexpected error occurred\";\n}\n\n/**\n * Error class for representing fetch operation failures.\n *\n * This class extends the standard Error to include additional\n * information about failed requests, including the response body,\n * status code, and headers. The error message is automatically\n * extracted from common error response formats.\n *\n * @template T - The type of the response body\n */\nexport class FetchError<T = unknown> extends Error {\n /** The original response body */\n body: T;\n /** HTTP status code of the failed response */\n status: number;\n /** Response headers */\n headers: Headers;\n\n /**\n * Creates a new FetchError instance\n *\n * @param body - The response body from the failed request\n * @param status - The HTTP status code\n * @param headers - The response headers\n */\n constructor(body: T, status: number, headers: Headers) {\n super(extractMessage(body));\n this.body = body;\n this.status = status;\n this.headers = headers;\n }\n}\n"],"names":["FetchError","Error","body","status","headers","constructor","super","typedBody","error","Array","isArray","messages","filter","map","length","join","extractMessage","this","chainFunctions","reduceRight","nextInChain","chainFunction","fetch"],"mappings":"aAsIO,MAAMA,UAAgCC,MAE3CC,KAEAC,OAEAC,QASA,WAAAC,CAAYH,EAASC,EAAgBC,GACnCE,MAzEJ,SAAwBJ,GACtB,GAAIA,GAAwB,iBAATA,EACjB,OAAOA,EAGT,GAAIA,GAAwB,iBAATA,EAAmB,CACpC,MAAMK,EAAYL,EAElB,GAAI,YAAaK,GAA6C,iBAAzBA,EAAmB,QACtD,OAAOA,EAAmB,QAG5B,GAAI,UAAWA,GAA2C,iBAAvBA,EAAiB,MAClD,OAAOA,EAAiB,MAG1B,GACE,UAAWA,GACXA,EAAiB,OACa,iBAAvBA,EAAiB,MACxB,CACA,MAAMC,EAAQD,EAAiB,MAC/B,GAAI,YAAaC,GAAqC,iBAArBA,EAAe,QAC9C,OAAOA,EAAe,OAE1B,CAEA,GAAI,WAAYD,GAAaE,MAAMC,QAAQH,EAAkB,QAAI,CAC/D,MAAMI,EAAYJ,EAAkB,OACjCK,QACEJ,GACkB,iBAAVA,GACG,OAAVA,GACA,YAAaA,GACyC,iBAA9CA,EAAwC,UAEnDK,KAAKL,GAAUA,EAAe,UAEjC,GAAIG,EAASG,OAAS,EACpB,OAAOH,EAASI,KAAK,KAEzB,CACF,CAEA,MAAO,8BACT,CA4BUC,CAAed,IACrBe,KAAKf,KAAOA,EACZe,KAAKd,OAASA,EACdc,KAAKb,QAAUA,CACjB,mDAzGK,SACLc,EAAkC,IAIlC,OAAOA,EAAeC,aACpB,CAACC,EAAaC,IAAkBA,EAAcD,IAC9CE,MAEJ"}
1
+ {"version":3,"file":"fetch-2PHmQBIJ.js","sources":["../src/fetch/fetch.ts"],"sourcesContent":["/**\n * Type definition for a fetch-like function.\n * Takes the same parameters as fetch and returns the same type.\n * This allows middleware to intercept and modify requests and responses.\n */\nexport type FetchFunction = (\n url: string,\n options?: RequestInit,\n) => Promise<Response>;\n\n/**\n * Type definition for a chain function (middleware).\n * Takes a fetch-like function and returns another fetch-like function.\n *\n * Chain functions can be used to implement:\n * - Authentication token handling\n * - Error handling and retry logic\n * - Request and response transformations\n * - Logging and metrics\n */\nexport type ChainFunction = (next: FetchFunction) => FetchFunction;\n\n/**\n * Creates an enhanced fetch function using a chain of middleware functions.\n *\n * The fetch chain executes in the order of the array, with each middleware\n * wrapping the next one in the chain. This allows each middleware to\n * intercept both the request (before calling next) and the response\n * (after calling next).\n *\n * @example\n * ```typescript\n * // Simple logging middleware\n * const loggingMiddleware: ChainFunction = (next) => {\n * return async (url, options) => {\n * console.log(`Request to ${url}`);\n * const response = await next(url, options);\n * console.log(`Response from ${url}: ${response.status}`);\n * return response;\n * };\n * };\n *\n * const enhancedFetch = createEnhancedFetch([loggingMiddleware]);\n * const response = await enhancedFetch('https://api.example.com/data');\n * ```\n *\n * @param chainFunctions - Array of chain functions to apply in order\n * @returns Enhanced fetch function with all middleware applied\n */\nexport function createEnhancedFetch(\n chainFunctions: ChainFunction[] = [],\n): FetchFunction {\n // Build the chain starting with vanilla fetch, but apply functions in reverse\n // to achieve the desired execution order\n return chainFunctions.reduceRight(\n (nextInChain, chainFunction) => chainFunction(nextInChain),\n fetch as FetchFunction,\n );\n}\n\n/**\n * Interface representing a structured API response.\n *\n * This interface provides a consistent structure for responses across the SDK,\n * offering access to the parsed response body along with status and headers.\n *\n * @template T - The type of the response body\n */\nexport interface FetchResponse<T> {\n /** The parsed response body */\n body: T;\n /** HTTP status code of the response */\n status: number;\n /** Response headers */\n headers: Headers;\n}\n\nfunction extractMessage(body: unknown): string {\n if (body && typeof body === \"string\") {\n return body;\n }\n\n if (body && typeof body === \"object\") {\n const typedBody = body as Record<string, unknown>;\n\n if (\"message\" in typedBody && typeof typedBody[\"message\"] === \"string\") {\n return typedBody[\"message\"];\n }\n\n if (\"error\" in typedBody && typeof typedBody[\"error\"] === \"string\") {\n return typedBody[\"error\"];\n }\n\n if (\n \"error\" in typedBody &&\n typedBody[\"error\"] &&\n typeof typedBody[\"error\"] === \"object\"\n ) {\n const error = typedBody[\"error\"] as Record<string, unknown>;\n if (\"message\" in error && typeof error[\"message\"] === \"string\") {\n return error[\"message\"];\n }\n }\n\n if (\"errors\" in typedBody && Array.isArray(typedBody[\"errors\"])) {\n const messages = (typedBody[\"errors\"] as unknown[])\n .filter(\n (error): error is { message: string } =>\n typeof error === \"object\" &&\n error !== null &&\n \"message\" in error &&\n typeof (error as { message: unknown })[\"message\"] === \"string\",\n )\n .map((error) => error[\"message\"]);\n\n if (messages.length > 0) {\n return messages.join(\", \");\n }\n }\n }\n\n return \"An unexpected error occurred\";\n}\n\n/**\n * Error class for representing fetch operation failures.\n *\n * This class extends the standard Error to include additional\n * information about failed requests, including the response body,\n * status code, and headers. The error message is automatically\n * extracted from common error response formats.\n *\n * @template T - The type of the response body\n */\nexport class FetchError<T = unknown> extends Error {\n /** The original response body */\n body: T;\n /** HTTP status code of the failed response */\n status: number;\n /** Response headers */\n headers: Headers;\n\n /**\n * Creates a new FetchError instance\n *\n * @param body - The response body from the failed request\n * @param status - The HTTP status code\n * @param headers - The response headers\n */\n constructor(body: T, status: number, headers: Headers) {\n super(extractMessage(body));\n this.body = body;\n this.status = status;\n this.headers = headers;\n }\n}\n"],"names":[],"mappings":"AAiDO,SAAS,oBACd,iBAAkC,IACnB;AAGf,SAAO,eAAe;AAAA,IACpB,CAAC,aAAa,kBAAkB,cAAc,WAAW;AAAA,IACzD;AAAA,EAAA;AAEJ;AAmBA,SAAS,eAAe,MAAuB;AAC7C,MAAI,QAAQ,OAAO,SAAS,UAAU;AACpC,WAAO;AAAA,EACT;AAEA,MAAI,QAAQ,OAAO,SAAS,UAAU;AACpC,UAAM,YAAY;AAElB,QAAI,aAAa,aAAa,OAAO,UAAU,SAAS,MAAM,UAAU;AACtE,aAAO,UAAU,SAAS;AAAA,IAC5B;AAEA,QAAI,WAAW,aAAa,OAAO,UAAU,OAAO,MAAM,UAAU;AAClE,aAAO,UAAU,OAAO;AAAA,IAC1B;AAEA,QACE,WAAW,aACX,UAAU,OAAO,KACjB,OAAO,UAAU,OAAO,MAAM,UAC9B;AACA,YAAM,QAAQ,UAAU,OAAO;AAC/B,UAAI,aAAa,SAAS,OAAO,MAAM,SAAS,MAAM,UAAU;AAC9D,eAAO,MAAM,SAAS;AAAA,MACxB;AAAA,IACF;AAEA,QAAI,YAAY,aAAa,MAAM,QAAQ,UAAU,QAAQ,CAAC,GAAG;AAC/D,YAAM,WAAY,UAAU,QAAQ,EACjC;AAAA,QACC,CAAC,UACC,OAAO,UAAU,YACjB,UAAU,QACV,aAAa,SACb,OAAQ,MAA+B,SAAS,MAAM;AAAA,MAAA,EAEzD,IAAI,CAAC,UAAU,MAAM,SAAS,CAAC;AAElC,UAAI,SAAS,SAAS,GAAG;AACvB,eAAO,SAAS,KAAK,IAAI;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAYO,MAAM,mBAAgC,MAAM;AAAA;AAAA,EAEjD;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,YAAY,MAAS,QAAgB,SAAkB;AACrD,UAAM,eAAe,IAAI,CAAC;AAC1B,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,UAAU;AAAA,EACjB;AACF;"}
@@ -1,2 +1,2 @@
1
1
  "use strict";class r extends Error{body;status;headers;constructor(r,e,t){super(function(r){if(r&&"string"==typeof r)return r;if(r&&"object"==typeof r){const e=r;if("message"in e&&"string"==typeof e.message)return e.message;if("error"in e&&"string"==typeof e.error)return e.error;if("error"in e&&e.error&&"object"==typeof e.error){const r=e.error;if("message"in r&&"string"==typeof r.message)return r.message}if("errors"in e&&Array.isArray(e.errors)){const r=e.errors.filter((r=>"object"==typeof r&&null!==r&&"message"in r&&"string"==typeof r.message)).map((r=>r.message));if(r.length>0)return r.join(", ")}}return"An unexpected error occurred"}(r)),this.body=r,this.status=e,this.headers=t}}exports.FetchError=r,exports.createEnhancedFetch=function(r=[]){return r.reduceRight(((r,e)=>e(r)),fetch)};
2
- //# sourceMappingURL=fetch-DWXwEnoe.js.map
2
+ //# sourceMappingURL=fetch-DWXwEnoe.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-2PHmQBIJ.mjs","sources":["../src/fetch/fetch.ts"],"sourcesContent":["/**\n * Type definition for a fetch-like function.\n * Takes the same parameters as fetch and returns the same type.\n * This allows middleware to intercept and modify requests and responses.\n */\nexport type FetchFunction = (\n url: string,\n options?: RequestInit,\n) => Promise<Response>;\n\n/**\n * Type definition for a chain function (middleware).\n * Takes a fetch-like function and returns another fetch-like function.\n *\n * Chain functions can be used to implement:\n * - Authentication token handling\n * - Error handling and retry logic\n * - Request and response transformations\n * - Logging and metrics\n */\nexport type ChainFunction = (next: FetchFunction) => FetchFunction;\n\n/**\n * Creates an enhanced fetch function using a chain of middleware functions.\n *\n * The fetch chain executes in the order of the array, with each middleware\n * wrapping the next one in the chain. This allows each middleware to\n * intercept both the request (before calling next) and the response\n * (after calling next).\n *\n * @example\n * ```typescript\n * // Simple logging middleware\n * const loggingMiddleware: ChainFunction = (next) => {\n * return async (url, options) => {\n * console.log(`Request to ${url}`);\n * const response = await next(url, options);\n * console.log(`Response from ${url}: ${response.status}`);\n * return response;\n * };\n * };\n *\n * const enhancedFetch = createEnhancedFetch([loggingMiddleware]);\n * const response = await enhancedFetch('https://api.example.com/data');\n * ```\n *\n * @param chainFunctions - Array of chain functions to apply in order\n * @returns Enhanced fetch function with all middleware applied\n */\nexport function createEnhancedFetch(\n chainFunctions: ChainFunction[] = [],\n): FetchFunction {\n // Build the chain starting with vanilla fetch, but apply functions in reverse\n // to achieve the desired execution order\n return chainFunctions.reduceRight(\n (nextInChain, chainFunction) => chainFunction(nextInChain),\n fetch as FetchFunction,\n );\n}\n\n/**\n * Interface representing a structured API response.\n *\n * This interface provides a consistent structure for responses across the SDK,\n * offering access to the parsed response body along with status and headers.\n *\n * @template T - The type of the response body\n */\nexport interface FetchResponse<T> {\n /** The parsed response body */\n body: T;\n /** HTTP status code of the response */\n status: number;\n /** Response headers */\n headers: Headers;\n}\n\nfunction extractMessage(body: unknown): string {\n if (body && typeof body === \"string\") {\n return body;\n }\n\n if (body && typeof body === \"object\") {\n const typedBody = body as Record<string, unknown>;\n\n if (\"message\" in typedBody && typeof typedBody[\"message\"] === \"string\") {\n return typedBody[\"message\"];\n }\n\n if (\"error\" in typedBody && typeof typedBody[\"error\"] === \"string\") {\n return typedBody[\"error\"];\n }\n\n if (\n \"error\" in typedBody &&\n typedBody[\"error\"] &&\n typeof typedBody[\"error\"] === \"object\"\n ) {\n const error = typedBody[\"error\"] as Record<string, unknown>;\n if (\"message\" in error && typeof error[\"message\"] === \"string\") {\n return error[\"message\"];\n }\n }\n\n if (\"errors\" in typedBody && Array.isArray(typedBody[\"errors\"])) {\n const messages = (typedBody[\"errors\"] as unknown[])\n .filter(\n (error): error is { message: string } =>\n typeof error === \"object\" &&\n error !== null &&\n \"message\" in error &&\n typeof (error as { message: unknown })[\"message\"] === \"string\",\n )\n .map((error) => error[\"message\"]);\n\n if (messages.length > 0) {\n return messages.join(\", \");\n }\n }\n }\n\n return \"An unexpected error occurred\";\n}\n\n/**\n * Error class for representing fetch operation failures.\n *\n * This class extends the standard Error to include additional\n * information about failed requests, including the response body,\n * status code, and headers. The error message is automatically\n * extracted from common error response formats.\n *\n * @template T - The type of the response body\n */\nexport class FetchError<T = unknown> extends Error {\n /** The original response body */\n body: T;\n /** HTTP status code of the failed response */\n status: number;\n /** Response headers */\n headers: Headers;\n\n /**\n * Creates a new FetchError instance\n *\n * @param body - The response body from the failed request\n * @param status - The HTTP status code\n * @param headers - The response headers\n */\n constructor(body: T, status: number, headers: Headers) {\n super(extractMessage(body));\n this.body = body;\n this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AAe,IAAI,CAAC;AAC1B,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,UAAU;AAAA,EACjB;AACF;"}
1
+ {"version":3,"file":"fetch-DWXwEnoe.cjs","sources":["../src/fetch/fetch.ts"],"sourcesContent":["/**\n * Type definition for a fetch-like function.\n * Takes the same parameters as fetch and returns the same type.\n * This allows middleware to intercept and modify requests and responses.\n */\nexport type FetchFunction = (\n url: string,\n options?: RequestInit,\n) => Promise<Response>;\n\n/**\n * Type definition for a chain function (middleware).\n * Takes a fetch-like function and returns another fetch-like function.\n *\n * Chain functions can be used to implement:\n * - Authentication token handling\n * - Error handling and retry logic\n * - Request and response transformations\n * - Logging and metrics\n */\nexport type ChainFunction = (next: FetchFunction) => FetchFunction;\n\n/**\n * Creates an enhanced fetch function using a chain of middleware functions.\n *\n * The fetch chain executes in the order of the array, with each middleware\n * wrapping the next one in the chain. This allows each middleware to\n * intercept both the request (before calling next) and the response\n * (after calling next).\n *\n * @example\n * ```typescript\n * // Simple logging middleware\n * const loggingMiddleware: ChainFunction = (next) => {\n * return async (url, options) => {\n * console.log(`Request to ${url}`);\n * const response = await next(url, options);\n * console.log(`Response from ${url}: ${response.status}`);\n * return response;\n * };\n * };\n *\n * const enhancedFetch = createEnhancedFetch([loggingMiddleware]);\n * const response = await enhancedFetch('https://api.example.com/data');\n * ```\n *\n * @param chainFunctions - Array of chain functions to apply in order\n * @returns Enhanced fetch function with all middleware applied\n */\nexport function createEnhancedFetch(\n chainFunctions: ChainFunction[] = [],\n): FetchFunction {\n // Build the chain starting with vanilla fetch, but apply functions in reverse\n // to achieve the desired execution order\n return chainFunctions.reduceRight(\n (nextInChain, chainFunction) => chainFunction(nextInChain),\n fetch as FetchFunction,\n );\n}\n\n/**\n * Interface representing a structured API response.\n *\n * This interface provides a consistent structure for responses across the SDK,\n * offering access to the parsed response body along with status and headers.\n *\n * @template T - The type of the response body\n */\nexport interface FetchResponse<T> {\n /** The parsed response body */\n body: T;\n /** HTTP status code of the response */\n status: number;\n /** Response headers */\n headers: Headers;\n}\n\nfunction extractMessage(body: unknown): string {\n if (body && typeof body === \"string\") {\n return body;\n }\n\n if (body && typeof body === \"object\") {\n const typedBody = body as Record<string, unknown>;\n\n if (\"message\" in typedBody && typeof typedBody[\"message\"] === \"string\") {\n return typedBody[\"message\"];\n }\n\n if (\"error\" in typedBody && typeof typedBody[\"error\"] === \"string\") {\n return typedBody[\"error\"];\n }\n\n if (\n \"error\" in typedBody &&\n typedBody[\"error\"] &&\n typeof typedBody[\"error\"] === \"object\"\n ) {\n const error = typedBody[\"error\"] as Record<string, unknown>;\n if (\"message\" in error && typeof error[\"message\"] === \"string\") {\n return error[\"message\"];\n }\n }\n\n if (\"errors\" in typedBody && Array.isArray(typedBody[\"errors\"])) {\n const messages = (typedBody[\"errors\"] as unknown[])\n .filter(\n (error): error is { message: string } =>\n typeof error === \"object\" &&\n error !== null &&\n \"message\" in error &&\n typeof (error as { message: unknown })[\"message\"] === \"string\",\n )\n .map((error) => error[\"message\"]);\n\n if (messages.length > 0) {\n return messages.join(\", \");\n }\n }\n }\n\n return \"An unexpected error occurred\";\n}\n\n/**\n * Error class for representing fetch operation failures.\n *\n * This class extends the standard Error to include additional\n * information about failed requests, including the response body,\n * status code, and headers. The error message is automatically\n * extracted from common error response formats.\n *\n * @template T - The type of the response body\n */\nexport class FetchError<T = unknown> extends Error {\n /** The original response body */\n body: T;\n /** HTTP status code of the failed response */\n status: number;\n /** Response headers */\n headers: Headers;\n\n /**\n * Creates a new FetchError instance\n *\n * @param body - The response body from the failed request\n * @param status - The HTTP status code\n * @param headers - The response headers\n */\n constructor(body: T, status: number, headers: Headers) {\n super(extractMessage(body));\n this.body = body;\n this.status = status;\n this.headers = headers;\n }\n}\n"],"names":["FetchError","Error","body","status","headers","constructor","super","typedBody","error","Array","isArray","messages","filter","map","length","join","extractMessage","this","chainFunctions","reduceRight","nextInChain","chainFunction","fetch"],"mappings":"aAsIO,MAAMA,UAAgCC,MAE3CC,KAEAC,OAEAC,QASA,WAAAC,CAAYH,EAASC,EAAgBC,GACnCE,MAzEJ,SAAwBJ,GACtB,GAAIA,GAAwB,iBAATA,EACjB,OAAOA,EAGT,GAAIA,GAAwB,iBAATA,EAAmB,CACpC,MAAMK,EAAYL,EAElB,GAAI,YAAaK,GAA6C,iBAAzBA,EAAmB,QACtD,OAAOA,EAAmB,QAG5B,GAAI,UAAWA,GAA2C,iBAAvBA,EAAiB,MAClD,OAAOA,EAAiB,MAG1B,GACE,UAAWA,GACXA,EAAiB,OACa,iBAAvBA,EAAiB,MACxB,CACA,MAAMC,EAAQD,EAAiB,MAC/B,GAAI,YAAaC,GAAqC,iBAArBA,EAAe,QAC9C,OAAOA,EAAe,OAE1B,CAEA,GAAI,WAAYD,GAAaE,MAAMC,QAAQH,EAAkB,QAAI,CAC/D,MAAMI,EAAYJ,EAAkB,OACjCK,QACEJ,GACkB,iBAAVA,GACG,OAAVA,GACA,YAAaA,GACyC,iBAA9CA,EAAwC,UAEnDK,KAAKL,GAAUA,EAAe,UAEjC,GAAIG,EAASG,OAAS,EACpB,OAAOH,EAASI,KAAK,KAEzB,CACF,CAEA,MAAO,8BACT,CA4BUC,CAAed,IACrBe,KAAKf,KAAOA,EACZe,KAAKd,OAASA,EACdc,KAAKb,QAAUA,CACjB,mDAzGK,SACLc,EAAkC,IAIlC,OAAOA,EAAeC,aACpB,CAACC,EAAaC,IAAkBA,EAAcD,IAC9CE,MAEJ"}
@@ -0,0 +1,2 @@
1
+ "use strict";const e=require("./refreshSession-Bw715ZmX.cjs");function s(e,s){return s.accessToken&&e.set("Authorization",`Bearer ${s.accessToken}`),e}exports.attachAccessTokenMiddleware=e=>n=>async(r,t={})=>{const a=new Headers(t.headers||{});if(a.has("Authorization"))return n(r,t);const i=e.get();if(i?.accessToken){const e={...t,headers:s(a,i)};return n(r,e)}return n(r,t)},exports.sessionRefreshMiddleware=(s,n,r)=>{const{marginSeconds:t=60}=r||{};return r=>async(a,i={})=>{if(function(e,s){const n=new Headers(s.headers||{});if(n.has("Authorization"))return!0;if(e.endsWith("/v1/token"))return!0;return!1}(a,i))return r(a,i);try{await e.refreshSession(s,n,t)}catch{}return r(a,i)}},exports.updateSessionFromResponseMiddleware=e=>s=>async(n,r)=>{const t=await s(n,r);try{if(n.endsWith("/signout"))return e.remove(),t;if(n.endsWith("/token")||n.includes("/signin/")||n.includes("/signup/")){const s=t.clone(),n=await s.json().catch((()=>null));if(n){const s=(e=>"string"==typeof e?null:"session"in e?e.session||null:"accessToken"in e&&"refreshToken"in e&&"user"in e?e:null)(n);s?.accessToken&&s.refreshToken&&e.set(s)}}}catch(a){console.warn("Error in session response middleware:",a)}return t},exports.withAdminSessionMiddleware=e=>s=>async(n,r={})=>{const t=new Headers(r.headers||{});if(t.has("x-hasura-admin-secret")||t.set("x-hasura-admin-secret",e.adminSecret),e.role&&!t.has("x-hasura-role")&&t.set("x-hasura-role",e.role),e.sessionVariables)for(const[s,a]of Object.entries(e.sessionVariables)){const e=s.startsWith("x-hasura-")?s:`x-hasura-${s}`;t.has(e)||t.set(e,a)}return s(n,{...r,headers:t})};
2
+ //# sourceMappingURL=middlewareWithAdminSession-DDApoLkL.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"middlewareWithAdminSession-w7fkl0J9.mjs","sources":["../src/fetch/middlewareAttachAccessToken.ts","../src/fetch/middlewareSessionRefresh.ts","../src/fetch/middlewareUpdateSessionFromResponse.ts","../src/fetch/middlewareWithAdminSession.ts"],"sourcesContent":["/**\n * 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 { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction, 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 attachAccessTokenMiddleware =\n (storage: SessionStorage): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): 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 * 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 * 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 } from \"../auth\";\nimport { refreshSession } from \"../session/refreshSession\";\nimport type { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\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 auth - 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 * @param options.marginSeconds - Number of seconds before token expiration to trigger a refresh, default is 60 seconds\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const sessionRefreshMiddleware = (\n auth: Client,\n storage: SessionStorage,\n options?: {\n marginSeconds?: number;\n },\n): ChainFunction => {\n const { marginSeconds = 60 } = options || {};\n\n // Create and return the chain function\n return (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n // Skip token handling for certain requests\n if (shouldSkipTokenHandling(url, options)) {\n return next(url, options);\n }\n\n try {\n await refreshSession(auth, storage, marginSeconds);\n } catch {\n // do nothing, we still want to call the next function\n }\n return next(url, options);\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 * @returns True if token handling should be skipped, false otherwise\n */\nfunction shouldSkipTokenHandling(url: string, options: RequestInit): 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.endsWith(\"/v1/token\")) {\n return true;\n }\n\n return false;\n}\n","/**\n * 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, SessionPayload } from \"../auth\";\nimport type { SessionStorage } from \"../session/storage\";\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 updateSessionFromResponseMiddleware = (\n storage: SessionStorage,\n): ChainFunction => {\n /**\n * Helper function to extract session data from various response formats\n *\n * @param body - Response data to extract session from\n * @returns Session object if found, null otherwise\n */\n const sessionExtractor = (\n body: Session | SessionPayload | string,\n ): Session | null => {\n if (typeof body === \"string\") {\n return null;\n }\n\n if (\"session\" in body) {\n // SessionPayload\n return body.session || null;\n }\n\n if (\"accessToken\" in body && \"refreshToken\" in body && \"user\" in body) {\n // Session\n return body;\n }\n\n return null;\n };\n\n return (next: (url: string, options?: RequestInit) => Promise<Response>) =>\n 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)) as\n | Session\n | SessionPayload;\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?.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 * Admin session middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * Hasura admin secret for admin permissions in requests.\n */\n\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\n\n/**\n * Configuration options for admin session middleware\n */\nexport interface AdminSessionOptions {\n /**\n * Hasura admin secret for elevated permissions (sets x-hasura-admin-secret header)\n */\n adminSecret: string;\n\n /**\n * Hasura role to use for the request (sets x-hasura-role header)\n */\n role?: string;\n\n /**\n * Additional Hasura session variables to attach to requests.\n * Keys will be automatically prefixed with 'x-hasura-' if not already present.\n *\n * @example\n * ```ts\n * {\n * 'user-id': '123',\n * 'org-id': '456'\n * }\n * // Results in headers:\n * // x-hasura-user-id: 123\n * // x-hasura-org-id: 456\n * ```\n */\n sessionVariables?: Record<string, string>;\n}\n\n/**\n * Creates a fetch middleware that attaches the Hasura admin secret and optional session variables to requests.\n *\n * This middleware:\n * 1. Sets the x-hasura-admin-secret header, which grants full admin access to Hasura\n * 2. Optionally sets the x-hasura-role header if a role is provided\n * 3. Optionally sets additional x-hasura-* headers for custom session variables\n *\n * **Security Warning**: Never use this middleware in client-side code or expose\n * the admin secret to end users. Admin secrets grant unrestricted access to your\n * entire database. This should only be used in trusted server-side environments.\n *\n * The middleware preserves request-specific headers when they conflict with the\n * admin session configuration.\n *\n * @param options - Admin session options including admin secret, role, and session variables\n * @returns A middleware function that can be used in the fetch chain\n *\n * @example\n * ```ts\n * // Create middleware with admin secret only\n * const adminMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET\n * });\n *\n * // Create middleware with admin secret and role\n * const adminUserMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET,\n * role: 'user'\n * });\n *\n * // Create middleware with admin secret, role, and custom session variables\n * const fullMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET,\n * role: 'user',\n * sessionVariables: {\n * 'user-id': '123',\n * 'org-id': '456'\n * }\n * });\n *\n * // Use with createCustomClient for an admin client\n * const adminClient = createCustomClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * chainFunctions: [adminMiddleware]\n * });\n * ```\n */\nexport const withAdminSessionMiddleware =\n (options: AdminSessionOptions): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, requestOptions: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(requestOptions.headers || {});\n\n // Set x-hasura-admin-secret if not already present\n if (!headers.has(\"x-hasura-admin-secret\")) {\n headers.set(\"x-hasura-admin-secret\", options.adminSecret);\n }\n\n // Set x-hasura-role if provided and not already present\n if (options.role && !headers.has(\"x-hasura-role\")) {\n headers.set(\"x-hasura-role\", options.role);\n }\n\n // Set custom session variables\n if (options.sessionVariables) {\n for (const [key, value] of Object.entries(options.sessionVariables)) {\n // Ensure the key has the x-hasura- prefix\n const headerKey = key.startsWith(\"x-hasura-\") ? key : `x-hasura-${key}`;\n\n // Only set if not already present in the request\n if (!headers.has(headerKey)) {\n headers.set(headerKey, value);\n }\n }\n }\n\n return next(url, { ...requestOptions, headers });\n };\n"],"names":["options"],"mappings":";AAyBO,MAAM,8BACX,CAAC,YACD,CAAC,SACD,OAAO,KAAa,UAAuB,OAA0B;AACnE,QAAM,UAAU,IAAI,QAAQ,QAAQ,WAAW,CAAA,CAAE;AAGjD,MAAI,QAAQ,IAAI,eAAe,GAAG;AAChC,WAAO,KAAK,KAAK,OAAO;AAAA,EAC1B;AAGA,QAAM,UAAU,QAAQ,IAAA;AAExB,MAAI,SAAS,aAAa;AAExB,UAAM,aAAa;AAAA,MACjB,GAAG;AAAA,MACH,SAAS,uBAAuB,SAAS,OAAO;AAAA,IAAA;AAIlD,WAAO,KAAK,KAAK,UAAU;AAAA,EAC7B;AAGA,SAAO,KAAK,KAAK,OAAO;AAC1B;AASF,SAAS,uBAAuB,SAAkB,SAA2B;AAC3E,MAAI,QAAQ,aAAa;AACvB,YAAQ,IAAI,iBAAiB,UAAU,QAAQ,WAAW,EAAE;AAAA,EAC9D;AACA,SAAO;AACT;ACrCO,MAAM,2BAA2B,CACtC,MACA,SACA,YAGkB;AAClB,QAAM,EAAE,gBAAgB,GAAA,IAAO,WAAW,CAAA;AAG1C,SAAO,CAAC,SACN,OAAO,KAAaA,WAAuB,CAAA,MAA0B;AAEnE,QAAI,wBAAwB,KAAKA,QAAO,GAAG;AACzC,aAAO,KAAK,KAAKA,QAAO;AAAA,IAC1B;AAEA,QAAI;AACF,YAAM,eAAe,MAAM,SAAS,aAAa;AAAA,IACnD,QAAQ;AAAA,IAER;AACA,WAAO,KAAK,KAAKA,QAAO;AAAA,EAC1B;AACJ;AASA,SAAS,wBAAwB,KAAa,SAA+B;AAC3E,QAAM,UAAU,IAAI,QAAQ,QAAQ,WAAW,CAAA,CAAE;AAGjD,MAAI,QAAQ,IAAI,eAAe,GAAG;AAChC,WAAO;AAAA,EACT;AAGA,MAAI,IAAI,SAAS,WAAW,GAAG;AAC7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,IAAI;AAAA,EAC3C;AAGA,MAAI,QAAQ,kBAAkB;AAC5B,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,gBAAgB,GAAG;AAEnE,YAAM,YAAY,IAAI,WAAW,WAAW,IAAI,MAAM,YAAY,GAAG;AAGrE,UAAI,CAAC,QAAQ,IAAI,SAAS,GAAG;AAC3B,gBAAQ,IAAI,WAAW,KAAK;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AAEA,SAAO,KAAK,KAAK,EAAE,GAAG,gBAAgB,SAAS;AACjD;"}
1
+ {"version":3,"file":"middlewareWithAdminSession-DDApoLkL.cjs","sources":["../src/fetch/middlewareAttachAccessToken.ts","../src/fetch/middlewareSessionRefresh.ts","../src/fetch/middlewareUpdateSessionFromResponse.ts","../src/fetch/middlewareWithAdminSession.ts"],"sourcesContent":["/**\n * 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 { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction, 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 attachAccessTokenMiddleware =\n (storage: SessionStorage): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): 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 * 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 * 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 } from \"../auth\";\nimport { refreshSession } from \"../session/refreshSession\";\nimport type { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\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 auth - 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 * @param options.marginSeconds - Number of seconds before token expiration to trigger a refresh, default is 60 seconds\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const sessionRefreshMiddleware = (\n auth: Client,\n storage: SessionStorage,\n options?: {\n marginSeconds?: number;\n },\n): ChainFunction => {\n const { marginSeconds = 60 } = options || {};\n\n // Create and return the chain function\n return (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n // Skip token handling for certain requests\n if (shouldSkipTokenHandling(url, options)) {\n return next(url, options);\n }\n\n try {\n await refreshSession(auth, storage, marginSeconds);\n } catch {\n // do nothing, we still want to call the next function\n }\n return next(url, options);\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 * @returns True if token handling should be skipped, false otherwise\n */\nfunction shouldSkipTokenHandling(url: string, options: RequestInit): 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.endsWith(\"/v1/token\")) {\n return true;\n }\n\n return false;\n}\n","/**\n * 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, SessionPayload } from \"../auth\";\nimport type { SessionStorage } from \"../session/storage\";\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 updateSessionFromResponseMiddleware = (\n storage: SessionStorage,\n): ChainFunction => {\n /**\n * Helper function to extract session data from various response formats\n *\n * @param body - Response data to extract session from\n * @returns Session object if found, null otherwise\n */\n const sessionExtractor = (\n body: Session | SessionPayload | string,\n ): Session | null => {\n if (typeof body === \"string\") {\n return null;\n }\n\n if (\"session\" in body) {\n // SessionPayload\n return body.session || null;\n }\n\n if (\"accessToken\" in body && \"refreshToken\" in body && \"user\" in body) {\n // Session\n return body;\n }\n\n return null;\n };\n\n return (next: (url: string, options?: RequestInit) => Promise<Response>) =>\n 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)) as\n | Session\n | SessionPayload;\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?.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 * Admin session middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * Hasura admin secret for admin permissions in requests.\n */\n\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\n\n/**\n * Configuration options for admin session middleware\n */\nexport interface AdminSessionOptions {\n /**\n * Hasura admin secret for elevated permissions (sets x-hasura-admin-secret header)\n */\n adminSecret: string;\n\n /**\n * Hasura role to use for the request (sets x-hasura-role header)\n */\n role?: string;\n\n /**\n * Additional Hasura session variables to attach to requests.\n * Keys will be automatically prefixed with 'x-hasura-' if not already present.\n *\n * @example\n * ```ts\n * {\n * 'user-id': '123',\n * 'org-id': '456'\n * }\n * // Results in headers:\n * // x-hasura-user-id: 123\n * // x-hasura-org-id: 456\n * ```\n */\n sessionVariables?: Record<string, string>;\n}\n\n/**\n * Creates a fetch middleware that attaches the Hasura admin secret and optional session variables to requests.\n *\n * This middleware:\n * 1. Sets the x-hasura-admin-secret header, which grants full admin access to Hasura\n * 2. Optionally sets the x-hasura-role header if a role is provided\n * 3. Optionally sets additional x-hasura-* headers for custom session variables\n *\n * **Security Warning**: Never use this middleware in client-side code or expose\n * the admin secret to end users. Admin secrets grant unrestricted access to your\n * entire database. This should only be used in trusted server-side environments.\n *\n * The middleware preserves request-specific headers when they conflict with the\n * admin session configuration.\n *\n * @param options - Admin session options including admin secret, role, and session variables\n * @returns A middleware function that can be used in the fetch chain\n *\n * @example\n * ```ts\n * // Create middleware with admin secret only\n * const adminMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET\n * });\n *\n * // Create middleware with admin secret and role\n * const adminUserMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET,\n * role: 'user'\n * });\n *\n * // Create middleware with admin secret, role, and custom session variables\n * const fullMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET,\n * role: 'user',\n * sessionVariables: {\n * 'user-id': '123',\n * 'org-id': '456'\n * }\n * });\n *\n * // Use with createCustomClient for an admin client\n * const adminClient = createCustomClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * chainFunctions: [adminMiddleware]\n * });\n * ```\n */\nexport const withAdminSessionMiddleware =\n (options: AdminSessionOptions): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, requestOptions: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(requestOptions.headers || {});\n\n // Set x-hasura-admin-secret if not already present\n if (!headers.has(\"x-hasura-admin-secret\")) {\n headers.set(\"x-hasura-admin-secret\", options.adminSecret);\n }\n\n // Set x-hasura-role if provided and not already present\n if (options.role && !headers.has(\"x-hasura-role\")) {\n headers.set(\"x-hasura-role\", options.role);\n }\n\n // Set custom session variables\n if (options.sessionVariables) {\n for (const [key, value] of Object.entries(options.sessionVariables)) {\n // Ensure the key has the x-hasura- prefix\n const headerKey = key.startsWith(\"x-hasura-\") ? key : `x-hasura-${key}`;\n\n // Only set if not already present in the request\n if (!headers.has(headerKey)) {\n headers.set(headerKey, value);\n }\n }\n }\n\n return next(url, { ...requestOptions, headers });\n };\n"],"names":["addAuthorizationHeader","headers","session","accessToken","set","storage","next","async","url","options","Headers","has","get","newOptions","auth","marginSeconds","endsWith","shouldSkipTokenHandling","refreshSession","response","remove","includes","clonedResponse","clone","body","json","catch","sessionExtractor","refreshToken","error","console","warn","requestOptions","adminSecret","role","sessionVariables","key","value","Object","entries","headerKey","startsWith"],"mappings":"8DA6DA,SAASA,EAAuBC,EAAkBC,GAIhD,OAHIA,EAAQC,aACVF,EAAQG,IAAI,gBAAiB,UAAUF,E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AgCiBG,CAAiBH,GAG7BtB,GAASC,aAAeD,EAAQ0B,cAClCvB,EAAQD,IAAIF,EAEhB,CACF,CACF,OAAS2B,GACPC,QAAQC,KAAK,wCAAyCF,EACxD,CAGA,OAAOV,CAAA,qCCPVV,GACAH,GACDC,MAAOC,EAAawB,EAA8B,MAChD,MAAM/B,EAAU,IAAIS,QAAQsB,EAAe/B,SAAW,CAAA,GAatD,GAVKA,EAAQU,IAAI,0BACfV,EAAQG,IAAI,wBAAyBK,EAAQwB,aAI3CxB,EAAQyB,OAASjC,EAAQU,IAAI,kBAC/BV,EAAQG,IAAI,gBAAiBK,EAAQyB,MAInCzB,EAAQ0B,iBACV,IAAA,MAAYC,EAAKC,KAAUC,OAAOC,QAAQ9B,EAAQ0B,kBAAmB,CAEnE,MAAMK,EAAYJ,EAAIK,WAAW,aAAeL,EAAM,YAAYA,IAG7DnC,EAAQU,IAAI6B,IACfvC,EAAQG,IAAIoC,EAAWH,EAE3B,CAGF,OAAO/B,EAAKE,EAAK,IAAKwB,EAAgB/B,WAAS"}
@@ -1,4 +1,4 @@
1
- import { r as refreshSession } from "./refreshSession-CG8GIEun.mjs";
1
+ import { r as refreshSession } from "./refreshSession-CG8GIEun.js";
2
2
  const attachAccessTokenMiddleware = (storage) => (next) => async (url, options = {}) => {
3
3
  const headers = new Headers(options.headers || {});
4
4
  if (headers.has("Authorization")) {
@@ -103,4 +103,4 @@ export {
103
103
  updateSessionFromResponseMiddleware as u,
104
104
  withAdminSessionMiddleware as w
105
105
  };
106
- //# sourceMappingURL=middlewareWithAdminSession-w7fkl0J9.mjs.map
106
+ //# sourceMappingURL=middlewareWithAdminSession-DLqDQUbW.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"middlewareWithAdminSession-BtFo6WUj.js","sources":["../src/fetch/middlewareAttachAccessToken.ts","../src/fetch/middlewareSessionRefresh.ts","../src/fetch/middlewareUpdateSessionFromResponse.ts","../src/fetch/middlewareWithAdminSession.ts"],"sourcesContent":["/**\n * 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 { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction, 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 attachAccessTokenMiddleware =\n (storage: SessionStorage): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): 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 * 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 * 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 } from \"../auth\";\nimport { refreshSession } from \"../session/refreshSession\";\nimport type { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\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 auth - 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 * @param options.marginSeconds - Number of seconds before token expiration to trigger a refresh, default is 60 seconds\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const sessionRefreshMiddleware = (\n auth: Client,\n storage: SessionStorage,\n options?: {\n marginSeconds?: number;\n },\n): ChainFunction => {\n const { marginSeconds = 60 } = options || {};\n\n // Create and return the chain function\n return (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n // Skip token handling for certain requests\n if (shouldSkipTokenHandling(url, options)) {\n return next(url, options);\n }\n\n try {\n await refreshSession(auth, storage, marginSeconds);\n } catch {\n // do nothing, we still want to call the next function\n }\n return next(url, options);\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 * @returns True if token handling should be skipped, false otherwise\n */\nfunction shouldSkipTokenHandling(url: string, options: RequestInit): 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.endsWith(\"/v1/token\")) {\n return true;\n }\n\n return false;\n}\n","/**\n * 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, SessionPayload } from \"../auth\";\nimport type { SessionStorage } from \"../session/storage\";\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 updateSessionFromResponseMiddleware = (\n storage: SessionStorage,\n): ChainFunction => {\n /**\n * Helper function to extract session data from various response formats\n *\n * @param body - Response data to extract session from\n * @returns Session object if found, null otherwise\n */\n const sessionExtractor = (\n body: Session | SessionPayload | string,\n ): Session | null => {\n if (typeof body === \"string\") {\n return null;\n }\n\n if (\"session\" in body) {\n // SessionPayload\n return body.session || null;\n }\n\n if (\"accessToken\" in body && \"refreshToken\" in body && \"user\" in body) {\n // Session\n return body;\n }\n\n return null;\n };\n\n return (next: (url: string, options?: RequestInit) => Promise<Response>) =>\n 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)) as\n | Session\n | SessionPayload;\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?.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 * Admin session middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * Hasura admin secret for admin permissions in requests.\n */\n\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\n\n/**\n * Configuration options for admin session middleware\n */\nexport interface AdminSessionOptions {\n /**\n * Hasura admin secret for elevated permissions (sets x-hasura-admin-secret header)\n */\n adminSecret: string;\n\n /**\n * Hasura role to use for the request (sets x-hasura-role header)\n */\n role?: string;\n\n /**\n * Additional Hasura session variables to attach to requests.\n * Keys will be automatically prefixed with 'x-hasura-' if not already present.\n *\n * @example\n * ```ts\n * {\n * 'user-id': '123',\n * 'org-id': '456'\n * }\n * // Results in headers:\n * // x-hasura-user-id: 123\n * // x-hasura-org-id: 456\n * ```\n */\n sessionVariables?: Record<string, string>;\n}\n\n/**\n * Creates a fetch middleware that attaches the Hasura admin secret and optional session variables to requests.\n *\n * This middleware:\n * 1. Sets the x-hasura-admin-secret header, which grants full admin access to Hasura\n * 2. Optionally sets the x-hasura-role header if a role is provided\n * 3. Optionally sets additional x-hasura-* headers for custom session variables\n *\n * **Security Warning**: Never use this middleware in client-side code or expose\n * the admin secret to end users. Admin secrets grant unrestricted access to your\n * entire database. This should only be used in trusted server-side environments.\n *\n * The middleware preserves request-specific headers when they conflict with the\n * admin session configuration.\n *\n * @param options - Admin session options including admin secret, role, and session variables\n * @returns A middleware function that can be used in the fetch chain\n *\n * @example\n * ```ts\n * // Create middleware with admin secret only\n * const adminMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET\n * });\n *\n * // Create middleware with admin secret and role\n * const adminUserMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET,\n * role: 'user'\n * });\n *\n * // Create middleware with admin secret, role, and custom session variables\n * const fullMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET,\n * role: 'user',\n * sessionVariables: {\n * 'user-id': '123',\n * 'org-id': '456'\n * }\n * });\n *\n * // Use with createCustomClient for an admin client\n * const adminClient = createCustomClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * chainFunctions: [adminMiddleware]\n * });\n * ```\n */\nexport const withAdminSessionMiddleware =\n (options: AdminSessionOptions): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, requestOptions: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(requestOptions.headers || {});\n\n // Set x-hasura-admin-secret if not already present\n if (!headers.has(\"x-hasura-admin-secret\")) {\n headers.set(\"x-hasura-admin-secret\", options.adminSecret);\n }\n\n // Set x-hasura-role if provided and not already present\n if (options.role && !headers.has(\"x-hasura-role\")) {\n headers.set(\"x-hasura-role\", options.role);\n }\n\n // Set custom session variables\n if (options.sessionVariables) {\n for (const [key, value] of Object.entries(options.sessionVariables)) {\n // Ensure the key has the x-hasura- prefix\n const headerKey = key.startsWith(\"x-hasura-\") ? key : `x-hasura-${key}`;\n\n // Only set if not already present in the request\n if (!headers.has(headerKey)) {\n headers.set(headerKey, value);\n }\n }\n }\n\n return next(url, { ...requestOptions, headers });\n };\n"],"names":["addAuthorizationHeader","headers","session","accessToken","set","storage","next","async","url","options","Headers","has","get","newOptions","auth","marginSeconds","endsWith","shouldSkipTokenHandling","refreshSession","response","remove","includes","clonedResponse","clone","body","json","catch","sessionExtractor","refreshToken","error","console","warn","requestOptions","adminSecret","role","sessionVariables","key","value","Object","entries","headerKey","startsWith"],"mappings":"6DA6DA,SAASA,EAAuBC,EAAkBC,GAIhD,OAHIA,EAAQC,aACVF,EAAQG,IAAI,gBAAiB,UAAUF,EAAQC,eAE1CF,CACT,qCAxCGI,GACAC,GACDC,MAAOC,EAAaC,EAAuB,MACzC,MAAMR,EAAU,IAAIS,QAAQD,EAAQR,SAAW,CAAA,GAG/C,GAAIA,EAAQU,IAAI,iBACd,OAAOL,EAAKE,EAAKC,GAInB,MAAMP,EAAUG,EAAQO,MAExB,GAAIV,GAASC,YAAa,CAExB,MAAMU,EAAa,IACdJ,EACHR,QAASD,EAAuBC,EAASC,IAI3C,OAAOI,EAAKE,EAAKK,EACnB,CAGA,OAAOP,EAAKE,EAAKC,EAAO,mCCtBY,CACtCK,EACAT,EACAI,KAIA,MAAMM,cAAEA,EAAgB,IAAON,GAAW,CAAA,EAG1C,OAAQH,GACNC,MAAOC,EAAaC,EAAuB,CAAA,KAEzC,GAoBN,SAAiCD,EAAaC,GAC5C,MAAMR,EAAU,IAAIS,QAAQD,EAAQR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IAG7DnC,EAAQU,IAAI6B,IACfvC,EAAQG,IAAIoC,EAAWH,EAE3B,CAGF,OAAO/B,EAAKE,EAAK,IAAKwB,EAAgB/B,WAAS"}
1
+ {"version":3,"file":"middlewareWithAdminSession-DLqDQUbW.js","sources":["../src/fetch/middlewareAttachAccessToken.ts","../src/fetch/middlewareSessionRefresh.ts","../src/fetch/middlewareUpdateSessionFromResponse.ts","../src/fetch/middlewareWithAdminSession.ts"],"sourcesContent":["/**\n * 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 { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction, 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 attachAccessTokenMiddleware =\n (storage: SessionStorage): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): 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 * 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 * 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 } from \"../auth\";\nimport { refreshSession } from \"../session/refreshSession\";\nimport type { SessionStorage } from \"../session/storage\";\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\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 auth - 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 * @param options.marginSeconds - Number of seconds before token expiration to trigger a refresh, default is 60 seconds\n * @returns A middleware function that can be used in the fetch chain\n */\nexport const sessionRefreshMiddleware = (\n auth: Client,\n storage: SessionStorage,\n options?: {\n marginSeconds?: number;\n },\n): ChainFunction => {\n const { marginSeconds = 60 } = options || {};\n\n // Create and return the chain function\n return (next: FetchFunction): FetchFunction =>\n async (url: string, options: RequestInit = {}): Promise<Response> => {\n // Skip token handling for certain requests\n if (shouldSkipTokenHandling(url, options)) {\n return next(url, options);\n }\n\n try {\n await refreshSession(auth, storage, marginSeconds);\n } catch {\n // do nothing, we still want to call the next function\n }\n return next(url, options);\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 * @returns True if token handling should be skipped, false otherwise\n */\nfunction shouldSkipTokenHandling(url: string, options: RequestInit): 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.endsWith(\"/v1/token\")) {\n return true;\n }\n\n return false;\n}\n","/**\n * 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, SessionPayload } from \"../auth\";\nimport type { SessionStorage } from \"../session/storage\";\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 updateSessionFromResponseMiddleware = (\n storage: SessionStorage,\n): ChainFunction => {\n /**\n * Helper function to extract session data from various response formats\n *\n * @param body - Response data to extract session from\n * @returns Session object if found, null otherwise\n */\n const sessionExtractor = (\n body: Session | SessionPayload | string,\n ): Session | null => {\n if (typeof body === \"string\") {\n return null;\n }\n\n if (\"session\" in body) {\n // SessionPayload\n return body.session || null;\n }\n\n if (\"accessToken\" in body && \"refreshToken\" in body && \"user\" in body) {\n // Session\n return body;\n }\n\n return null;\n };\n\n return (next: (url: string, options?: RequestInit) => Promise<Response>) =>\n 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)) as\n | Session\n | SessionPayload;\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?.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 * Admin session middleware for the Nhost SDK.\n *\n * This module provides middleware functionality to automatically attach\n * Hasura admin secret for admin permissions in requests.\n */\n\nimport type { ChainFunction, FetchFunction } from \"./fetch\";\n\n/**\n * Configuration options for admin session middleware\n */\nexport interface AdminSessionOptions {\n /**\n * Hasura admin secret for elevated permissions (sets x-hasura-admin-secret header)\n */\n adminSecret: string;\n\n /**\n * Hasura role to use for the request (sets x-hasura-role header)\n */\n role?: string;\n\n /**\n * Additional Hasura session variables to attach to requests.\n * Keys will be automatically prefixed with 'x-hasura-' if not already present.\n *\n * @example\n * ```ts\n * {\n * 'user-id': '123',\n * 'org-id': '456'\n * }\n * // Results in headers:\n * // x-hasura-user-id: 123\n * // x-hasura-org-id: 456\n * ```\n */\n sessionVariables?: Record<string, string>;\n}\n\n/**\n * Creates a fetch middleware that attaches the Hasura admin secret and optional session variables to requests.\n *\n * This middleware:\n * 1. Sets the x-hasura-admin-secret header, which grants full admin access to Hasura\n * 2. Optionally sets the x-hasura-role header if a role is provided\n * 3. Optionally sets additional x-hasura-* headers for custom session variables\n *\n * **Security Warning**: Never use this middleware in client-side code or expose\n * the admin secret to end users. Admin secrets grant unrestricted access to your\n * entire database. This should only be used in trusted server-side environments.\n *\n * The middleware preserves request-specific headers when they conflict with the\n * admin session configuration.\n *\n * @param options - Admin session options including admin secret, role, and session variables\n * @returns A middleware function that can be used in the fetch chain\n *\n * @example\n * ```ts\n * // Create middleware with admin secret only\n * const adminMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET\n * });\n *\n * // Create middleware with admin secret and role\n * const adminUserMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET,\n * role: 'user'\n * });\n *\n * // Create middleware with admin secret, role, and custom session variables\n * const fullMiddleware = withAdminSessionMiddleware({\n * adminSecret: process.env.NHOST_ADMIN_SECRET,\n * role: 'user',\n * sessionVariables: {\n * 'user-id': '123',\n * 'org-id': '456'\n * }\n * });\n *\n * // Use with createCustomClient for an admin client\n * const adminClient = createCustomClient({\n * subdomain: 'myproject',\n * region: 'eu-central-1',\n * chainFunctions: [adminMiddleware]\n * });\n * ```\n */\nexport const withAdminSessionMiddleware =\n (options: AdminSessionOptions): ChainFunction =>\n (next: FetchFunction): FetchFunction =>\n async (url: string, requestOptions: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(requestOptions.headers || {});\n\n // Set x-hasura-admin-secret if not already present\n if (!headers.has(\"x-hasura-admin-secret\")) {\n headers.set(\"x-hasura-admin-secret\", options.adminSecret);\n }\n\n // Set x-hasura-role if provided and not already present\n if (options.role && !headers.has(\"x-hasura-role\")) {\n headers.set(\"x-hasura-role\", options.role);\n }\n\n // Set custom session variables\n if (options.sessionVariables) {\n for (const [key, value] of Object.entries(options.sessionVariables)) {\n // Ensure the key has the x-hasura- prefix\n const headerKey = key.startsWith(\"x-hasura-\") ? key : `x-hasura-${key}`;\n\n // Only set if not already present in the request\n if (!headers.has(headerKey)) {\n headers.set(headerKey, value);\n }\n }\n }\n\n return next(url, { ...requestOptions, headers });\n };\n"],"names":["options"],"mappings":";AAyBO,MAAM,8BACX,CAAC,YACD,CAAC,SACD,OAAO,KAAa,UAAuB,OAA0B;AACnE,QAAM,UAAU,IAAI,QAAQ,QAAQ,WAAW,CAAA,CAAE;AAGjD,MAAI,QAAQ,IAAI,eAAe,GAAG;AAChC,WAAO,KAAK,KAAK,OAAO;AAAA,EAC1B;AAGA,QAAM,UAAU,QAAQ,IAAA;AAExB,MAAI,SAAS,aAAa;AAExB,UAAM,aAAa;AAAA,MACjB,GAAG;AAAA,MACH,SAAS,uBAAuB,SAAS,OAAO;AAAA,IAAA;AAIlD,WAAO,KAAK,KAAK,UAAU;AAAA,EAC7B;AAGA,SAAO,KAAK,KAAK,OAAO;AAC1B;AASF,SAAS,uBAAuB,SAAkB,SAA2B;AAC3E,MAAI,QAAQ,aAAa;AACvB,YAAQ,IAAI,iBAAiB,UAAU,QAAQ,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AAM,eAAe,OAAO,MAAM,MAAM,IAAI;AAI1D,YAAI,MAAM;AAER,gBAAM,UAAU,iBAAiB,IAAI;AAGrC,cAAI,SAAS,eAAe,QAAQ,cAAc;AAChD,oBAAQ,IAAI,OAAO;AAAA,UACrB;AAAA,QACF;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AACd,cAAQ,KAAK,yCAAyC,KAAK;AAAA,IAC7D;AAGA,WAAO;AAAA,EACT;AACJ;ACVO,MAAM,6BACX,CAAC,YACD,CAAC,SACD,OAAO,KAAa,iBAA8B,OAA0B;AAC1E,QAAM,UAAU,IAAI,QAAQ,eAAe,WAAW,CAAA,CAAE;AAGxD,MAAI,CAAC,QAAQ,IAAI,uBAAuB,GAAG;AACzC,YAAQ,IAAI,yBAAyB,QAAQ,WAAW;AAAA,EAC1D;AAGA,MAAI,QAAQ,QAAQ,CAAC,QAAQ,IAAI,eAAe,GAAG;AACjD,YAAQ,IAAI,iBAAiB,QAAQ,IAAI;AAAA,EAC3C;AAGA,MAAI,QAAQ,kBAAkB;AAC5B,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,gBAAgB,GAAG;AAEnE,YAAM,YAAY,IAAI,WAAW,WAAW,IAAI,MAAM,YAAY,GAAG;AAGrE,UAAI,CAAC,QAAQ,IAAI,SAAS,GAAG;AAC3B,gBAAQ,IAAI,WAAW,KAAK;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AAEA,SAAO,KAAK,KAAK,EAAE,GAAG,gBAAgB,SAAS;AACjD;"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("../fetch-DWXwEnoe.cjs");exports.createAPIClient=(s,e=[])=>{let a=t.createEnhancedFetch(e);return{baseURL:s,pushChainFunction:s=>{e.push(s),a=t.createEnhancedFetch(e)},getJWKs:async e=>{const n=`${s}/.well-known/jwks.json`,r=await a(n,{...e,method:"GET",headers:{...e?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},elevateWebauthn:async e=>{const n=`${s}/elevate/webauthn`,r=await a(n,{...e,method:"POST",headers:{...e?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},verifyElevateWebauthn:async(e,n)=>{const r=`${s}/elevate/webauthn/verify`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},healthCheckGet:async e=>{const n=`${s}/healthz`,r=await a(n,{...e,method:"GET",headers:{...e?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},healthCheckHead:async e=>{const n=`${s}/healthz`,r=await a(n,{...e,method:"HEAD",headers:{...e?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,r.status,r.headers)}return{body:void 0,status:r.status,headers:r.headers}},linkIdToken:async(e,n)=>{const r=`${s}/link/idtoken`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},changeUserMfa:async e=>{const n=`${s}/mfa/totp/generate`,r=await a(n,{...e,method:"GET",headers:{...e?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},createPAT:async(e,n)=>{const r=`${s}/pat`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInAnonymous:async(e,n)=>{const r=`${s}/signin/anonymous`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInEmailPassword:async(e,n)=>{const r=`${s}/signin/email-password`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInIdToken:async(e,n)=>{const r=`${s}/signin/idtoken`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifySignInMfaTotp:async(e,n)=>{const r=`${s}/signin/mfa/totp`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInOTPEmail:async(e,n)=>{const r=`${s}/signin/otp/email`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifySignInOTPEmail:async(e,n)=>{const r=`${s}/signin/otp/email/verify`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInPasswordlessEmail:async(e,n)=>{const r=`${s}/signin/passwordless/email`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInPasswordlessSms:async(e,n)=>{const r=`${s}/signin/passwordless/sms`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifySignInPasswordlessSms:async(e,n)=>{const r=`${s}/signin/passwordless/sms/otp`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInPAT:async(e,n)=>{const r=`${s}/signin/pat`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInProviderURL:(t,e)=>{const a=e&&Object.entries(e).flatMap((([t,s])=>{if("providerSpecificParams"===t)return"object"!=typeof s||null===s||Array.isArray(s)?[`${t}=${encodeURIComponent(String(s))}`]:Object.entries(s).map((([t,s])=>`${t}=${encodeURIComponent(String(s))}`));const e=Array.isArray(s)?s.join(","):"object"==typeof s&&null!==s?JSON.stringify(s):String(s);return[`${t}=${encodeURIComponent(e)}`]})).join("&");return a?`${s}/signin/provider/${t}?${a}`:`${s}/signin/provider/${t}`},getProviderTokens:async(e,n)=>{const r=`${s}/signin/provider/${e}/callback/tokens`,i=await a(r,{...n,method:"GET",headers:{...n?.headers}});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signInWebauthn:async(e,n)=>{const r=`${s}/signin/webauthn`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifySignInWebauthn:async(e,n)=>{const r=`${s}/signin/webauthn/verify`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signOut:async(e,n)=>{const r=`${s}/signout`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signUpEmailPassword:async(e,n)=>{const r=`${s}/signup/email-password`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},signUpWebauthn:async(e,n)=>{const r=`${s}/signup/webauthn`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifySignUpWebauthn:async(e,n)=>{const r=`${s}/signup/webauthn/verify`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},refreshToken:async(e,n)=>{const r=`${s}/token`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},refreshProviderToken:async(e,n,r)=>{const i=`${s}/token/provider/${e}`,o=await a(i,{...r,method:"POST",headers:{"Content-Type":"application/json",...r?.headers},body:JSON.stringify(n)});if(o.status>=300){const s=[412].includes(o.status)?null:await o.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,o.status,o.headers)}const u=[204,205,304].includes(o.status)?null:await o.text();return{body:u?JSON.parse(u):{},status:o.status,headers:o.headers}},verifyToken:async(e,n)=>{const r=`${s}/token/verify`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},getUser:async e=>{const n=`${s}/user`,r=await a(n,{...e,method:"GET",headers:{...e?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},deanonymizeUser:async(e,n)=>{const r=`${s}/user/deanonymize`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},changeUserEmail:async(e,n)=>{const r=`${s}/user/email/change`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},sendVerificationEmail:async(e,n)=>{const r=`${s}/user/email/send-verification-email`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifyChangeUserMfa:async(e,n)=>{const r=`${s}/user/mfa`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},changeUserPassword:async(e,n)=>{const r=`${s}/user/password`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},sendPasswordResetEmail:async(e,n)=>{const r=`${s}/user/password/reset`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},addSecurityKey:async e=>{const n=`${s}/user/webauthn/add`,r=await a(n,{...e,method:"POST",headers:{...e?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}},verifyAddSecurityKey:async(e,n)=>{const r=`${s}/user/webauthn/verify`,i=await a(r,{...n,method:"POST",headers:{"Content-Type":"application/json",...n?.headers},body:JSON.stringify(e)});if(i.status>=300){const s=[412].includes(i.status)?null:await i.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,i.status,i.headers)}const o=[204,205,304].includes(i.status)?null:await i.text();return{body:o?JSON.parse(o):{},status:i.status,headers:i.headers}},verifyTicketURL:t=>{const e=t&&Object.entries(t).flatMap((([t,s])=>{const e=Array.isArray(s)?s.join(","):"object"==typeof s&&null!==s?JSON.stringify(s):String(s);return[`${t}=${encodeURIComponent(e)}`]})).join("&");return e?`${s}/verify?${e}`:`${s}/verify`},getVersion:async e=>{const n=`${s}/version`,r=await a(n,{...e,method:"GET",headers:{...e?.headers}});if(r.status>=300){const s=[412].includes(r.status)?null:await r.text(),e=s?JSON.parse(s):{};throw new t.FetchError(e,r.status,r.headers)}const i=[204,205,304].includes(r.status)?null:await r.text();return{body:i?JSON.parse(i):{},status:r.status,headers:r.headers}}}};
2
+ //# sourceMappingURL=auth.cjs.map