firebase 13.2.0-eap-sql.a9a137e67 → 13.2.0-eap-sql.b903ef716

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 (47) hide show
  1. package/app/dist/esm/index.esm.js +1 -1
  2. package/app/dist/index.cjs.js +1 -1
  3. package/app/dist/index.mjs +1 -1
  4. package/compat/app/dist/esm/index.esm.js +1 -1
  5. package/compat/app/dist/index.cjs.js +1 -1
  6. package/compat/app/dist/index.mjs +1 -1
  7. package/compat/dist/esm/index.esm.js +2 -2
  8. package/compat/dist/index.node.cjs +2 -2
  9. package/compat/dist/index.rn.cjs.js +2 -2
  10. package/firebase-ai.js +1 -1
  11. package/firebase-analytics-compat.js +1 -1
  12. package/firebase-analytics.js +1 -1
  13. package/firebase-app-check-compat.js +1 -1
  14. package/firebase-app-check.js +1 -1
  15. package/firebase-app-compat.js +2 -2
  16. package/firebase-app.js +5 -5
  17. package/firebase-auth-compat.js +1 -1
  18. package/firebase-auth-cordova.js +1 -1
  19. package/firebase-auth-web-extension.js +1 -1
  20. package/firebase-auth.js +1 -1
  21. package/firebase-compat.js +6 -6
  22. package/firebase-crashlytics.js +1 -1
  23. package/firebase-data-connect.js +1 -1
  24. package/firebase-database-compat.js +1 -1
  25. package/firebase-database.js +1 -1
  26. package/firebase-firestore-compat.js +2 -2
  27. package/firebase-firestore-lite-pipelines.js +1 -1
  28. package/firebase-firestore-lite.js +1 -1
  29. package/firebase-firestore-pipelines.js +1 -1
  30. package/firebase-firestore.js +1 -1
  31. package/firebase-functions-compat.js +1 -1
  32. package/firebase-functions.js +1 -1
  33. package/firebase-installations-compat.js +1 -1
  34. package/firebase-installations.js +1 -1
  35. package/firebase-messaging-compat.js +1 -1
  36. package/firebase-messaging-sw.js +1 -1
  37. package/firebase-messaging.js +1 -1
  38. package/firebase-performance-compat.js +1 -1
  39. package/firebase-performance-standalone-compat.js +7 -7
  40. package/firebase-performance.js +1 -1
  41. package/firebase-remote-config-compat.js +1 -1
  42. package/firebase-remote-config.js +1 -1
  43. package/firebase-sql.js +1 -1
  44. package/firebase-sql.js.map +1 -1
  45. package/firebase-storage-compat.js +1 -1
  46. package/firebase-storage.js +1 -1
  47. package/package.json +31 -31
@@ -1 +1 @@
1
- {"version":3,"file":"firebase-sql.js","sources":["../util/src/crypt.ts","../util/src/errors.ts","../util/src/json.ts","../component/src/component.ts","../component/src/types.ts","../../node_modules/@supabase/postgrest-js/src/PostgrestError.ts","../../node_modules/@supabase/postgrest-js/src/types/common/common.ts","../../node_modules/@supabase/postgrest-js/src/fetchWithRetry.ts","../../node_modules/@supabase/postgrest-js/src/PostgrestBuilder.ts","../../node_modules/@supabase/postgrest-js/src/PostgrestTransformBuilder.ts","../../node_modules/@supabase/postgrest-js/src/PostgrestFilterBuilder.ts","../../node_modules/@supabase/postgrest-js/src/PostgrestQueryBuilder.ts","../../node_modules/@supabase/postgrest-js/src/PostgrestClient.ts","../logger/src/logger.ts","../sql/src/core/error.ts","../sql/src/core/errorMapper.ts","../sql/src/core/version.ts","../sql/src/network/headers.ts","../sql/src/core/settings.ts","../sql/src/util/constants.ts","../sql/src/logger.ts","../sql/src/core/tokenProviders/AbstractTokenProvider.ts","../sql/src/core/tokenProviders/AppCheckTokenProvider.ts","../sql/src/core/tokenProviders/FirebaseAuthTokenProvider.ts","../sql/src/network/transport.ts","../util/src/jwt.ts","../sql/src/network/fetch.ts","../util/src/url.ts","../sql/src/util/url.ts","../sql/src/api/impl/FilterBuilderImpl.ts","../sql/src/api/impl/QueryBuilderImpl.ts","../sql/src/api/FirebaseSql.ts","../sql/src/register.ts","../sql/src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length;) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw new DecodeBase64StringError();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // TypeScript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map<Err, string> = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record<string, unknown>\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n // which we can now use since we no longer target ES5.\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap<ErrorCode>\n ) {}\n\n create<K extends ErrorCode>(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n try {\n let ptr = 0;\n let result = '';\n while (ptr < template.length) {\n const start = template.indexOf('{$', ptr);\n if (start === -1) {\n result += template.substring(ptr);\n break;\n }\n const end = template.indexOf('}', start + 2);\n if (end === -1) {\n result += template.substring(ptr);\n break;\n }\n const key = template.substring(start + 2, end);\n const value = data[key];\n result +=\n template.substring(ptr, start) +\n (value != null ? String(value) : `<${key}?>`);\n ptr = end + 1;\n }\n return result;\n } catch (e) {\n // Should never happen, but fallback just in case\n return template;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nexport function jsonEval(str: string): unknown {\n return JSON.parse(str);\n}\n\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data JavaScript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nexport function stringify(data: unknown): string {\n return JSON.stringify(data);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component<T extends Name = Name> {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback<T> | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory<T>,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ComponentContainer } from './component_container';\n\nexport const enum InstantiationMode {\n LAZY = 'LAZY', // Currently most components are LAZY in JS SDK\n EAGER = 'EAGER', // EAGER components are initialized immediately upon registration\n EXPLICIT = 'EXPLICIT' // component needs to be initialized explicitly by calling Provider.initialize()\n}\n\n/**\n * PUBLIC: A public component provides a set of public APIs to customers. A service namespace will be patched\n * onto `firebase` namespace. Assume the component name is `test`, customers will be able\n * to get the service by calling `firebase.test()` or `app.test()` where `app` is a `FirebaseApp` instance.\n *\n * PRIVATE: A private component provides a set of private APIs that are used internally by other\n * Firebase SDKs. No service namespace is created in `firebase` namespace and customers have no way to get them.\n */\nexport const enum ComponentType {\n PUBLIC = 'PUBLIC',\n PRIVATE = 'PRIVATE',\n VERSION = 'VERSION'\n}\n\nexport interface InstanceFactoryOptions {\n instanceIdentifier?: string;\n options?: {};\n}\n\nexport type InitializeOptions = InstanceFactoryOptions;\n\n/**\n * Factory to create an instance of type T, given a ComponentContainer.\n * ComponentContainer is the IOC container that provides {@link Provider}\n * for dependencies.\n *\n * NOTE: The container only provides {@link Provider} rather than the actual instances of dependencies.\n * It is useful for lazily loaded dependencies and optional dependencies.\n */\nexport type InstanceFactory<T extends Name> = (\n container: ComponentContainer,\n options: InstanceFactoryOptions\n) => NameServiceMapping[T];\n\nexport type onInstanceCreatedCallback<T extends Name> = (\n container: ComponentContainer,\n instanceIdentifier: string,\n instance: NameServiceMapping[T]\n) => void;\n\nexport interface Dictionary {\n [key: string]: unknown;\n}\n\n/**\n * This interface will be extended by Firebase SDKs to provide service name and service type mapping.\n * It is used as a generic constraint to ensure type safety.\n */\nexport interface NameServiceMapping {}\n\nexport type Name = keyof NameServiceMapping;\nexport type Service = NameServiceMapping[Name];\n\nexport type OnInitCallBack<T extends Name> = (\n instance: NameServiceMapping[T],\n identifier: string\n) => void;\n","/**\n * Error format\n *\n * Returned by every PostgREST request that fails. When something fails, the\n * single most useful field is usually `hint` — Postgres often returns the\n * actionable fix there, not in `message`. Always log the full object (e.g.\n * `console.error(error)`); logging only `error.message` hides the hint.\n *\n * Read the fields in roughly this order of usefulness:\n *\n * - `hint` — actionable guidance from the database when available. For\n * permission-denied errors (`42501`), this is the literal SQL to fix the\n * problem, e.g.\n * `\"Grant the required privileges to the current role with: GRANT SELECT ON public.users TO anon;\"`.\n * Missing column? `hint` suggests the column you probably meant. Whenever\n * Postgres knows the fix, it puts it in `hint`.\n * - `code` — stable error code from PostgREST (e.g. `PGRST301`) or Postgres\n * (e.g. `42501`). Branch on this rather than on `message` text.\n * - `details` — extra context, often the offending value, key, or row.\n * - `message` — human-readable summary. Useful in UI strings; less useful\n * for debugging.\n *\n * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes}\n */\nexport default class PostgrestError extends Error {\n details: string\n hint: string\n code: string\n\n /**\n * @example\n * ```ts\n * import PostgrestError from '@supabase/postgrest-js'\n *\n * throw new PostgrestError({\n * message: 'Row level security prevented the request',\n * details: 'RLS denied the insert',\n * hint: 'Check your policies',\n * code: 'PGRST301',\n * })\n * ```\n */\n constructor(context: { message: string; details: string; hint: string; code: string }) {\n super(context.message)\n this.name = 'PostgrestError'\n this.details = context.details\n this.hint = context.hint\n this.code = context.code\n }\n\n toJSON(): { name: string; message: string; details: string; hint: string; code: string } {\n return {\n name: this.name,\n message: this.message,\n details: this.details,\n hint: this.hint,\n code: this.code,\n }\n }\n}\n","// Types that are shared between supabase-js and postgrest-js\n\nexport type Fetch = typeof fetch\n\n/**\n * Default number of retry attempts.\n */\nexport const DEFAULT_MAX_RETRIES = 3\n\n/**\n * Default exponential backoff delay function.\n * Delays: 1s, 2s, 4s, 8s, ... (max 30s)\n *\n * @param attemptIndex - Zero-based index of the retry attempt\n * @returns Delay in milliseconds before the next retry\n */\nexport const getRetryDelay = (attemptIndex: number): number =>\n Math.min(1000 * 2 ** attemptIndex, 30000)\n\n/**\n * Status codes that are safe to retry.\n * 520 = Cloudflare timeout/connection errors (transient)\n * 503 = PostgREST schema cache not yet loaded (transient, signals retry via Retry-After header)\n */\nexport const RETRYABLE_STATUS_CODES = [520, 503] as const\n\n/**\n * HTTP methods that are safe to retry (idempotent operations).\n */\nexport const RETRYABLE_METHODS = ['GET', 'HEAD', 'OPTIONS'] as const\n\nexport type GenericRelationship = {\n foreignKeyName: string\n columns: string[]\n isOneToOne?: boolean\n referencedRelation: string\n referencedColumns: string[]\n}\n\nexport type GenericTable = {\n Row: Record<string, unknown>\n Insert: Record<string, unknown>\n Update: Record<string, unknown>\n Relationships: GenericRelationship[]\n /**\n * Names of the `Row` keys that are computed fields (functions taking the row), which\n * PostgREST leaves out of `select('*')`. Generated types declare it; when absent, the\n * computed fields are inferred from `Functions`.\n */\n ComputedFields?: string\n}\n\nexport type GenericUpdatableView = {\n Row: Record<string, unknown>\n Insert: Record<string, unknown>\n Update: Record<string, unknown>\n Relationships: GenericRelationship[]\n ComputedFields?: string\n}\n\nexport type GenericNonUpdatableView = {\n Row: Record<string, unknown>\n Relationships: GenericRelationship[]\n ComputedFields?: string\n}\n\nexport type GenericView = GenericUpdatableView | GenericNonUpdatableView\n\nexport type GenericSetofOption = {\n isSetofReturn?: boolean | undefined\n isOneToOne?: boolean | undefined\n isNotNullable?: boolean | undefined\n to: string\n from: string\n}\n\nexport type GenericFunction = {\n Args: Record<string, unknown> | never\n Returns: unknown\n SetofOptions?: GenericSetofOption\n}\n\nexport type GenericSchema = {\n Tables: Record<string, GenericTable>\n Views: Record<string, GenericView>\n Functions: Record<string, GenericFunction>\n}\n\nexport type ClientServerOptions = {\n PostgrestVersion?: string\n}\n","import {\n DEFAULT_MAX_RETRIES,\n Fetch,\n getRetryDelay,\n RETRYABLE_METHODS,\n RETRYABLE_STATUS_CODES,\n} from './types/common/common'\n\n/**\n * Sleep for a given number of milliseconds.\n * If an AbortSignal is provided, the sleep resolves early when the signal is aborted.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n const id = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n function onAbort() {\n clearTimeout(id)\n resolve()\n }\n signal?.addEventListener('abort', onAbort)\n })\n}\n\n/**\n * Check if a request should be retried based on method and status code.\n */\nfunction shouldRetry(\n method: string,\n status: number,\n attemptCount: number,\n retryEnabled: boolean\n): boolean {\n // Don't retry if retries are disabled or we've exhausted attempts\n if (!retryEnabled || attemptCount >= DEFAULT_MAX_RETRIES) {\n return false\n }\n\n // Only retry idempotent methods (GET, HEAD, OPTIONS)\n if (!RETRYABLE_METHODS.includes(method as (typeof RETRYABLE_METHODS)[number])) {\n return false\n }\n\n // Only retry on specific status codes (520 - Cloudflare errors)\n if (!RETRYABLE_STATUS_CODES.includes(status as (typeof RETRYABLE_STATUS_CODES)[number])) {\n return false\n }\n\n return true\n}\n\nexport interface RetryableRequest {\n method: string\n /** Plain object, never a Headers instance: React Native's XHR-based fetch drops the latter. */\n headers: Record<string, string>\n body?: string\n signal?: AbortSignal\n}\n\n/**\n * Perform a request with the retry policy shared by every PostgREST call.\n *\n * Idempotent methods (GET, HEAD, OPTIONS) are retried up to\n * `DEFAULT_MAX_RETRIES` times when the fetch rejects or the server answers\n * with a retryable status (503, 520). The wait honours the `Retry-After`\n * header when present and backs off exponentially otherwise. Retried\n * attempts carry an `X-Retry-Count` header. Aborted requests (including\n * `AbortSignal.timeout()`, which rejects with `TimeoutError`) and\n * non-idempotent methods are never retried: their rejection propagates\n * unchanged. A response body is drained before its request is retried.\n */\nexport async function fetchWithRetry(\n fetchImpl: Fetch,\n url: string,\n request: RetryableRequest,\n retryEnabled: boolean\n): Promise<Response> {\n let attemptCount = 0\n\n while (true) {\n const headers: Record<string, string> = { ...request.headers }\n if (attemptCount > 0) {\n headers['X-Retry-Count'] = String(attemptCount)\n }\n\n let res: Response\n try {\n res = await fetchImpl(url, {\n method: request.method,\n headers,\n body: request.body,\n signal: request.signal,\n })\n // JS allows throwing any value, and serverless or realm-crossing fetch\n // implementations can reject with non-Error objects. `instanceof Error`\n // is too narrow here; narrow at the use site with optional chaining.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (fetchError: any) {\n // Never retry aborted requests. `AbortSignal.timeout()` rejects with\n // `TimeoutError` rather than `AbortError`, so it needs its own check.\n // Gated on `request.signal?.aborted` because `TimeoutError`, unlike\n // `AbortError`, isn't exclusive to aborts: a custom fetch implementation\n // may throw it for an unrelated, retryable timeout of its own.\n if (\n fetchError?.name === 'AbortError' ||\n fetchError?.code === 'ABORT_ERR' ||\n (fetchError?.name === 'TimeoutError' && request.signal?.aborted)\n ) {\n throw fetchError\n }\n\n // Don't retry network errors for non-idempotent methods\n if (!RETRYABLE_METHODS.includes(request.method as (typeof RETRYABLE_METHODS)[number])) {\n throw fetchError\n }\n\n // Check if we should retry network errors\n if (retryEnabled && attemptCount < DEFAULT_MAX_RETRIES) {\n const delay = getRetryDelay(attemptCount)\n attemptCount++\n await sleep(delay, request.signal)\n continue\n }\n\n // Exhausted retries or retries disabled, throw the last error\n throw fetchError\n }\n\n // Check if we should retry this HTTP response\n if (shouldRetry(request.method, res.status, attemptCount, retryEnabled)) {\n const retryAfterHeader = res.headers?.get('Retry-After') ?? null\n const delay =\n retryAfterHeader !== null\n ? Math.max(0, parseInt(retryAfterHeader, 10) || 0) * 1000\n : getRetryDelay(attemptCount)\n await res.text()\n attemptCount++\n await sleep(delay, request.signal)\n continue\n }\n\n return res\n }\n}\n","import type {\n PostgrestSingleResponse,\n PostgrestResponseSuccess,\n CheckMatchingArrayTypes,\n MergePartialResult,\n IsValidResultOverride,\n} from './types/types'\nimport { ClientServerOptions, Fetch } from './types/common/common'\nimport PostgrestError from './PostgrestError'\nimport { fetchWithRetry } from './fetchWithRetry'\nimport { ContainsNull } from './select-query-parser/types'\n\nexport default abstract class PostgrestBuilder<\n ClientOptions extends ClientServerOptions,\n Result,\n ThrowOnError extends boolean = false,\n> implements PromiseLike<\n ThrowOnError extends true ? PostgrestResponseSuccess<Result> : PostgrestSingleResponse<Result>\n> {\n protected method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'\n protected url: URL\n protected headers: Headers\n protected schema?: string\n protected body?: unknown\n protected shouldThrowOnError = false\n protected signal?: AbortSignal\n protected fetch: Fetch\n protected isMaybeSingle: boolean\n protected shouldStripNulls: boolean\n protected urlLengthLimit: number\n\n // Retry configuration - enabled by default\n protected retryEnabled: boolean = true\n\n /**\n * Creates a builder configured for a specific PostgREST request.\n *\n * @example Using supabase-js (recommended)\n * ```ts\n * import { createClient } from '@supabase/supabase-js'\n *\n * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n * const { data, error } = await supabase.from('users').select('*')\n * ```\n *\n * @category Database\n *\n * @example Standalone import for bundle-sensitive environments\n * ```ts\n * import { PostgrestQueryBuilder } from '@supabase/postgrest-js'\n *\n * const builder = new PostgrestQueryBuilder(\n * new URL('https://xyzcompany.supabase.co/rest/v1/users'),\n * { headers: new Headers({ apikey: 'your-publishable-key' }) }\n * )\n * ```\n */\n constructor(builder: {\n method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'\n url: URL\n headers: HeadersInit\n schema?: string\n body?: unknown\n shouldThrowOnError?: boolean\n signal?: AbortSignal\n fetch?: Fetch\n isMaybeSingle?: boolean\n shouldStripNulls?: boolean\n urlLengthLimit?: number\n // Retry option\n retry?: boolean\n }) {\n this.method = builder.method\n this.url = builder.url\n this.headers = new Headers(builder.headers)\n this.schema = builder.schema\n this.body = builder.body\n this.shouldThrowOnError = builder.shouldThrowOnError ?? false\n this.signal = builder.signal\n this.isMaybeSingle = builder.isMaybeSingle ?? false\n this.shouldStripNulls = builder.shouldStripNulls ?? false\n this.urlLengthLimit = builder.urlLengthLimit ?? 8000\n this.retryEnabled = builder.retry ?? true\n\n if (builder.fetch) {\n this.fetch = builder.fetch\n } else {\n this.fetch = fetch\n }\n }\n\n /**\n * If there's an error with the query, throwOnError will reject the promise by\n * throwing the error instead of returning it as part of a successful response.\n *\n * {@link https://github.com/supabase/supabase-js/issues/92}\n *\n * @category Database\n * @subcategory Using modifiers\n */\n throwOnError(): PostgrestBuilder<ClientOptions, Result, true> {\n this.shouldThrowOnError = true\n return this as PostgrestBuilder<ClientOptions, Result, true>\n }\n\n /**\n * Strip null values from the response data. Properties with `null` values\n * will be omitted from the returned JSON objects.\n *\n * Requires PostgREST 11.2.0+.\n *\n * {@link https://docs.postgrest.org/en/stable/references/api/resource_representation.html#stripped-nulls}\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .stripNulls()\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text, bio text);\n *\n * insert into\n * characters (id, name, bio)\n * values\n * (1, 'Luke', null),\n * (2, 'Leia', 'Princess of Alderaan');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * },\n * {\n * \"id\": 2,\n * \"name\": \"Leia\",\n * \"bio\": \"Princess of Alderaan\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n stripNulls(): this {\n if (this.headers.get('Accept') === 'text/csv') {\n throw new Error('stripNulls() cannot be used with csv()')\n }\n this.shouldStripNulls = true\n return this\n }\n\n /**\n * Set an HTTP header on this single PostgREST request, overriding any header\n * with the same name set on the client.\n *\n * This is an advanced escape hatch for one-off needs (passing a custom\n * `Authorization` for a single query, attaching a tracing header, etc.).\n * Most callers do not need it: configure client-wide headers via the\n * `headers` option when constructing the client, and authentication via\n * Supabase Auth.\n *\n * @param name - HTTP header name\n * @param value - HTTP header value\n *\n * @category Database\n * @subcategory Using modifiers\n */\n setHeader(name: string, value: string): this {\n this.headers = new Headers(this.headers)\n this.headers.set(name, value)\n return this\n }\n\n /**\n * @category Database\n * @subcategory Using modifiers\n *\n * Configure retry behavior for this request.\n *\n * By default, retries are enabled for idempotent requests (GET, HEAD, OPTIONS)\n * that fail with network errors or specific HTTP status codes (503, 520).\n * Retries use exponential backoff (1s, 2s, 4s) with a maximum of 3 attempts.\n *\n * @param enabled - Whether to enable retries for this request\n *\n * @example\n * ```ts\n * // Disable retries for a specific query\n * const { data, error } = await supabase\n * .from('users')\n * .select()\n * .retry(false)\n * ```\n */\n retry(enabled: boolean): this {\n this.retryEnabled = enabled\n return this\n }\n\n then<\n TResult1 = ThrowOnError extends true\n ? PostgrestResponseSuccess<Result>\n : PostgrestSingleResponse<Result>,\n TResult2 = never,\n >(\n onfulfilled?:\n | ((\n value: ThrowOnError extends true\n ? PostgrestResponseSuccess<Result>\n : PostgrestSingleResponse<Result>\n ) => TResult1 | PromiseLike<TResult1>)\n | undefined\n | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null\n ): PromiseLike<TResult1 | TResult2> {\n // https://postgrest.org/en/stable/api.html#switching-schemas\n if (this.schema === undefined) {\n // skip\n } else if (['GET', 'HEAD'].includes(this.method)) {\n this.headers.set('Accept-Profile', this.schema)\n } else {\n this.headers.set('Content-Profile', this.schema)\n }\n if (this.method !== 'GET' && this.method !== 'HEAD') {\n this.headers.set('Content-Type', 'application/json')\n }\n\n // https://docs.postgrest.org/en/stable/references/api/resource_representation.html#stripped-nulls\n if (this.shouldStripNulls) {\n const currentAccept = this.headers.get('Accept')\n if (currentAccept === 'application/vnd.pgrst.object+json') {\n this.headers.set('Accept', 'application/vnd.pgrst.object+json;nulls=stripped')\n } else if (!currentAccept || currentAccept === 'application/json') {\n this.headers.set('Accept', 'application/vnd.pgrst.array+json;nulls=stripped')\n }\n }\n\n // NOTE: Invoke w/o `this` to avoid illegal invocation error.\n // https://github.com/supabase/postgrest-js/pull/247\n const _fetch = this.fetch\n\n // Execute fetch with retry logic\n const executeWithRetry = async (): Promise<{\n error: any\n data: any\n count: number | null\n status: number\n statusText: string\n }> => {\n // Serialize headers as a plain object rather than a Headers instance.\n // React Native's XHR-based fetch silently drops headers (notably Content-Type)\n // when given a Headers instance, causing PGRST202 on parameter-less RPC calls.\n // See supabase/supabase-js#1562 and facebook/react-native#33933.\n // All sibling packages (auth-js, storage-js, functions-js) already pass plain objects.\n const headers: Record<string, string> = {}\n this.headers.forEach((value, key) => {\n headers[key] = value\n })\n\n // Only the fetch itself is retried — processResponse errors must never trigger retries\n const res = await fetchWithRetry(\n _fetch,\n this.url.toString(),\n {\n method: this.method,\n headers,\n body: JSON.stringify(this.body, (_, value) =>\n typeof value === 'bigint' ? value.toString() : value\n ),\n signal: this.signal,\n },\n this.retryEnabled\n )\n\n return await this.processResponse(res)\n }\n\n let res = executeWithRetry()\n\n if (!this.shouldThrowOnError) {\n res = res.catch((fetchError) => {\n // Build detailed error information including cause if available\n // Note: We don't populate code/hint for client-side network errors since those\n // fields are meant for upstream service errors (PostgREST/PostgreSQL)\n let errorDetails = ''\n let hint = ''\n let code = ''\n\n // Add cause information if available (e.g., DNS errors, network failures)\n const cause = fetchError?.cause\n if (cause) {\n const causeMessage = cause?.message ?? ''\n const causeCode = cause?.code ?? ''\n\n errorDetails = `${fetchError?.name ?? 'FetchError'}: ${fetchError?.message}`\n errorDetails += `\\n\\nCaused by: ${cause?.name ?? 'Error'}: ${causeMessage}`\n if (causeCode) {\n errorDetails += ` (${causeCode})`\n }\n if (cause?.stack) {\n errorDetails += `\\n${cause.stack}`\n }\n } else {\n // No cause available, just include the error stack\n errorDetails = fetchError?.stack ?? ''\n }\n\n // Get URL length for potential hints\n const urlLength = this.url.toString().length\n\n // Handle AbortError specially with helpful hints\n if (fetchError?.name === 'AbortError' || fetchError?.code === 'ABORT_ERR') {\n code = ''\n hint = 'Request was aborted (timeout or manual cancellation)'\n\n if (urlLength > this.urlLengthLimit) {\n hint += `. Note: Your request URL is ${urlLength} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`\n }\n }\n // Handle HeadersOverflowError from undici (Node.js fetch implementation)\n else if (\n cause?.name === 'HeadersOverflowError' ||\n cause?.code === 'UND_ERR_HEADERS_OVERFLOW'\n ) {\n code = ''\n hint = 'HTTP headers exceeded server limits (typically 16KB)'\n\n if (urlLength > this.urlLengthLimit) {\n hint += `. Your request URL is ${urlLength} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`\n }\n }\n\n return {\n success: false as const,\n error: {\n message: `${fetchError?.name ?? 'FetchError'}: ${fetchError?.message}`,\n details: errorDetails,\n hint: hint,\n code: code,\n },\n data: null,\n count: null,\n status: 0,\n statusText: '',\n }\n })\n }\n\n return (\n res as Promise<\n ThrowOnError extends true\n ? PostgrestResponseSuccess<Result>\n : PostgrestSingleResponse<Result>\n >\n ).then(onfulfilled, onrejected)\n }\n\n /**\n * Process a fetch response and return the standardized postgrest response.\n */\n private async processResponse(res: Response): Promise<{\n success: boolean\n error: any\n data: any\n count: number | null\n status: number\n statusText: string\n }> {\n let error = null\n let data = null\n let count: number | null = null\n let status = res.status\n let statusText = res.statusText\n\n if (res.ok) {\n if (this.method !== 'HEAD') {\n const body = await res.text()\n if (body === '') {\n // Prefer: return=minimal\n } else if (this.headers.get('Accept') === 'text/csv') {\n data = body\n } else if (\n this.headers.get('Accept') &&\n this.headers.get('Accept')?.includes('application/vnd.pgrst.plan+text')\n ) {\n data = body\n } else {\n try {\n data = JSON.parse(body)\n } catch {\n // A 2xx status doesn't guarantee a JSON body; mirror the non-2xx fallback below.\n error = { message: body }\n data = null\n\n if (this.shouldThrowOnError) {\n throw new PostgrestError({ message: body, details: '', hint: '', code: '' })\n }\n }\n }\n }\n\n const countHeader = this.headers.get('Prefer')?.match(/count=(exact|planned|estimated)/)\n const contentRange = res.headers.get('content-range')?.split('/')\n if (countHeader && contentRange && contentRange.length > 1) {\n count = parseInt(contentRange[1])\n }\n\n // Fix for https://github.com/supabase/postgrest-js/issues/361 — applies to all methods.\n if (this.isMaybeSingle && Array.isArray(data)) {\n if (data.length > 1) {\n error = {\n // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553\n code: 'PGRST116',\n details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`,\n hint: null,\n message: 'JSON object requested, multiple (or no) rows returned',\n }\n data = null\n count = null\n status = 406\n statusText = 'Not Acceptable'\n\n if (this.shouldThrowOnError) {\n // `hint` is null in the returned error to match PostgREST, but\n // PostgrestError types it as a string, like the other throws here.\n throw new PostgrestError({ ...error, hint: error.hint ?? '' })\n }\n } else if (data.length === 1) {\n data = data[0]\n } else {\n data = null\n }\n }\n } else {\n const body = await res.text()\n\n try {\n error = JSON.parse(body)\n\n // Workaround for https://github.com/supabase/postgrest-js/issues/295\n if (Array.isArray(error) && res.status === 404) {\n data = []\n error = null\n status = 200\n statusText = 'OK'\n }\n } catch {\n // Workaround for https://github.com/supabase/postgrest-js/issues/295\n if (res.status === 404 && body === '') {\n status = 204\n statusText = 'No Content'\n } else {\n error = {\n message: body,\n }\n }\n }\n\n if (error && this.shouldThrowOnError) {\n throw new PostgrestError(error)\n }\n }\n\n return {\n success: error === null,\n error,\n data,\n count,\n status,\n statusText,\n }\n }\n\n /**\n * Override the type of the returned `data`.\n *\n * @typeParam NewResult - The new result type to override with\n * @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead\n *\n * @category Database\n * @subcategory Using modifiers\n */\n returns<NewResult>(): PostgrestBuilder<\n ClientOptions,\n CheckMatchingArrayTypes<Result, NewResult>,\n ThrowOnError\n > {\n /* istanbul ignore next */\n return this as unknown as PostgrestBuilder<\n ClientOptions,\n CheckMatchingArrayTypes<Result, NewResult>,\n ThrowOnError\n >\n }\n\n /**\n * Override the type of the returned `data` field in the response.\n *\n * @typeParam NewResult - The new type to cast the response data to\n * @typeParam Options - Optional type configuration (defaults to { merge: true })\n * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true)\n * @example\n * ```typescript\n * // Merge with existing types (default behavior)\n * const query = supabase\n * .from('users')\n * .select()\n * .overrideTypes<{ custom_field: string }>()\n *\n * // Replace existing types completely\n * const replaceQuery = supabase\n * .from('users')\n * .select()\n * .overrideTypes<{ id: number; name: string }, { merge: false }>()\n * ```\n * @returns A PostgrestBuilder instance with the new type\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example Complete Override type of successful response\n * ```ts\n * const { data } = await supabase\n * .from('countries')\n * .select()\n * .overrideTypes<Array<MyType>, { merge: false }>()\n * ```\n *\n * @exampleResponse Complete Override type of successful response\n * ```ts\n * let x: typeof data // MyType[]\n * ```\n *\n * @example Complete Override type of object response\n * ```ts\n * const { data } = await supabase\n * .from('countries')\n * .select()\n * .maybeSingle()\n * .overrideTypes<MyType, { merge: false }>()\n * ```\n *\n * @exampleResponse Complete Override type of object response\n * ```ts\n * let x: typeof data // MyType | null\n * ```\n *\n * @example Partial Override type of successful response\n * ```ts\n * const { data } = await supabase\n * .from('countries')\n * .select()\n * .overrideTypes<Array<{ status: \"A\" | \"B\" }>>()\n * ```\n *\n * @exampleResponse Partial Override type of successful response\n * ```ts\n * let x: typeof data // Array<CountryRowProperties & { status: \"A\" | \"B\" }>\n * ```\n *\n * @example Partial Override type of object response\n * ```ts\n * const { data } = await supabase\n * .from('countries')\n * .select()\n * .maybeSingle()\n * .overrideTypes<{ status: \"A\" | \"B\" }>()\n * ```\n *\n * @exampleResponse Partial Override type of object response\n * ```ts\n * let x: typeof data // CountryRowProperties & { status: \"A\" | \"B\" } | null\n * ```\n *\n * @example Merge vs replace existing types\n * ```typescript\n * // Merge with existing types (default behavior)\n * const query = supabase\n * .from('users')\n * .select()\n * .overrideTypes<{ custom_field: string }>()\n *\n * // Replace existing types completely\n * const replaceQuery = supabase\n * .from('users')\n * .select()\n * .overrideTypes<{ id: number; name: string }, { merge: false }>()\n * ```\n */\n overrideTypes<\n NewResult,\n Options extends { merge?: boolean } = { merge: true },\n >(): PostgrestBuilder<\n ClientOptions,\n IsValidResultOverride<Result, NewResult, false, false> extends true\n ? // Preserve the optionality of the result if the overriden type is an object (case of chaining with `maybeSingle`)\n ContainsNull<Result> extends true\n ? MergePartialResult<NewResult, NonNullable<Result>, Options> | null\n : MergePartialResult<NewResult, Result, Options>\n : CheckMatchingArrayTypes<Result, NewResult>,\n ThrowOnError\n > {\n return this as unknown as PostgrestBuilder<\n ClientOptions,\n IsValidResultOverride<Result, NewResult, false, false> extends true\n ? // Preserve the optionality of the result if the overriden type is an object (case of chaining with `maybeSingle`)\n ContainsNull<Result> extends true\n ? MergePartialResult<NewResult, NonNullable<Result>, Options> | null\n : MergePartialResult<NewResult, Result, Options>\n : CheckMatchingArrayTypes<Result, NewResult>,\n ThrowOnError\n >\n }\n}\n","import PostgrestBuilder from './PostgrestBuilder'\nimport PostgrestFilterBuilder, { InvalidMethodError } from './PostgrestFilterBuilder'\nimport { GetResult } from './select-query-parser/result'\nimport { CheckMatchingArrayTypes } from './types/types'\nimport { ClientServerOptions, GenericSchema } from './types/common/common'\nimport type { MaxAffectedEnabled } from './types/feature-flags'\n\nexport default class PostgrestTransformBuilder<\n ClientOptions extends ClientServerOptions,\n Schema extends GenericSchema,\n Row extends Record<string, unknown>,\n Result,\n RelationName = unknown,\n Relationships = unknown,\n Method = unknown,\n ThrowOnError extends boolean = false,\n> extends PostgrestBuilder<ClientOptions, Result, ThrowOnError> {\n throwOnError(): PostgrestTransformBuilder<\n ClientOptions,\n Schema,\n Row,\n Result,\n RelationName,\n Relationships,\n Method,\n true\n > {\n return super.throwOnError() as PostgrestTransformBuilder<\n ClientOptions,\n Schema,\n Row,\n Result,\n RelationName,\n Relationships,\n Method,\n true\n >\n }\n\n /**\n * Perform a SELECT on the query result.\n *\n * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not\n * return modified rows. By calling this method, modified rows are returned in\n * `data`.\n *\n * @param columns - The columns to retrieve, separated by commas\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `upsert()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .upsert({ id: 1, name: 'Han Solo' })\n * .select()\n * ```\n *\n * @exampleSql With `upsert()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Han');\n * ```\n *\n * @exampleResponse With `upsert()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Han Solo\"\n * }\n * ],\n * \"status\": 201,\n * \"statusText\": \"\"\n * }\n * ```\n */\n select<\n Query extends string = '*',\n NewResultOne = GetResult<Schema, Row, RelationName, Relationships, Query, ClientOptions>,\n >(\n columns?: Query\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Row,\n Method extends 'RPC'\n ? Result extends unknown[]\n ? NewResultOne[]\n : NewResultOne\n : NewResultOne[],\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n > {\n // Remove whitespaces except when quoted\n let quoted = false\n const cleanedColumns = (columns ?? '*')\n .split('')\n .map((c) => {\n if (/\\s/.test(c) && !quoted) {\n return ''\n }\n if (c === '\"') {\n quoted = !quoted\n }\n return c\n })\n .join('')\n this.url.searchParams.set('select', cleanedColumns)\n this.headers.append('Prefer', 'return=representation')\n return this as unknown as PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Row,\n Method extends 'RPC'\n ? Result extends unknown[]\n ? NewResultOne[]\n : NewResultOne\n : NewResultOne[],\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n >\n }\n\n /**\n * Order the query result by `column`.\n *\n * You can call this method multiple times to order by multiple columns.\n *\n * You can order referenced tables, but it only affects the ordering of the\n * parent table if you use `!inner` in the query.\n *\n * @param column - The column to order by\n * @param options - Named parameters\n * @param options.ascending - If `true`, the result will be in ascending order\n * @param options.nullsFirst - If `true`, `null`s appear first. If `false`,\n * `null`s appear last.\n * @param options.referencedTable - Set this to order a referenced table by\n * its columns\n *\n * @category Database\n * @subcategory Using modifiers\n */\n order<ColumnName extends string & keyof Row>(\n column: ColumnName,\n options?: { ascending?: boolean; nullsFirst?: boolean; referencedTable?: undefined }\n ): this\n order(\n column: string,\n options?: { ascending?: boolean; nullsFirst?: boolean; referencedTable?: string }\n ): this\n /**\n * @deprecated Use `options.referencedTable` instead of `options.foreignTable`\n */\n order<ColumnName extends string & keyof Row>(\n column: ColumnName,\n options?: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: undefined }\n ): this\n /**\n * @deprecated Use `options.referencedTable` instead of `options.foreignTable`\n */\n order(\n column: string,\n options?: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: string }\n ): this\n /**\n * Order the query result by `column`.\n *\n * You can call this method multiple times to order by multiple columns.\n *\n * You can order referenced tables, but it only affects the ordering of the\n * parent table if you use `!inner` in the query.\n *\n * @param column - The column to order by\n * @param options - Named parameters\n * @param options.ascending - If `true`, the result will be in ascending order\n * @param options.nullsFirst - If `true`, `null`s appear first. If `false`,\n * `null`s appear last.\n * @param options.referencedTable - Set this to order a referenced table by\n * its columns\n * @param options.foreignTable - Deprecated, use `options.referencedTable`\n * instead\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('id, name')\n * .order('id', { ascending: false })\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 3,\n * \"name\": \"Han\"\n * },\n * {\n * \"id\": 2,\n * \"name\": \"Leia\"\n * },\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription On a referenced table\n * Ordering with `referencedTable` doesn't affect the ordering of the\n * parent table.\n *\n * @example On a referenced table\n * ```ts\n * const { data, error } = await supabase\n * .from('orchestral_sections')\n * .select(`\n * name,\n * instruments (\n * name\n * )\n * `)\n * .order('name', { referencedTable: 'instruments', ascending: false })\n *\n * ```\n *\n * @exampleSql On a referenced table\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 1, 'harp'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse On a referenced table\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"strings\",\n * \"instruments\": [\n * {\n * \"name\": \"violin\"\n * },\n * {\n * \"name\": \"harp\"\n * }\n * ]\n * },\n * {\n * \"name\": \"woodwinds\",\n * \"instruments\": []\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Order parent table by a referenced table\n * Ordering with `referenced_table(col)` affects the ordering of the\n * parent table.\n *\n * @example Order parent table by a referenced table\n * ```ts\n * const { data, error } = await supabase\n * .from('instruments')\n * .select(`\n * name,\n * section:orchestral_sections (\n * name\n * )\n * `)\n * .order('section(name)', { ascending: true })\n *\n * ```\n *\n * @exampleSql Order parent table by a referenced table\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 2, 'flute'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse Order parent table by a referenced table\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"violin\",\n * \"orchestral_sections\": {\"name\": \"strings\"}\n * },\n * {\n * \"name\": \"flute\",\n * \"orchestral_sections\": {\"name\": \"woodwinds\"}\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n order(\n column: string,\n {\n ascending = true,\n nullsFirst,\n foreignTable,\n referencedTable = foreignTable,\n }: {\n ascending?: boolean\n nullsFirst?: boolean\n foreignTable?: string\n referencedTable?: string\n } = {}\n ): this {\n const key = referencedTable ? `${referencedTable}.order` : 'order'\n const existingOrder = this.url.searchParams.get(key)\n\n this.url.searchParams.set(\n key,\n `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${\n nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'\n }`\n )\n return this\n }\n\n /**\n * Limit the query result by `rows`.\n *\n * @param rows - The maximum number of rows to return\n * @param options - Named parameters\n * @param options.referencedTable - Set this to limit rows of referenced\n * tables instead of the parent table\n * @param options.foreignTable - Deprecated, use `options.referencedTable`\n * instead\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * .limit(1)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Luke\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example On a referenced table\n * ```ts\n * const { data, error } = await supabase\n * .from('orchestral_sections')\n * .select(`\n * name,\n * instruments (\n * name\n * )\n * `)\n * .limit(1, { referencedTable: 'instruments' })\n * ```\n *\n * @exampleSql On a referenced table\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 1, 'harp'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse On a referenced table\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"strings\",\n * \"instruments\": [\n * {\n * \"name\": \"violin\"\n * }\n * ]\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n limit(\n rows: number,\n {\n foreignTable,\n referencedTable = foreignTable,\n }: { foreignTable?: string; referencedTable?: string } = {}\n ): this {\n const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`\n this.url.searchParams.set(key, `${rows}`)\n return this\n }\n\n /**\n * Limit the query result by starting at an offset `from` and ending at the offset `to`.\n * Only records within this range are returned.\n * This respects the query order and if there is no order clause the range could behave unexpectedly.\n * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third\n * and fourth rows of the query.\n *\n * @param from - The starting index from which to limit the result\n * @param to - The last index to which to limit the result\n * @param options - Named parameters\n * @param options.referencedTable - Set this to limit rows of referenced\n * tables instead of the parent table\n * @param options.foreignTable - Deprecated, use `options.referencedTable`\n * instead\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * .range(0, 1)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Luke\"\n * },\n * {\n * \"name\": \"Leia\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n range(\n from: number,\n to: number,\n {\n foreignTable,\n referencedTable = foreignTable,\n }: { foreignTable?: string; referencedTable?: string } = {}\n ): this {\n const keyOffset =\n typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset`\n const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`\n this.url.searchParams.set(keyOffset, `${from}`)\n // Range is inclusive, so add 1\n this.url.searchParams.set(keyLimit, `${to - from + 1}`)\n return this\n }\n\n /**\n * Set the AbortSignal for the fetch request.\n *\n * @param signal - The AbortSignal to use for the fetch request\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @remarks\n * You can use this to set a timeout for the request.\n *\n * @exampleDescription Aborting requests in-flight\n * You can use an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to abort requests.\n * Note that `status` and `statusText` don't mean anything for aborted requests as the request wasn't fulfilled.\n *\n * @example Aborting requests in-flight\n * ```ts\n * const ac = new AbortController()\n *\n * const { data, error } = await supabase\n * .from('very_big_table')\n * .select()\n * .abortSignal(ac.signal)\n *\n * // Abort the request after 100 ms\n * setTimeout(() => ac.abort(), 100)\n * ```\n *\n * @exampleResponse Aborting requests in-flight\n * ```json\n * {\n * \"error\": {\n * \"message\": \"AbortError: The user aborted a request.\",\n * \"details\": \"\",\n * \"hint\": \"The request was aborted locally via the provided AbortSignal.\",\n * \"code\": \"\"\n * },\n * \"status\": 0,\n * \"statusText\": \"\"\n * }\n *\n * ```\n *\n * @example Set a timeout\n * ```ts\n * const { data, error } = await supabase\n * .from('very_big_table')\n * .select()\n * .abortSignal(AbortSignal.timeout(1000 /* ms *\\/))\n * ```\n *\n * @exampleResponse Set a timeout\n * ```json\n * {\n * \"error\": {\n * \"message\": \"FetchError: The user aborted a request.\",\n * \"details\": \"\",\n * \"hint\": \"\",\n * \"code\": \"\"\n * },\n * \"status\": 0,\n * \"statusText\": \"\"\n * }\n *\n * ```\n */\n abortSignal(signal: AbortSignal): this {\n this.signal = signal\n return this\n }\n\n /**\n * Return `data` as a single object instead of an array of objects.\n *\n * Query result must be one row (e.g. using `.limit(1)`), otherwise this\n * returns an error.\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * .limit(1)\n * .single()\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": {\n * \"name\": \"Luke\"\n * },\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n single<ResultOne = Result extends (infer ResultOne)[] ? ResultOne : never>(): PostgrestBuilder<\n ClientOptions,\n ResultOne,\n ThrowOnError\n > {\n this.headers.set('Accept', 'application/vnd.pgrst.object+json')\n return this as unknown as PostgrestBuilder<ClientOptions, ResultOne, ThrowOnError>\n }\n\n /**\n * Return `data` as a single object instead of an array of objects.\n *\n * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise\n * this returns an error.\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .eq('name', 'Katniss')\n * .maybeSingle()\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n maybeSingle<\n ResultOne = Result extends (infer ResultOne)[] ? ResultOne : never,\n >(): PostgrestBuilder<ClientOptions, ResultOne | null, ThrowOnError> {\n // No Accept header override — we fetch as a list and enforce cardinality client-side.\n // Fixes https://github.com/supabase/postgrest-js/issues/361 for all request methods.\n this.isMaybeSingle = true\n return this as unknown as PostgrestBuilder<ClientOptions, ResultOne | null, ThrowOnError>\n }\n\n /**\n * Return `data` as a string in CSV format.\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @exampleDescription Return data as CSV\n * By default, the data is returned in JSON format, but can also be returned as Comma Separated Values.\n *\n * @example Return data as CSV\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .csv()\n * ```\n *\n * @exampleSql Return data as CSV\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse Return data as CSV\n * ```json\n * {\n * \"data\": \"id,name\\n1,Luke\\n2,Leia\\n3,Han\",\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n csv(): PostgrestBuilder<ClientOptions, string, ThrowOnError> {\n this.headers.set('Accept', 'text/csv')\n return this as unknown as PostgrestBuilder<ClientOptions, string, ThrowOnError>\n }\n\n /**\n * Return `data` as an object in [GeoJSON](https://geojson.org) format.\n *\n * @category Database\n * @subcategory Using modifiers\n */\n geojson(): PostgrestBuilder<ClientOptions, Record<string, unknown>, ThrowOnError> {\n this.headers.set('Accept', 'application/geo+json')\n return this as unknown as PostgrestBuilder<ClientOptions, Record<string, unknown>, ThrowOnError>\n }\n\n /**\n * Return `data` as the EXPLAIN plan for the query.\n *\n * You need to enable the\n * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain)\n * setting before using this method.\n *\n * @param options - Named parameters\n *\n * @param options.analyze - If `true`, the query will be executed and the\n * actual run time will be returned\n *\n * @param options.verbose - If `true`, the query identifier will be returned\n * and `data` will include the output columns of the query\n *\n * @param options.settings - If `true`, include information on configuration\n * parameters that affect query planning\n *\n * @param options.buffers - If `true`, include information on buffer usage\n *\n * @param options.wal - If `true`, include information on WAL record generation\n *\n * @param options.format - The format of the output, can be `\"text\"` (default)\n * or `\"json\"`\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @exampleDescription Get the execution plan\n * By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter.\n *\n * @example Get the execution plan\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .explain()\n * ```\n *\n * @exampleSql Get the execution plan\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse Get the execution plan\n * ```js\n * Aggregate (cost=33.34..33.36 rows=1 width=112)\n * -> Limit (cost=0.00..18.33 rows=1000 width=40)\n * -> Seq Scan on characters (cost=0.00..22.00 rows=1200 width=40)\n * ```\n *\n * @exampleDescription Get the execution plan with analyze and verbose\n * By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter.\n *\n * @example Get the execution plan with analyze and verbose\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .explain({analyze:true,verbose:true})\n * ```\n *\n * @exampleSql Get the execution plan with analyze and verbose\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse Get the execution plan with analyze and verbose\n * ```js\n * Aggregate (cost=33.34..33.36 rows=1 width=112) (actual time=0.041..0.041 rows=1 loops=1)\n * Output: NULL::bigint, count(ROW(characters.id, characters.name)), COALESCE(json_agg(ROW(characters.id, characters.name)), '[]'::json), NULLIF(current_setting('response.headers'::text, true), ''::text), NULLIF(current_setting('response.status'::text, true), ''::text)\n * -> Limit (cost=0.00..18.33 rows=1000 width=40) (actual time=0.005..0.006 rows=3 loops=1)\n * Output: characters.id, characters.name\n * -> Seq Scan on public.characters (cost=0.00..22.00 rows=1200 width=40) (actual time=0.004..0.005 rows=3 loops=1)\n * Output: characters.id, characters.name\n * Query Identifier: -4730654291623321173\n * Planning Time: 0.407 ms\n * Execution Time: 0.119 ms\n * ```\n */\n explain({\n analyze = false,\n verbose = false,\n settings = false,\n buffers = false,\n wal = false,\n format = 'text',\n }: {\n analyze?: boolean\n verbose?: boolean\n settings?: boolean\n buffers?: boolean\n wal?: boolean\n format?: 'json' | 'text'\n } = {}) {\n const options = [\n analyze ? 'analyze' : null,\n verbose ? 'verbose' : null,\n settings ? 'settings' : null,\n buffers ? 'buffers' : null,\n wal ? 'wal' : null,\n ]\n .filter(Boolean)\n .join('|')\n // An Accept header can carry multiple media types but postgrest-js always sends one\n const forMediatype = this.headers.get('Accept') ?? 'application/json'\n this.headers.set(\n 'Accept',\n `application/vnd.pgrst.plan+${format}; for=\"${forMediatype}\"; options=${options};`\n )\n if (format === 'json') {\n return this as unknown as PostgrestBuilder<\n ClientOptions,\n Record<string, unknown>[],\n ThrowOnError\n >\n } else {\n return this as unknown as PostgrestBuilder<ClientOptions, string, ThrowOnError>\n }\n }\n\n /**\n * Dry-run this request: execute the query but discard the changes.\n *\n * Server-side, PostgREST runs the query inside a transaction and rolls it back\n * instead of committing. The response still contains the data that *would* have\n * been returned — `RETURNING` clauses execute and RLS, triggers, and constraints\n * are all evaluated — but no row is actually inserted, updated, or deleted.\n *\n * This affects only the single request it is chained to. The JS caller has no\n * handle on the transaction: supabase-js does not group multiple queries into\n * one transaction. For multi-statement transactional logic, use a database\n * function (`supabase.rpc(...)`).\n *\n * Sets the `Prefer: tx=rollback` header. See PostgREST's docs on transaction\n * preferences for the underlying mechanism.\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example Validate an insert without persisting\n * ```ts\n * const { data, error } = await supabase\n * .from('countries')\n * .insert({ name: 'France' })\n * .select()\n * .rollback()\n * // `data` shows what would have been inserted; nothing is saved.\n * ```\n */\n rollback(): this {\n this.headers.append('Prefer', 'tx=rollback')\n return this\n }\n\n /**\n * Override the type of the returned `data`.\n *\n * @typeParam NewResult - The new result type to override with\n * @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @remarks\n * - Deprecated: use overrideTypes method instead\n *\n * @example Override type of successful response\n * ```ts\n * const { data } = await supabase\n * .from('countries')\n * .select()\n * .returns<Array<MyType>>()\n * ```\n *\n * @exampleResponse Override type of successful response\n * ```js\n * let x: typeof data // MyType[]\n * ```\n *\n * @example Override type of object response\n * ```ts\n * const { data } = await supabase\n * .from('countries')\n * .select()\n * .maybeSingle()\n * .returns<MyType>()\n * ```\n *\n * @exampleResponse Override type of object response\n * ```js\n * let x: typeof data // MyType | null\n * ```\n */\n returns<NewResult>(): PostgrestTransformBuilder<\n ClientOptions,\n Schema,\n Row,\n CheckMatchingArrayTypes<Result, NewResult>,\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n > {\n return this as unknown as PostgrestTransformBuilder<\n ClientOptions,\n Schema,\n Row,\n CheckMatchingArrayTypes<Result, NewResult>,\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n >\n }\n\n /**\n * Set the maximum number of rows that can be affected by the query.\n * Only available in PostgREST v13+ and only works with PATCH and DELETE methods.\n *\n * @param rows - The maximum number of rows that can be affected\n *\n * @category Database\n * @subcategory Using modifiers\n */\n maxAffected(rows: number): MaxAffectedEnabled<ClientOptions['PostgrestVersion']> extends true\n ? // TODO: update the RPC case to only work on RPC that returns SETOF rows\n Method extends 'PATCH' | 'DELETE' | 'RPC'\n ? this\n : InvalidMethodError<'maxAffected method only available on update or delete'>\n : InvalidMethodError<'maxAffected method only available on postgrest 13+'> {\n this.headers.append('Prefer', 'handling=strict')\n this.headers.append('Prefer', `max-affected=${rows}`)\n return this as unknown as MaxAffectedEnabled<ClientOptions['PostgrestVersion']> extends true\n ? Method extends 'PATCH' | 'DELETE' | 'RPC'\n ? this\n : InvalidMethodError<'maxAffected method only available on update or delete'>\n : InvalidMethodError<'maxAffected method only available on postgrest 13+'>\n }\n}\n","import PostgrestTransformBuilder from './PostgrestTransformBuilder'\nimport { JsonPathToAccessor, JsonPathToType } from './select-query-parser/utils'\nimport { ClientServerOptions, GenericSchema } from './types/common/common'\n\ntype FilterOperator =\n | 'eq'\n | 'neq'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'like'\n | 'ilike'\n | 'is'\n | 'isdistinct'\n | 'in'\n | 'cs'\n | 'cd'\n | 'sl'\n | 'sr'\n | 'nxl'\n | 'nxr'\n | 'adj'\n | 'ov'\n | 'fts'\n | 'plfts'\n | 'phfts'\n | 'wfts'\n | 'match'\n | 'imatch'\n\nexport type IsStringOperator<Path extends string> = Path extends `${string}->>${string}`\n ? true\n : false\n\nconst PostgrestReservedCharsRegexp = new RegExp('[,()]')\n\n// Match relationship filters with `table.column` syntax and resolve underlying\n// column value. If not matched, fallback to generic type.\n// TODO: Validate the relationship itself ala select-query-parser. Currently we\n// assume that all tables have valid relationships to each other, despite\n// nonexistent foreign keys.\ntype ResolveFilterValue<\n Schema extends GenericSchema,\n Row extends Record<string, unknown>,\n ColumnName extends string,\n> = ColumnName extends `${infer RelationshipTable}.${infer Remainder}`\n ? Remainder extends `${infer _}.${infer _}`\n ? ResolveFilterValue<Schema, Row, Remainder>\n : ResolveFilterRelationshipValue<Schema, RelationshipTable, Remainder>\n : ColumnName extends keyof Row\n ? Row[ColumnName]\n : // If the column selection is a jsonpath like `data->value` or `data->>value` we attempt to match\n // the expected type with the parsed custom json type\n IsStringOperator<ColumnName> extends true\n ? string\n : JsonPathToType<Row, JsonPathToAccessor<ColumnName>> extends infer JsonPathValue\n ? JsonPathValue extends never\n ? never\n : JsonPathValue\n : never\n\ntype ResolveFilterRelationshipValue<\n Schema extends GenericSchema,\n RelationshipTable extends string,\n RelationshipColumn extends string,\n> = Schema['Tables'] & Schema['Views'] extends infer TablesAndViews\n ? RelationshipTable extends keyof TablesAndViews\n ? 'Row' extends keyof TablesAndViews[RelationshipTable]\n ? RelationshipColumn extends keyof TablesAndViews[RelationshipTable]['Row']\n ? TablesAndViews[RelationshipTable]['Row'][RelationshipColumn]\n : unknown\n : unknown\n : unknown\n : never\n\nexport type InvalidMethodError<S extends string> = { Error: S }\n\ntype NonNullableColumn<T extends Record<string, unknown>, Col extends string> = Col extends keyof T\n ? { [K in keyof T]: K extends Col ? NonNullable<T[K]> : T[K] }\n : T\n\ntype NarrowResultColumn<T, Col extends string> = T extends (infer Item)[]\n ? Item extends Record<string, unknown>\n ? Col extends keyof Item\n ? { [K in keyof Item]: K extends Col ? NonNullable<Item[K]> : Item[K] }[]\n : T\n : T\n : T extends Record<string, unknown>\n ? Col extends keyof T\n ? { [K in keyof T]: K extends Col ? NonNullable<T[K]> : T[K] }\n : T\n : T\n\nexport default class PostgrestFilterBuilder<\n ClientOptions extends ClientServerOptions,\n Schema extends GenericSchema,\n Row extends Record<string, unknown>,\n Result,\n RelationName = unknown,\n Relationships = unknown,\n Method = unknown,\n ThrowOnError extends boolean = false,\n> extends PostgrestTransformBuilder<\n ClientOptions,\n Schema,\n Row,\n Result,\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n> {\n throwOnError(): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Row,\n Result,\n RelationName,\n Relationships,\n Method,\n true\n > {\n return super.throwOnError() as PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Row,\n Result,\n RelationName,\n Relationships,\n Method,\n true\n >\n }\n\n /**\n * Match only rows where `column` is equal to `value`.\n *\n * To check if the value of `column` is NULL, you should use `.is()` instead.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .eq('name', 'Leia')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 2,\n * \"name\": \"Leia\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n eq<ColumnName extends string>(\n column: ColumnName extends keyof Row\n ? ColumnName\n : ColumnName extends `${string}.${string}` | `${string}->${string}`\n ? ColumnName\n : string extends ColumnName\n ? string\n : keyof Row,\n value: ResolveFilterValue<Schema, Row, ColumnName> extends never\n ? NonNullable<unknown>\n : ResolveFilterValue<Schema, Row, ColumnName> extends infer ResolvedFilterValue\n ? NonNullable<ResolvedFilterValue>\n : never\n ): this {\n this.url.searchParams.append(column as string, `eq.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` is not equal to `value`.\n *\n * This filter does not include rows where `column` is `NULL`. To match null\n * values, use `.is(column, null)` instead.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .neq('name', 'Leia')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * },\n * {\n * \"id\": 3,\n * \"name\": \"Han\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n neq<ColumnName extends string>(\n column: ColumnName extends keyof Row\n ? ColumnName\n : ColumnName extends `${string}.${string}` | `${string}->${string}`\n ? ColumnName\n : string extends ColumnName\n ? string\n : keyof Row,\n value: ResolveFilterValue<Schema, Row, ColumnName> extends never\n ? unknown\n : ResolveFilterValue<Schema, Row, ColumnName> extends infer Resolved\n ? Resolved\n : never\n ): this {\n this.url.searchParams.append(column as string, `neq.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` is greater than `value`.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription With `select()`\n * When using [reserved words](https://www.postgresql.org/docs/current/sql-keywords-appendix.html) for column names you need\n * to add double quotes e.g. `.gt('\"order\"', 2)`\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .gt('id', 2)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 3,\n * \"name\": \"Han\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n gt<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n gt(column: string, value: unknown): this\n gt(column: string, value: unknown): this {\n this.url.searchParams.append(column, `gt.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` is greater than or equal to `value`.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .gte('id', 2)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 2,\n * \"name\": \"Leia\"\n * },\n * {\n * \"id\": 3,\n * \"name\": \"Han\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n gte<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n gte(column: string, value: unknown): this\n gte(column: string, value: unknown): this {\n this.url.searchParams.append(column, `gte.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` is less than `value`.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .lt('id', 2)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n lt<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n lt(column: string, value: unknown): this\n lt(column: string, value: unknown): this {\n this.url.searchParams.append(column, `lt.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` is less than or equal to `value`.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .lte('id', 2)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * },\n * {\n * \"id\": 2,\n * \"name\": \"Leia\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n lte<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n lte(column: string, value: unknown): this\n lte(column: string, value: unknown): this {\n this.url.searchParams.append(column, `lte.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches `pattern` case-sensitively.\n *\n * @param column - The column to filter on\n * @param pattern - The pattern to match with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .like('name', '%Lu%')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n like<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n like(column: string, pattern: string): this\n like(column: string, pattern: string): this {\n this.url.searchParams.append(column, `like.${pattern}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches all of `patterns` case-sensitively.\n *\n * @param column - The column to filter on\n * @param patterns - The patterns to match with\n *\n * @category Database\n * @subcategory Using filters\n */\n likeAllOf<ColumnName extends string & keyof Row>(\n column: ColumnName,\n patterns: readonly string[]\n ): this\n likeAllOf(column: string, patterns: readonly string[]): this\n likeAllOf(column: string, patterns: readonly string[]): this {\n this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches any of `patterns` case-sensitively.\n *\n * @param column - The column to filter on\n * @param patterns - The patterns to match with\n *\n * @category Database\n * @subcategory Using filters\n */\n likeAnyOf<ColumnName extends string & keyof Row>(\n column: ColumnName,\n patterns: readonly string[]\n ): this\n likeAnyOf(column: string, patterns: readonly string[]): this\n likeAnyOf(column: string, patterns: readonly string[]): this {\n this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches `pattern` case-insensitively.\n *\n * @param column - The column to filter on\n * @param pattern - The pattern to match with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .ilike('name', '%lu%')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n ilike<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n ilike(column: string, pattern: string): this\n ilike(column: string, pattern: string): this {\n this.url.searchParams.append(column, `ilike.${pattern}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches all of `patterns` case-insensitively.\n *\n * @param column - The column to filter on\n * @param patterns - The patterns to match with\n *\n * @category Database\n * @subcategory Using filters\n */\n ilikeAllOf<ColumnName extends string & keyof Row>(\n column: ColumnName,\n patterns: readonly string[]\n ): this\n ilikeAllOf(column: string, patterns: readonly string[]): this\n ilikeAllOf(column: string, patterns: readonly string[]): this {\n this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches any of `patterns` case-insensitively.\n *\n * @param column - The column to filter on\n * @param patterns - The patterns to match with\n *\n * @category Database\n * @subcategory Using filters\n */\n ilikeAnyOf<ColumnName extends string & keyof Row>(\n column: ColumnName,\n patterns: readonly string[]\n ): this\n ilikeAnyOf(column: string, patterns: readonly string[]): this\n ilikeAnyOf(column: string, patterns: readonly string[]): this {\n this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches the PostgreSQL regex `pattern`\n * case-sensitively (using the `~` operator).\n *\n * @param column - The column to filter on\n * @param pattern - The PostgreSQL regular expression pattern to match with\n */\n regexMatch<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n regexMatch(column: string, pattern: string): this\n regexMatch(column: string, pattern: string): this {\n this.url.searchParams.append(column, `match.${pattern}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches the PostgreSQL regex `pattern`\n * case-insensitively (using the `~*` operator).\n *\n * @param column - The column to filter on\n * @param pattern - The PostgreSQL regular expression pattern to match with\n */\n regexIMatch<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n regexIMatch(column: string, pattern: string): this\n regexIMatch(column: string, pattern: string): this {\n this.url.searchParams.append(column, `imatch.${pattern}`)\n return this\n }\n\n /**\n * Match only rows where `column` IS `value`.\n *\n * For non-boolean columns, this is only relevant for checking if the value of\n * `column` is NULL by setting `value` to `null`.\n *\n * For boolean columns, you can also set `value` to `true` or `false` and it\n * will behave the same way as `.eq()`.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription Checking for nullness, true or false\n * Using the `eq()` filter doesn't work when filtering for `null`.\n *\n * Instead, you need to use `is()`.\n *\n * @example Checking for nullness, true or false\n * ```ts\n * const { data, error } = await supabase\n * .from('countries')\n * .select()\n * .is('name', null)\n * ```\n *\n * @exampleSql Checking for nullness, true or false\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n *\n * insert into\n * countries (id, name)\n * values\n * (1, 'null'),\n * (2, null);\n * ```\n *\n * @exampleResponse Checking for nullness, true or false\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 2,\n * \"name\": \"null\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n is<ColumnName extends string & keyof Row>(\n column: ColumnName,\n value: Row[ColumnName] & (boolean | null)\n ): this\n is(column: string, value: boolean | null): this\n is(column: string, value: boolean | null): this {\n this.url.searchParams.append(column, `is.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` IS DISTINCT FROM `value`.\n *\n * Unlike `.neq()`, this treats `NULL` as a comparable value. Two `NULL` values\n * are considered equal (not distinct), and comparing `NULL` with any non-NULL\n * value returns true (distinct).\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n */\n isDistinct<ColumnName extends string>(\n column: ColumnName,\n value: ResolveFilterValue<Schema, Row, ColumnName> extends never\n ? unknown\n : ResolveFilterValue<Schema, Row, ColumnName> extends infer ResolvedFilterValue\n ? ResolvedFilterValue\n : never\n ): this {\n this.url.searchParams.append(column, `isdistinct.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` is included in the `values` array.\n *\n * @param column - The column to filter on\n * @param values - The values array to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .in('name', ['Leia', 'Han'])\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 2,\n * \"name\": \"Leia\"\n * },\n * {\n * \"id\": 3,\n * \"name\": \"Han\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n in<ColumnName extends string>(\n column: ColumnName,\n values: ReadonlyArray<\n ResolveFilterValue<Schema, Row, ColumnName> extends never\n ? unknown\n : // We want to infer the type before wrapping it into a `NonNullable` to avoid too deep\n // type resolution error\n ResolveFilterValue<Schema, Row, ColumnName> extends infer ResolvedFilterValue\n ? ResolvedFilterValue\n : // We should never enter this case as all the branches are covered above\n never\n >\n ): this {\n const cleanedValues = Array.from(new Set(values))\n .map((s) => {\n // handle postgrest reserved characters\n // https://postgrest.org/en/v7.0.0/api.html#reserved-characters\n if (typeof s === 'string' && PostgrestReservedCharsRegexp.test(s)) return `\"${s}\"`\n else return `${s}`\n })\n .join(',')\n this.url.searchParams.append(column, `in.(${cleanedValues})`)\n return this\n }\n\n /**\n * Match only rows where `column` is NOT included in the `values` array.\n *\n * @param column - The column to filter on\n * @param values - The values array to filter with\n */\n notIn<ColumnName extends string>(\n column: ColumnName,\n values: ReadonlyArray<\n ResolveFilterValue<Schema, Row, ColumnName> extends never\n ? unknown\n : ResolveFilterValue<Schema, Row, ColumnName> extends infer ResolvedFilterValue\n ? ResolvedFilterValue\n : never\n >\n ): this {\n const cleanedValues = Array.from(new Set(values))\n .map((s) => {\n // handle postgrest reserved characters\n // https://postgrest.org/en/v7.0.0/api.html#reserved-characters\n if (typeof s === 'string' && PostgrestReservedCharsRegexp.test(s)) return `\"${s}\"`\n else return `${s}`\n })\n .join(',')\n this.url.searchParams.append(column, `not.in.(${cleanedValues})`)\n return this\n }\n\n /**\n * Only relevant for jsonb, array, and range columns. Match only rows where\n * `column` contains every element appearing in `value`.\n *\n * @param column - The jsonb, array, or range column to filter on\n * @param value - The jsonb, array, or range value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example On array columns\n * ```ts\n * const { data, error } = await supabase\n * .from('issues')\n * .select()\n * .contains('tags', ['is:open', 'priority:low'])\n * ```\n *\n * @exampleSql On array columns\n * ```sql\n * create table\n * issues (\n * id int8 primary key,\n * title text,\n * tags text[]\n * );\n *\n * insert into\n * issues (id, title, tags)\n * values\n * (1, 'Cache invalidation is not working', array['is:open', 'severity:high', 'priority:low']),\n * (2, 'Use better names', array['is:open', 'severity:low', 'priority:medium']);\n * ```\n *\n * @exampleResponse On array columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"title\": \"Cache invalidation is not working\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription On range columns\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example On range columns\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .contains('during', '[2000-01-01 13:00, 2000-01-01 13:30)')\n * ```\n *\n * @exampleSql On range columns\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse On range columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"room_name\": \"Emerald\",\n * \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example On `jsonb` columns\n * ```ts\n * const { data, error } = await supabase\n * .from('users')\n * .select('name')\n * .contains('address', { postcode: 90210 })\n * ```\n *\n * @exampleSql On `jsonb` columns\n * ```sql\n * create table\n * users (\n * id int8 primary key,\n * name text,\n * address jsonb\n * );\n *\n * insert into\n * users (id, name, address)\n * values\n * (1, 'Michael', '{ \"postcode\": 90210, \"street\": \"Melrose Place\" }'),\n * (2, 'Jane', '{}');\n * ```\n *\n * @exampleResponse On `jsonb` columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Michael\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n contains<ColumnName extends string & keyof Row>(\n column: ColumnName,\n value: string | ReadonlyArray<Row[ColumnName]> | Record<string, unknown>\n ): this\n contains(column: string, value: string | readonly unknown[] | Record<string, unknown>): this\n contains(column: string, value: string | readonly unknown[] | Record<string, unknown>): this {\n if (typeof value === 'string') {\n // range types can be inclusive '[', ']' or exclusive '(', ')' so just\n // keep it simple and accept a string\n this.url.searchParams.append(column, `cs.${value}`)\n } else if (Array.isArray(value)) {\n // array\n this.url.searchParams.append(column, `cs.{${value.join(',')}}`)\n } else {\n // json\n this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`)\n }\n return this\n }\n\n /**\n * Only relevant for jsonb, array, and range columns. Match only rows where\n * every element appearing in `column` is contained by `value`.\n *\n * @param column - The jsonb, array, or range column to filter on\n * @param value - The jsonb, array, or range value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example On array columns\n * ```ts\n * const { data, error } = await supabase\n * .from('classes')\n * .select('name')\n * .containedBy('days', ['monday', 'tuesday', 'wednesday', 'friday'])\n * ```\n *\n * @exampleSql On array columns\n * ```sql\n * create table\n * classes (\n * id int8 primary key,\n * name text,\n * days text[]\n * );\n *\n * insert into\n * classes (id, name, days)\n * values\n * (1, 'Chemistry', array['monday', 'friday']),\n * (2, 'History', array['monday', 'wednesday', 'thursday']);\n * ```\n *\n * @exampleResponse On array columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Chemistry\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription On range columns\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example On range columns\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .containedBy('during', '[2000-01-01 00:00, 2000-01-01 23:59)')\n * ```\n *\n * @exampleSql On range columns\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse On range columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"room_name\": \"Emerald\",\n * \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example On `jsonb` columns\n * ```ts\n * const { data, error } = await supabase\n * .from('users')\n * .select('name')\n * .containedBy('address', {})\n * ```\n *\n * @exampleSql On `jsonb` columns\n * ```sql\n * create table\n * users (\n * id int8 primary key,\n * name text,\n * address jsonb\n * );\n *\n * insert into\n * users (id, name, address)\n * values\n * (1, 'Michael', '{ \"postcode\": 90210, \"street\": \"Melrose Place\" }'),\n * (2, 'Jane', '{}');\n * ```\n *\n * @exampleResponse On `jsonb` columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Jane\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n *\n * ```\n */\n containedBy<ColumnName extends string & keyof Row>(\n column: ColumnName,\n value: string | ReadonlyArray<Row[ColumnName]> | Record<string, unknown>\n ): this\n containedBy(column: string, value: string | readonly unknown[] | Record<string, unknown>): this\n containedBy(column: string, value: string | readonly unknown[] | Record<string, unknown>): this {\n if (typeof value === 'string') {\n // range\n this.url.searchParams.append(column, `cd.${value}`)\n } else if (Array.isArray(value)) {\n // array\n this.url.searchParams.append(column, `cd.{${value.join(',')}}`)\n } else {\n // json\n this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`)\n }\n return this\n }\n\n /**\n * Only relevant for range columns. Match only rows where every element in\n * `column` is greater than any element in `range`.\n *\n * @param column - The range column to filter on\n * @param range - The range to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription With `select()`\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .rangeGt('during', '[2000-01-02 08:00, 2000-01-02 09:00)')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 2,\n * \"room_name\": \"Topaz\",\n * \"during\": \"[\\\"2000-01-02 09:00:00\\\",\\\"2000-01-02 10:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n *\n * ```\n */\n rangeGt<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeGt(column: string, range: string): this\n rangeGt(column: string, range: string): this {\n this.url.searchParams.append(column, `sr.${range}`)\n return this\n }\n\n /**\n * Only relevant for range columns. Match only rows where every element in\n * `column` is either contained in `range` or greater than any element in\n * `range`.\n *\n * @param column - The range column to filter on\n * @param range - The range to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription With `select()`\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .rangeGte('during', '[2000-01-02 08:30, 2000-01-02 09:30)')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 2,\n * \"room_name\": \"Topaz\",\n * \"during\": \"[\\\"2000-01-02 09:00:00\\\",\\\"2000-01-02 10:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n *\n * ```\n */\n rangeGte<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeGte(column: string, range: string): this\n rangeGte(column: string, range: string): this {\n this.url.searchParams.append(column, `nxl.${range}`)\n return this\n }\n\n /**\n * Only relevant for range columns. Match only rows where every element in\n * `column` is less than any element in `range`.\n *\n * @param column - The range column to filter on\n * @param range - The range to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription With `select()`\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .rangeLt('during', '[2000-01-01 15:00, 2000-01-01 16:00)')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"room_name\": \"Emerald\",\n * \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n rangeLt<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeLt(column: string, range: string): this\n rangeLt(column: string, range: string): this {\n this.url.searchParams.append(column, `sl.${range}`)\n return this\n }\n\n /**\n * Only relevant for range columns. Match only rows where every element in\n * `column` is either contained in `range` or less than any element in\n * `range`.\n *\n * @param column - The range column to filter on\n * @param range - The range to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription With `select()`\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .rangeLte('during', '[2000-01-01 14:00, 2000-01-01 16:00)')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"room_name\": \"Emerald\",\n * \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n *\n * ```\n */\n rangeLte<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeLte(column: string, range: string): this\n rangeLte(column: string, range: string): this {\n this.url.searchParams.append(column, `nxr.${range}`)\n return this\n }\n\n /**\n * Only relevant for range columns. Match only rows where `column` is\n * mutually exclusive to `range` and there can be no element between the two\n * ranges.\n *\n * @param column - The range column to filter on\n * @param range - The range to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription With `select()`\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .rangeAdjacent('during', '[2000-01-01 12:00, 2000-01-01 13:00)')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"room_name\": \"Emerald\",\n * \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n rangeAdjacent<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeAdjacent(column: string, range: string): this\n rangeAdjacent(column: string, range: string): this {\n this.url.searchParams.append(column, `adj.${range}`)\n return this\n }\n\n /**\n * Only relevant for array and range columns. Match only rows where\n * `column` and `value` have an element in common.\n *\n * @param column - The array or range column to filter on\n * @param value - The array or range value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example On array columns\n * ```ts\n * const { data, error } = await supabase\n * .from('issues')\n * .select('title')\n * .overlaps('tags', ['is:closed', 'severity:high'])\n * ```\n *\n * @exampleSql On array columns\n * ```sql\n * create table\n * issues (\n * id int8 primary key,\n * title text,\n * tags text[]\n * );\n *\n * insert into\n * issues (id, title, tags)\n * values\n * (1, 'Cache invalidation is not working', array['is:open', 'severity:high', 'priority:low']),\n * (2, 'Use better names', array['is:open', 'severity:low', 'priority:medium']);\n * ```\n *\n * @exampleResponse On array columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"title\": \"Cache invalidation is not working\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription On range columns\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example On range columns\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .overlaps('during', '[2000-01-01 12:45, 2000-01-01 13:15)')\n * ```\n *\n * @exampleSql On range columns\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse On range columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"room_name\": \"Emerald\",\n * \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n overlaps<ColumnName extends string & keyof Row>(\n column: ColumnName,\n value: string | ReadonlyArray<Row[ColumnName]>\n ): this\n overlaps(column: string, value: string | readonly unknown[]): this\n overlaps(column: string, value: string | readonly unknown[]): this {\n if (typeof value === 'string') {\n // range\n this.url.searchParams.append(column, `ov.${value}`)\n } else {\n // array\n this.url.searchParams.append(column, `ov.{${value.join(',')}}`)\n }\n return this\n }\n\n /**\n * Only relevant for text and tsvector columns. Match only rows where\n * `column` matches the query string in `query`.\n *\n * @param column - The text or tsvector column to filter on\n * @param query - The query text to match with\n * @param options - Named parameters\n * @param options.config - The text search configuration to use\n * @param options.type - Change how the `query` text is interpreted\n *\n * @category Database\n * @subcategory Using filters\n *\n * @remarks\n * - For more information, see [Postgres full text search](/docs/guides/database/full-text-search).\n *\n * @example Text search\n * ```ts\n * const result = await supabase\n * .from(\"texts\")\n * .select(\"content\")\n * .textSearch(\"content\", `'eggs' & 'ham'`, {\n * config: \"english\",\n * });\n * ```\n *\n * @exampleSql Text search\n * ```sql\n * create table texts (\n * id bigint\n * primary key\n * generated always as identity,\n * content text\n * );\n *\n * insert into texts (content) values\n * ('Four score and seven years ago'),\n * ('The road goes ever on and on'),\n * ('Green eggs and ham')\n * ;\n * ```\n *\n * @exampleResponse Text search\n * ```json\n * {\n * \"data\": [\n * {\n * \"content\": \"Green eggs and ham\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Basic normalization\n * Uses PostgreSQL's `plainto_tsquery` function.\n *\n * @example Basic normalization\n * ```ts\n * const { data, error } = await supabase\n * .from('quotes')\n * .select('catchphrase')\n * .textSearch('catchphrase', `'fat' & 'cat'`, {\n * type: 'plain',\n * config: 'english'\n * })\n * ```\n *\n * @exampleDescription Full normalization\n * Uses PostgreSQL's `phraseto_tsquery` function.\n *\n * @example Full normalization\n * ```ts\n * const { data, error } = await supabase\n * .from('quotes')\n * .select('catchphrase')\n * .textSearch('catchphrase', `'fat' & 'cat'`, {\n * type: 'phrase',\n * config: 'english'\n * })\n * ```\n *\n * @exampleDescription Websearch\n * Uses PostgreSQL's `websearch_to_tsquery` function.\n * This function will never raise syntax errors, which makes it possible to use raw user-supplied input for search, and can be used\n * with advanced operators.\n *\n * - `unquoted text`: text not inside quote marks will be converted to terms separated by & operators, as if processed by plainto_tsquery.\n * - `\"quoted text\"`: text inside quote marks will be converted to terms separated by `<->` operators, as if processed by phraseto_tsquery.\n * - `OR`: the word “or” will be converted to the | operator.\n * - `-`: a dash will be converted to the ! operator.\n *\n * @example Websearch\n * ```ts\n * const { data, error } = await supabase\n * .from('quotes')\n * .select('catchphrase')\n * .textSearch('catchphrase', `'fat or cat'`, {\n * type: 'websearch',\n * config: 'english'\n * })\n * ```\n */\n textSearch<ColumnName extends string & keyof Row>(\n column: ColumnName,\n query: string,\n options?: { config?: string; type?: 'plain' | 'phrase' | 'websearch' }\n ): this\n textSearch(\n column: string,\n query: string,\n options?: { config?: string; type?: 'plain' | 'phrase' | 'websearch' }\n ): this\n textSearch(\n column: string,\n query: string,\n { config, type }: { config?: string; type?: 'plain' | 'phrase' | 'websearch' } = {}\n ): this {\n let typePart = ''\n if (type === 'plain') {\n typePart = 'pl'\n } else if (type === 'phrase') {\n typePart = 'ph'\n } else if (type === 'websearch') {\n typePart = 'w'\n }\n const configPart = config === undefined ? '' : `(${config})`\n this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`)\n return this\n }\n\n /**\n * Match only rows where each column in `query` keys is equal to its\n * associated value. Shorthand for multiple `.eq()`s.\n *\n * @param query - The object to filter with, with column names as keys mapped\n * to their filter values\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * .match({ id: 2, name: 'Leia' })\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Leia\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n match<ColumnName extends string & keyof Row>(query: Record<ColumnName, Row[ColumnName]>): this\n match(query: Record<string, unknown>): this\n match(query: Record<string, unknown>): this {\n Object.entries(query)\n // columns with `undefined` value needs to be filtered out, otherwise it'll\n // show up as `?column=eq.undefined`\n .filter(([_, value]) => value !== undefined)\n .forEach(([column, value]) => {\n this.url.searchParams.append(column, `eq.${value}`)\n })\n return this\n }\n\n /**\n * Match only rows which doesn't satisfy the filter.\n *\n * Unlike most filters, `opearator` and `value` are used as-is and need to\n * follow [PostgREST\n * syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n * to make sure they are properly sanitized.\n *\n * @param column - The column to filter on\n * @param operator - The operator to be negated to filter with, following\n * PostgREST syntax\n * @param value - The value to filter with, following PostgREST syntax\n *\n * @category Database\n * @subcategory Using filters\n */\n not<ColumnName extends string & keyof Row>(\n column: ColumnName,\n operator: 'is',\n value: null\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n NonNullableColumn<Row, ColumnName>,\n NarrowResultColumn<Result, ColumnName>,\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n > &\n this\n not<ColumnName extends string & keyof Row>(\n column: ColumnName,\n operator: FilterOperator,\n value: Row[ColumnName]\n ): this\n not(column: string, operator: string, value: unknown): this\n /**\n * Match only rows which doesn't satisfy the filter.\n *\n * Unlike most filters, `opearator` and `value` are used as-is and need to\n * follow [PostgREST\n * syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n * to make sure they are properly sanitized.\n *\n * @param column - The column to filter on\n * @param operator - The operator to be negated to filter with, following\n * PostgREST syntax\n * @param value - The value to filter with, following PostgREST syntax\n *\n * @category Database\n * @subcategory Using filters\n *\n * @remarks\n * not() expects you to use the raw PostgREST syntax for the filter values.\n *\n * ```ts\n * .not('id', 'in', '(5,6,7)') // Use `()` for `in` filter\n * .not('arraycol', 'cs', '{\"a\",\"b\"}') // Use `cs` for `contains()`, `{}` for array values\n * ```\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('countries')\n * .select()\n * .not('name', 'is', null)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n *\n * insert into\n * countries (id, name)\n * values\n * (1, 'null'),\n * (2, null);\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"null\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n *\n * ```\n */\n not(\n column: string,\n operator: string,\n value: unknown\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n any,\n any,\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n > &\n this {\n this.url.searchParams.append(column, `not.${operator}.${value}`)\n return this as any\n }\n\n /**\n * Match only rows which satisfy at least one of the filters.\n *\n * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST\n * syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n * to make sure it's properly sanitized.\n *\n * It's currently not possible to do an `.or()` filter across multiple tables.\n *\n * @param filters - The filters to use, following PostgREST syntax\n * @param options - Named parameters\n * @param options.referencedTable - Set this to filter on referenced tables\n * instead of the parent table\n * @param options.foreignTable - Deprecated, use `referencedTable` instead\n *\n * @category Database\n * @subcategory Using filters\n *\n * @remarks\n * or() expects you to use the raw PostgREST syntax for the filter names and values.\n *\n * ```ts\n * .or('id.in.(5,6,7), arraycol.cs.{\"a\",\"b\"}') // Use `()` for `in` filter, `{}` for array values and `cs` for `contains()`.\n * .or('id.in.(5,6,7), arraycol.cd.{\"a\",\"b\"}') // Use `cd` for `containedBy()`\n * ```\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * .or('id.eq.2,name.eq.Han')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Leia\"\n * },\n * {\n * \"name\": \"Han\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example Use `or` with `and`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * .or('id.gt.3,and(id.eq.1,name.eq.Luke)')\n * ```\n *\n * @exampleSql Use `or` with `and`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse Use `or` with `and`\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Luke\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example Use `or` on referenced tables\n * ```ts\n * const { data, error } = await supabase\n * .from('orchestral_sections')\n * .select(`\n * name,\n * instruments!inner (\n * name\n * )\n * `)\n * .or('section_id.eq.1,name.eq.guzheng', { referencedTable: 'instruments' })\n * ```\n *\n * @exampleSql Use `or` on referenced tables\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 2, 'flute'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse Use `or` on referenced tables\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"strings\",\n * \"instruments\": [\n * {\n * \"name\": \"violin\"\n * }\n * ]\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n or(\n filters: string,\n {\n foreignTable,\n referencedTable = foreignTable,\n }: { foreignTable?: string; referencedTable?: string } = {}\n ): this {\n const key = referencedTable ? `${referencedTable}.or` : 'or'\n this.url.searchParams.append(key, `(${filters})`)\n return this\n }\n\n /**\n * Match only rows which satisfy the filter. This is an escape hatch - you\n * should use the specific filter methods wherever possible.\n *\n * Unlike most filters, `opearator` and `value` are used as-is and need to\n * follow [PostgREST\n * syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n * to make sure they are properly sanitized.\n *\n * @param column - The column to filter on\n * @param operator - The operator to filter with, following PostgREST syntax\n * @param value - The value to filter with, following PostgREST syntax\n *\n * @category Database\n * @subcategory Using filters\n *\n * @remarks\n * filter() expects you to use the raw PostgREST syntax for the filter values.\n *\n * ```ts\n * .filter('id', 'in', '(5,6,7)') // Use `()` for `in` filter\n * .filter('arraycol', 'cs', '{\"a\",\"b\"}') // Use `cs` for `contains()`, `{}` for array values\n * ```\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .filter('name', 'in', '(\"Han\",\"Yoda\")')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 3,\n * \"name\": \"Han\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example On a referenced table\n * ```ts\n * const { data, error } = await supabase\n * .from('orchestral_sections')\n * .select(`\n * name,\n * instruments!inner (\n * name\n * )\n * `)\n * .filter('instruments.name', 'eq', 'flute')\n * ```\n *\n * @exampleSql On a referenced table\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 2, 'flute'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse On a referenced table\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"woodwinds\",\n * \"instruments\": [\n * {\n * \"name\": \"flute\"\n * }\n * ]\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n filter<ColumnName extends string & keyof Row>(\n column: ColumnName,\n operator: `${'' | 'not.'}${FilterOperator}`,\n value: unknown\n ): this\n filter(column: string, operator: string, value: unknown): this\n filter(column: string, operator: string, value: unknown): this {\n this.url.searchParams.append(column, `${operator}.${value}`)\n return this\n }\n}\n","import PostgrestFilterBuilder from './PostgrestFilterBuilder'\nimport { GetResult } from './select-query-parser/result'\nimport {\n ClientServerOptions,\n Fetch,\n GenericSchema,\n GenericTable,\n GenericView,\n} from './types/common/common'\nimport { RejectExcessProperties } from './types/types'\n\nexport default class PostgrestQueryBuilder<\n ClientOptions extends ClientServerOptions,\n Schema extends GenericSchema,\n Relation extends GenericTable | GenericView,\n RelationName = unknown,\n Relationships = Relation extends { Relationships: infer R } ? R : unknown,\n> {\n url: URL\n headers: Headers\n schema?: string\n signal?: AbortSignal\n fetch?: Fetch\n urlLengthLimit: number\n\n /**\n * Enable or disable automatic retries for transient errors.\n * When enabled, idempotent requests (GET/HEAD/OPTIONS) that fail with network\n * errors or HTTP 503/520 responses are automatically retried with exponential\n * backoff (1s, 2s, 4s, up to 3 attempts). Defaults to `true` when not specified.\n */\n retry?: boolean\n\n /**\n * Creates a query builder scoped to a Postgres table or view.\n *\n * @category Database\n *\n * @param url - The URL for the query\n * @param options - Named parameters\n * @param options.headers - Custom headers\n * @param options.schema - Postgres schema to use\n * @param options.fetch - Custom fetch implementation\n * @param options.urlLengthLimit - Maximum URL length before warning\n * @param options.retry - Enable automatic retries for transient errors (default: true)\n *\n * @example Using supabase-js (recommended)\n * ```ts\n * import { createClient } from '@supabase/supabase-js'\n *\n * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n * const { data, error } = await supabase.from('users').select('*')\n * ```\n *\n * @example Standalone import for bundle-sensitive environments\n * ```ts\n * import { PostgrestQueryBuilder } from '@supabase/postgrest-js'\n *\n * const query = new PostgrestQueryBuilder(\n * new URL('https://xyzcompany.supabase.co/rest/v1/users'),\n * { headers: { apikey: 'your-publishable-key' }, retry: true }\n * )\n * ```\n */\n constructor(\n url: URL,\n {\n headers = {},\n schema,\n fetch,\n urlLengthLimit = 8000,\n retry,\n }: {\n headers?: HeadersInit\n schema?: string\n fetch?: Fetch\n urlLengthLimit?: number\n retry?: boolean\n }\n ) {\n this.url = url\n this.headers = new Headers(headers)\n this.schema = schema\n this.fetch = fetch\n this.urlLengthLimit = urlLengthLimit\n this.retry = retry\n }\n\n /**\n * Clone URL and headers to prevent shared state between operations.\n */\n private cloneRequestState(): { url: URL; headers: Headers } {\n return {\n url: new URL(this.url.toString()),\n headers: new Headers(this.headers),\n }\n }\n\n /**\n * Perform a SELECT query on the table or view.\n *\n * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName`\n *\n * @param options - Named parameters\n *\n * @param options.head - When set to `true`, `data` will not be returned.\n * Useful if you only need the count.\n *\n * @param options.count - Count algorithm to use to count rows in the table or view.\n *\n * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n * hood.\n *\n * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n * statistics under the hood.\n *\n * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n * numbers.\n *\n * @remarks\n * When using `count` with `.range()` or `.limit()`, the returned `count` is the total number of rows\n * that match your filters, not the number of rows in the current page. Use this to build pagination UI.\n \n * - By default, Supabase projects return a maximum of 1,000 rows. This setting can be changed in your project's [API settings](/dashboard/project/_/settings/api). It's recommended that you keep it low to limit the payload size of accidental or malicious requests. You can use `range()` queries to paginate through your data.\n * - `select()` can be combined with [Filters](/docs/reference/javascript/using-filters)\n * - `select()` can be combined with [Modifiers](/docs/reference/javascript/using-modifiers)\n * - `apikey` is a reserved keyword if you're using the [Supabase Platform](/docs/guides/platform) and [should be avoided as a column name](https://github.com/supabase/supabase/issues/5465). *\n * @category Database\n *\n * @example Getting your data\n * ```js\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * ```\n *\n * @exampleSql Getting your data\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Harry'),\n * (2, 'Frodo'),\n * (3, 'Katniss');\n * ```\n *\n * @exampleResponse Getting your data\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Harry\"\n * },\n * {\n * \"id\": 2,\n * \"name\": \"Frodo\"\n * },\n * {\n * \"id\": 3,\n * \"name\": \"Katniss\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Handling errors\n * The most useful field on a Postgres error is usually `hint` — when the database knows the fix, it puts the literal SQL there. For example, a permission-denied error (`code: '42501'`) arrives with a `hint` like `\"Grant the required privileges to the current role with: GRANT SELECT ON public.characters TO anon;\"`. Log the full `error` object so the hint isn't hidden behind `error.message`.\n *\n * @example Handling errors\n * ```js\n * const { data, error } = await supabase.from('characters').select()\n * if (error) {\n * // Logs the full error: message, code, details, and hint.\n * console.error(error)\n * return\n * }\n * ```\n *\n * @exampleResponse Handling errors\n * ```json\n * {\n * \"error\": {\n * \"code\": \"42501\",\n * \"details\": null,\n * \"hint\": \"Grant the required privileges to the current role with: GRANT SELECT ON public.characters TO anon;\",\n * \"message\": \"permission denied for table characters\"\n * },\n * \"status\": 401,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @example Selecting specific columns\n * ```js\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * ```\n *\n * @exampleSql Selecting specific columns\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Frodo'),\n * (2, 'Harry'),\n * (3, 'Katniss');\n * ```\n *\n * @exampleResponse Selecting specific columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Frodo\"\n * },\n * {\n * \"name\": \"Harry\"\n * },\n * {\n * \"name\": \"Katniss\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Query referenced tables\n * If your database has foreign key relationships, you can query related tables too.\n *\n * @example Query referenced tables\n * ```js\n * const { data, error } = await supabase\n * .from('orchestral_sections')\n * .select(`\n * name,\n * instruments (\n * name\n * )\n * `)\n * ```\n *\n * @exampleSql Query referenced tables\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 2, 'flute'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse Query referenced tables\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"strings\",\n * \"instruments\": [\n * {\n * \"name\": \"violin\"\n * }\n * ]\n * },\n * {\n * \"name\": \"woodwinds\",\n * \"instruments\": [\n * {\n * \"name\": \"flute\"\n * }\n * ]\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Query referenced tables with spaces in their names\n * If your table name contains spaces, you must use double quotes in the `select` statement to reference the table.\n *\n * @example Query referenced tables with spaces in their names\n * ```js\n * const { data, error } = await supabase\n * .from('orchestral sections')\n * .select(`\n * name,\n * \"musical instruments\" (\n * name\n * )\n * `)\n * ```\n *\n * @exampleSql Query referenced tables with spaces in their names\n * ```sql\n * create table\n * \"orchestral sections\" (id int8 primary key, name text);\n * create table\n * \"musical instruments\" (\n * id int8 primary key,\n * section_id int8 not null references \"orchestral sections\",\n * name text\n * );\n *\n * insert into\n * \"orchestral sections\" (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * \"musical instruments\" (id, section_id, name)\n * values\n * (1, 2, 'flute'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse Query referenced tables with spaces in their names\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"strings\",\n * \"musical instruments\": [\n * {\n * \"name\": \"violin\"\n * }\n * ]\n * },\n * {\n * \"name\": \"woodwinds\",\n * \"musical instruments\": [\n * {\n * \"name\": \"flute\"\n * }\n * ]\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Query referenced tables through a join table\n * If you're in a situation where your tables are **NOT** directly\n * related, but instead are joined by a _join table_, you can still use\n * the `select()` method to query the related data. The join table needs\n * to have the foreign keys as part of its composite primary key.\n *\n * @example Query referenced tables through a join table\n * ```ts\n * const { data, error } = await supabase\n * .from('users')\n * .select(`\n * name,\n * teams (\n * name\n * )\n * `)\n * \n * ```\n *\n * @exampleSql Query referenced tables through a join table\n * ```sql\n * create table\n * users (\n * id int8 primary key,\n * name text\n * );\n * create table\n * teams (\n * id int8 primary key,\n * name text\n * );\n * -- join table\n * create table\n * users_teams (\n * user_id int8 not null references users,\n * team_id int8 not null references teams,\n * -- both foreign keys must be part of a composite primary key\n * primary key (user_id, team_id)\n * );\n *\n * insert into\n * users (id, name)\n * values\n * (1, 'Kiran'),\n * (2, 'Evan');\n * insert into\n * teams (id, name)\n * values\n * (1, 'Green'),\n * (2, 'Blue');\n * insert into\n * users_teams (user_id, team_id)\n * values\n * (1, 1),\n * (1, 2),\n * (2, 2);\n * ```\n *\n * @exampleResponse Query referenced tables through a join table\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Kiran\",\n * \"teams\": [\n * {\n * \"name\": \"Green\"\n * },\n * {\n * \"name\": \"Blue\"\n * }\n * ]\n * },\n * {\n * \"name\": \"Evan\",\n * \"teams\": [\n * {\n * \"name\": \"Blue\"\n * }\n * ]\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * \n * ```\n *\n * @exampleDescription Query the same referenced table multiple times\n * If you need to query the same referenced table twice, use the name of the\n * joined column to identify which join to use. You can also give each\n * column an alias.\n *\n * @example Query the same referenced table multiple times\n * ```ts\n * const { data, error } = await supabase\n * .from('messages')\n * .select(`\n * content,\n * from:sender_id(name),\n * to:receiver_id(name)\n * `)\n *\n * // To infer types, use the name of the table (in this case `users`) and\n * // the name of the foreign key constraint.\n * const { data, error } = await supabase\n * .from('messages')\n * .select(`\n * content,\n * from:users!messages_sender_id_fkey(name),\n * to:users!messages_receiver_id_fkey(name)\n * `)\n * ```\n *\n * @exampleSql Query the same referenced table multiple times\n * ```sql\n * create table\n * users (id int8 primary key, name text);\n *\n * create table\n * messages (\n * sender_id int8 not null references users,\n * receiver_id int8 not null references users,\n * content text\n * );\n *\n * insert into\n * users (id, name)\n * values\n * (1, 'Kiran'),\n * (2, 'Evan');\n *\n * insert into\n * messages (sender_id, receiver_id, content)\n * values\n * (1, 2, '👋');\n * ```\n * ```\n *\n * @exampleResponse Query the same referenced table multiple times\n * ```json\n * {\n * \"data\": [\n * {\n * \"content\": \"👋\",\n * \"from\": {\n * \"name\": \"Kiran\"\n * },\n * \"to\": {\n * \"name\": \"Evan\"\n * }\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Query nested foreign tables through a join table\n * You can use the result of a joined table to gather data in\n * another foreign table. With multiple references to the same foreign\n * table you must specify the column on which to conduct the join.\n *\n * @example Query nested foreign tables through a join table\n * ```ts\n * const { data, error } = await supabase\n * .from('games')\n * .select(`\n * game_id:id,\n * away_team:teams!games_away_team_fkey (\n * users (\n * id,\n * name\n * )\n * )\n * `)\n * \n * ```\n *\n * @exampleSql Query nested foreign tables through a join table\n * ```sql\n * ```sql\n * create table\n * users (\n * id int8 primary key,\n * name text\n * );\n * create table\n * teams (\n * id int8 primary key,\n * name text\n * );\n * -- join table\n * create table\n * users_teams (\n * user_id int8 not null references users,\n * team_id int8 not null references teams,\n *\n * primary key (user_id, team_id)\n * );\n * create table\n * games (\n * id int8 primary key,\n * home_team int8 not null references teams,\n * away_team int8 not null references teams,\n * name text\n * );\n *\n * insert into users (id, name)\n * values\n * (1, 'Kiran'),\n * (2, 'Evan');\n * insert into\n * teams (id, name)\n * values\n * (1, 'Green'),\n * (2, 'Blue');\n * insert into\n * users_teams (user_id, team_id)\n * values\n * (1, 1),\n * (1, 2),\n * (2, 2);\n * insert into\n * games (id, home_team, away_team, name)\n * values\n * (1, 1, 2, 'Green vs Blue'),\n * (2, 2, 1, 'Blue vs Green');\n * ```\n *\n * @exampleResponse Query nested foreign tables through a join table\n * ```json\n * {\n * \"data\": [\n * {\n * \"game_id\": 1,\n * \"away_team\": {\n * \"users\": [\n * {\n * \"id\": 1,\n * \"name\": \"Kiran\"\n * },\n * {\n * \"id\": 2,\n * \"name\": \"Evan\"\n * }\n * ]\n * }\n * },\n * {\n * \"game_id\": 2,\n * \"away_team\": {\n * \"users\": [\n * {\n * \"id\": 1,\n * \"name\": \"Kiran\"\n * }\n * ]\n * }\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * \n * ```\n *\n * @exampleDescription Filtering through referenced tables\n * If the filter on a referenced table's column is not satisfied, the referenced\n * table returns `[]` or `null` but the parent table is not filtered out.\n * If you want to filter out the parent table rows, use the `!inner` hint\n *\n * @example Filtering through referenced tables\n * ```ts\n * const { data, error } = await supabase\n * .from('instruments')\n * .select('name, orchestral_sections(*)')\n * .eq('orchestral_sections.name', 'percussion')\n * ```\n *\n * @exampleSql Filtering through referenced tables\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 2, 'flute'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse Filtering through referenced tables\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"flute\",\n * \"orchestral_sections\": null\n * },\n * {\n * \"name\": \"violin\",\n * \"orchestral_sections\": null\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Querying referenced table with count\n * You can get the number of rows in a related table by using the\n * **count** property.\n *\n * @example Querying referenced table with count\n * ```ts\n * const { data, error } = await supabase\n * .from('orchestral_sections')\n * .select(`*, instruments(count)`)\n * ```\n *\n * @exampleSql Querying referenced table with count\n * ```sql\n * create table orchestral_sections (\n * \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n * \"name\" text\n * );\n *\n * create table characters (\n * \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n * \"name\" text,\n * \"section_id\" \"uuid\" references public.orchestral_sections on delete cascade\n * );\n *\n * with section as (\n * insert into orchestral_sections (name)\n * values ('strings') returning id\n * )\n * insert into instruments (name, section_id) values\n * ('violin', (select id from section)),\n * ('viola', (select id from section)),\n * ('cello', (select id from section)),\n * ('double bass', (select id from section));\n * ```\n *\n * @exampleResponse Querying referenced table with count\n * ```json\n * [\n * {\n * \"id\": \"693694e7-d993-4360-a6d7-6294e325d9b6\",\n * \"name\": \"strings\",\n * \"instruments\": [\n * {\n * \"count\": 4\n * }\n * ]\n * }\n * ]\n * ```\n *\n * @exampleDescription Querying with count option\n * You can get the number of rows by using the\n * [count](/docs/reference/javascript/select#parameters) option.\n *\n * @example Querying with count option\n * ```ts\n * const { count, error } = await supabase\n * .from('characters')\n * .select('*', { count: 'exact', head: true })\n * ```\n *\n * @exampleSql Querying with count option\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse Querying with count option\n * ```json\n * {\n * \"count\": 3,\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Querying JSON data\n * You can select and filter data inside of\n * [JSON](/docs/guides/database/json) columns. Postgres offers some\n * [operators](/docs/guides/database/json#query-the-jsonb-data) for\n * querying JSON data.\n *\n * @example Querying JSON data\n * ```ts\n * const { data, error } = await supabase\n * .from('users')\n * .select(`\n * id, name,\n * address->city\n * `)\n * ```\n *\n * @exampleSql Querying JSON data\n * ```sql\n * create table\n * users (\n * id int8 primary key,\n * name text,\n * address jsonb\n * );\n *\n * insert into\n * users (id, name, address)\n * values\n * (1, 'Frodo', '{\"city\":\"Hobbiton\"}');\n * ```\n *\n * @exampleResponse Querying JSON data\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Frodo\",\n * \"city\": \"Hobbiton\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Querying referenced table with inner join\n * If you don't want to return the referenced table contents, you can leave the parenthesis empty.\n * Like `.select('name, orchestral_sections!inner()')`.\n *\n * @example Querying referenced table with inner join\n * ```ts\n * const { data, error } = await supabase\n * .from('instruments')\n * .select('name, orchestral_sections!inner(name)')\n * .eq('orchestral_sections.name', 'woodwinds')\n * .limit(1)\n * ```\n *\n * @exampleSql Querying referenced table with inner join\n * ```sql\n * create table orchestral_sections (\n * \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n * \"name\" text\n * );\n *\n * create table instruments (\n * \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n * \"name\" text,\n * \"section_id\" \"uuid\" references public.orchestral_sections on delete cascade\n * );\n *\n * with section as (\n * insert into orchestral_sections (name)\n * values ('woodwinds') returning id\n * )\n * insert into instruments (name, section_id) values\n * ('flute', (select id from section)),\n * ('clarinet', (select id from section)),\n * ('bassoon', (select id from section)),\n * ('piccolo', (select id from section));\n * ```\n *\n * @exampleResponse Querying referenced table with inner join\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"flute\",\n * \"orchestral_sections\": {\"name\": \"woodwinds\"}\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Switching schemas per query\n * In addition to setting the schema during initialization, you can also switch schemas on a per-query basis.\n * Make sure you've set up your [database privileges and API settings](/docs/guides/api/using-custom-schemas).\n *\n * @example Switching schemas per query\n * ```ts\n * const { data, error } = await supabase\n * .schema('myschema')\n * .from('mytable')\n * .select()\n * ```\n *\n * @exampleSql Switching schemas per query\n * ```sql\n * create schema myschema;\n *\n * create table myschema.mytable (\n * id uuid primary key default gen_random_uuid(),\n * data text\n * );\n *\n * insert into myschema.mytable (data) values ('mydata');\n * ```\n *\n * @exampleResponse Switching schemas per query\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": \"4162e008-27b0-4c0f-82dc-ccaeee9a624d\",\n * \"data\": \"mydata\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n select<\n Query extends string = '*',\n ResultOne = GetResult<\n Schema,\n Relation['Row'],\n RelationName,\n Relationships,\n Query,\n ClientOptions\n >,\n >(\n columns?: Query,\n options?: {\n head?: boolean\n count?: 'exact' | 'planned' | 'estimated' | (string & {})\n }\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n ResultOne[],\n RelationName,\n Relationships,\n 'GET'\n > {\n const { head = false, count } = options ?? {}\n\n const method = head ? 'HEAD' : 'GET'\n // Remove whitespaces except when quoted\n let quoted = false\n const cleanedColumns = (columns ?? '*')\n .split('')\n .map((c) => {\n if (/\\s/.test(c) && !quoted) {\n return ''\n }\n if (c === '\"') {\n quoted = !quoted\n }\n return c\n })\n .join('')\n\n const { url, headers } = this.cloneRequestState()\n url.searchParams.set('select', cleanedColumns)\n\n if (count) {\n headers.append('Prefer', `count=${count}`)\n }\n\n return new PostgrestFilterBuilder({\n method,\n url,\n headers,\n schema: this.schema,\n fetch: this.fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n\n /**\n * Perform an INSERT into the table or view.\n *\n * By default, inserted rows are not returned. To return it, chain the call\n * with `.select()`.\n *\n * @param values - The values to insert. Pass an object to insert a single row\n * or an array to insert multiple rows.\n *\n * @param options - Named parameters\n *\n * @param options.count - Count algorithm to use to count inserted rows.\n *\n * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n * hood.\n *\n * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n * statistics under the hood.\n *\n * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n * numbers.\n *\n * @param options.defaultToNull - Make missing fields default to `null`.\n * Otherwise, use the default value for the column. Only applies for bulk\n * inserts.\n *\n * @category Database\n *\n * @example Create a record\n * ```ts\n * const { error } = await supabase\n * .from('countries')\n * .insert({ id: 1, name: 'Mordor' })\n * ```\n *\n * @exampleSql Create a record\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n * ```\n *\n * @exampleResponse Create a record\n * ```json\n * {\n * \"status\": 201,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @exampleDescription Handling errors\n * `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT INSERT ON public.countries TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n *\n * @example Handling errors\n * ```js\n * const { error } = await supabase.from('countries').insert({ id: 1, name: 'Mordor' })\n * if (error) console.error(error)\n * ```\n *\n * @example Create a record and return it\n * ```ts\n * const { data, error } = await supabase\n * .from('countries')\n * .insert({ id: 1, name: 'Mordor' })\n * .select()\n * ```\n *\n * @exampleSql Create a record and return it\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n * ```\n *\n * @exampleResponse Create a record and return it\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Mordor\"\n * }\n * ],\n * \"status\": 201,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @exampleDescription Bulk create\n * A bulk create operation is handled in a single transaction.\n * If any of the inserts fail, none of the rows are inserted.\n *\n * @example Bulk create\n * ```ts\n * const { error } = await supabase\n * .from('countries')\n * .insert([\n * { id: 1, name: 'Mordor' },\n * { id: 1, name: 'The Shire' },\n * ])\n * ```\n *\n * @exampleSql Bulk create\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n * ```\n *\n * @exampleResponse Bulk create\n * ```json\n * {\n * \"error\": {\n * \"code\": \"23505\",\n * \"details\": \"Key (id)=(1) already exists.\",\n * \"hint\": null,\n * \"message\": \"duplicate key value violates unique constraint \\\"countries_pkey\\\"\"\n * },\n * \"status\": 409,\n * \"statusText\": \"\"\n * }\n * ```\n */\n insert<Row extends Relation extends { Insert: unknown } ? Relation['Insert'] : never>(\n values:\n | RejectExcessProperties<\n Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n Row\n >\n | RejectExcessProperties<\n Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n Row\n >[],\n {\n count,\n defaultToNull = true,\n }: {\n count?: 'exact' | 'planned' | 'estimated' | (string & {})\n defaultToNull?: boolean\n } = {}\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n null,\n RelationName,\n Relationships,\n 'POST'\n > {\n const method = 'POST'\n const { url, headers } = this.cloneRequestState()\n\n if (count) {\n headers.append('Prefer', `count=${count}`)\n }\n if (!defaultToNull) {\n headers.append('Prefer', `missing=default`)\n }\n\n if (Array.isArray(values)) {\n const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), [] as string[])\n if (columns.length > 0) {\n const uniqueColumns = [...new Set(columns)].map((column) => `\"${column}\"`)\n url.searchParams.set('columns', uniqueColumns.join(','))\n }\n }\n\n return new PostgrestFilterBuilder({\n method,\n url,\n headers,\n schema: this.schema,\n body: values,\n fetch: this.fetch ?? fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n\n /**\n * Perform an UPSERT on the table or view. Depending on the column(s) passed\n * to `onConflict`, `.upsert()` allows you to perform the equivalent of\n * `.insert()` if a row with the corresponding `onConflict` columns doesn't\n * exist, or if it does exist, perform an alternative action depending on\n * `ignoreDuplicates`.\n *\n * By default, upserted rows are not returned. To return it, chain the call\n * with `.select()`.\n *\n * @param values - The values to upsert with. Pass an object to upsert a\n * single row or an array to upsert multiple rows.\n *\n * @param options - Named parameters\n *\n * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how\n * duplicate rows are determined. Two rows are duplicates if all the\n * `onConflict` columns are equal.\n *\n * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If\n * `false`, duplicate rows are merged with existing rows.\n *\n * @param options.count - Count algorithm to use to count upserted rows.\n *\n * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n * hood.\n *\n * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n * statistics under the hood.\n *\n * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n * numbers.\n *\n * @param options.defaultToNull - Make missing fields default to `null`.\n * Otherwise, use the default value for the column. This only applies when\n * inserting new rows, not when merging with existing rows under\n * `ignoreDuplicates: false`. This also only applies when doing bulk upserts.\n *\n * @example Upsert a single row using a unique key\n * ```ts\n * // Upserting a single row, overwriting based on the 'username' unique column\n * const { data, error } = await supabase\n * .from('users')\n * .upsert({ username: 'supabot' }, { onConflict: 'username' })\n *\n * // Example response:\n * // {\n * // data: [\n * // { id: 4, message: 'bar', username: 'supabot' }\n * // ],\n * // error: null\n * // }\n * ```\n *\n * @example Upsert with conflict resolution and exact row counting\n * ```ts\n * // Upserting and returning exact count\n * const { data, error, count } = await supabase\n * .from('users')\n * .upsert(\n * {\n * id: 3,\n * message: 'foo',\n * username: 'supabot'\n * },\n * {\n * onConflict: 'username',\n * count: 'exact'\n * }\n * )\n *\n * // Example response:\n * // {\n * // data: [\n * // {\n * // id: 42,\n * // handle: \"saoirse\",\n * // display_name: \"Saoirse\"\n * // }\n * // ],\n * // count: 1,\n * // error: null\n * // }\n * ```\n *\n * @category Database\n *\n * @remarks\n * - Primary keys must be included in `values` to use upsert.\n *\n * @example Upsert your data\n * ```ts\n * const { data, error } = await supabase\n * .from('instruments')\n * .upsert({ id: 1, name: 'piano' })\n * .select()\n * ```\n *\n * @exampleSql Upsert your data\n * ```sql\n * create table\n * instruments (id int8 primary key, name text);\n *\n * insert into\n * instruments (id, name)\n * values\n * (1, 'harpsichord');\n * ```\n *\n * @exampleResponse Upsert your data\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"piano\"\n * }\n * ],\n * \"status\": 201,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @exampleDescription Handling errors\n * `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT INSERT, UPDATE ON public.instruments TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n *\n * @example Handling errors\n * ```js\n * const { data, error } = await supabase.from('instruments').upsert({ id: 1, name: 'piano' }).select()\n * if (error) console.error(error)\n * ```\n *\n * @example Bulk Upsert your data\n * ```ts\n * const { data, error } = await supabase\n * .from('instruments')\n * .upsert([\n * { id: 1, name: 'piano' },\n * { id: 2, name: 'harp' },\n * ])\n * .select()\n * ```\n *\n * @exampleSql Bulk Upsert your data\n * ```sql\n * create table\n * instruments (id int8 primary key, name text);\n *\n * insert into\n * instruments (id, name)\n * values\n * (1, 'harpsichord');\n * ```\n *\n * @exampleResponse Bulk Upsert your data\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"piano\"\n * },\n * {\n * \"id\": 2,\n * \"name\": \"harp\"\n * }\n * ],\n * \"status\": 201,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @exampleDescription Upserting into tables with constraints\n * In the following query, `upsert()` implicitly uses the `id`\n * (primary key) column to determine conflicts. If there is no existing\n * row with the same `id`, `upsert()` inserts a new row, which\n * will fail in this case as there is already a row with `handle` `\"saoirse\"`.\n * Using the `onConflict` option, you can instruct `upsert()` to use\n * another column with a unique constraint to determine conflicts.\n *\n * @example Upserting into tables with constraints\n * ```ts\n * const { data, error } = await supabase\n * .from('users')\n * .upsert({ id: 42, handle: 'saoirse', display_name: 'Saoirse' })\n * .select()\n * ```\n *\n * @exampleSql Upserting into tables with constraints\n * ```sql\n * create table\n * users (\n * id int8 generated by default as identity primary key,\n * handle text not null unique,\n * display_name text\n * );\n *\n * insert into\n * users (id, handle, display_name)\n * values\n * (1, 'saoirse', null);\n * ```\n *\n * @exampleResponse Upserting into tables with constraints\n * ```json\n * {\n * \"error\": {\n * \"code\": \"23505\",\n * \"details\": \"Key (handle)=(saoirse) already exists.\",\n * \"hint\": null,\n * \"message\": \"duplicate key value violates unique constraint \\\"users_handle_key\\\"\"\n * },\n * \"status\": 409,\n * \"statusText\": \"\"\n * }\n * ```\n */\n\n upsert<Row extends Relation extends { Insert: unknown } ? Relation['Insert'] : never>(\n values:\n | RejectExcessProperties<\n Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n Row\n >\n | RejectExcessProperties<\n Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n Row\n >[],\n {\n onConflict,\n ignoreDuplicates = false,\n count,\n defaultToNull = true,\n }: {\n onConflict?: string\n ignoreDuplicates?: boolean\n count?: 'exact' | 'planned' | 'estimated' | (string & {})\n defaultToNull?: boolean\n } = {}\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n null,\n RelationName,\n Relationships,\n 'POST'\n > {\n const method = 'POST'\n const { url, headers } = this.cloneRequestState()\n\n headers.append('Prefer', `resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`)\n\n if (onConflict !== undefined) url.searchParams.set('on_conflict', onConflict)\n if (count) {\n headers.append('Prefer', `count=${count}`)\n }\n if (!defaultToNull) {\n headers.append('Prefer', 'missing=default')\n }\n\n if (Array.isArray(values)) {\n const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), [] as string[])\n if (columns.length > 0) {\n const uniqueColumns = [...new Set(columns)].map((column) => `\"${column}\"`)\n url.searchParams.set('columns', uniqueColumns.join(','))\n }\n }\n\n return new PostgrestFilterBuilder({\n method,\n url,\n headers,\n schema: this.schema,\n body: values,\n fetch: this.fetch ?? fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n\n /**\n * Perform an UPDATE on the table or view.\n *\n * By default, updated rows are not returned. To return it, chain the call\n * with `.select()` after filters.\n *\n * @param values - The values to update with\n *\n * @param options - Named parameters\n *\n * @param options.count - Count algorithm to use to count updated rows.\n *\n * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n * hood.\n *\n * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n * statistics under the hood.\n *\n * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n * numbers.\n *\n * @category Database\n *\n * @remarks\n * - `update()` should always be combined with [Filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to update.\n *\n * @example Updating your data\n * ```ts\n * const { error } = await supabase\n * .from('instruments')\n * .update({ name: 'piano' })\n * .eq('id', 1)\n * ```\n *\n * @exampleSql Updating your data\n * ```sql\n * create table\n * instruments (id int8 primary key, name text);\n *\n * insert into\n * instruments (id, name)\n * values\n * (1, 'harpsichord');\n * ```\n *\n * @exampleResponse Updating your data\n * ```json\n * {\n * \"status\": 204,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @exampleDescription Handling errors\n * `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT UPDATE ON public.instruments TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n *\n * @example Handling errors\n * ```js\n * const { error } = await supabase.from('instruments').update({ name: 'piano' }).eq('id', 1)\n * if (error) console.error(error)\n * ```\n *\n * @example Update a record and return it\n * ```ts\n * const { data, error } = await supabase\n * .from('instruments')\n * .update({ name: 'piano' })\n * .eq('id', 1)\n * .select()\n * ```\n *\n * @exampleSql Update a record and return it\n * ```sql\n * create table\n * instruments (id int8 primary key, name text);\n *\n * insert into\n * instruments (id, name)\n * values\n * (1, 'harpsichord');\n * ```\n *\n * @exampleResponse Update a record and return it\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"piano\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Updating JSON data\n * Postgres offers some\n * [operators](/docs/guides/database/json#query-the-jsonb-data) for\n * working with JSON data. Currently, it is only possible to update the entire JSON document.\n *\n * @example Updating JSON data\n * ```ts\n * const { data, error } = await supabase\n * .from('users')\n * .update({\n * address: {\n * street: 'Melrose Place',\n * postcode: 90210\n * }\n * })\n * .eq('address->postcode', 90210)\n * .select()\n * ```\n *\n * @exampleSql Updating JSON data\n * ```sql\n * create table\n * users (\n * id int8 primary key,\n * name text,\n * address jsonb\n * );\n *\n * insert into\n * users (id, name, address)\n * values\n * (1, 'Michael', '{ \"postcode\": 90210 }');\n * ```\n *\n * @exampleResponse Updating JSON data\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Michael\",\n * \"address\": {\n * \"street\": \"Melrose Place\",\n * \"postcode\": 90210\n * }\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n update<Row extends Relation extends { Update: unknown } ? Relation['Update'] : never>(\n values: RejectExcessProperties<\n Relation extends { Update: unknown } ? Relation['Update'] : never,\n Row\n >,\n {\n count,\n }: {\n count?: 'exact' | 'planned' | 'estimated' | (string & {})\n } = {}\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n null,\n RelationName,\n Relationships,\n 'PATCH'\n > {\n const method = 'PATCH'\n const { url, headers } = this.cloneRequestState()\n\n if (count) {\n headers.append('Prefer', `count=${count}`)\n }\n\n return new PostgrestFilterBuilder({\n method,\n url,\n headers,\n schema: this.schema,\n body: values,\n fetch: this.fetch ?? fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n\n /**\n * Perform a DELETE on the table or view.\n *\n * By default, deleted rows are not returned. To return it, chain the call\n * with `.select()` after filters.\n *\n * @param options - Named parameters\n *\n * @param options.count - Count algorithm to use to count deleted rows.\n *\n * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n * hood.\n *\n * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n * statistics under the hood.\n *\n * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n * numbers.\n *\n * @category Database\n *\n * @remarks\n * - `delete()` should always be combined with [filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to delete.\n * - If you use `delete()` with filters and you have\n * [RLS](/docs/learn/auth-deep-dive/auth-row-level-security) enabled, only\n * rows visible through `SELECT` policies are deleted. Note that by default\n * no rows are visible, so you need at least one `SELECT`/`ALL` policy that\n * makes the rows visible.\n * - When using `delete().in()`, specify an array of values to target multiple rows with a single query. This is particularly useful for batch deleting entries that share common criteria, such as deleting users by their IDs. Ensure that the array you provide accurately represents all records you intend to delete to avoid unintended data removal.\n *\n * @example Delete a single record\n * ```ts\n * const response = await supabase\n * .from('countries')\n * .delete()\n * .eq('id', 1)\n * ```\n *\n * @exampleSql Delete a single record\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n *\n * insert into\n * countries (id, name)\n * values\n * (1, 'Mordor');\n * ```\n *\n * @exampleResponse Delete a single record\n * ```json\n * {\n * \"status\": 204,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @exampleDescription Handling errors\n * `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT DELETE ON public.countries TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n *\n * @example Handling errors\n * ```js\n * const { error } = await supabase.from('countries').delete().eq('id', 1)\n * if (error) console.error(error)\n * ```\n *\n * @example Delete a record and return it\n * ```ts\n * const { data, error } = await supabase\n * .from('countries')\n * .delete()\n * .eq('id', 1)\n * .select()\n * ```\n *\n * @exampleSql Delete a record and return it\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n *\n * insert into\n * countries (id, name)\n * values\n * (1, 'Mordor');\n * ```\n *\n * @exampleResponse Delete a record and return it\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Mordor\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example Delete multiple records\n * ```ts\n * const response = await supabase\n * .from('countries')\n * .delete()\n * .in('id', [1, 2, 3])\n * ```\n *\n * @exampleSql Delete multiple records\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n *\n * insert into\n * countries (id, name)\n * values\n * (1, 'Rohan'), (2, 'The Shire'), (3, 'Mordor');\n * ```\n *\n * @exampleResponse Delete multiple records\n * ```json\n * {\n * \"status\": 204,\n * \"statusText\": \"\"\n * }\n * ```\n */\n delete({\n count,\n }: {\n count?: 'exact' | 'planned' | 'estimated' | (string & {})\n } = {}): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n null,\n RelationName,\n Relationships,\n 'DELETE'\n > {\n const method = 'DELETE'\n const { url, headers } = this.cloneRequestState()\n\n if (count) {\n headers.append('Prefer', `count=${count}`)\n }\n\n return new PostgrestFilterBuilder({\n method,\n url,\n headers,\n schema: this.schema,\n fetch: this.fetch ?? fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n}\n","import PostgrestQueryBuilder from './PostgrestQueryBuilder'\nimport PostgrestFilterBuilder from './PostgrestFilterBuilder'\nimport { Fetch, GenericSchema, ClientServerOptions } from './types/common/common'\nimport { GetRpcFunctionFilterBuilderByArgs } from './types/common/rpc'\nimport PostgrestError from './PostgrestError'\nimport { fetchWithRetry } from './fetchWithRetry'\nimport {\n PostgrestOpenApiSpec,\n PostgrestResponseFailure,\n PostgrestSingleResponse,\n} from './types/types'\n\n/**\n * Build the error for a failed OpenAPI request. PostgREST answers with a JSON\n * error object when it produced the failure itself; proxies and disabled\n * OpenAPI output answer with plain text or an empty body, in which case the\n * body (or, failing that, the status text) becomes the message.\n */\nfunction toOpenApiError(body: string, statusText: string): PostgrestError {\n try {\n const parsed = JSON.parse(body)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return new PostgrestError({\n message: String(parsed.message ?? body),\n details: parsed.details ?? '',\n hint: parsed.hint ?? '',\n code: parsed.code ?? '',\n })\n }\n } catch {\n // Not JSON; fall through to the plain-text message.\n }\n return new PostgrestError({ message: body || statusText, details: '', hint: '', code: '' })\n}\n\n/**\n * Build the response for a request that yielded no readable body: the fetch\n * itself rejected (no status is known, so it is 0), or the body stream failed\n * while being read (the response status is preserved).\n */\nfunction toTransportFailure(\n cause: unknown,\n status: number,\n statusText: string\n): PostgrestResponseFailure {\n const err = cause as { name?: string; message?: string } | null | undefined\n return {\n success: false,\n error: new PostgrestError({\n message: `${err?.name ?? 'FetchError'}: ${err?.message}`,\n details: '',\n hint: '',\n code: '',\n }),\n data: null,\n count: null,\n status,\n statusText,\n }\n}\n\n/**\n * PostgREST client.\n *\n * @typeParam Database - Types for the schema from the [type\n * generator](https://supabase.com/docs/reference/javascript/next/typescript-support)\n *\n * @typeParam SchemaName - Postgres schema to switch to. Must be a string\n * literal, the same one passed to the constructor. If the schema is not\n * `\"public\"`, this must be supplied manually.\n */\nexport default class PostgrestClient<\n Database = any,\n ClientOptions extends ClientServerOptions = Database extends {\n __InternalSupabase: infer I extends ClientServerOptions\n }\n ? I\n : {},\n SchemaName extends string & keyof Omit<Database, '__InternalSupabase'> =\n 'public' extends keyof Omit<Database, '__InternalSupabase'>\n ? 'public'\n : string & keyof Omit<Database, '__InternalSupabase'>,\n Schema extends GenericSchema = Omit<\n Database,\n '__InternalSupabase'\n >[SchemaName] extends GenericSchema\n ? Omit<Database, '__InternalSupabase'>[SchemaName]\n : any,\n> {\n url: string\n headers: Headers\n schemaName?: SchemaName\n fetch?: Fetch\n urlLengthLimit: number\n\n // Retry configuration - enabled by default\n retry?: boolean\n\n // TODO: Add back shouldThrowOnError once we figure out the typings\n /**\n * Creates a PostgREST client.\n *\n * @param url - URL of the PostgREST endpoint\n * @param options - Named parameters\n * @param options.headers - Custom headers\n * @param options.schema - Postgres schema to switch to\n * @param options.fetch - Custom fetch\n * @param options.timeout - Optional timeout in milliseconds for all requests. When set, requests will automatically abort after this duration to prevent indefinite hangs.\n * @param options.urlLengthLimit - Maximum URL length in characters before warnings/errors are triggered. Defaults to 8000.\n * @param options.retry - Enable or disable automatic retries for transient errors.\n * When enabled, idempotent requests (GET, HEAD, OPTIONS) that fail with network\n * errors or HTTP 503/520 responses will be automatically retried up to 3 times\n * with exponential backoff (1s, 2s, 4s). Defaults to `true`.\n * @example Using supabase-js (recommended)\n * ```ts\n * import { createClient } from '@supabase/supabase-js'\n *\n * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n * const { data, error } = await supabase.from('profiles').select('*')\n * ```\n *\n * @category Database\n *\n * @remarks\n * - A `timeout` option (in milliseconds) can be set to automatically abort requests that take too long.\n * - A `urlLengthLimit` option (default: 8000) can be set to control when URL length warnings are included in error messages for aborted requests.\n *\n * @example Standalone import for bundle-sensitive environments\n * ```ts\n * import { PostgrestClient } from '@supabase/postgrest-js'\n *\n * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', {\n * headers: { apikey: 'your-publishable-key' },\n * schema: 'public',\n * timeout: 30000, // 30 second timeout\n * })\n * ```\n */\n constructor(\n url: string,\n {\n headers = {},\n schema,\n fetch,\n timeout,\n urlLengthLimit = 8000,\n retry,\n }: {\n headers?: HeadersInit\n schema?: SchemaName\n fetch?: Fetch\n timeout?: number\n urlLengthLimit?: number\n retry?: boolean\n } = {}\n ) {\n this.url = url\n this.headers = new Headers(headers)\n this.schemaName = schema\n this.urlLengthLimit = urlLengthLimit\n\n const originalFetch = fetch ?? globalThis.fetch\n\n // Wrap fetch with timeout if specified\n if (timeout !== undefined && timeout > 0) {\n this.fetch = (input, init) => {\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n // Merge abort signals if one already exists\n const existingSignal = init?.signal\n if (existingSignal) {\n // If the existing signal is already aborted, use it directly\n if (existingSignal.aborted) {\n clearTimeout(timeoutId)\n return originalFetch(input, init)\n }\n\n // Listen to existing signal and abort our controller too\n const abortHandler = () => {\n clearTimeout(timeoutId)\n controller.abort()\n }\n existingSignal.addEventListener('abort', abortHandler, { once: true })\n\n return originalFetch(input, {\n ...init,\n signal: controller.signal,\n }).finally(() => {\n clearTimeout(timeoutId)\n existingSignal.removeEventListener('abort', abortHandler)\n })\n }\n\n return originalFetch(input, {\n ...init,\n signal: controller.signal,\n }).finally(() => clearTimeout(timeoutId))\n }\n } else {\n this.fetch = originalFetch\n }\n this.retry = retry\n }\n /**\n * Perform a query on a table or a view.\n *\n * @param relation - The table or view name to query\n *\n * @category Database\n */\n from<\n TableName extends string & keyof Schema['Tables'],\n Table extends Schema['Tables'][TableName],\n >(relation: TableName): PostgrestQueryBuilder<ClientOptions, Schema, Table, TableName>\n from<ViewName extends string & keyof Schema['Views'], View extends Schema['Views'][ViewName]>(\n relation: ViewName\n ): PostgrestQueryBuilder<ClientOptions, Schema, View, ViewName>\n from(\n relation: (string & keyof Schema['Tables']) | (string & keyof Schema['Views'])\n ): PostgrestQueryBuilder<ClientOptions, Schema, any, any> {\n if (!relation || typeof relation !== 'string' || relation.trim() === '') {\n throw new Error('Invalid relation name: relation must be a non-empty string.')\n }\n\n const url = new URL(`${this.url}/${relation}`)\n return new PostgrestQueryBuilder(url, {\n headers: new Headers(this.headers),\n schema: this.schemaName,\n fetch: this.fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n\n /**\n * Select a schema to query or perform an function (rpc) call.\n *\n * The schema needs to be on the list of exposed schemas inside Supabase.\n *\n * @param schema - The schema to query\n *\n * @category Database\n */\n schema<DynamicSchema extends string & keyof Omit<Database, '__InternalSupabase'>>(\n schema: DynamicSchema\n ): PostgrestClient<\n Database,\n ClientOptions,\n DynamicSchema,\n Database[DynamicSchema] extends GenericSchema ? Database[DynamicSchema] : any\n > {\n return new PostgrestClient(this.url, {\n headers: this.headers,\n schema,\n fetch: this.fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n\n /**\n * Fetch the OpenAPI description PostgREST publishes for this client's schema.\n *\n * The document lists only the tables, views and functions the caller's role\n * holds privileges on; PostgREST applies that filtering server-side. The\n * schema is the one this client was created with, so call `.schema()` first\n * to describe a different one. Transient failures are retried according to\n * the client's `retry` option, like any other idempotent request.\n *\n * @example\n * ```ts\n * const { data, error } = await supabase.getOpenApiSpec()\n * ```\n *\n * @example Describe a schema other than the client default\n * ```ts\n * const { data, error } = await supabase.schema('billing').getOpenApiSpec()\n * ```\n *\n * @category Database\n */\n async getOpenApiSpec(): Promise<PostgrestSingleResponse<PostgrestOpenApiSpec>> {\n const headers = new Headers(this.headers)\n headers.set('Accept', 'application/openapi+json')\n if (this.schemaName) {\n headers.set('Accept-Profile', this.schemaName)\n }\n\n // Headers reach the fetch implementation as a plain object, as in\n // PostgrestBuilder: React Native's XHR-based fetch drops headers that are\n // supplied as a Headers instance.\n const requestHeaders: Record<string, string> = {}\n headers.forEach((value, key) => {\n requestHeaders[key] = value\n })\n\n const fetchImpl = this.fetch ?? globalThis.fetch\n let res: Response\n try {\n res = await fetchWithRetry(\n fetchImpl,\n `${this.url}/`,\n { method: 'GET', headers: requestHeaders },\n this.retry ?? true\n )\n } catch (fetchError) {\n return toTransportFailure(fetchError, 0, '')\n }\n\n let body: string\n try {\n body = await res.text()\n } catch (readError) {\n return toTransportFailure(readError, res.status, res.statusText)\n }\n\n if (res.ok) {\n try {\n return {\n success: true,\n error: null,\n data: JSON.parse(body) as PostgrestOpenApiSpec,\n count: null,\n status: res.status,\n statusText: res.statusText,\n }\n } catch {\n // A 2xx status does not guarantee a JSON body; report it like a failure.\n }\n }\n\n return {\n success: false,\n error: toOpenApiError(body, res.statusText),\n data: null,\n count: null,\n status: res.status,\n statusText: res.statusText,\n }\n }\n\n /**\n * Perform a function call.\n *\n * @param fn - The function name to call\n * @param args - The arguments to pass to the function call\n * @param options - Named parameters\n * @param options.head - When set to `true`, `data` will not be returned.\n * Useful if you only need the count.\n * @param options.get - When set to `true`, the function will be called with\n * read-only access mode.\n * @param options.count - Count algorithm to use to count rows returned by the\n * function. Only applicable for [set-returning\n * functions](https://www.postgresql.org/docs/current/functions-srf.html).\n *\n * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n * hood.\n *\n * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n * statistics under the hood.\n *\n * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n * numbers.\n *\n * @example\n * ```ts\n * // For cross-schema functions where type inference fails, use overrideTypes:\n * const { data } = await supabase\n * .schema('schema_b')\n * .rpc('function_a', {})\n * .overrideTypes<{ id: string; user_id: string }[]>()\n * ```\n *\n * @category Database\n *\n * @example Call a Postgres function without arguments\n * ```ts\n * const { data, error } = await supabase.rpc('hello_world')\n * ```\n *\n * @exampleSql Call a Postgres function without arguments\n * ```sql\n * create function hello_world() returns text as $$\n * select 'Hello world';\n * $$ language sql;\n * ```\n *\n * @exampleResponse Call a Postgres function without arguments\n * ```json\n * {\n * \"data\": \"Hello world\",\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example Call a Postgres function with arguments\n * ```ts\n * const { data, error } = await supabase.rpc('echo', { say: '👋' })\n * ```\n *\n * @exampleSql Call a Postgres function with arguments\n * ```sql\n * create function echo(say text) returns text as $$\n * select say;\n * $$ language sql;\n * ```\n *\n * @exampleResponse Call a Postgres function with arguments\n * ```json\n * {\n * \"data\": \"👋\",\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n *\n * ```\n *\n * @exampleDescription Bulk processing\n * You can process large payloads by passing in an array as an argument.\n *\n * @example Bulk processing\n * ```ts\n * const { data, error } = await supabase.rpc('add_one_each', { arr: [1, 2, 3] })\n * ```\n *\n * @exampleSql Bulk processing\n * ```sql\n * create function add_one_each(arr int[]) returns int[] as $$\n * select array_agg(n + 1) from unnest(arr) as n;\n * $$ language sql;\n * ```\n *\n * @exampleResponse Bulk processing\n * ```json\n * {\n * \"data\": [\n * 2,\n * 3,\n * 4\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Call a Postgres function with filters\n * Postgres functions that return tables can also be combined with [Filters](/docs/reference/javascript/using-filters) and [Modifiers](/docs/reference/javascript/using-modifiers).\n *\n * @example Call a Postgres function with filters\n * ```ts\n * const { data, error } = await supabase\n * .rpc('list_stored_countries')\n * .eq('id', 1)\n * .single()\n * ```\n *\n * @exampleSql Call a Postgres function with filters\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n *\n * insert into\n * countries (id, name)\n * values\n * (1, 'Rohan'),\n * (2, 'The Shire');\n *\n * create function list_stored_countries() returns setof countries as $$\n * select * from countries;\n * $$ language sql;\n * ```\n *\n * @exampleResponse Call a Postgres function with filters\n * ```json\n * {\n * \"data\": {\n * \"id\": 1,\n * \"name\": \"Rohan\"\n * },\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example Call a read-only Postgres function\n * ```ts\n * const { data, error } = await supabase.rpc('hello_world', undefined, { get: true })\n * ```\n *\n * @exampleSql Call a read-only Postgres function\n * ```sql\n * create function hello_world() returns text as $$\n * select 'Hello world';\n * $$ language sql;\n * ```\n *\n * @exampleResponse Call a read-only Postgres function\n * ```json\n * {\n * \"data\": \"Hello world\",\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n rpc<\n FnName extends string & keyof Schema['Functions'],\n Args extends Schema['Functions'][FnName]['Args'] = never,\n FilterBuilder extends GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args> =\n GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args>,\n >(\n fn: FnName,\n args: Args = {} as Args,\n {\n head = false,\n get = false,\n count,\n }: {\n head?: boolean\n get?: boolean\n count?: 'exact' | 'planned' | 'estimated' | (string & {})\n } = {}\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n FilterBuilder['Row'],\n FilterBuilder['Result'],\n FilterBuilder['RelationName'],\n FilterBuilder['Relationships'],\n 'RPC'\n > {\n let method: 'HEAD' | 'GET' | 'POST'\n const url = new URL(`${this.url}/rpc/${fn}`)\n let body: unknown | undefined\n // objects/arrays-of-objects can't be serialized to URL params, use POST + return=minimal instead\n const _isObject = (v: unknown): boolean =>\n v !== null && typeof v === 'object' && (!Array.isArray(v) || v.some(_isObject))\n const _hasObjectArg = head && Object.values(args as object).some(_isObject)\n if (_hasObjectArg) {\n method = 'POST'\n body = args\n } else if (head || get) {\n method = head ? 'HEAD' : 'GET'\n Object.entries(args)\n // params with undefined value needs to be filtered out, otherwise it'll\n // show up as `?param=undefined`\n .filter(([_, value]) => value !== undefined)\n // array values need special syntax\n .map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`])\n .forEach(([name, value]) => {\n url.searchParams.append(name, value)\n })\n } else {\n method = 'POST'\n body = args\n }\n\n const headers = new Headers(this.headers)\n if (_hasObjectArg) {\n headers.set('Prefer', count ? `count=${count},return=minimal` : 'return=minimal')\n } else if (count) {\n headers.set('Prefer', `count=${count}`)\n }\n\n return new PostgrestFilterBuilder({\n method,\n url,\n headers,\n schema: this.schemaName,\n body,\n fetch: this.fetch ?? fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n 'debug' | 'verbose' | 'info' | 'warn' | 'error' | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * Error codes emitted by Firebase SQL client and platform operations.\n */\nexport type FirebaseSqlErrorCode =\n | 'other'\n | 'already-initialized'\n | 'not-initialized'\n | 'not-supported'\n | 'invalid-argument'\n | 'partial-error'\n | 'unauthorized';\n\n/**\n * Error codes emitted by Firebase SQL client and platform operations.\n */\nexport type Code = FirebaseSqlErrorCode;\n\n/**\n * Error codes emitted by Firebase SQL client and platform operations.\n */\nexport const Code = Object.freeze({\n OTHER: 'other' as const satisfies FirebaseSqlErrorCode,\n ALREADY_INITIALIZED:\n 'already-initialized' as const satisfies FirebaseSqlErrorCode,\n NOT_INITIALIZED: 'not-initialized' as const satisfies FirebaseSqlErrorCode,\n NOT_SUPPORTED: 'not-supported' as const satisfies FirebaseSqlErrorCode,\n INVALID_ARGUMENT: 'invalid-argument' as const satisfies FirebaseSqlErrorCode,\n PARTIAL_ERROR: 'partial-error' as const satisfies FirebaseSqlErrorCode,\n UNAUTHORIZED: 'unauthorized' as const satisfies FirebaseSqlErrorCode\n});\n\n/**\n * Categories identifying the origin of a `FirebaseSqlError`.\n */\nexport type FirebaseSqlErrorCategory =\n 'sql-postgrest' | 'sql-platform' | 'sql-client';\n\n/**\n * Categories identifying the origin of a `FirebaseSqlError`.\n */\nexport const FirebaseSqlErrorCategory = Object.freeze({\n SQL_POSTGREST: 'sql-postgrest' as const satisfies FirebaseSqlErrorCategory,\n SQL_PLATFORM: 'sql-platform' as const satisfies FirebaseSqlErrorCategory,\n SQL_CLIENT: 'sql-client' as const satisfies FirebaseSqlErrorCategory\n});\n\n/**\n * Plain JSON-serializable representation of a `FirebaseSqlError`.\n */\nexport interface SerializedFirebaseSqlError {\n /** Error class name ('FirebaseSqlError').\n * @internal\n */\n name: string;\n /** PostgREST wire error code or Firebase SQL platform/client error code. */\n code: string;\n /** Human-readable error message. */\n message: string;\n /** Error origin discriminator ('sql-postgrest' | 'sql-platform' | 'sql-client'). */\n category: string;\n /** Optional detailed error explanation returned by the server. */\n details?: string | undefined;\n /** Optional remediation hint returned by the server. */\n hint?: string | undefined;\n /** Optional HTTP status code associated with the failure. */\n status?: number | undefined;\n}\n\n/**\n * Error class thrown or returned by Firebase SQL operations.\n */\nexport class FirebaseSqlError extends FirebaseError {\n /** Error class name ('FirebaseSqlError').\n * @internal\n */\n readonly name: string = 'FirebaseSqlError';\n /** PostgREST wire error code or Firebase SQL platform/client error code. */\n readonly code: string;\n /** Error origin discriminator ('sql-postgrest' | 'sql-platform' | 'sql-client'). */\n readonly category: string;\n /** Optional detailed error explanation returned by the server. */\n readonly details?: string | undefined;\n /** Optional remediation hint returned by the server. */\n readonly hint?: string | undefined;\n /** Optional HTTP status code associated with the failure. */\n readonly status?: number | undefined;\n\n constructor(\n code: string,\n message: string,\n category: string,\n details?: string | undefined,\n hint?: string | undefined,\n status?: number | undefined\n ) {\n super(code, message);\n this.code = code;\n this.category = category;\n this.details = details;\n this.hint = hint;\n this.status = status;\n\n // Ensure the instanceof operator works as expected on subclasses of Error.\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types\n // and https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n Object.setPrototypeOf(this, FirebaseSqlError.prototype);\n }\n\n /**\n * Serializes this error into a plain JSON-compatible object.\n */\n toJSON(): SerializedFirebaseSqlError {\n const serialized: SerializedFirebaseSqlError = {\n name: this.name,\n code: this.code,\n message: this.message,\n category: this.category\n };\n if (this.details !== undefined) {\n serialized.details = this.details;\n }\n if (this.hint !== undefined) {\n serialized.hint = this.hint;\n }\n if (this.status !== undefined) {\n serialized.status = this.status;\n }\n return serialized;\n }\n\n /** @internal */\n toString(): string {\n const detailsText = this.details ? ` (details: ${this.details})` : '';\n const hintText = this.hint ? ` (hint: ${this.hint})` : '';\n return `${this.name}[code=${this.code}]: ${this.message}${detailsText}${hintText}`.trim();\n }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Code,\n FirebaseSqlError,\n FirebaseSqlErrorCategory,\n type FirebaseSqlErrorCode\n} from './error';\nimport type { MapPostgrestError } from './state';\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\n}\n\nfunction normalizeNonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction normalizeDetails(details: unknown): string | undefined {\n const stringDetails = normalizeNonEmptyString(details);\n if (stringDetails !== undefined) {\n return stringDetails;\n }\n // PostgREST PGRST201 (ambiguous embedding) and Google OnePlatform RPC errors\n // emit structured object/array details rather than strings.\n if (typeof details === 'object' && details !== null) {\n return JSON.stringify(details);\n }\n return undefined;\n}\n\nfunction normalizeHint(hint: unknown): string | undefined {\n return normalizeNonEmptyString(hint);\n}\n\nfunction mapPlatformStatusToCode(\n status: number,\n rpcStatus?: unknown\n): FirebaseSqlErrorCode {\n if (\n status === 401 ||\n status === 403 ||\n rpcStatus === 'UNAUTHENTICATED' ||\n rpcStatus === 'PERMISSION_DENIED'\n ) {\n return Code.UNAUTHORIZED;\n }\n if (status === 400 || rpcStatus === 'INVALID_ARGUMENT') {\n return Code.INVALID_ARGUMENT;\n }\n if (status === 501 || rpcStatus === 'UNIMPLEMENTED') {\n return Code.NOT_SUPPORTED;\n }\n return Code.OTHER;\n}\n\n/**\n * Maps low-level transport and PostgREST HTTP failures into canonical `FirebaseSqlError` instances.\n *\n * Cross-Platform Architecture Note (see go/fsql-postgrest-sdk):\n * All Firebase SQL client platforms (Web/JS, Android/Kotlin, Apple/Swift, Flutter/Dart) communicate\n * with the same Google Cloud PostgREST backend behind Google's ESF gateway and encounter three\n * identical tiers of error responses:\n *\n * 1. `SQL_CLIENT`: Local client or network transport failures (offline, network drops, client termination\n * via `NOT_INITIALIZED`, or invalid client configuration).\n * 2. `SQL_PLATFORM`: Google OnePlatform / ESF pre-adapter JSON envelopes (`{ error: { code, message, status, details } }`)\n * emitted by Google Cloud infrastructure before reaching PostgREST (e.g. invalid App Check token,\n * IAM authentication/permission rejections, quota limits).\n * 3. `POSTGREST`: PostgREST JSON envelopes (`{ code, message, details, hint }`) containing PostgREST\n * error codes or PostgreSQL SQLSTATE codes (`23505` uniqueness violation, `42P01` undefined table, etc.)\n * mapped to canonical `Code.*` values.\n *\n * @internal\n */\nexport const mapPostgrestFailureToFirebaseSqlError: MapPostgrestError = (\n rawError,\n status,\n statusText\n) => {\n if (rawError instanceof FirebaseSqlError) {\n return rawError;\n }\n\n const normalizedStatus = status > 0 ? status : undefined;\n\n if (status === 0) {\n const message =\n isPlainRecord(rawError) &&\n typeof rawError.message === 'string' &&\n rawError.message.length > 0\n ? rawError.message\n : rawError instanceof Error && rawError.message.length > 0\n ? rawError.message\n : typeof rawError === 'string' && rawError.length > 0\n ? rawError\n : 'Network request failed.';\n const details = isPlainRecord(rawError)\n ? normalizeDetails(rawError.details)\n : rawError instanceof Error\n ? normalizeDetails(rawError.stack)\n : undefined;\n const hint = isPlainRecord(rawError)\n ? normalizeHint(rawError.hint)\n : undefined;\n return new FirebaseSqlError(\n Code.OTHER,\n message,\n FirebaseSqlErrorCategory.SQL_CLIENT,\n details,\n hint\n );\n }\n\n const envelopeCandidate =\n Array.isArray(rawError) && rawError.length === 1 ? rawError[0] : rawError;\n\n // Google OnePlatform / ESF pre-adapter rejections wrap errors under a top-level\n // `error` envelope (`{ error: { code, message, status, details } }` or single-element\n // array `[{ error: { ... } }]`), which @supabase/postgrest-js leaves nested via raw JSON.parse.\n if (\n isPlainRecord(envelopeCandidate) &&\n isPlainRecord(envelopeCandidate.error)\n ) {\n const inner = envelopeCandidate.error;\n const code = mapPlatformStatusToCode(status, inner.status);\n const message =\n typeof inner.message === 'string' && inner.message.length > 0\n ? inner.message\n : statusText || `HTTP Error ${status}`;\n return new FirebaseSqlError(\n code,\n message,\n FirebaseSqlErrorCategory.SQL_PLATFORM,\n normalizeDetails(inner.details),\n normalizeHint(inner.hint),\n normalizedStatus\n );\n }\n\n if (\n isPlainRecord(rawError) &&\n typeof rawError.error === 'string' &&\n rawError.error.length > 0\n ) {\n const message =\n typeof rawError.error_description === 'string' &&\n rawError.error_description.length > 0\n ? rawError.error_description\n : typeof rawError.message === 'string' && rawError.message.length > 0\n ? rawError.message\n : rawError.error;\n return new FirebaseSqlError(\n mapPlatformStatusToCode(status, rawError.status),\n message,\n FirebaseSqlErrorCategory.SQL_PLATFORM,\n normalizeDetails(rawError.details),\n normalizeHint(rawError.hint),\n normalizedStatus\n );\n }\n\n if (\n isPlainRecord(rawError) &&\n typeof rawError.code === 'string' &&\n rawError.code.length > 0 &&\n typeof rawError.status !== 'string'\n ) {\n const message =\n typeof rawError.message === 'string' && rawError.message.length > 0\n ? rawError.message\n : statusText || rawError.code;\n return new FirebaseSqlError(\n rawError.code,\n message,\n FirebaseSqlErrorCategory.SQL_POSTGREST,\n normalizeDetails(rawError.details),\n normalizeHint(rawError.hint),\n normalizedStatus\n );\n }\n\n const fallbackMessage =\n isPlainRecord(rawError) &&\n typeof rawError.message === 'string' &&\n rawError.message.length > 0\n ? rawError.message\n : typeof rawError === 'string' && rawError.length > 0\n ? rawError\n : statusText || `HTTP Error ${status}`;\n const fallbackDetails = isPlainRecord(rawError)\n ? normalizeDetails(rawError.details)\n : Array.isArray(rawError)\n ? normalizeDetails(rawError)\n : undefined;\n const fallbackHint = isPlainRecord(rawError)\n ? normalizeHint(rawError.hint)\n : undefined;\n\n return new FirebaseSqlError(\n mapPlatformStatusToCode(\n status,\n isPlainRecord(rawError) ? rawError.status : undefined\n ),\n fallbackMessage,\n FirebaseSqlErrorCategory.SQL_PLATFORM,\n fallbackDetails,\n fallbackHint,\n normalizedStatus\n );\n};\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nexport let SDK_VERSION = '';\n\n/**\n * SDK_VERSION should be set before any database instance is created\n * @internal\n */\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppCheckTokenResult } from '@firebase/app-check-interop-types';\nimport { FirebaseAuthTokenData } from '@firebase/auth-interop-types';\n\nimport {\n Code,\n FirebaseSqlError,\n FirebaseSqlErrorCategory\n} from '../core/error';\nimport { SDK_VERSION } from '../core/version';\n\n/**\n * Lowercased HTTP header keys used by transport for authorization, telemetry, etc.\n * @internal\n */\nexport type FirebaseHeaders = Lowercase<\n | 'x-goog-api-client'\n | 'x-client-version'\n | 'x-firebase-gmpid'\n | 'x-firebase-auth-token'\n | 'x-firebase-appcheck'\n>;\n\n/**\n * Lowercased HTTP Header keys used by transport for authorization, telemetry, etc.\n * @internal\n */\nexport const FirebaseHeaders = Object.freeze({\n GOOG_API_CLIENT: 'x-goog-api-client' as const satisfies FirebaseHeaders,\n CLIENT_VERSION: 'x-client-version' as const satisfies FirebaseHeaders,\n FIREBASE_GMPID: 'x-firebase-gmpid' as const satisfies FirebaseHeaders,\n FIREBASE_AUTH_TOKEN:\n 'x-firebase-auth-token' as const satisfies FirebaseHeaders,\n FIREBASE_APPCHECK: 'x-firebase-appcheck' as const satisfies FirebaseHeaders\n});\n\n/**\n * Lowercased HTTP header keys forbidden for FSQL SDK.\n * Keep in sync with go/firebasesql:sdk:headers.\n */\nconst FORBIDDEN_HEADERS = [\n 'x-firebase-sqlconnect-affinity',\n 'x-goog-request-params',\n 'x-firebase-client',\n 'x-firebase-client-log-type',\n 'authorization'\n] as const;\n\n/** @internal */\nexport const LOWERCASE_DISALLOWED_HEADER_KEYS: ReadonlySet<string> =\n new Set<string>([...Object.values(FirebaseHeaders), ...FORBIDDEN_HEADERS]);\n\n/**\n * Returns the {@linkcode FirebaseHeaders.GOOG_API_CLIENT | 'x-goog-api-client'} header value.\n * @internal\n */\nexport function getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n\n/**\n * Validates that the given header name is not a protected header key (case-insensitive).\n * @throws `FirebaseSqlError` with `Code.INVALID_ARGUMENT` and\n * `FirebaseSqlErrorCategory.SQL_CLIENT` if the header name is a protected\n * header key.\n * @internal\n */\nexport function validateHeaderName(name: string): string {\n // Coerce to a string exactly once. Header validation is a security boundary\n // guarding protected wire headers (e.g. auth and telemetry). Single coercion\n // prevents untyped JS callers from bypassing validation with stateful\n // toString() / [Symbol.toPrimitive] objects that return an allowed name\n // during validation and a forbidden name when applied downstream.\n const headerName = String(name);\n if (LOWERCASE_DISALLOWED_HEADER_KEYS.has(headerName.trim().toLowerCase())) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n `Cannot set protected header ${headerName}.`,\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n return headerName;\n}\n\n/**\n * Validates that the given headers do not contain any protected header keys (case-insensitive).\n * @throws `FirebaseSqlError` with `Code.INVALID_ARGUMENT` and\n * `FirebaseSqlErrorCategory.SQL_CLIENT` if the headers contain any protected\n * header keys.\n * @internal\n */\nexport function validateHeaders(\n headers?: Record<string, string> | undefined\n): void {\n if (!headers) {\n return;\n }\n for (const key of Object.keys(headers)) {\n validateHeaderName(key);\n }\n}\n\n/**\n * Merges headers from any valid `HeadersInit` source into a target `Headers` instance.\n * Normalizes across `Headers` instances, plain records, and tuple arrays using the standard\n * `Headers` constructor.\n *\n * @param target - The destination `Headers` instance to mutate.\n * @param source - Source headers in any valid `HeadersInit` format.\n * @returns The mutated `target` `Headers` instance for convenient chaining.\n * @internal\n */\nexport function mergeHeadersInit(\n target: Headers,\n source?: HeadersInit\n): Headers {\n if (source) {\n new Headers(source).forEach((value, key) => {\n target.set(key, value);\n });\n }\n return target;\n}\n\n/**\n * Resolves and normalizes wire-level request headers from request init options,\n * telemetry, and SDK auth / App Check providers.\n * @internal\n */\nexport function resolveRequestHeaders(\n authToken: FirebaseAuthTokenData | null,\n appCheckToken: AppCheckTokenResult | null,\n init?: RequestInit,\n _appId?: string\n): Record<string, string> {\n const headers = new Headers();\n\n mergeHeadersInit(headers, init?.headers);\n\n for (const key of FORBIDDEN_HEADERS) {\n headers.delete(key);\n }\n\n // Firebase token headers\n // user-supplied authorization headers are overwritten\n if (authToken?.accessToken) {\n headers.set(FirebaseHeaders.FIREBASE_AUTH_TOKEN, authToken.accessToken);\n } else {\n headers.delete(FirebaseHeaders.FIREBASE_AUTH_TOKEN);\n }\n\n if (appCheckToken?.token) {\n headers.set(FirebaseHeaders.FIREBASE_APPCHECK, appCheckToken.token);\n } else {\n headers.delete(FirebaseHeaders.FIREBASE_APPCHECK);\n }\n\n // Telemetry headers\n headers.set(FirebaseHeaders.GOOG_API_CLIENT, getGoogApiClientValue());\n headers.set(FirebaseHeaders.CLIENT_VERSION, 'web/' + SDK_VERSION);\n if (_appId !== undefined) {\n headers.set(FirebaseHeaders.FIREBASE_GMPID, _appId);\n } else {\n headers.delete(FirebaseHeaders.FIREBASE_GMPID);\n }\n\n // Normalize headers\n const headersRecord: Record<string, string> = {};\n headers.forEach((value, key) => {\n headersRecord[key] = value;\n });\n return headersRecord;\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateHeaders } from '../network/headers';\n\nimport { FirebaseSqlErrorCategory, Code, FirebaseSqlError } from './error';\n\n/**\n * Service connection settings for configuring a Firebase SQL client instance.\n */\nexport interface SqlServiceSettings {\n /** Optional PostgreSQL schema name. */\n schemaName?: string | undefined;\n /** Custom HTTP headers to include with outgoing requests. */\n headers?: Record<string, string> | undefined;\n /** Firebase SQL service identifier. */\n serviceId: string;\n /** Firebase SQL service location identifier. */\n location: string;\n /** Optional custom host for emulator or proxy routing. */\n host?: string | undefined;\n /** Optional custom port for emulator or proxy routing. Must be a number between `1` and `65535`. */\n port?: number | undefined;\n /** Whether SSL is enabled (defaults to true; set to false for local HTTP). */\n sslEnabled?: boolean | undefined;\n}\n\n/**\n * Creates a deep defensive copy of a `SqlServiceSettings` object.\n */\nexport function copySqlServiceSettings(\n settings: SqlServiceSettings\n): SqlServiceSettings {\n const settingsCopy: SqlServiceSettings = Object.assign({}, settings);\n if (settings.headers !== undefined) {\n settingsCopy.headers = Object.assign({}, settings.headers);\n }\n return settingsCopy;\n}\n\n/**\n * Freezes a deep copy of the `SqlServiceSettings`.\n * @internal\n */\nexport function freezeSqlServiceSettings(\n settings: SqlServiceSettings\n): SqlServiceSettings {\n const settingsCopy = copySqlServiceSettings(settings);\n if (settingsCopy.headers !== undefined) {\n Object.freeze(settingsCopy.headers);\n }\n return Object.freeze(settingsCopy);\n}\n\n/**\n * Validates that the provided port is a valid TCP port number.\n *\n * @throws `FirebaseSqlError` with `Code.INVALID_ARGUMENT` and `FirebaseSqlErrorCategory.SQL_CLIENT` if port is invalid.\n */\nfunction validatePort(port: unknown): void {\n if (port === undefined) {\n return;\n }\n if (\n typeof port !== 'number' ||\n !Number.isInteger(port) ||\n port < 1 ||\n port > 65535\n ) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n `Port must be a valid integer between 1 and 65535 if provided. Received: ${String(port)}.`,\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n}\n\n/**\n * Validates required `SqlServiceSettings` fields.\n *\n * @returns a deep, frozen copy of the settings.\n * @throws `FirebaseSqlError` with `Code.INVALID_ARGUMENT` and `FirebaseSqlErrorCategory.SQL_CLIENT` if required fields are missing or invalid.\n * @internal\n */\nexport function validateSqlServiceSettings(\n settings: SqlServiceSettings\n): SqlServiceSettings {\n if (!settings) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n 'SqlServiceSettings must be provided.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (!settings.serviceId) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n 'serviceId is required.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (!settings.location) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n 'location is required.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n validatePort(settings.port);\n validateHeaders(settings.headers);\n return freezeSqlServiceSettings(settings);\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @internal */\nexport const FIREBASE_SQL_COMPONENT_NAME = 'firebase-sql';\n\n/** @internal */\nexport const FIREBASE_SQL_PACKAGE_NAME = '@firebase/sql';\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from './core/version';\nimport { FIREBASE_SQL_PACKAGE_NAME } from './util/constants';\n\n/** @internal */\nexport const logger = new Logger(FIREBASE_SQL_PACKAGE_NAME);\n\nexport function getLogLevel(): LogLevelString {\n return LogLevel[logger.logLevel].toLowerCase() as LogLevelString;\n}\nexport function setLogLevel(logLevel: LogLevelString): void {\n logger.setLogLevel(logLevel);\n}\nexport function logDebug(msg: string): void {\n logger.debug(`Firebase SQL (${SDK_VERSION}): ${msg}`);\n}\n\nexport function logError(msg: string): void {\n logger.error(`Firebase SQL (${SDK_VERSION}): ${msg}`);\n}\n\n/**\n * The App Check \"placeholder\" token, i.e. base64 of `{\"error\":\"UNKNOWN_ERROR\"}`,\n * sent when App Check fails to obtain a real token.\n * See `formatDummyToken(defaultTokenErrorData)` in `@firebase/app-check`.\n */\nconst PLACEHOLDER_APP_CHECK_TOKEN = 'eyJlcnJvciI6IlVOS05PV05fRVJST1IifQ==';\n\n/**\n * Returns a partially redacted access token, keeping only a short prefix and\n * suffix so that tokens can be correlated in logs without exposing them.\n * @internal\n */\nexport function redactToken(token: string | null): string {\n if (token === null) {\n return 'null';\n }\n if (token === PLACEHOLDER_APP_CHECK_TOKEN) {\n return `${token} (the \"placeholder\" App Check token)`;\n }\n if (token.length < 30) {\n return '<redacted>';\n }\n return `${token.slice(0, 6)}<redacted>${token.slice(-6)}`;\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Name, Provider } from '@firebase/component';\n\nimport { logError } from '../../logger';\n\n/**\n * Options for retrieving a token.\n *\n * {@linkcode forceRefresh} - if true, forces a token refresh from the underlying service. If no token\n * is available in the underlying service, null will be returned.\n *\n * @internal\n */\nexport interface TokenOptions {\n forceRefresh?: boolean;\n}\n\n/**\n * Common token provider interface for SQL client access token providers.\n * @internal\n */\nexport interface TokenProvider<TToken, TListener> {\n getToken(options?: TokenOptions): Promise<TToken | null>;\n addTokenChangeListener(listener: TListener): void;\n removeTokenChangeListener(listener: TListener): void;\n terminate(): void;\n}\n\n/**\n * Abstract base class managing token retrieval lifecycle, in-flight deduplication,\n * delayed component initialization, and listener registration.\n * @internal\n */\nexport abstract class AbstractTokenProvider<\n Token,\n Component,\n Listener,\n ComponentName extends Name = Name\n> implements TokenProvider<Token, Listener> {\n protected component: Component | undefined;\n /** Promise to dedupe concurrent in-flight getToken() requests */\n private activeGetTokenPromise?: Promise<Token | null> | undefined = undefined;\n /** Promise to dedupe concurrent in-flight getToken({ forceRefresh: true }) requests */\n private activeForceRefreshPromise?: Promise<Token | null> | undefined =\n undefined;\n /** Resolver to settle active inFlightGetToken early when a concurrent force-refresh returns */\n private resolveActiveGetTokenPromise?:\n ((token: Token | null) => void) | undefined = undefined;\n\n /** Unsubscribe callback to release onInit listener from the provider */\n private onInitUnsubscribe?: (() => void) | undefined = undefined;\n\n /**\n * Array of token change listeners registered on this provider.\n * Used to cleanup listeners when the instance is deleted.\n */\n private activeListeners: Listener[] = [];\n /** Array of token change listeners queued to be registered on this provider once it initializes. */\n private queuedListeners: Listener[] = [];\n\n /**\n * @param provider Provider for a Firebase service component\n * @param serverAppToken Static token from a Firebase Server App\n */\n constructor(\n protected readonly provider: Provider<ComponentName> | undefined,\n protected readonly serverAppToken?: string | undefined\n ) {\n this.component =\n (provider?.getImmediate({ optional: true }) as Component) ?? undefined;\n if (!this.component) {\n this.onInitUnsubscribe = provider?.onInit(component => {\n this.component = component as Component;\n const n = this.queuedListeners.length;\n for (let i = 0; i < n; i++) {\n const oldestListener = this.queuedListeners.shift();\n oldestListener && this.addTokenChangeListener(oldestListener);\n }\n this.cancelOnInit();\n });\n }\n }\n\n /**\n * Retrieves the token, deduplicating concurrent in-flight requests.\n *\n * NOTE: Calls {@linkcode requestToken()} which provides the {@linkcode serverAppToken} token if one was provided and no token is available from the\n * underlying service (and `TokenOptions.forceRefresh === false`).\n *\n * {@linkcode TokenOptions.forceRefresh} - if true, forces a token refresh from the underlying service. If no token\n * is available in the underlying service, null will be returned.\n */\n getToken(\n options: TokenOptions = { forceRefresh: false }\n ): Promise<Token | null> {\n if (!this.activeForceRefreshPromise && options.forceRefresh) {\n const forcedPromise = this.requestToken(options)\n .then(token => {\n this.resolveActiveGetTokenPromise?.(token);\n return token;\n })\n .finally(() => {\n if (this.activeForceRefreshPromise === forcedPromise) {\n this.activeForceRefreshPromise = undefined;\n }\n });\n this.activeForceRefreshPromise = forcedPromise;\n }\n if (this.activeForceRefreshPromise) {\n return this.activeForceRefreshPromise;\n }\n\n if (!this.activeGetTokenPromise) {\n const unforcedPromise = new Promise<Token | null>((resolve, reject) => {\n this.resolveActiveGetTokenPromise = resolve;\n this.requestToken(options).then(resolve, reject);\n }).finally(() => {\n if (this.activeGetTokenPromise === unforcedPromise) {\n this.activeGetTokenPromise = undefined;\n this.resolveActiveGetTokenPromise = undefined;\n }\n });\n this.activeGetTokenPromise = unforcedPromise;\n }\n return this.activeGetTokenPromise;\n }\n\n /**\n * Invoke the underlying service to fetch a token.\n * Allows for delayed initialization.\n */\n private requestToken(\n options: TokenOptions = { forceRefresh: false }\n ): Promise<Token | null> {\n if (this.component) {\n return this.fetchToken(this.component, options);\n }\n\n if (!this.provider) {\n if (this.serverAppToken && !options.forceRefresh) {\n return Promise.resolve(this.convertServerAppToken(this.serverAppToken));\n }\n return Promise.resolve(null);\n }\n\n return new Promise<Token | null>((resolve, reject) => {\n // Support delayed initialization. This allows our customers to initialize\n // the Firebase SQL SDK before initializing Auth or AppCheck and ensures that\n // all requests are authenticated if a token becomes available before the timeout expires.\n setTimeout(() => {\n if (this.component) {\n this.requestToken(options).then(resolve, reject);\n } else if (this.serverAppToken && !options.forceRefresh) {\n resolve(this.convertServerAppToken(this.serverAppToken));\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n\n /**\n * Invoke the underlying service component to add a token change listener. If the service is not\n * yet initialized, the listener is buffered and added once the service initializes.\n *\n * NOTE: Does NOT filter out duplicate listeners.\n */\n addTokenChangeListener(listener: Listener): void {\n if (this.component) {\n try {\n this.activeListeners.push(listener);\n this.addListener(this.component, listener);\n } catch (err) {\n this.activeListeners.pop();\n logError(err instanceof Error ? err.message : String(err));\n }\n } else {\n this.queuedListeners.push(listener);\n }\n }\n\n /**\n * Invoke the underlying service component to remove a token change listener. If the service is not\n * yet initialized, the listener is removed from the pending buffer.\n */\n removeTokenChangeListener(listener: Listener): void {\n if (this.component) {\n try {\n removeFirstOccurrenceFromList(listener, this.activeListeners);\n this.removeListener(this.component, listener);\n } catch (err) {\n logError(err instanceof Error ? err.message : String(err));\n }\n }\n removeFirstOccurrenceFromList(listener, this.queuedListeners);\n }\n\n /**\n * Convert the Firebase Server App token to the appropriate token type.\n */\n protected abstract convertServerAppToken(token: string): Token;\n\n /**\n * Get token from underlying service component\n */\n protected abstract fetchToken(\n component: Component,\n options: TokenOptions\n ): Promise<Token | null>;\n\n /**\n * Add a token change listener to the underlying service component\n */\n protected abstract addListener(\n component: Component,\n listener: Listener\n ): void;\n\n /**\n * Remove an added token change listener from the underlying service component\n */\n protected abstract removeListener(\n component: Component,\n listener: Listener\n ): void;\n\n /**\n * Cleans up any pending initialization callbacks.\n * @internal\n */\n protected cancelOnInit(): void {\n this.onInitUnsubscribe?.();\n this.onInitUnsubscribe = undefined;\n this.queuedListeners = [];\n }\n\n /**\n * Terminates the `TokenProvider` instance. Cleans up any outstanding resources.\n * @internal\n */\n terminate(): void {\n this.cancelOnInit();\n [...this.activeListeners].forEach(listener =>\n this.removeTokenChangeListener(listener)\n );\n }\n}\n\n/**\n * Removes the first occurrence of an item from the list.\n * @internal\n */\nfunction removeFirstOccurrenceFromList<Element>(\n item: Element,\n list: Element[]\n): boolean {\n const index = list.indexOf(item);\n if (index !== -1) {\n list.splice(index, 1);\n }\n return index !== -1;\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport {\n AbstractTokenProvider,\n TokenOptions,\n TokenProvider\n} from './AbstractTokenProvider';\n\n/** @internal */\nexport interface AppCheckTokenProvider extends TokenProvider<\n AppCheckTokenResult,\n AppCheckTokenListener\n> {}\n\n/**\n * App Check Provider backed by the `@firebase/app-check-interop-types` component\n * or a `FirebaseServerApp` static `appCheckToken`.\n * @internal\n */\nexport class AppCheckProvider\n extends AbstractTokenProvider<\n AppCheckTokenResult,\n FirebaseAppCheckInternal,\n AppCheckTokenListener,\n AppCheckInternalComponentName\n >\n implements AppCheckTokenProvider\n{\n constructor(\n app: FirebaseApp,\n appCheckInternalProvider:\n Provider<AppCheckInternalComponentName> | undefined\n ) {\n const serverAppToken = _isFirebaseServerApp(app)\n ? app.settings.appCheckToken\n : undefined;\n super(appCheckInternalProvider, serverAppToken);\n }\n\n protected convertServerAppToken(token: string): AppCheckTokenResult {\n return { token };\n }\n\n protected fetchToken(\n component: FirebaseAppCheckInternal,\n options: TokenOptions = { forceRefresh: false }\n ): Promise<AppCheckTokenResult | null> {\n return component.getToken(options.forceRefresh);\n }\n\n protected addListener(\n component: FirebaseAppCheckInternal,\n listener: AppCheckTokenListener\n ): void {\n component.addTokenListener(listener);\n }\n\n protected removeListener(\n component: FirebaseAppCheckInternal,\n listener: AppCheckTokenListener\n ): void {\n component.removeTokenListener(listener);\n }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName,\n FirebaseAuthTokenData\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { logDebug, logError } from '../../logger';\n\nimport {\n AbstractTokenProvider,\n TokenOptions,\n TokenProvider\n} from './AbstractTokenProvider';\n\n/** @internal */\nexport interface FirebaseAuthTokenProvider extends TokenProvider<\n FirebaseAuthTokenData,\n AuthTokenListener\n> {\n getAuth(): FirebaseAuthInternal | undefined;\n}\n\n/** @internal */\nexport type AuthTokenListener = (token: string | null) => void;\n\n/**\n * Auth Token Provider backed by the `@firebase/auth-interop-types` component\n * or a `FirebaseServerApp` static `authIdToken`.\n * @internal\n */\nexport class FirebaseAuthProvider\n extends AbstractTokenProvider<\n FirebaseAuthTokenData,\n FirebaseAuthInternal,\n AuthTokenListener,\n FirebaseAuthInternalName\n >\n implements FirebaseAuthTokenProvider\n{\n constructor(\n app: FirebaseApp,\n authInternalProvider: Provider<FirebaseAuthInternalName> | undefined\n ) {\n const serverAppToken = _isFirebaseServerApp(app)\n ? app.settings.authIdToken\n : undefined;\n super(authInternalProvider, serverAppToken);\n }\n\n getAuth(): FirebaseAuthInternal | undefined {\n return this.component;\n }\n\n protected convertServerAppToken(token: string): FirebaseAuthTokenData {\n return { accessToken: token };\n }\n\n protected fetchToken(\n component: FirebaseAuthInternal,\n options: TokenOptions = { forceRefresh: false }\n ): Promise<FirebaseAuthTokenData | null> {\n return component.getToken(options.forceRefresh).catch((error: unknown) => {\n if (\n error &&\n typeof error === 'object' &&\n 'code' in error &&\n error.code === 'auth/token-not-initialized'\n ) {\n logDebug(\n 'Got auth/token-not-initialized error. Treating as null token.'\n );\n return null;\n }\n const errorMsg = error instanceof Error ? error.message : String(error);\n logError('Error received when attempting to retrieve token: ' + errorMsg);\n return Promise.reject(error);\n });\n }\n\n protected addListener(\n component: FirebaseAuthInternal,\n listener: AuthTokenListener\n ): void {\n component.addAuthTokenListener(listener);\n }\n\n protected removeListener(\n component: FirebaseAuthInternal,\n listener: AuthTokenListener\n ): void {\n component.removeAuthTokenListener(listener);\n }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseAuthTokenData } from '@firebase/auth-interop-types';\nimport { decode, isCloudWorkstation } from '@firebase/util';\n\nimport {\n Code,\n FirebaseSqlError,\n FirebaseSqlErrorCategory\n} from '../core/error';\nimport { SqlServiceSettings } from '../core/settings';\nimport type {\n BuilderExecutionTracker,\n CreateBuilderFetch,\n SqlClientState\n} from '../core/state';\nimport { AppCheckTokenProvider } from '../core/tokenProviders/AppCheckTokenProvider';\nimport { FirebaseAuthTokenProvider } from '../core/tokenProviders/FirebaseAuthTokenProvider';\n\nimport { Fetch, getFetch } from './fetch';\nimport { FirebaseHeaders, resolveRequestHeaders } from './headers';\n\n/**\n * Extracts the user UID from an Auth ID token's `sub` claim.\n *\n * The \"sub\" claim is documented to be \"a non-empty string and must be the uid of the user or device\"\n * (see http://goo.gle/4oGjEQt). Extracting the UID directly from the cryptographic token avoids race\n * conditions where the auth manager's current UID may have changed since the token was issued.\n *\n * @internal\n */\nexport function getAuthUidFromToken(\n token: string | null | undefined\n): string | null {\n if (!token) {\n return null;\n }\n try {\n const parts = token.split('.');\n if (parts.length !== 3) {\n return null;\n }\n const claims = decode(token).claims;\n const sub = claims?.sub;\n return typeof sub === 'string' && sub.length > 0 ? sub : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Normalizes an AbortSignal abort reason or thrown error into a standard AbortError,\n * preserving any existing FirebaseSqlError, AbortError, or TimeoutError.\n *\n * @internal\n */\nexport function toAbortError(signal: AbortSignal, thrown?: unknown): Error {\n const reason: unknown = thrown !== undefined ? thrown : signal.reason;\n if (\n reason instanceof Error &&\n (reason.name === 'AbortError' ||\n reason.name === 'TimeoutError' ||\n reason instanceof FirebaseSqlError)\n ) {\n return reason;\n }\n const message =\n reason instanceof Error\n ? reason.message\n : typeof reason === 'string'\n ? reason\n : 'This operation was aborted';\n const error = new Error(message);\n error.name = 'AbortError';\n return error;\n}\n\n/**\n * Composes two AbortSignals into a single effective AbortSignal.\n *\n * @internal\n */\nexport function composeSignals(\n signal1: AbortSignal | undefined,\n signal2: AbortSignal | undefined\n): { signal: AbortSignal | undefined; cleanup: () => void } {\n if (!signal1) {\n return { signal: signal2, cleanup: () => {} };\n }\n if (!signal2) {\n return { signal: signal1, cleanup: () => {} };\n }\n if (signal1.aborted) {\n return { signal: signal1, cleanup: () => {} };\n }\n if (signal2.aborted) {\n return { signal: signal2, cleanup: () => {} };\n }\n\n if (typeof AbortSignal.any === 'function') {\n return {\n signal: AbortSignal.any([signal1, signal2]),\n cleanup: () => {}\n };\n }\n\n const controller = new AbortController();\n const onAbort1 = (): void => controller.abort(signal1.reason);\n const onAbort2 = (): void => controller.abort(signal2.reason);\n signal1.addEventListener('abort', onAbort1, { once: true });\n signal2.addEventListener('abort', onAbort2, { once: true });\n\n const cleanup = (): void => {\n signal1.removeEventListener('abort', onAbort1);\n signal2.removeEventListener('abort', onAbort2);\n };\n return { signal: controller.signal, cleanup };\n}\n\n/**\n * Interface defining the external API of the transport layer.\n * @internal\n */\nexport interface FirebaseSqlTransportInterface {\n readonly settings?: SqlServiceSettings;\n\n /**\n * Constructs and executes an FSQL HTTP request, and returns the response.\n */\n invokePostgrestOperation(\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response>;\n\n /**\n * Returns a standard `fetch` implementation bound to this transport instance,\n * optionally tracking `FirebaseSqlError` instances on `tracker.clientError` and\n * throwing `AbortError` to immediately short-circuit PostgREST retries.\n */\n toFetch(tracker?: BuilderExecutionTracker): typeof fetch;\n}\n\n/**\n * Configuration options for FirebaseSqlTransport.\n * @internal\n */\nexport interface FirebaseSqlTransportOptions {\n settings?: SqlServiceSettings;\n appId?: string | undefined;\n authTokenProvider?: FirebaseAuthTokenProvider | undefined;\n appCheckTokenProvider?: AppCheckTokenProvider | undefined;\n terminationSignal?: AbortSignal | undefined;\n state?: SqlClientState | undefined;\n}\n\n/**\n * HTTP transport layer for Firebase SQL.\n * @internal\n */\nexport class FirebaseSqlTransport implements FirebaseSqlTransportInterface {\n readonly settings?: SqlServiceSettings;\n protected _appId?: string;\n // TODO: Update _isUsingEmulator if we add emulator support in the future.\n protected _isUsingEmulator = false;\n protected authProvider?: FirebaseAuthTokenProvider;\n protected appCheckProvider?: AppCheckTokenProvider;\n protected _terminationSignal?: AbortSignal;\n protected _state?: SqlClientState;\n\n constructor(options: FirebaseSqlTransportOptions = {}) {\n this.settings = options.settings;\n this._appId = options.appId;\n this.authProvider = options.authTokenProvider;\n this.appCheckProvider = options.appCheckTokenProvider;\n this._terminationSignal = options.terminationSignal;\n this._state = options.state;\n }\n\n /**\n * Constructs and executes an FSQL HTTP request, and returns the response.\n */\n async invokePostgrestOperation(\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response> {\n if (this._state && this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.toString()\n : input.url;\n\n const authProvider =\n this._state?.active?.authTokenProvider ?? this.authProvider;\n const appCheckProvider =\n this._state?.active?.appCheckTokenProvider ?? this.appCheckProvider;\n const appId = this._state?.active?.appId ?? this._appId;\n const terminationSignal =\n this._state?.terminationSignal ?? this._terminationSignal;\n\n if (terminationSignal?.aborted) {\n throw toAbortError(terminationSignal);\n }\n\n const inputSignal =\n init?.signal !== undefined\n ? (init.signal ?? undefined)\n : typeof Request !== 'undefined' && input instanceof Request\n ? input.signal\n : undefined;\n\n const { signal: effectiveSignal, cleanup } = composeSignals(\n inputSignal,\n terminationSignal\n );\n\n const isRequest =\n typeof Request !== 'undefined' && input instanceof Request;\n let mergedHeadersInit: HeadersInit | undefined = init?.headers;\n if (isRequest) {\n if (init?.headers === undefined) {\n mergedHeadersInit = input.headers;\n } else {\n const combined = new Headers(input.headers);\n new Headers(init.headers).forEach((value, key) => {\n combined.set(key, value);\n });\n mergedHeadersInit = combined;\n }\n }\n\n const mergedInit: RequestInit = {\n ...(isRequest\n ? {\n method: input.method,\n body: input.body,\n mode: input.mode,\n credentials: input.credentials,\n cache: input.cache,\n redirect: input.redirect,\n referrer: input.referrer,\n integrity: input.integrity\n }\n : undefined),\n ...init,\n headers: mergedHeadersInit\n };\n\n try {\n const fetchImpl = getFetch();\n\n let authToken: FirebaseAuthTokenData | null = null;\n let appCheckToken: { token: string } | null = null;\n\n try {\n const [authData, appCheckData] = await Promise.all([\n authProvider\n ? authProvider.getToken({ forceRefresh: false })\n : Promise.resolve(null),\n appCheckProvider\n ? appCheckProvider\n .getToken({ forceRefresh: false })\n .catch(() => null)\n : Promise.resolve(null)\n ]);\n authToken = authData;\n appCheckToken = appCheckData;\n } catch (err) {\n if (this._state && this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (effectiveSignal?.aborted) {\n throw toAbortError(effectiveSignal, err);\n }\n throw err;\n }\n\n if (this._state && this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (effectiveSignal?.aborted) {\n throw toAbortError(effectiveSignal);\n }\n\n const headers = resolveRequestHeaders(\n authToken,\n appCheckToken,\n mergedInit,\n appId\n );\n const requestInit = this.buildRequestInit(\n mergedInit,\n headers,\n url,\n effectiveSignal\n );\n const initialUid = getAuthUidFromToken(authToken?.accessToken);\n const canReplayBody = !(\n typeof ReadableStream !== 'undefined' &&\n (requestInit.body instanceof ReadableStream ||\n (isRequest && init?.body === undefined && input.bodyUsed))\n );\n\n return await fetchImpl(url, requestInit)\n .then(async response => {\n if (this._state && this._state.active === null) {\n if (typeof response.body?.cancel === 'function') {\n await response.body.cancel().catch(() => {});\n }\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (\n response.status === 401 &&\n authToken &&\n canReplayBody &&\n authProvider\n ) {\n return this.refreshAuthAndRefetch(\n fetchImpl,\n url,\n requestInit,\n headers,\n authToken,\n response,\n initialUid,\n authProvider\n );\n }\n return response;\n })\n .catch(async err => {\n if (this._state && this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (effectiveSignal?.aborted) {\n throw toAbortError(effectiveSignal, err);\n }\n throw err;\n });\n } finally {\n cleanup();\n }\n }\n\n /**\n * Constructs the final `RequestInit` configuration by merging caller-supplied init options\n * and normalized headers, while applying Cloud Workstation credentials if applicable.\n */\n private buildRequestInit(\n init: RequestInit | undefined,\n headers: Record<string, string>,\n requestUrl: string,\n signal?: AbortSignal | undefined\n ): RequestInit {\n const requestInit: RequestInit = Object.assign({}, init, { headers });\n if (signal !== undefined) {\n requestInit.signal = signal;\n }\n\n // Forward workstation auth cookies when targeting an emulator host in\n // Cloud Workstations, where forwarded ports require cookie auth.\n if (\n isCloudWorkstation(requestUrl) &&\n this._isUsingEmulator &&\n !requestInit.credentials\n ) {\n requestInit.credentials = 'include';\n }\n\n return requestInit;\n }\n\n /**\n * Force-refreshes the Firebase Auth token and retries the request once if a new token was\n * successfully obtained.\n */\n private async refreshAuthAndRefetch(\n fetchImpl: Fetch,\n requestUrl: string,\n requestInit: RequestInit,\n headers: Record<string, string>,\n currentToken: FirebaseAuthTokenData,\n originalResponse: Response,\n initialUid: string | null,\n authProvider: FirebaseAuthTokenProvider\n ): Promise<Response> {\n if (!authProvider) {\n return originalResponse;\n }\n\n const signal = requestInit.signal;\n if (signal?.aborted) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n throw toAbortError(signal);\n }\n\n if (this._state && this._state.active === null) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n\n // Check cached token first to avoid redundant Auth network trips if another\n // concurrent request already refreshed the token in the background.\n let refreshedToken: FirebaseAuthTokenData | null = null;\n try {\n refreshedToken = await authProvider\n .getToken({ forceRefresh: false })\n .then(data => data ?? null)\n .catch(() => null);\n\n if (signal?.aborted) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n throw toAbortError(signal);\n }\n\n if (this._state && this._state.active === null) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n\n if (\n !refreshedToken?.accessToken ||\n refreshedToken.accessToken === currentToken.accessToken\n ) {\n refreshedToken = await authProvider\n .getToken({ forceRefresh: true })\n .then(data => data ?? null)\n .catch(() => null);\n }\n } catch (err) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n if (this._state && this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (signal?.aborted) {\n throw toAbortError(signal, err);\n }\n throw err;\n }\n\n if (signal?.aborted) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n throw toAbortError(signal);\n }\n\n if (this._state && this._state.active === null) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n\n if (\n refreshedToken?.accessToken &&\n refreshedToken.accessToken !== currentToken.accessToken\n ) {\n const refreshedUid = getAuthUidFromToken(refreshedToken.accessToken);\n if (initialUid !== null && refreshedUid !== initialUid) {\n return originalResponse;\n }\n\n // Cancel original response body ReadableStream if it exists\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n const retryHeaders: Record<string, string> = Object.assign({}, headers);\n retryHeaders[FirebaseHeaders.FIREBASE_AUTH_TOKEN] =\n refreshedToken.accessToken;\n const retryRequestInit: RequestInit = Object.assign({}, requestInit, {\n headers: retryHeaders\n });\n return fetchImpl(requestUrl, retryRequestInit);\n }\n return originalResponse;\n }\n\n /**\n * Returns a standard `fetch` implementation bound to this transport instance,\n * optionally tracking `FirebaseSqlError` instances on `tracker.clientError` and\n * throwing `AbortError` to immediately short-circuit PostgREST retries.\n */\n toFetch(tracker?: BuilderExecutionTracker): typeof fetch {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response> => {\n try {\n return await this.invokePostgrestOperation(input, init);\n } catch (err) {\n const errorToTrack =\n this._state && this._state.active === null\n ? new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n )\n : err instanceof FirebaseSqlError\n ? err\n : null;\n\n if (tracker && errorToTrack) {\n tracker.clientError = errorToTrack;\n const abortError = new Error(errorToTrack.message);\n abortError.name = 'AbortError';\n throw abortError;\n }\n throw err;\n }\n };\n }\n}\n\n/** @internal */\nexport const createBuilderFetch: CreateBuilderFetch = (state, tracker) => {\n const transport = new FirebaseSqlTransport({ state });\n return transport.toFetch(tracker);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { jsonEval } from './json';\n\ninterface Claims {\n [key: string]: {};\n}\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const decode = function (token: string): DecodedToken {\n let header = {},\n claims: Claims = {},\n data = {},\n signature = '';\n\n try {\n const parts = token.split('.');\n header = jsonEval(base64Decode(parts[0]) || '') as object;\n claims = jsonEval(base64Decode(parts[1]) || '') as Claims;\n signature = parts[2];\n data = claims['d'] || {};\n delete claims['d'];\n } catch (e) {}\n\n return {\n header,\n claims,\n data,\n signature\n };\n};\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidTimestamp = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n const now: number = Math.floor(new Date().getTime() / 1000);\n let validSince: number = 0,\n validUntil: number = 0;\n\n if (typeof claims === 'object') {\n if (claims.hasOwnProperty('nbf')) {\n validSince = claims['nbf'] as number;\n } else if (claims.hasOwnProperty('iat')) {\n validSince = claims['iat'] as number;\n }\n\n if (claims.hasOwnProperty('exp')) {\n validUntil = claims['exp'] as number;\n } else {\n // token will expire after 24h by default\n validUntil = validSince + 86400;\n }\n }\n\n return (\n !!now &&\n !!validSince &&\n !!validUntil &&\n now >= validSince &&\n now <= validUntil\n );\n};\n\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const issuedAtTime = function (token: string): number | null {\n const claims: Claims = decode(token).claims;\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n return claims['iat'] as number;\n }\n return null;\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidFormat = function (token: string): boolean {\n const decoded = decode(token),\n claims = decoded.claims;\n\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isAdmin = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n return typeof claims === 'object' && claims['admin'] === true;\n};\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseSqlErrorCategory,\n Code,\n FirebaseSqlError\n} from '../core/error';\n\n/** @internal */\nexport type Fetch = typeof fetch;\n\n/**\n * Retrieves the fetch implementation to use for a Firebase SQL network request.\n *\n * `globalThis.fetch` is read on every call (rather than captured once when this\n * module is loaded) so that replacing or stubbing the global, for example with\n * `vi.stubGlobal('fetch', ...)` in tests, takes effect regardless of module load\n * order.\n *\n * @returns The current `globalThis.fetch` function.\n * @throws `FirebaseSqlError` if no fetch implementation is available.\n * @internal\n */\nexport function getFetch(): Fetch {\n const fetchImpl: Fetch | undefined = globalThis.fetch;\n if (!fetchImpl) {\n throw new FirebaseSqlError(\n Code.NOT_SUPPORTED,\n 'No Fetch implementation detected in the current environment.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n return fetchImpl;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks whether host is a cloud workstation or not.\n * @public\n */\nexport function isCloudWorkstation(url: string): boolean {\n // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions\n // In HTTP request builders, it's called with the protocol.\n // If called with protocol prefix, it's a valid URL, so we extract the hostname\n // If called without, we assume the string is the hostname.\n try {\n const host =\n url.startsWith('http://') || url.startsWith('https://')\n ? new URL(url).hostname\n : url;\n return host.endsWith('.cloudworkstations.dev');\n } catch {\n return false;\n }\n}\n\n/**\n * Makes a fetch request to the given server.\n * Mostly used for forwarding cookies in Firebase Studio.\n * @public\n */\nexport async function pingServer(endpoint: string): Promise<boolean> {\n const result = await fetch(endpoint, {\n credentials: 'include'\n });\n return result.ok;\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SqlServiceSettings } from '../core/settings';\n\n/** @internal */\nexport const PROD_HOST = 'firebasedataconnect.googleapis.com';\n\n/**\n * Builds the resolved PostgREST endpoint URL for a given SQL service configuration.\n * Assumes settings have been validated!\n *\n * @throws TypeError if the hostname + protocol combination is invalid for the URL constructor.\n * @internal\n */\nexport function resolvePostgrestUrl(\n settings: SqlServiceSettings,\n projectId: string\n): string {\n const protocol = settings.sslEnabled === false ? 'http' : 'https';\n const host = settings.host ?? PROD_HOST;\n const url = new URL(`${protocol}://${host}`);\n\n if (settings.port !== undefined) {\n url.port = String(settings.port);\n }\n\n const encodedProjectId = encodeURIComponent(projectId);\n const encodedLocation = encodeURIComponent(settings.location);\n const encodedServiceId = encodeURIComponent(settings.serviceId);\n url.pathname = `/v1/projects/${encodedProjectId}/locations/${encodedLocation}/services/${encodedServiceId}/postgrest`;\n\n return url.toString();\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PostgrestFilterBuilder } from '@supabase/postgrest-js';\n\nimport {\n Code,\n FirebaseSqlError,\n FirebaseSqlErrorCategory\n} from '../../core/error';\nimport type {\n BuilderExecutionTracker,\n CreateBuilderFetch,\n MapPostgrestError,\n SqlClientState\n} from '../../core/state';\nimport type {\n UntypedClientOptions,\n UntypedSchema\n} from '../../core/untypedSchema';\nimport { validateHeaderName } from '../../network/headers';\nimport type {\n Builder,\n CheckMatchingArrayTypes,\n ContainsNull,\n IsValidResultOverride,\n MergePartialResult,\n OperationFailure,\n OperationResult,\n OperationSuccess\n} from '../Builder';\nimport type {\n FilterBuilder,\n FilterOperator,\n FilterOrOptions,\n FilterTextSearchOptions,\n NarrowResultColumn\n} from '../FilterBuilder';\nimport type {\n InvalidMethodError,\n TransformBuilder,\n TransformExplainOptions,\n TransformLimitOptions,\n TransformOrderOptions,\n TransformRangeOptions\n} from '../TransformBuilder';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type AnyPostgrestFilterBuilder =\n | PostgrestFilterBuilder<any, any, any, any, any>\n | PostgrestFilterBuilder<\n UntypedClientOptions,\n UntypedSchema,\n never,\n any,\n any,\n any,\n any,\n any\n >;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nexport class FilterBuilderImpl<T, Method = unknown> implements FilterBuilder<\n T,\n Method,\n false\n> {\n private readonly _delegate: AnyPostgrestFilterBuilder;\n private readonly _state: Readonly<SqlClientState>;\n private readonly _createFetch: CreateBuilderFetch;\n private readonly _mapError: MapPostgrestError;\n private _shouldThrowOnError = false;\n\n constructor(\n delegate: AnyPostgrestFilterBuilder,\n state: Readonly<SqlClientState>,\n createFetch: CreateBuilderFetch,\n mapError: MapPostgrestError\n ) {\n this._delegate = delegate;\n this._state = state;\n this._createFetch = createFetch;\n this._mapError = mapError;\n }\n\n throwOnError(): FilterBuilder<T, Method, true> {\n // Keep _delegate in its default shouldThrowOnError = false mode so `await this._delegate`\n // always resolves with HTTP status/statusText intact instead of throwing a PostgrestError\n // that discards them, allowing _execute() to map all errors to FirebaseSqlError first.\n this._shouldThrowOnError = true;\n return this as unknown as FilterBuilder<T, Method, true>;\n }\n\n stripNulls(): this {\n // Delegate without catching so synchronous validation errors (e.g. `.csv().stripNulls()`)\n // propagate unwrapped as raw Error instances matching @supabase/postgrest-js.\n // `void` is used across synchronous builder mutations because PostgrestFilterBuilder is a lazy\n // PromiseLike that only executes when `.then()` is invoked, satisfying no-floating-promises.\n void this._delegate.stripNulls();\n return this;\n }\n\n setHeader(name: string, value: string): this {\n const headerName = validateHeaderName(name);\n void this._delegate.setHeader(headerName, value);\n return this;\n }\n\n retry(enabled: boolean): this {\n void this._delegate.retry(enabled);\n return this;\n }\n\n returns<NewResult>(): TransformBuilder<\n CheckMatchingArrayTypes<T, NewResult>,\n Method,\n false\n > {\n void this._delegate.returns();\n return this as unknown as TransformBuilder<\n CheckMatchingArrayTypes<T, NewResult>,\n Method,\n false\n >;\n }\n\n overrideTypes<\n NewResult,\n Options extends {\n merge?: boolean | undefined;\n } = {\n merge: true;\n }\n >(): Builder<\n IsValidResultOverride<T, NewResult, false, false> extends true\n ? ContainsNull<T> extends true\n ? MergePartialResult<NewResult, NonNullable<T>, Options> | null\n : MergePartialResult<NewResult, T, Options>\n : CheckMatchingArrayTypes<T, NewResult>,\n false\n > {\n void this._delegate.overrideTypes();\n return this as unknown as Builder<\n IsValidResultOverride<T, NewResult, false, false> extends true\n ? ContainsNull<T> extends true\n ? MergePartialResult<NewResult, NonNullable<T>, Options> | null\n : MergePartialResult<NewResult, T, Options>\n : CheckMatchingArrayTypes<T, NewResult>,\n false\n >;\n }\n\n select(\n columns?: string | undefined\n ): FilterBuilder<\n Method extends 'RPC'\n ? unknown extends T\n ? T\n : T extends readonly unknown[]\n ? Array<Record<string, unknown>>\n : Record<string, unknown>\n : Array<Record<string, unknown>>,\n Method,\n false\n > {\n void this._delegate.select(columns);\n return this as unknown as FilterBuilder<\n Method extends 'RPC'\n ? unknown extends T\n ? T\n : T extends readonly unknown[]\n ? Array<Record<string, unknown>>\n : Record<string, unknown>\n : Array<Record<string, unknown>>,\n Method,\n false\n >;\n }\n\n order(\n column: string,\n options?: Readonly<TransformOrderOptions> | undefined\n ): this {\n void this._delegate.order(column, options);\n return this;\n }\n\n limit(\n rows: number,\n options?: Readonly<TransformLimitOptions> | undefined\n ): this {\n void this._delegate.limit(rows, options);\n return this;\n }\n\n range(\n from: number,\n to: number,\n options?: Readonly<TransformRangeOptions> | undefined\n ): this {\n void this._delegate.range(from, to, options);\n return this;\n }\n\n abortSignal(signal: AbortSignal): this {\n void this._delegate.abortSignal(signal);\n return this;\n }\n\n single<\n ResultOne = unknown extends T\n ? Record<string, unknown>\n : T extends ReadonlyArray<infer R>\n ? R\n : never\n >(): Builder<ResultOne, false> {\n void this._delegate.single();\n return this as unknown as Builder<ResultOne, false>;\n }\n\n maybeSingle<\n ResultOne = unknown extends T\n ? Record<string, unknown>\n : T extends ReadonlyArray<infer R>\n ? R\n : never\n >(): Builder<ResultOne | null, false> {\n void this._delegate.maybeSingle();\n return this as unknown as Builder<ResultOne | null, false>;\n }\n\n csv(): Builder<string, false> {\n void this._delegate.csv();\n return this as unknown as Builder<string, false>;\n }\n\n geojson(): Builder<Record<string, unknown>, false> {\n void this._delegate.geojson();\n return this as unknown as Builder<Record<string, unknown>, false>;\n }\n\n explain(\n options?: Readonly<TransformExplainOptions> | undefined\n ): Builder<Array<Record<string, unknown>>, false> | Builder<string, false> {\n void this._delegate.explain(options);\n return this as unknown as\n Builder<Array<Record<string, unknown>>, false> | Builder<string, false>;\n }\n\n rollback(): this {\n void this._delegate.rollback();\n return this;\n }\n\n maxAffected(\n rows: number\n ): Method extends 'PATCH' | 'DELETE' | 'RPC'\n ? this\n : InvalidMethodError<'maxAffected method only available on update or delete'> {\n void this._delegate.maxAffected(rows);\n return this as unknown as Method extends 'PATCH' | 'DELETE' | 'RPC'\n ? this\n : InvalidMethodError<'maxAffected method only available on update or delete'>;\n }\n\n eq(column: string, value: NonNullable<unknown>): this {\n void this._delegate.eq(column, value);\n return this;\n }\n\n neq(column: string, value: unknown): this {\n void this._delegate.neq(column, value);\n return this;\n }\n\n gt(column: string, value: unknown): this {\n void this._delegate.gt(column, value);\n return this;\n }\n\n gte(column: string, value: unknown): this {\n void this._delegate.gte(column, value);\n return this;\n }\n\n lt(column: string, value: unknown): this {\n void this._delegate.lt(column, value);\n return this;\n }\n\n lte(column: string, value: unknown): this {\n void this._delegate.lte(column, value);\n return this;\n }\n\n like(column: string, pattern: string): this {\n void this._delegate.like(column, pattern);\n return this;\n }\n\n likeAllOf(column: string, patterns: readonly string[]): this {\n void this._delegate.likeAllOf(column, patterns);\n return this;\n }\n\n likeAnyOf(column: string, patterns: readonly string[]): this {\n void this._delegate.likeAnyOf(column, patterns);\n return this;\n }\n\n ilike(column: string, pattern: string): this {\n void this._delegate.ilike(column, pattern);\n return this;\n }\n\n ilikeAllOf(column: string, patterns: readonly string[]): this {\n void this._delegate.ilikeAllOf(column, patterns);\n return this;\n }\n\n ilikeAnyOf(column: string, patterns: readonly string[]): this {\n void this._delegate.ilikeAnyOf(column, patterns);\n return this;\n }\n\n regexMatch(column: string, pattern: string): this {\n void this._delegate.regexMatch(column, pattern);\n return this;\n }\n\n regexIMatch(column: string, pattern: string): this {\n void this._delegate.regexIMatch(column, pattern);\n return this;\n }\n\n is(column: string, value: boolean | null): this {\n void this._delegate.is(column, value);\n return this;\n }\n\n isDistinct(column: string, value: unknown): this {\n void this._delegate.isDistinct(column, value);\n return this;\n }\n\n in(column: string, values: readonly unknown[]): this {\n void this._delegate.in(column, values);\n return this;\n }\n\n notIn(column: string, values: readonly unknown[]): this {\n void this._delegate.notIn(column, values);\n return this;\n }\n\n contains<\n Value extends object & {\n readonly [K in keyof Value]: unknown;\n } & {\n readonly [Symbol.iterator]?: never;\n } = Record<string, unknown>\n >(column: string, value: string | readonly unknown[] | Value): this {\n void this._delegate.contains(\n column,\n value as string | readonly unknown[] | Record<string, unknown>\n );\n return this;\n }\n\n containedBy<\n Value extends object & {\n readonly [K in keyof Value]: unknown;\n } & {\n readonly [Symbol.iterator]?: never;\n } = Record<string, unknown>\n >(column: string, value: string | readonly unknown[] | Value): this {\n void this._delegate.containedBy(\n column,\n value as string | readonly unknown[] | Record<string, unknown>\n );\n return this;\n }\n\n rangeGt(column: string, range: string): this {\n void this._delegate.rangeGt(column, range);\n return this;\n }\n\n rangeGte(column: string, range: string): this {\n void this._delegate.rangeGte(column, range);\n return this;\n }\n\n rangeLt(column: string, range: string): this {\n void this._delegate.rangeLt(column, range);\n return this;\n }\n\n rangeLte(column: string, range: string): this {\n void this._delegate.rangeLte(column, range);\n return this;\n }\n\n rangeAdjacent(column: string, range: string): this {\n void this._delegate.rangeAdjacent(column, range);\n return this;\n }\n\n overlaps(column: string, value: string | readonly unknown[]): this {\n void this._delegate.overlaps(column, value);\n return this;\n }\n\n textSearch(\n column: string,\n query: string,\n options?: Readonly<FilterTextSearchOptions> | undefined\n ): this {\n void this._delegate.textSearch(column, query, options);\n return this;\n }\n\n match<\n Query extends object & {\n readonly [K in keyof Query]: unknown;\n } & {\n readonly [Symbol.iterator]?: never;\n } = Record<string, unknown>\n >(query: Query): this {\n void this._delegate.match(query as Record<string, unknown>);\n return this;\n }\n\n not<ColumnName extends string>(\n column: ColumnName,\n operator: 'is',\n value: null\n ): FilterBuilder<NarrowResultColumn<T, ColumnName>, Method, false> & this;\n not(\n column: string,\n operator: FilterOperator | (string & {}),\n value: unknown\n ): this;\n not<ColumnName extends string>(\n column: ColumnName,\n operator: FilterOperator | (string & {}),\n value: unknown\n ):\n | (FilterBuilder<NarrowResultColumn<T, ColumnName>, Method, false> & this)\n | this {\n void this._delegate.not(column, operator, value);\n return this as unknown as FilterBuilder<\n NarrowResultColumn<T, ColumnName>,\n Method,\n false\n > &\n this;\n }\n\n or(filters: string, options?: Readonly<FilterOrOptions> | undefined): this {\n void this._delegate.or(filters, options);\n return this;\n }\n\n filter(\n column: string,\n operator: `${'' | 'not.'}${FilterOperator}` | (string & {}),\n value: unknown\n ): this {\n void this._delegate.filter(column, operator, value);\n return this;\n }\n\n then<TResult1 = OperationResult<T>, TResult2 = never>(\n onfulfilled?:\n | ((value: OperationResult<T>) => TResult1 | PromiseLike<TResult1>)\n | null\n | undefined,\n onrejected?:\n ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined\n ): PromiseLike<TResult1 | TResult2> {\n const result = this._execute();\n return onfulfilled || onrejected\n ? result.then(onfulfilled, onrejected)\n : (result as PromiseLike<TResult1 | TResult2>);\n }\n\n private _fail(\n error: FirebaseSqlError,\n status: number,\n statusText: string\n ): OperationResult<T> {\n if (this._shouldThrowOnError) {\n throw error;\n }\n const failure: OperationFailure = {\n success: false,\n error,\n data: null,\n count: null,\n status,\n statusText\n };\n return failure;\n }\n\n private _execute(): PromiseLike<OperationResult<T>> {\n // Bind a fresh per-execution tracker synchronously before invoking `this._delegate.then(...)`.\n // PostgrestFilterBuilder snapshots `this.fetch` synchronously on entry before yielding microtasks.\n // Dynamic per-execution binding ensures concurrent executions of the same builder instance\n // (e.g. `Promise.all([query, query])`) each receive an isolated `BuilderExecutionTracker`\n // closure, preventing cross-talk between concurrent error/success attributions.\n const tracker: BuilderExecutionTracker = { clientError: null };\n Reflect.set(\n this._delegate,\n 'fetch',\n this._createFetch(this._state, tracker)\n );\n try {\n return this._delegate.then(raw => {\n // Re-check state.active and tracker.clientError after _delegate settles in case terminate()\n // was called in-flight or the transport recorded a pre-flight/token error and aborted fetchWithRetry.\n if (this._state.active === null) {\n return this._fail(\n new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'FirebaseSql instance has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n ),\n 0,\n ''\n );\n }\n\n if (tracker.clientError !== null) {\n return this._fail(tracker.clientError, 0, '');\n }\n\n // @supabase/postgrest-js sets `success: error === null` after `JSON.parse(body)`,\n // so non-2xx responses with a `\"null\"` JSON body arrive with `raw.success === true`\n // and `raw.error === null` (whereas empty `404` rewrites normalize status to `200`/`204`).\n if (\n !raw.success ||\n raw.error !== null ||\n raw.status < 200 ||\n raw.status >= 300\n ) {\n return this._fail(\n this._mapError(raw.error, raw.status, raw.statusText),\n raw.status,\n raw.statusText\n );\n }\n\n const success: OperationSuccess<T> = {\n success: true,\n error: null,\n data: raw.data as T,\n count: raw.count,\n status: raw.status,\n statusText: raw.statusText\n };\n return success;\n });\n } finally {\n Reflect.set(this._delegate, 'fetch', undefined);\n }\n }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PostgrestQueryBuilder } from '@supabase/postgrest-js';\n\nimport type {\n CreateBuilderFetch,\n MapPostgrestError,\n SqlClientState\n} from '../../core/state';\nimport type {\n UntypedClientOptions,\n UntypedSchema,\n UntypedTable\n} from '../../core/untypedSchema';\nimport type { FilterBuilder } from '../FilterBuilder';\nimport type {\n NonIterable,\n QueryBuilder,\n QueryDeleteOptions,\n QueryInsertOptions,\n QuerySelectOptions,\n QueryUpdateOptions,\n QueryUpsertOptions\n} from '../QueryBuilder';\n\nimport {\n type AnyPostgrestFilterBuilder,\n FilterBuilderImpl\n} from './FilterBuilderImpl';\n\nexport class QueryBuilderImpl implements QueryBuilder {\n private readonly _delegate: PostgrestQueryBuilder<\n UntypedClientOptions,\n UntypedSchema,\n UntypedTable\n >;\n private readonly _state: Readonly<SqlClientState>;\n private readonly _createFetch: CreateBuilderFetch;\n private readonly _mapError: MapPostgrestError;\n\n constructor(\n delegate: PostgrestQueryBuilder<\n UntypedClientOptions,\n UntypedSchema,\n UntypedTable\n >,\n state: Readonly<SqlClientState>,\n createFetch: CreateBuilderFetch,\n mapError: MapPostgrestError\n ) {\n this._delegate = delegate;\n this._state = state;\n this._createFetch = createFetch;\n this._mapError = mapError;\n }\n\n private _wrap<T, Method>(\n delegate: AnyPostgrestFilterBuilder\n ): FilterBuilder<T, Method> {\n return new FilterBuilderImpl<T, Method>(\n delegate,\n this._state,\n this._createFetch,\n this._mapError\n );\n }\n\n select(\n columns?: string | undefined,\n options?: Readonly<QuerySelectOptions> | undefined\n ): FilterBuilder<Array<Record<string, unknown>>, 'GET'> {\n return this._wrap(this._delegate.select(columns, options));\n }\n\n insert<\n Row extends NonIterable<\n object & {\n readonly [K in keyof Row]: unknown;\n }\n > = Record<string, unknown>\n >(\n values: Row | readonly Row[],\n options?: Readonly<QueryInsertOptions> | undefined\n ): FilterBuilder<null, 'POST'> {\n return this._wrap(\n this._delegate.insert(\n values as Record<string, unknown> | Array<Record<string, unknown>>,\n options\n )\n );\n }\n\n upsert<\n Row extends NonIterable<\n object & {\n readonly [K in keyof Row]: unknown;\n }\n > = Record<string, unknown>\n >(\n values: Row | readonly Row[],\n options?: Readonly<QueryUpsertOptions> | undefined\n ): FilterBuilder<null, 'POST'> {\n return this._wrap(\n this._delegate.upsert(\n values as Record<string, unknown> | Array<Record<string, unknown>>,\n options\n )\n );\n }\n\n update<\n Row extends NonIterable<\n object & {\n readonly [K in keyof Row]: unknown;\n }\n > = Record<string, unknown>\n >(\n values: Row,\n options?: Readonly<QueryUpdateOptions> | undefined\n ): FilterBuilder<null, 'PATCH'> {\n return this._wrap(\n this._delegate.update(values as Record<string, unknown>, options)\n );\n }\n\n delete(\n options?: Readonly<QueryDeleteOptions> | undefined\n ): FilterBuilder<null, 'DELETE'> {\n return this._wrap(this._delegate.delete(options));\n }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseApp,\n getApp,\n _getProvider,\n _removeServiceInstance\n} from '@firebase/app';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\nimport { PostgrestClient } from '@supabase/postgrest-js';\n\nimport {\n Code,\n FirebaseSqlError,\n FirebaseSqlErrorCategory\n} from '../core/error';\nimport { mapPostgrestFailureToFirebaseSqlError } from '../core/errorMapper';\nimport {\n SqlServiceSettings,\n validateSqlServiceSettings\n} from '../core/settings';\nimport type { SqlClientState } from '../core/state';\nimport { AppCheckProvider } from '../core/tokenProviders/AppCheckTokenProvider';\nimport { FirebaseAuthProvider } from '../core/tokenProviders/FirebaseAuthTokenProvider';\nimport type {\n UntypedClientOptions,\n UntypedDatabase,\n UntypedSchema\n} from '../core/untypedSchema';\nimport { logDebug } from '../logger';\nimport { createBuilderFetch } from '../network/transport';\nimport { FIREBASE_SQL_COMPONENT_NAME } from '../util/constants';\nimport { resolvePostgrestUrl } from '../util/url';\n\nimport type { FilterBuilder } from './FilterBuilder';\nimport { FilterBuilderImpl } from './impl/FilterBuilderImpl';\nimport { QueryBuilderImpl } from './impl/QueryBuilderImpl';\nimport type { QueryBuilder, QueryCountStrategy } from './QueryBuilder';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n [FIREBASE_SQL_COMPONENT_NAME]: FirebaseSql;\n }\n}\n\nexport interface FirebaseSqlRpcOptions {\n head?: boolean | undefined;\n get?: boolean | undefined;\n count?: QueryCountStrategy | undefined;\n}\n\n/**\n * The Firebase SQL service client instance.\n */\nexport class FirebaseSql {\n /** @internal */\n readonly _postgrestUrl: string;\n\n /** @internal */\n private readonly _state: SqlClientState;\n\n private readonly _terminationController = new AbortController();\n\n private readonly _postgrestClient: PostgrestClient<\n UntypedDatabase,\n UntypedClientOptions,\n string,\n UntypedSchema\n >;\n\n /**\n * Should only be called by {@linkcode getSql()}, after validating inputs.\n * @internal\n */\n constructor(\n /** The bound FirebaseApp instance. */\n readonly app: FirebaseApp,\n /** Resolved configuration settings. */\n readonly settings: SqlServiceSettings,\n /** @internal */\n readonly _instanceIdentifier: string,\n /** @internal */\n authInternalProvider: Provider<FirebaseAuthInternalName>,\n /** @internal */\n appCheckInternalProvider: Provider<AppCheckInternalComponentName>\n ) {\n this._postgrestUrl = resolvePostgrestUrl(\n this.settings,\n app.options.projectId!\n );\n\n this._state = {\n active: {\n appId: app.options.appId,\n authTokenProvider: new FirebaseAuthProvider(app, authInternalProvider),\n appCheckTokenProvider: new AppCheckProvider(\n app,\n appCheckInternalProvider\n )\n },\n terminationSignal: this._terminationController.signal\n };\n\n // PostgrestClient is deliberately instantiated without a static `fetch` option.\n // Instead, `createBuilderFetch` is passed down to query/filter builders, which\n // bind an execution-isolated `fetch` dynamically on each query execution to ensure\n // concurrent executions of the same builder instance do not share a single\n // `BuilderExecutionTracker` closure.\n this._postgrestClient = new PostgrestClient(this._postgrestUrl, {\n headers: this.settings.headers,\n schema: this.settings.schemaName\n });\n }\n\n /** @internal */\n _delete(): Promise<void> {\n if (this._state.active !== null) {\n const active = this._state.active;\n this._state.active = null;\n this._terminationController.abort(\n new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n )\n );\n active.appCheckTokenProvider.terminate();\n active.authTokenProvider.terminate();\n _removeServiceInstance(\n this.app,\n FIREBASE_SQL_COMPONENT_NAME,\n this._instanceIdentifier\n );\n }\n return Promise.resolve();\n }\n\n // Encode table and RPC names so `/`, `?`, `#`, and dot-segments cannot traverse out of\n // `/postgrest` or inject query parameters on the shared `firebasedataconnect.googleapis.com`\n // origin (deviating from `PostgrestClient`'s raw URL interpolation while leaving blank\n // `from('')` inputs untouched so `@supabase/postgrest-js`'s raw `Error` still propagates).\n private _encodeResourceSegment(\n segment: string,\n preserveBlank: boolean\n ): string {\n if (segment === '.' || segment === '..') {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n `Invalid resource name \"${segment}\".`,\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (\n typeof segment !== 'string' ||\n segment.length === 0 ||\n (preserveBlank && segment.trim() === '')\n ) {\n return segment;\n }\n return encodeURIComponent(segment);\n }\n\n from(table: string): QueryBuilder {\n if (this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'FirebaseSql instance has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n const delegate = this._postgrestClient.from(\n this._encodeResourceSegment(table, true)\n );\n return new QueryBuilderImpl(\n delegate,\n this._state,\n createBuilderFetch,\n mapPostgrestFailureToFirebaseSqlError\n );\n }\n\n /**\n * Calls a Postgres stored procedure or function (RPC).\n *\n * Untyped RPC results default to `unknown` for type safety. Call `.returns<T>()` or\n * `.overrideTypes<T>()` on the returned builder to specify the expected return type.\n *\n * @param fn - The function name to call.\n * @param params - Named arguments to pass to the function.\n * @param options - Execution options.\n */\n rpc<\n Args extends object & {\n readonly [K in keyof Args]: unknown;\n } & {\n readonly [Symbol.iterator]?: never;\n } = Record<string, unknown>\n >(\n fn: string,\n params?: Args | undefined,\n options?: Readonly<FirebaseSqlRpcOptions> | undefined\n ): FilterBuilder<unknown, 'RPC'> {\n if (this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'FirebaseSql instance has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n const delegate = this._postgrestClient.rpc(\n this._encodeResourceSegment(fn, false),\n params as Record<string, unknown> | undefined,\n options\n );\n return new FilterBuilderImpl<unknown, 'RPC'>(\n delegate,\n this._state,\n createBuilderFetch,\n mapPostgrestFailureToFirebaseSqlError\n );\n }\n}\n\n/**\n * Returns the cached or newly initialized `FirebaseSql` instance for the default `FirebaseApp`.\n *\n * @param settings - Configuration settings for the Firebase SQL service instance.\n */\nexport function getSql(settings: SqlServiceSettings): FirebaseSql;\n\n/**\n * Returns the cached or newly initialized `FirebaseSql` instance for the given `FirebaseApp`.\n *\n * @param app - The `FirebaseApp` instance to bind to.\n * @param settings - Configuration settings for the Firebase SQL service instance.\n */\nexport function getSql(\n app: FirebaseApp,\n settings: SqlServiceSettings\n): FirebaseSql;\n\nexport function getSql(\n appOrSettings: FirebaseApp | SqlServiceSettings,\n settingsArg?: SqlServiceSettings\n): FirebaseSql {\n let app: FirebaseApp;\n let rawSettings: SqlServiceSettings;\n\n if (settingsArg === undefined) {\n app = getApp();\n rawSettings = appOrSettings as SqlServiceSettings;\n } else {\n if (appOrSettings === undefined) {\n app = getApp();\n } else if (\n !appOrSettings ||\n typeof appOrSettings !== 'object' ||\n !('options' in appOrSettings)\n ) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n 'First argument passed to getSql() must be a FirebaseApp or SqlServiceSettings instance.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n } else {\n app = appOrSettings;\n }\n rawSettings = settingsArg;\n }\n\n const validatedSettings = validateSqlServiceSettings(rawSettings);\n\n if (\n typeof app.options?.projectId !== 'string' ||\n app.options.projectId.length === 0\n ) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n 'Project ID must be provided in FirebaseApp options. Did you pass in a proper projectId to initializeApp?',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n\n const instanceIdentifier = getInstanceIdentifier(\n validatedSettings,\n app.options.projectId\n );\n const provider = _getProvider(app, FIREBASE_SQL_COMPONENT_NAME);\n\n if (provider.isInitialized(instanceIdentifier)) {\n logDebug(\n 'Re-using cached instance (NOTE: custom headers set on the original FSQL client are RE-USED when that client is re-used from the instance cache. Creating multiple FSQL clients with the same settings and app, but different headers, is NOT supported. Instead, use .setHeaders() while building an operation chain to set custom headers for that specific operation.)'\n );\n return provider.getImmediate({ identifier: instanceIdentifier });\n }\n\n logDebug('Creating new Firebase SQL instance');\n return provider.initialize({\n instanceIdentifier,\n options: validatedSettings\n });\n}\n\n/**\n * Terminates the `FirebaseSql` instance and removes it from the app's component registry.\n *\n * @param sql - The `FirebaseSql` instance to terminate.\n */\nexport function terminate(sql: FirebaseSql): Promise<void> {\n return sql._delete();\n}\n\n/**\n * Computes a deterministic JSON instance identifier string.\n * Assumes settings have been validated!\n * @internal\n */\nexport function getInstanceIdentifier(\n settings: SqlServiceSettings,\n projectId: string\n): string {\n const resolvedUrl = resolvePostgrestUrl(settings, projectId);\n return JSON.stringify({\n resolvedUrl,\n schemaName: settings.schemaName\n });\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from '../package.json';\n\nimport { FirebaseSql, getInstanceIdentifier } from './api/FirebaseSql';\nimport { FirebaseSqlErrorCategory, Code, FirebaseSqlError } from './core/error';\nimport { SqlServiceSettings } from './core/settings';\nimport { setSDKVersion } from './core/version';\nimport { FIREBASE_SQL_COMPONENT_NAME } from './util/constants';\n\n/**\n * Registers the `@firebase/sql` service component and SDK version with Firebase App.\n *\n * @param variant - Optional SDK build variant identifier.\n * @internal\n */\nexport function registerSql(variant?: string): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n FIREBASE_SQL_COMPONENT_NAME,\n (container, { instanceIdentifier, options }) => {\n const settings = options as SqlServiceSettings;\n const app = container.getProvider('app').getImmediate()!;\n const authProvider = container.getProvider('auth-internal');\n const appCheckProvider = container.getProvider('app-check-internal');\n if (\n typeof app.options?.projectId !== 'string' ||\n app.options.projectId.length === 0\n ) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n 'Project ID must be provided in FirebaseApp options. Did you pass in a proper projectId to initializeApp?',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n const id =\n instanceIdentifier ??\n getInstanceIdentifier(settings, app.options.projectId);\n return new FirebaseSql(\n app,\n settings,\n id,\n authProvider,\n appCheckProvider\n );\n },\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Firebase SQL\n *\n * @packageDocumentation\n */\n\nimport { registerSql } from './register';\n\nexport * from './api';\n\nregisterSql();\n"],"names":["base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","this","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","Error","init_","byteToCharMap","output","i","length","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","push","join","encodeString","btoa","str","out","p","c","charCodeAt","stringToByteArray","decodeString","bytes","pos","c1","String","fromCharCode","c2","u","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","DecodeBase64StringError","constructor","name","base64Decode","e","console","error","FirebaseError","code","message","customData","super","Object","setPrototypeOf","prototype","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","replaceTemplate","ptr","result","start","indexOf","substring","end","key","value","fullMessage","jsonEval","JSON","parse","Component","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","callback","InstantiationMode","ComponentType","PostgrestError","context","details","hint","toJSON","getRetryDelay","attemptIndex","Math","min","RETRYABLE_STATUS_CODES","RETRYABLE_METHODS","sleep","ms","signal","Promise","resolve","aborted","id","setTimeout","removeEventListener","onAbort","clearTimeout","addEventListener","shouldRetry","method","status","attemptCount","retryEnabled","includes","async","fetchWithRetry","fetchImpl","url","request","headers: Record<string, string>","headers","res: Response","res","body","fetchError: any","fetchError","_request$signal","delay","retryAfterHeader","_res$headers$get","_res$headers","get","max","parseInt","text","PostgrestBuilder","builder","shouldThrowOnError","Headers","schema","_builder$shouldThrowO","isMaybeSingle","_builder$isMaybeSingl","shouldStripNulls","_builder$shouldStripN","urlLengthLimit","_builder$urlLengthLim","_builder$retry","retry","fetch","throwOnError","stripNulls","setHeader","set","enabled","then","onfulfilled","onrejected","currentAccept","_fetch","_this","forEach","toString","stringify","_","processResponse","executeWithRetry","catch","errorDetails","cause","causeMessage","_cause$message","causeCode","_cause$code","_fetchError$name","_cause$name","stack","_fetchError$stack","urlLength","success","_fetchError$name2","count","statusText","count: number | null","ok","_this$headers$get","_unused","countHeader","_this$headers$get2","match","contentRange","split","_objectSpread2","_error$hint","_unused2","returns","overrideTypes","PostgrestTransformBuilder","select","columns","quoted","cleanedColumns","map","test","searchParams","append","order","column","ascending","nullsFirst","foreignTable","referencedTable","existingOrder","limit","rows","range","from","to","keyOffset","keyLimit","abortSignal","single","maybeSingle","csv","geojson","explain","analyze","verbose","settings","buffers","wal","format","options","filter","Boolean","forMediatype","rollback","maxAffected","PostgrestReservedCharsRegexp","RegExp","PostgrestFilterBuilder","eq","neq","gt","gte","lt","lte","like","pattern","likeAllOf","patterns","likeAnyOf","ilike","ilikeAllOf","ilikeAnyOf","regexMatch","regexIMatch","is","isDistinct","values","cleanedValues","Set","s","notIn","contains","containedBy","rangeGt","rangeGte","rangeLt","rangeLte","rangeAdjacent","overlaps","textSearch","query","config","typePart","configPart","entries","not","operator","or","filters","PostgrestQueryBuilder","fetch$1","cloneRequestState","URL","head","insert","defaultToNull","reduce","acc","x","concat","keys","uniqueColumns","_this$fetch","upsert","onConflict","ignoreDuplicates","_this$fetch2","update","_this$fetch3","_this$fetch4","toOpenApiError","parsed","_parsed$message","_parsed$details","_parsed$hint","_parsed$code","toTransportFailure","err","_err$name","LogLevel","PostgrestClient","timeout","schemaName","originalFetch","globalThis","init","controller","AbortController","timeoutId","abort","existingSignal","abortHandler","once","finally","relation","trim","getOpenApiSpec","requestHeaders: Record<string, string>","requestHeaders","body: string","_this$retry","readError","rpc","fn","args","method: 'HEAD' | 'GET' | 'POST'","body: unknown | undefined","_isObject","v","some","_hasObjectArg","levelStringToEnum","debug","DEBUG","VERBOSE","info","INFO","warn","WARN","ERROR","silent","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","instance","logType","logLevel","now","Date","toISOString","Code","freeze","OTHER","ALREADY_INITIALIZED","NOT_INITIALIZED","NOT_SUPPORTED","INVALID_ARGUMENT","PARTIAL_ERROR","UNAUTHORIZED","FirebaseSqlErrorCategory","SQL_POSTGREST","SQL_PLATFORM","SQL_CLIENT","FirebaseSqlError","category","serialized","undefined","detailsText","hintText","isPlainRecord","proto","getPrototypeOf","normalizeNonEmptyString","normalizeDetails","stringDetails","normalizeHint","mapPlatformStatusToCode","rpcStatus","mapPostgrestFailureToFirebaseSqlError","rawError","normalizedStatus","envelopeCandidate","inner","error_description","fallbackMessage","fallbackDetails","fallbackHint","SDK_VERSION","FirebaseHeaders","GOOG_API_CLIENT","CLIENT_VERSION","FIREBASE_GMPID","FIREBASE_AUTH_TOKEN","FIREBASE_APPCHECK","FORBIDDEN_HEADERS","LOWERCASE_DISALLOWED_HEADER_KEYS","validateHeaderName","headerName","has","toLowerCase","resolveRequestHeaders","authToken","appCheckToken","_appId","mergeHeadersInit","target","source","delete","accessToken","token","getGoogApiClientValue","headersRecord","copySqlServiceSettings","settingsCopy","assign","validateSqlServiceSettings","serviceId","location","validatePort","port","Number","isInteger","validateHeaders","freezeSqlServiceSettings","FIREBASE_SQL_COMPONENT_NAME","logger","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","log","logDebug","msg","logError","AbstractTokenProvider","provider","serverAppToken","activeGetTokenPromise","activeForceRefreshPromise","resolveActiveGetTokenPromise","onInitUnsubscribe","activeListeners","queuedListeners","component","getImmediate","optional","onInit","n","oldestListener","shift","addTokenChangeListener","cancelOnInit","getToken","forceRefresh","forcedPromise","requestToken","unforcedPromise","reject","fetchToken","convertServerAppToken","listener","addListener","pop","removeTokenChangeListener","removeFirstOccurrenceFromList","removeListener","terminate","item","list","index","splice","AppCheckProvider","app","appCheckInternalProvider","_isFirebaseServerApp","addTokenListener","removeTokenListener","FirebaseAuthProvider","authInternalProvider","authIdToken","getAuth","addAuthTokenListener","removeAuthTokenListener","getAuthUidFromToken","claims","header","signature","parts","decode","sub","toAbortError","thrown","reason","FirebaseSqlTransport","_isUsingEmulator","appId","authProvider","authTokenProvider","appCheckProvider","appCheckTokenProvider","_terminationSignal","terminationSignal","_state","state","invokePostgrestOperation","active","inputSignal","Request","effectiveSignal","cleanup","composeSignals","signal1","signal2","AbortSignal","any","onAbort1","onAbort2","isRequest","mergedHeadersInit","combined","mergedInit","credentials","cache","redirect","referrer","integrity","getFetch","authData","appCheckData","all","requestInit","buildRequestInit","initialUid","canReplayBody","ReadableStream","bodyUsed","response","cancel","refreshAuthAndRefetch","requestUrl","isCloudWorkstation","startsWith","hostname","endsWith","currentToken","originalResponse","refreshedToken","refreshedUid","retryHeaders","toFetch","tracker","errorToTrack","clientError","abortError","createBuilderFetch","resolvePostgrestUrl","projectId","protocol","sslEnabled","host","encodedProjectId","encodeURIComponent","encodedLocation","encodedServiceId","pathname","FilterBuilderImpl","delegate","createFetch","mapError","_shouldThrowOnError","_delegate","_createFetch","_mapError","in","_execute","_fail","Reflect","raw","QueryBuilderImpl","_wrap","FirebaseSql","_instanceIdentifier","_terminationController","_postgrestUrl","_postgrestClient","_delete","_removeServiceInstance","_encodeResourceSegment","segment","preserveBlank","table","params","getSql","appOrSettings","settingsArg","rawSettings","getApp","validatedSettings","instanceIdentifier","getInstanceIdentifier","_getProvider","isInitialized","identifier","initialize","sql","resolvedUrl","registerSql","variant","setSDKVersion","version","_registerComponent","container","getProvider","registerVersion"],"mappings":"wKAiBA,MA0FaA,EAAiB,CAI5BC,eAAgB,KAKhBC,eAAgB,KAMhBC,sBAAuB,KAMvBC,sBAAuB,KAMvBC,kBACE,iEAKF,gBAAIC,GACF,OAAOC,KAAKF,kBAAoB,KAClC,EAKA,wBAAIG,GACF,OAAOD,KAAKF,kBAAoB,KAClC,EASAI,mBAAoC,mBAATC,KAW3B,eAAAC,CAAgBC,EAA8BC,GAC5C,IAAKC,MAAMC,QAAQH,GACjB,MAAMI,MAAM,iDAGdT,KAAKU,QAEL,MAAMC,EAAgBL,EAClBN,KAAKJ,sBACLI,KAAKN,eAEHkB,EAAS,GAEf,IAAK,IAAIC,EAAI,EAAGA,EAAIR,EAAMS,OAAQD,GAAK,EAAG,CACxC,MAAME,EAAQV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YAEzB,ECjTM,SAAUsT,YAAYC,IhBdtB,SAAUC,cAAcC,GAC5BnO,EAAcmO,CAChB,CgBaED,CAAclO,GACdoO,EACE,IAAIhjB,UACFiX,GACA,CAACgM,GAAab,qBAAoBjY,cAChC,MAAMJ,EAAWI,EACXmQ,EAAM2I,EAAUC,YAAY,OAAOxK,eACnCoD,EAAemH,EAAUC,YAAY,iBACrClH,EAAmBiH,EAAUC,YAAY,sBAC/C,GACoC,iBAA3B5I,EAAInQ,SAASuV,WACa,IAAjCpF,EAAInQ,QAAQuV,UAAUjkB,OAEtB,MAAM,IAAI2X,iBACRb,EAAKM,iBACL,2GACAG,EAAyBG,YAG7B,MAAMlR,EACJmgB,GACAC,sBAAsBtY,EAAUuQ,EAAInQ,QAAQuV,WAC9C,OAAO,IAAIwB,YACT5G,EACAvQ,EACA9H,EACA6Z,EACAE,EACD,GACF,UAEDvb,sBAAqB,IAEzB0iB,EAAgBtlB,EAAMklB,EAASF,GAC/BM,EAAgBtlB,EAAMklB,EAAS,UACjC,CC/CAH","x_google_ignoreList":[5,6,7,8,9,10,11,12],"preExistingComment":"firebase-sql.js.map"}
1
+ {"version":3,"file":"firebase-sql.js","sources":["../util/src/crypt.ts","../util/src/errors.ts","../util/src/json.ts","../component/src/component.ts","../component/src/types.ts","../../node_modules/@supabase/postgrest-js/src/PostgrestError.ts","../../node_modules/@supabase/postgrest-js/src/types/common/common.ts","../../node_modules/@supabase/postgrest-js/src/fetchWithRetry.ts","../../node_modules/@supabase/postgrest-js/src/PostgrestBuilder.ts","../../node_modules/@supabase/postgrest-js/src/PostgrestTransformBuilder.ts","../../node_modules/@supabase/postgrest-js/src/PostgrestFilterBuilder.ts","../../node_modules/@supabase/postgrest-js/src/PostgrestQueryBuilder.ts","../../node_modules/@supabase/postgrest-js/src/PostgrestClient.ts","../logger/src/logger.ts","../sql/src/core/error.ts","../sql/src/core/errorMapper.ts","../sql/src/core/version.ts","../sql/src/network/headers.ts","../sql/src/core/settings.ts","../sql/src/util/constants.ts","../sql/src/logger.ts","../sql/src/core/tokenProviders/AbstractTokenProvider.ts","../sql/src/core/tokenProviders/AppCheckTokenProvider.ts","../sql/src/core/tokenProviders/FirebaseAuthTokenProvider.ts","../sql/src/network/transport.ts","../util/src/jwt.ts","../sql/src/network/fetch.ts","../util/src/url.ts","../sql/src/util/url.ts","../sql/src/api/impl/FilterBuilderImpl.ts","../sql/src/api/impl/QueryBuilderImpl.ts","../sql/src/api/FirebaseSql.ts","../sql/src/register.ts","../sql/src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\n// TODO(dlarocque): Define this as a class, since we no longer target ES5.\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length;) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw new DecodeBase64StringError();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * An error encountered while decoding base64 string.\n */\nexport class DecodeBase64StringError extends Error {\n readonly name = 'DecodeBase64StringError';\n}\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // TypeScript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map<Err, string> = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record<string, unknown>\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n // which we can now use since we no longer target ES5.\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap<ErrorCode>\n ) {}\n\n create<K extends ErrorCode>(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n try {\n let ptr = 0;\n let result = '';\n while (ptr < template.length) {\n const start = template.indexOf('{$', ptr);\n if (start === -1) {\n result += template.substring(ptr);\n break;\n }\n const end = template.indexOf('}', start + 2);\n if (end === -1) {\n result += template.substring(ptr);\n break;\n }\n const key = template.substring(start + 2, end);\n const value = data[key];\n result +=\n template.substring(ptr, start) +\n (value != null ? String(value) : `<${key}?>`);\n ptr = end + 1;\n }\n return result;\n } catch (e) {\n // Should never happen, but fallback just in case\n return template;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nexport function jsonEval(str: string): unknown {\n return JSON.parse(str);\n}\n\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data JavaScript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nexport function stringify(data: unknown): string {\n return JSON.stringify(data);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component<T extends Name = Name> {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback<T> | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory<T>,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ComponentContainer } from './component_container';\n\nexport const enum InstantiationMode {\n LAZY = 'LAZY', // Currently most components are LAZY in JS SDK\n EAGER = 'EAGER', // EAGER components are initialized immediately upon registration\n EXPLICIT = 'EXPLICIT' // component needs to be initialized explicitly by calling Provider.initialize()\n}\n\n/**\n * PUBLIC: A public component provides a set of public APIs to customers. A service namespace will be patched\n * onto `firebase` namespace. Assume the component name is `test`, customers will be able\n * to get the service by calling `firebase.test()` or `app.test()` where `app` is a `FirebaseApp` instance.\n *\n * PRIVATE: A private component provides a set of private APIs that are used internally by other\n * Firebase SDKs. No service namespace is created in `firebase` namespace and customers have no way to get them.\n */\nexport const enum ComponentType {\n PUBLIC = 'PUBLIC',\n PRIVATE = 'PRIVATE',\n VERSION = 'VERSION'\n}\n\nexport interface InstanceFactoryOptions {\n instanceIdentifier?: string;\n options?: {};\n}\n\nexport type InitializeOptions = InstanceFactoryOptions;\n\n/**\n * Factory to create an instance of type T, given a ComponentContainer.\n * ComponentContainer is the IOC container that provides {@link Provider}\n * for dependencies.\n *\n * NOTE: The container only provides {@link Provider} rather than the actual instances of dependencies.\n * It is useful for lazily loaded dependencies and optional dependencies.\n */\nexport type InstanceFactory<T extends Name> = (\n container: ComponentContainer,\n options: InstanceFactoryOptions\n) => NameServiceMapping[T];\n\nexport type onInstanceCreatedCallback<T extends Name> = (\n container: ComponentContainer,\n instanceIdentifier: string,\n instance: NameServiceMapping[T]\n) => void;\n\nexport interface Dictionary {\n [key: string]: unknown;\n}\n\n/**\n * This interface will be extended by Firebase SDKs to provide service name and service type mapping.\n * It is used as a generic constraint to ensure type safety.\n */\nexport interface NameServiceMapping {}\n\nexport type Name = keyof NameServiceMapping;\nexport type Service = NameServiceMapping[Name];\n\nexport type OnInitCallBack<T extends Name> = (\n instance: NameServiceMapping[T],\n identifier: string\n) => void;\n","/**\n * Error format\n *\n * Returned by every PostgREST request that fails. When something fails, the\n * single most useful field is usually `hint` — Postgres often returns the\n * actionable fix there, not in `message`. Always log the full object (e.g.\n * `console.error(error)`); logging only `error.message` hides the hint.\n *\n * Read the fields in roughly this order of usefulness:\n *\n * - `hint` — actionable guidance from the database when available. For\n * permission-denied errors (`42501`), this is the literal SQL to fix the\n * problem, e.g.\n * `\"Grant the required privileges to the current role with: GRANT SELECT ON public.users TO anon;\"`.\n * Missing column? `hint` suggests the column you probably meant. Whenever\n * Postgres knows the fix, it puts it in `hint`.\n * - `code` — stable error code from PostgREST (e.g. `PGRST301`) or Postgres\n * (e.g. `42501`). Branch on this rather than on `message` text.\n * - `details` — extra context, often the offending value, key, or row.\n * - `message` — human-readable summary. Useful in UI strings; less useful\n * for debugging.\n *\n * {@link https://postgrest.org/en/stable/api.html?highlight=options#errors-and-http-status-codes}\n */\nexport default class PostgrestError extends Error {\n details: string\n hint: string\n code: string\n\n /**\n * @example\n * ```ts\n * import PostgrestError from '@supabase/postgrest-js'\n *\n * throw new PostgrestError({\n * message: 'Row level security prevented the request',\n * details: 'RLS denied the insert',\n * hint: 'Check your policies',\n * code: 'PGRST301',\n * })\n * ```\n */\n constructor(context: { message: string; details: string; hint: string; code: string }) {\n super(context.message)\n this.name = 'PostgrestError'\n this.details = context.details\n this.hint = context.hint\n this.code = context.code\n }\n\n toJSON(): { name: string; message: string; details: string; hint: string; code: string } {\n return {\n name: this.name,\n message: this.message,\n details: this.details,\n hint: this.hint,\n code: this.code,\n }\n }\n}\n","// Types that are shared between supabase-js and postgrest-js\n\nexport type Fetch = typeof fetch\n\n/**\n * Default number of retry attempts.\n */\nexport const DEFAULT_MAX_RETRIES = 3\n\n/**\n * Default exponential backoff delay function.\n * Delays: 1s, 2s, 4s, 8s, ... (max 30s)\n *\n * @param attemptIndex - Zero-based index of the retry attempt\n * @returns Delay in milliseconds before the next retry\n */\nexport const getRetryDelay = (attemptIndex: number): number =>\n Math.min(1000 * 2 ** attemptIndex, 30000)\n\n/**\n * Status codes that are safe to retry.\n * 520 = Cloudflare timeout/connection errors (transient)\n * 503 = PostgREST schema cache not yet loaded (transient, signals retry via Retry-After header)\n */\nexport const RETRYABLE_STATUS_CODES = [520, 503] as const\n\n/**\n * HTTP methods that are safe to retry (idempotent operations).\n */\nexport const RETRYABLE_METHODS = ['GET', 'HEAD', 'OPTIONS'] as const\n\nexport type GenericRelationship = {\n foreignKeyName: string\n columns: string[]\n isOneToOne?: boolean\n referencedRelation: string\n referencedColumns: string[]\n}\n\nexport type GenericTable = {\n Row: Record<string, unknown>\n Insert: Record<string, unknown>\n Update: Record<string, unknown>\n Relationships: GenericRelationship[]\n /**\n * Names of the `Row` keys that are computed fields (functions taking the row), which\n * PostgREST leaves out of `select('*')`. Generated types declare it; when absent, the\n * computed fields are inferred from `Functions`.\n */\n ComputedFields?: string\n}\n\nexport type GenericUpdatableView = {\n Row: Record<string, unknown>\n Insert: Record<string, unknown>\n Update: Record<string, unknown>\n Relationships: GenericRelationship[]\n ComputedFields?: string\n}\n\nexport type GenericNonUpdatableView = {\n Row: Record<string, unknown>\n Relationships: GenericRelationship[]\n ComputedFields?: string\n}\n\nexport type GenericView = GenericUpdatableView | GenericNonUpdatableView\n\nexport type GenericSetofOption = {\n isSetofReturn?: boolean | undefined\n isOneToOne?: boolean | undefined\n isNotNullable?: boolean | undefined\n to: string\n from: string\n}\n\nexport type GenericFunction = {\n Args: Record<string, unknown> | never\n Returns: unknown\n SetofOptions?: GenericSetofOption\n}\n\nexport type GenericSchema = {\n Tables: Record<string, GenericTable>\n Views: Record<string, GenericView>\n Functions: Record<string, GenericFunction>\n}\n\nexport type ClientServerOptions = {\n PostgrestVersion?: string\n}\n","import {\n DEFAULT_MAX_RETRIES,\n Fetch,\n getRetryDelay,\n RETRYABLE_METHODS,\n RETRYABLE_STATUS_CODES,\n} from './types/common/common'\n\n/**\n * Sleep for a given number of milliseconds.\n * If an AbortSignal is provided, the sleep resolves early when the signal is aborted.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n const id = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n function onAbort() {\n clearTimeout(id)\n resolve()\n }\n signal?.addEventListener('abort', onAbort)\n })\n}\n\n/**\n * Check if a request should be retried based on method and status code.\n */\nfunction shouldRetry(\n method: string,\n status: number,\n attemptCount: number,\n retryEnabled: boolean\n): boolean {\n // Don't retry if retries are disabled or we've exhausted attempts\n if (!retryEnabled || attemptCount >= DEFAULT_MAX_RETRIES) {\n return false\n }\n\n // Only retry idempotent methods (GET, HEAD, OPTIONS)\n if (!RETRYABLE_METHODS.includes(method as (typeof RETRYABLE_METHODS)[number])) {\n return false\n }\n\n // Only retry on specific status codes (520 - Cloudflare errors)\n if (!RETRYABLE_STATUS_CODES.includes(status as (typeof RETRYABLE_STATUS_CODES)[number])) {\n return false\n }\n\n return true\n}\n\nexport interface RetryableRequest {\n method: string\n /** Plain object, never a Headers instance: React Native's XHR-based fetch drops the latter. */\n headers: Record<string, string>\n body?: string\n signal?: AbortSignal\n}\n\n/**\n * Perform a request with the retry policy shared by every PostgREST call.\n *\n * Idempotent methods (GET, HEAD, OPTIONS) are retried up to\n * `DEFAULT_MAX_RETRIES` times when the fetch rejects or the server answers\n * with a retryable status (503, 520). The wait honours the `Retry-After`\n * header when present and backs off exponentially otherwise. Retried\n * attempts carry an `X-Retry-Count` header. Aborted requests (including\n * `AbortSignal.timeout()`, which rejects with `TimeoutError`) and\n * non-idempotent methods are never retried: their rejection propagates\n * unchanged. A response body is drained before its request is retried.\n */\nexport async function fetchWithRetry(\n fetchImpl: Fetch,\n url: string,\n request: RetryableRequest,\n retryEnabled: boolean\n): Promise<Response> {\n let attemptCount = 0\n\n while (true) {\n const headers: Record<string, string> = { ...request.headers }\n if (attemptCount > 0) {\n headers['X-Retry-Count'] = String(attemptCount)\n }\n\n let res: Response\n try {\n res = await fetchImpl(url, {\n method: request.method,\n headers,\n body: request.body,\n signal: request.signal,\n })\n // JS allows throwing any value, and serverless or realm-crossing fetch\n // implementations can reject with non-Error objects. `instanceof Error`\n // is too narrow here; narrow at the use site with optional chaining.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (fetchError: any) {\n // Never retry aborted requests. `AbortSignal.timeout()` rejects with\n // `TimeoutError` rather than `AbortError`, so it needs its own check.\n // Gated on `request.signal?.aborted` because `TimeoutError`, unlike\n // `AbortError`, isn't exclusive to aborts: a custom fetch implementation\n // may throw it for an unrelated, retryable timeout of its own.\n if (\n fetchError?.name === 'AbortError' ||\n fetchError?.code === 'ABORT_ERR' ||\n (fetchError?.name === 'TimeoutError' && request.signal?.aborted)\n ) {\n throw fetchError\n }\n\n // Don't retry network errors for non-idempotent methods\n if (!RETRYABLE_METHODS.includes(request.method as (typeof RETRYABLE_METHODS)[number])) {\n throw fetchError\n }\n\n // Check if we should retry network errors\n if (retryEnabled && attemptCount < DEFAULT_MAX_RETRIES) {\n const delay = getRetryDelay(attemptCount)\n attemptCount++\n await sleep(delay, request.signal)\n continue\n }\n\n // Exhausted retries or retries disabled, throw the last error\n throw fetchError\n }\n\n // Check if we should retry this HTTP response\n if (shouldRetry(request.method, res.status, attemptCount, retryEnabled)) {\n const retryAfterHeader = res.headers?.get('Retry-After') ?? null\n const delay =\n retryAfterHeader !== null\n ? Math.max(0, parseInt(retryAfterHeader, 10) || 0) * 1000\n : getRetryDelay(attemptCount)\n await res.text()\n attemptCount++\n await sleep(delay, request.signal)\n continue\n }\n\n return res\n }\n}\n","import type {\n PostgrestSingleResponse,\n PostgrestResponseSuccess,\n CheckMatchingArrayTypes,\n MergePartialResult,\n IsValidResultOverride,\n} from './types/types'\nimport { ClientServerOptions, Fetch } from './types/common/common'\nimport PostgrestError from './PostgrestError'\nimport { fetchWithRetry } from './fetchWithRetry'\nimport { ContainsNull } from './select-query-parser/types'\n\nexport default abstract class PostgrestBuilder<\n ClientOptions extends ClientServerOptions,\n Result,\n ThrowOnError extends boolean = false,\n> implements PromiseLike<\n ThrowOnError extends true ? PostgrestResponseSuccess<Result> : PostgrestSingleResponse<Result>\n> {\n protected method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'\n protected url: URL\n protected headers: Headers\n protected schema?: string\n protected body?: unknown\n protected shouldThrowOnError = false\n protected signal?: AbortSignal\n protected fetch: Fetch\n protected isMaybeSingle: boolean\n protected shouldStripNulls: boolean\n protected urlLengthLimit: number\n\n // Retry configuration - enabled by default\n protected retryEnabled: boolean = true\n\n /**\n * Creates a builder configured for a specific PostgREST request.\n *\n * @example Using supabase-js (recommended)\n * ```ts\n * import { createClient } from '@supabase/supabase-js'\n *\n * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n * const { data, error } = await supabase.from('users').select('*')\n * ```\n *\n * @category Database\n *\n * @example Standalone import for bundle-sensitive environments\n * ```ts\n * import { PostgrestQueryBuilder } from '@supabase/postgrest-js'\n *\n * const builder = new PostgrestQueryBuilder(\n * new URL('https://xyzcompany.supabase.co/rest/v1/users'),\n * { headers: new Headers({ apikey: 'your-publishable-key' }) }\n * )\n * ```\n */\n constructor(builder: {\n method: 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE'\n url: URL\n headers: HeadersInit\n schema?: string\n body?: unknown\n shouldThrowOnError?: boolean\n signal?: AbortSignal\n fetch?: Fetch\n isMaybeSingle?: boolean\n shouldStripNulls?: boolean\n urlLengthLimit?: number\n // Retry option\n retry?: boolean\n }) {\n this.method = builder.method\n this.url = builder.url\n this.headers = new Headers(builder.headers)\n this.schema = builder.schema\n this.body = builder.body\n this.shouldThrowOnError = builder.shouldThrowOnError ?? false\n this.signal = builder.signal\n this.isMaybeSingle = builder.isMaybeSingle ?? false\n this.shouldStripNulls = builder.shouldStripNulls ?? false\n this.urlLengthLimit = builder.urlLengthLimit ?? 8000\n this.retryEnabled = builder.retry ?? true\n\n if (builder.fetch) {\n this.fetch = builder.fetch\n } else {\n this.fetch = fetch\n }\n }\n\n /**\n * If there's an error with the query, throwOnError will reject the promise by\n * throwing the error instead of returning it as part of a successful response.\n *\n * {@link https://github.com/supabase/supabase-js/issues/92}\n *\n * @category Database\n * @subcategory Using modifiers\n */\n throwOnError(): PostgrestBuilder<ClientOptions, Result, true> {\n this.shouldThrowOnError = true\n return this as PostgrestBuilder<ClientOptions, Result, true>\n }\n\n /**\n * Strip null values from the response data. Properties with `null` values\n * will be omitted from the returned JSON objects.\n *\n * Requires PostgREST 11.2.0+.\n *\n * {@link https://docs.postgrest.org/en/stable/references/api/resource_representation.html#stripped-nulls}\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .stripNulls()\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text, bio text);\n *\n * insert into\n * characters (id, name, bio)\n * values\n * (1, 'Luke', null),\n * (2, 'Leia', 'Princess of Alderaan');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * },\n * {\n * \"id\": 2,\n * \"name\": \"Leia\",\n * \"bio\": \"Princess of Alderaan\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n stripNulls(): this {\n if (this.headers.get('Accept') === 'text/csv') {\n throw new Error('stripNulls() cannot be used with csv()')\n }\n this.shouldStripNulls = true\n return this\n }\n\n /**\n * Set an HTTP header on this single PostgREST request, overriding any header\n * with the same name set on the client.\n *\n * This is an advanced escape hatch for one-off needs (passing a custom\n * `Authorization` for a single query, attaching a tracing header, etc.).\n * Most callers do not need it: configure client-wide headers via the\n * `headers` option when constructing the client, and authentication via\n * Supabase Auth.\n *\n * @param name - HTTP header name\n * @param value - HTTP header value\n *\n * @category Database\n * @subcategory Using modifiers\n */\n setHeader(name: string, value: string): this {\n this.headers = new Headers(this.headers)\n this.headers.set(name, value)\n return this\n }\n\n /**\n * @category Database\n * @subcategory Using modifiers\n *\n * Configure retry behavior for this request.\n *\n * By default, retries are enabled for idempotent requests (GET, HEAD, OPTIONS)\n * that fail with network errors or specific HTTP status codes (503, 520).\n * Retries use exponential backoff (1s, 2s, 4s) with a maximum of 3 attempts.\n *\n * @param enabled - Whether to enable retries for this request\n *\n * @example\n * ```ts\n * // Disable retries for a specific query\n * const { data, error } = await supabase\n * .from('users')\n * .select()\n * .retry(false)\n * ```\n */\n retry(enabled: boolean): this {\n this.retryEnabled = enabled\n return this\n }\n\n then<\n TResult1 = ThrowOnError extends true\n ? PostgrestResponseSuccess<Result>\n : PostgrestSingleResponse<Result>,\n TResult2 = never,\n >(\n onfulfilled?:\n | ((\n value: ThrowOnError extends true\n ? PostgrestResponseSuccess<Result>\n : PostgrestSingleResponse<Result>\n ) => TResult1 | PromiseLike<TResult1>)\n | undefined\n | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null\n ): PromiseLike<TResult1 | TResult2> {\n // https://postgrest.org/en/stable/api.html#switching-schemas\n if (this.schema === undefined) {\n // skip\n } else if (['GET', 'HEAD'].includes(this.method)) {\n this.headers.set('Accept-Profile', this.schema)\n } else {\n this.headers.set('Content-Profile', this.schema)\n }\n if (this.method !== 'GET' && this.method !== 'HEAD') {\n this.headers.set('Content-Type', 'application/json')\n }\n\n // https://docs.postgrest.org/en/stable/references/api/resource_representation.html#stripped-nulls\n if (this.shouldStripNulls) {\n const currentAccept = this.headers.get('Accept')\n if (currentAccept === 'application/vnd.pgrst.object+json') {\n this.headers.set('Accept', 'application/vnd.pgrst.object+json;nulls=stripped')\n } else if (!currentAccept || currentAccept === 'application/json') {\n this.headers.set('Accept', 'application/vnd.pgrst.array+json;nulls=stripped')\n }\n }\n\n // NOTE: Invoke w/o `this` to avoid illegal invocation error.\n // https://github.com/supabase/postgrest-js/pull/247\n const _fetch = this.fetch\n\n // Execute fetch with retry logic\n const executeWithRetry = async (): Promise<{\n error: any\n data: any\n count: number | null\n status: number\n statusText: string\n }> => {\n // Serialize headers as a plain object rather than a Headers instance.\n // React Native's XHR-based fetch silently drops headers (notably Content-Type)\n // when given a Headers instance, causing PGRST202 on parameter-less RPC calls.\n // See supabase/supabase-js#1562 and facebook/react-native#33933.\n // All sibling packages (auth-js, storage-js, functions-js) already pass plain objects.\n const headers: Record<string, string> = {}\n this.headers.forEach((value, key) => {\n headers[key] = value\n })\n\n // Only the fetch itself is retried — processResponse errors must never trigger retries\n const res = await fetchWithRetry(\n _fetch,\n this.url.toString(),\n {\n method: this.method,\n headers,\n body: JSON.stringify(this.body, (_, value) =>\n typeof value === 'bigint' ? value.toString() : value\n ),\n signal: this.signal,\n },\n this.retryEnabled\n )\n\n return await this.processResponse(res)\n }\n\n let res = executeWithRetry()\n\n if (!this.shouldThrowOnError) {\n res = res.catch((fetchError) => {\n // Build detailed error information including cause if available\n // Note: We don't populate code/hint for client-side network errors since those\n // fields are meant for upstream service errors (PostgREST/PostgreSQL)\n let errorDetails = ''\n let hint = ''\n let code = ''\n\n // Add cause information if available (e.g., DNS errors, network failures)\n const cause = fetchError?.cause\n if (cause) {\n const causeMessage = cause?.message ?? ''\n const causeCode = cause?.code ?? ''\n\n errorDetails = `${fetchError?.name ?? 'FetchError'}: ${fetchError?.message}`\n errorDetails += `\\n\\nCaused by: ${cause?.name ?? 'Error'}: ${causeMessage}`\n if (causeCode) {\n errorDetails += ` (${causeCode})`\n }\n if (cause?.stack) {\n errorDetails += `\\n${cause.stack}`\n }\n } else {\n // No cause available, just include the error stack\n errorDetails = fetchError?.stack ?? ''\n }\n\n // Get URL length for potential hints\n const urlLength = this.url.toString().length\n\n // Handle AbortError specially with helpful hints\n if (fetchError?.name === 'AbortError' || fetchError?.code === 'ABORT_ERR') {\n code = ''\n hint = 'Request was aborted (timeout or manual cancellation)'\n\n if (urlLength > this.urlLengthLimit) {\n hint += `. Note: Your request URL is ${urlLength} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`\n }\n }\n // Handle HeadersOverflowError from undici (Node.js fetch implementation)\n else if (\n cause?.name === 'HeadersOverflowError' ||\n cause?.code === 'UND_ERR_HEADERS_OVERFLOW'\n ) {\n code = ''\n hint = 'HTTP headers exceeded server limits (typically 16KB)'\n\n if (urlLength > this.urlLengthLimit) {\n hint += `. Your request URL is ${urlLength} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`\n }\n }\n\n return {\n success: false as const,\n error: {\n message: `${fetchError?.name ?? 'FetchError'}: ${fetchError?.message}`,\n details: errorDetails,\n hint: hint,\n code: code,\n },\n data: null,\n count: null,\n status: 0,\n statusText: '',\n }\n })\n }\n\n return (\n res as Promise<\n ThrowOnError extends true\n ? PostgrestResponseSuccess<Result>\n : PostgrestSingleResponse<Result>\n >\n ).then(onfulfilled, onrejected)\n }\n\n /**\n * Process a fetch response and return the standardized postgrest response.\n */\n private async processResponse(res: Response): Promise<{\n success: boolean\n error: any\n data: any\n count: number | null\n status: number\n statusText: string\n }> {\n let error = null\n let data = null\n let count: number | null = null\n let status = res.status\n let statusText = res.statusText\n\n if (res.ok) {\n if (this.method !== 'HEAD') {\n const body = await res.text()\n if (body === '') {\n // Prefer: return=minimal\n } else if (this.headers.get('Accept') === 'text/csv') {\n data = body\n } else if (\n this.headers.get('Accept') &&\n this.headers.get('Accept')?.includes('application/vnd.pgrst.plan+text')\n ) {\n data = body\n } else {\n try {\n data = JSON.parse(body)\n } catch {\n // A 2xx status doesn't guarantee a JSON body; mirror the non-2xx fallback below.\n error = { message: body }\n data = null\n\n if (this.shouldThrowOnError) {\n throw new PostgrestError({ message: body, details: '', hint: '', code: '' })\n }\n }\n }\n }\n\n const countHeader = this.headers.get('Prefer')?.match(/count=(exact|planned|estimated)/)\n const contentRange = res.headers.get('content-range')?.split('/')\n if (countHeader && contentRange && contentRange.length > 1) {\n count = parseInt(contentRange[1])\n }\n\n // Fix for https://github.com/supabase/postgrest-js/issues/361 — applies to all methods.\n if (this.isMaybeSingle && Array.isArray(data)) {\n if (data.length > 1) {\n error = {\n // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553\n code: 'PGRST116',\n details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`,\n hint: null,\n message: 'JSON object requested, multiple (or no) rows returned',\n }\n data = null\n count = null\n status = 406\n statusText = 'Not Acceptable'\n\n if (this.shouldThrowOnError) {\n // `hint` is null in the returned error to match PostgREST, but\n // PostgrestError types it as a string, like the other throws here.\n throw new PostgrestError({ ...error, hint: error.hint ?? '' })\n }\n } else if (data.length === 1) {\n data = data[0]\n } else {\n data = null\n }\n }\n } else {\n const body = await res.text()\n\n try {\n error = JSON.parse(body)\n\n // Workaround for https://github.com/supabase/postgrest-js/issues/295\n if (Array.isArray(error) && res.status === 404) {\n data = []\n error = null\n status = 200\n statusText = 'OK'\n }\n } catch {\n // Workaround for https://github.com/supabase/postgrest-js/issues/295\n if (res.status === 404 && body === '') {\n status = 204\n statusText = 'No Content'\n } else {\n error = {\n message: body,\n }\n }\n }\n\n if (error && this.shouldThrowOnError) {\n throw new PostgrestError(error)\n }\n }\n\n return {\n success: error === null,\n error,\n data,\n count,\n status,\n statusText,\n }\n }\n\n /**\n * Override the type of the returned `data`.\n *\n * @typeParam NewResult - The new result type to override with\n * @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead\n *\n * @category Database\n * @subcategory Using modifiers\n */\n returns<NewResult>(): PostgrestBuilder<\n ClientOptions,\n CheckMatchingArrayTypes<Result, NewResult>,\n ThrowOnError\n > {\n /* istanbul ignore next */\n return this as unknown as PostgrestBuilder<\n ClientOptions,\n CheckMatchingArrayTypes<Result, NewResult>,\n ThrowOnError\n >\n }\n\n /**\n * Override the type of the returned `data` field in the response.\n *\n * @typeParam NewResult - The new type to cast the response data to\n * @typeParam Options - Optional type configuration (defaults to { merge: true })\n * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true)\n * @example\n * ```typescript\n * // Merge with existing types (default behavior)\n * const query = supabase\n * .from('users')\n * .select()\n * .overrideTypes<{ custom_field: string }>()\n *\n * // Replace existing types completely\n * const replaceQuery = supabase\n * .from('users')\n * .select()\n * .overrideTypes<{ id: number; name: string }, { merge: false }>()\n * ```\n * @returns A PostgrestBuilder instance with the new type\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example Complete Override type of successful response\n * ```ts\n * const { data } = await supabase\n * .from('countries')\n * .select()\n * .overrideTypes<Array<MyType>, { merge: false }>()\n * ```\n *\n * @exampleResponse Complete Override type of successful response\n * ```ts\n * let x: typeof data // MyType[]\n * ```\n *\n * @example Complete Override type of object response\n * ```ts\n * const { data } = await supabase\n * .from('countries')\n * .select()\n * .maybeSingle()\n * .overrideTypes<MyType, { merge: false }>()\n * ```\n *\n * @exampleResponse Complete Override type of object response\n * ```ts\n * let x: typeof data // MyType | null\n * ```\n *\n * @example Partial Override type of successful response\n * ```ts\n * const { data } = await supabase\n * .from('countries')\n * .select()\n * .overrideTypes<Array<{ status: \"A\" | \"B\" }>>()\n * ```\n *\n * @exampleResponse Partial Override type of successful response\n * ```ts\n * let x: typeof data // Array<CountryRowProperties & { status: \"A\" | \"B\" }>\n * ```\n *\n * @example Partial Override type of object response\n * ```ts\n * const { data } = await supabase\n * .from('countries')\n * .select()\n * .maybeSingle()\n * .overrideTypes<{ status: \"A\" | \"B\" }>()\n * ```\n *\n * @exampleResponse Partial Override type of object response\n * ```ts\n * let x: typeof data // CountryRowProperties & { status: \"A\" | \"B\" } | null\n * ```\n *\n * @example Merge vs replace existing types\n * ```typescript\n * // Merge with existing types (default behavior)\n * const query = supabase\n * .from('users')\n * .select()\n * .overrideTypes<{ custom_field: string }>()\n *\n * // Replace existing types completely\n * const replaceQuery = supabase\n * .from('users')\n * .select()\n * .overrideTypes<{ id: number; name: string }, { merge: false }>()\n * ```\n */\n overrideTypes<\n NewResult,\n Options extends { merge?: boolean } = { merge: true },\n >(): PostgrestBuilder<\n ClientOptions,\n IsValidResultOverride<Result, NewResult, false, false> extends true\n ? // Preserve the optionality of the result if the overriden type is an object (case of chaining with `maybeSingle`)\n ContainsNull<Result> extends true\n ? MergePartialResult<NewResult, NonNullable<Result>, Options> | null\n : MergePartialResult<NewResult, Result, Options>\n : CheckMatchingArrayTypes<Result, NewResult>,\n ThrowOnError\n > {\n return this as unknown as PostgrestBuilder<\n ClientOptions,\n IsValidResultOverride<Result, NewResult, false, false> extends true\n ? // Preserve the optionality of the result if the overriden type is an object (case of chaining with `maybeSingle`)\n ContainsNull<Result> extends true\n ? MergePartialResult<NewResult, NonNullable<Result>, Options> | null\n : MergePartialResult<NewResult, Result, Options>\n : CheckMatchingArrayTypes<Result, NewResult>,\n ThrowOnError\n >\n }\n}\n","import PostgrestBuilder from './PostgrestBuilder'\nimport PostgrestFilterBuilder, { InvalidMethodError } from './PostgrestFilterBuilder'\nimport { GetResult } from './select-query-parser/result'\nimport { CheckMatchingArrayTypes } from './types/types'\nimport { ClientServerOptions, GenericSchema } from './types/common/common'\nimport type { MaxAffectedEnabled } from './types/feature-flags'\n\nexport default class PostgrestTransformBuilder<\n ClientOptions extends ClientServerOptions,\n Schema extends GenericSchema,\n Row extends Record<string, unknown>,\n Result,\n RelationName = unknown,\n Relationships = unknown,\n Method = unknown,\n ThrowOnError extends boolean = false,\n> extends PostgrestBuilder<ClientOptions, Result, ThrowOnError> {\n throwOnError(): PostgrestTransformBuilder<\n ClientOptions,\n Schema,\n Row,\n Result,\n RelationName,\n Relationships,\n Method,\n true\n > {\n return super.throwOnError() as PostgrestTransformBuilder<\n ClientOptions,\n Schema,\n Row,\n Result,\n RelationName,\n Relationships,\n Method,\n true\n >\n }\n\n /**\n * Perform a SELECT on the query result.\n *\n * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not\n * return modified rows. By calling this method, modified rows are returned in\n * `data`.\n *\n * @param columns - The columns to retrieve, separated by commas\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `upsert()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .upsert({ id: 1, name: 'Han Solo' })\n * .select()\n * ```\n *\n * @exampleSql With `upsert()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Han');\n * ```\n *\n * @exampleResponse With `upsert()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Han Solo\"\n * }\n * ],\n * \"status\": 201,\n * \"statusText\": \"\"\n * }\n * ```\n */\n select<\n Query extends string = '*',\n NewResultOne = GetResult<Schema, Row, RelationName, Relationships, Query, ClientOptions>,\n >(\n columns?: Query\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Row,\n Method extends 'RPC'\n ? Result extends unknown[]\n ? NewResultOne[]\n : NewResultOne\n : NewResultOne[],\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n > {\n // Remove whitespaces except when quoted\n let quoted = false\n const cleanedColumns = (columns ?? '*')\n .split('')\n .map((c) => {\n if (/\\s/.test(c) && !quoted) {\n return ''\n }\n if (c === '\"') {\n quoted = !quoted\n }\n return c\n })\n .join('')\n this.url.searchParams.set('select', cleanedColumns)\n this.headers.append('Prefer', 'return=representation')\n return this as unknown as PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Row,\n Method extends 'RPC'\n ? Result extends unknown[]\n ? NewResultOne[]\n : NewResultOne\n : NewResultOne[],\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n >\n }\n\n /**\n * Order the query result by `column`.\n *\n * You can call this method multiple times to order by multiple columns.\n *\n * You can order referenced tables, but it only affects the ordering of the\n * parent table if you use `!inner` in the query.\n *\n * @param column - The column to order by\n * @param options - Named parameters\n * @param options.ascending - If `true`, the result will be in ascending order\n * @param options.nullsFirst - If `true`, `null`s appear first. If `false`,\n * `null`s appear last.\n * @param options.referencedTable - Set this to order a referenced table by\n * its columns\n *\n * @category Database\n * @subcategory Using modifiers\n */\n order<ColumnName extends string & keyof Row>(\n column: ColumnName,\n options?: { ascending?: boolean; nullsFirst?: boolean; referencedTable?: undefined }\n ): this\n order(\n column: string,\n options?: { ascending?: boolean; nullsFirst?: boolean; referencedTable?: string }\n ): this\n /**\n * @deprecated Use `options.referencedTable` instead of `options.foreignTable`\n */\n order<ColumnName extends string & keyof Row>(\n column: ColumnName,\n options?: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: undefined }\n ): this\n /**\n * @deprecated Use `options.referencedTable` instead of `options.foreignTable`\n */\n order(\n column: string,\n options?: { ascending?: boolean; nullsFirst?: boolean; foreignTable?: string }\n ): this\n /**\n * Order the query result by `column`.\n *\n * You can call this method multiple times to order by multiple columns.\n *\n * You can order referenced tables, but it only affects the ordering of the\n * parent table if you use `!inner` in the query.\n *\n * @param column - The column to order by\n * @param options - Named parameters\n * @param options.ascending - If `true`, the result will be in ascending order\n * @param options.nullsFirst - If `true`, `null`s appear first. If `false`,\n * `null`s appear last.\n * @param options.referencedTable - Set this to order a referenced table by\n * its columns\n * @param options.foreignTable - Deprecated, use `options.referencedTable`\n * instead\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('id, name')\n * .order('id', { ascending: false })\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 3,\n * \"name\": \"Han\"\n * },\n * {\n * \"id\": 2,\n * \"name\": \"Leia\"\n * },\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription On a referenced table\n * Ordering with `referencedTable` doesn't affect the ordering of the\n * parent table.\n *\n * @example On a referenced table\n * ```ts\n * const { data, error } = await supabase\n * .from('orchestral_sections')\n * .select(`\n * name,\n * instruments (\n * name\n * )\n * `)\n * .order('name', { referencedTable: 'instruments', ascending: false })\n *\n * ```\n *\n * @exampleSql On a referenced table\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 1, 'harp'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse On a referenced table\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"strings\",\n * \"instruments\": [\n * {\n * \"name\": \"violin\"\n * },\n * {\n * \"name\": \"harp\"\n * }\n * ]\n * },\n * {\n * \"name\": \"woodwinds\",\n * \"instruments\": []\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Order parent table by a referenced table\n * Ordering with `referenced_table(col)` affects the ordering of the\n * parent table.\n *\n * @example Order parent table by a referenced table\n * ```ts\n * const { data, error } = await supabase\n * .from('instruments')\n * .select(`\n * name,\n * section:orchestral_sections (\n * name\n * )\n * `)\n * .order('section(name)', { ascending: true })\n *\n * ```\n *\n * @exampleSql Order parent table by a referenced table\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 2, 'flute'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse Order parent table by a referenced table\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"violin\",\n * \"orchestral_sections\": {\"name\": \"strings\"}\n * },\n * {\n * \"name\": \"flute\",\n * \"orchestral_sections\": {\"name\": \"woodwinds\"}\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n order(\n column: string,\n {\n ascending = true,\n nullsFirst,\n foreignTable,\n referencedTable = foreignTable,\n }: {\n ascending?: boolean\n nullsFirst?: boolean\n foreignTable?: string\n referencedTable?: string\n } = {}\n ): this {\n const key = referencedTable ? `${referencedTable}.order` : 'order'\n const existingOrder = this.url.searchParams.get(key)\n\n this.url.searchParams.set(\n key,\n `${existingOrder ? `${existingOrder},` : ''}${column}.${ascending ? 'asc' : 'desc'}${\n nullsFirst === undefined ? '' : nullsFirst ? '.nullsfirst' : '.nullslast'\n }`\n )\n return this\n }\n\n /**\n * Limit the query result by `rows`.\n *\n * @param rows - The maximum number of rows to return\n * @param options - Named parameters\n * @param options.referencedTable - Set this to limit rows of referenced\n * tables instead of the parent table\n * @param options.foreignTable - Deprecated, use `options.referencedTable`\n * instead\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * .limit(1)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Luke\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example On a referenced table\n * ```ts\n * const { data, error } = await supabase\n * .from('orchestral_sections')\n * .select(`\n * name,\n * instruments (\n * name\n * )\n * `)\n * .limit(1, { referencedTable: 'instruments' })\n * ```\n *\n * @exampleSql On a referenced table\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 1, 'harp'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse On a referenced table\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"strings\",\n * \"instruments\": [\n * {\n * \"name\": \"violin\"\n * }\n * ]\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n limit(\n rows: number,\n {\n foreignTable,\n referencedTable = foreignTable,\n }: { foreignTable?: string; referencedTable?: string } = {}\n ): this {\n const key = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`\n this.url.searchParams.set(key, `${rows}`)\n return this\n }\n\n /**\n * Limit the query result by starting at an offset `from` and ending at the offset `to`.\n * Only records within this range are returned.\n * This respects the query order and if there is no order clause the range could behave unexpectedly.\n * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third\n * and fourth rows of the query.\n *\n * @param from - The starting index from which to limit the result\n * @param to - The last index to which to limit the result\n * @param options - Named parameters\n * @param options.referencedTable - Set this to limit rows of referenced\n * tables instead of the parent table\n * @param options.foreignTable - Deprecated, use `options.referencedTable`\n * instead\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * .range(0, 1)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Luke\"\n * },\n * {\n * \"name\": \"Leia\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n range(\n from: number,\n to: number,\n {\n foreignTable,\n referencedTable = foreignTable,\n }: { foreignTable?: string; referencedTable?: string } = {}\n ): this {\n const keyOffset =\n typeof referencedTable === 'undefined' ? 'offset' : `${referencedTable}.offset`\n const keyLimit = typeof referencedTable === 'undefined' ? 'limit' : `${referencedTable}.limit`\n this.url.searchParams.set(keyOffset, `${from}`)\n // Range is inclusive, so add 1\n this.url.searchParams.set(keyLimit, `${to - from + 1}`)\n return this\n }\n\n /**\n * Set the AbortSignal for the fetch request.\n *\n * @param signal - The AbortSignal to use for the fetch request\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @remarks\n * You can use this to set a timeout for the request.\n *\n * @exampleDescription Aborting requests in-flight\n * You can use an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to abort requests.\n * Note that `status` and `statusText` don't mean anything for aborted requests as the request wasn't fulfilled.\n *\n * @example Aborting requests in-flight\n * ```ts\n * const ac = new AbortController()\n *\n * const { data, error } = await supabase\n * .from('very_big_table')\n * .select()\n * .abortSignal(ac.signal)\n *\n * // Abort the request after 100 ms\n * setTimeout(() => ac.abort(), 100)\n * ```\n *\n * @exampleResponse Aborting requests in-flight\n * ```json\n * {\n * \"error\": {\n * \"message\": \"AbortError: The user aborted a request.\",\n * \"details\": \"\",\n * \"hint\": \"The request was aborted locally via the provided AbortSignal.\",\n * \"code\": \"\"\n * },\n * \"status\": 0,\n * \"statusText\": \"\"\n * }\n *\n * ```\n *\n * @example Set a timeout\n * ```ts\n * const { data, error } = await supabase\n * .from('very_big_table')\n * .select()\n * .abortSignal(AbortSignal.timeout(1000 /* ms *\\/))\n * ```\n *\n * @exampleResponse Set a timeout\n * ```json\n * {\n * \"error\": {\n * \"message\": \"FetchError: The user aborted a request.\",\n * \"details\": \"\",\n * \"hint\": \"\",\n * \"code\": \"\"\n * },\n * \"status\": 0,\n * \"statusText\": \"\"\n * }\n *\n * ```\n */\n abortSignal(signal: AbortSignal): this {\n this.signal = signal\n return this\n }\n\n /**\n * Return `data` as a single object instead of an array of objects.\n *\n * Query result must be one row (e.g. using `.limit(1)`), otherwise this\n * returns an error.\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * .limit(1)\n * .single()\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": {\n * \"name\": \"Luke\"\n * },\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n single<ResultOne = Result extends (infer ResultOne)[] ? ResultOne : never>(): PostgrestBuilder<\n ClientOptions,\n ResultOne,\n ThrowOnError\n > {\n this.headers.set('Accept', 'application/vnd.pgrst.object+json')\n return this as unknown as PostgrestBuilder<ClientOptions, ResultOne, ThrowOnError>\n }\n\n /**\n * Return `data` as a single object instead of an array of objects.\n *\n * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise\n * this returns an error.\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .eq('name', 'Katniss')\n * .maybeSingle()\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n maybeSingle<\n ResultOne = Result extends (infer ResultOne)[] ? ResultOne : never,\n >(): PostgrestBuilder<ClientOptions, ResultOne | null, ThrowOnError> {\n // No Accept header override — we fetch as a list and enforce cardinality client-side.\n // Fixes https://github.com/supabase/postgrest-js/issues/361 for all request methods.\n this.isMaybeSingle = true\n return this as unknown as PostgrestBuilder<ClientOptions, ResultOne | null, ThrowOnError>\n }\n\n /**\n * Return `data` as a string in CSV format.\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @exampleDescription Return data as CSV\n * By default, the data is returned in JSON format, but can also be returned as Comma Separated Values.\n *\n * @example Return data as CSV\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .csv()\n * ```\n *\n * @exampleSql Return data as CSV\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse Return data as CSV\n * ```json\n * {\n * \"data\": \"id,name\\n1,Luke\\n2,Leia\\n3,Han\",\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n csv(): PostgrestBuilder<ClientOptions, string, ThrowOnError> {\n this.headers.set('Accept', 'text/csv')\n return this as unknown as PostgrestBuilder<ClientOptions, string, ThrowOnError>\n }\n\n /**\n * Return `data` as an object in [GeoJSON](https://geojson.org) format.\n *\n * @category Database\n * @subcategory Using modifiers\n */\n geojson(): PostgrestBuilder<ClientOptions, Record<string, unknown>, ThrowOnError> {\n this.headers.set('Accept', 'application/geo+json')\n return this as unknown as PostgrestBuilder<ClientOptions, Record<string, unknown>, ThrowOnError>\n }\n\n /**\n * Return `data` as the EXPLAIN plan for the query.\n *\n * You need to enable the\n * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain)\n * setting before using this method.\n *\n * @param options - Named parameters\n *\n * @param options.analyze - If `true`, the query will be executed and the\n * actual run time will be returned\n *\n * @param options.verbose - If `true`, the query identifier will be returned\n * and `data` will include the output columns of the query\n *\n * @param options.settings - If `true`, include information on configuration\n * parameters that affect query planning\n *\n * @param options.buffers - If `true`, include information on buffer usage\n *\n * @param options.wal - If `true`, include information on WAL record generation\n *\n * @param options.format - The format of the output, can be `\"text\"` (default)\n * or `\"json\"`\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @exampleDescription Get the execution plan\n * By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter.\n *\n * @example Get the execution plan\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .explain()\n * ```\n *\n * @exampleSql Get the execution plan\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse Get the execution plan\n * ```js\n * Aggregate (cost=33.34..33.36 rows=1 width=112)\n * -> Limit (cost=0.00..18.33 rows=1000 width=40)\n * -> Seq Scan on characters (cost=0.00..22.00 rows=1200 width=40)\n * ```\n *\n * @exampleDescription Get the execution plan with analyze and verbose\n * By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter.\n *\n * @example Get the execution plan with analyze and verbose\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .explain({analyze:true,verbose:true})\n * ```\n *\n * @exampleSql Get the execution plan with analyze and verbose\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse Get the execution plan with analyze and verbose\n * ```js\n * Aggregate (cost=33.34..33.36 rows=1 width=112) (actual time=0.041..0.041 rows=1 loops=1)\n * Output: NULL::bigint, count(ROW(characters.id, characters.name)), COALESCE(json_agg(ROW(characters.id, characters.name)), '[]'::json), NULLIF(current_setting('response.headers'::text, true), ''::text), NULLIF(current_setting('response.status'::text, true), ''::text)\n * -> Limit (cost=0.00..18.33 rows=1000 width=40) (actual time=0.005..0.006 rows=3 loops=1)\n * Output: characters.id, characters.name\n * -> Seq Scan on public.characters (cost=0.00..22.00 rows=1200 width=40) (actual time=0.004..0.005 rows=3 loops=1)\n * Output: characters.id, characters.name\n * Query Identifier: -4730654291623321173\n * Planning Time: 0.407 ms\n * Execution Time: 0.119 ms\n * ```\n */\n explain({\n analyze = false,\n verbose = false,\n settings = false,\n buffers = false,\n wal = false,\n format = 'text',\n }: {\n analyze?: boolean\n verbose?: boolean\n settings?: boolean\n buffers?: boolean\n wal?: boolean\n format?: 'json' | 'text'\n } = {}) {\n const options = [\n analyze ? 'analyze' : null,\n verbose ? 'verbose' : null,\n settings ? 'settings' : null,\n buffers ? 'buffers' : null,\n wal ? 'wal' : null,\n ]\n .filter(Boolean)\n .join('|')\n // An Accept header can carry multiple media types but postgrest-js always sends one\n const forMediatype = this.headers.get('Accept') ?? 'application/json'\n this.headers.set(\n 'Accept',\n `application/vnd.pgrst.plan+${format}; for=\"${forMediatype}\"; options=${options};`\n )\n if (format === 'json') {\n return this as unknown as PostgrestBuilder<\n ClientOptions,\n Record<string, unknown>[],\n ThrowOnError\n >\n } else {\n return this as unknown as PostgrestBuilder<ClientOptions, string, ThrowOnError>\n }\n }\n\n /**\n * Dry-run this request: execute the query but discard the changes.\n *\n * Server-side, PostgREST runs the query inside a transaction and rolls it back\n * instead of committing. The response still contains the data that *would* have\n * been returned — `RETURNING` clauses execute and RLS, triggers, and constraints\n * are all evaluated — but no row is actually inserted, updated, or deleted.\n *\n * This affects only the single request it is chained to. The JS caller has no\n * handle on the transaction: supabase-js does not group multiple queries into\n * one transaction. For multi-statement transactional logic, use a database\n * function (`supabase.rpc(...)`).\n *\n * Sets the `Prefer: tx=rollback` header. See PostgREST's docs on transaction\n * preferences for the underlying mechanism.\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @example Validate an insert without persisting\n * ```ts\n * const { data, error } = await supabase\n * .from('countries')\n * .insert({ name: 'France' })\n * .select()\n * .rollback()\n * // `data` shows what would have been inserted; nothing is saved.\n * ```\n */\n rollback(): this {\n this.headers.append('Prefer', 'tx=rollback')\n return this\n }\n\n /**\n * Override the type of the returned `data`.\n *\n * @typeParam NewResult - The new result type to override with\n * @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead\n *\n * @category Database\n * @subcategory Using modifiers\n *\n * @remarks\n * - Deprecated: use overrideTypes method instead\n *\n * @example Override type of successful response\n * ```ts\n * const { data } = await supabase\n * .from('countries')\n * .select()\n * .returns<Array<MyType>>()\n * ```\n *\n * @exampleResponse Override type of successful response\n * ```js\n * let x: typeof data // MyType[]\n * ```\n *\n * @example Override type of object response\n * ```ts\n * const { data } = await supabase\n * .from('countries')\n * .select()\n * .maybeSingle()\n * .returns<MyType>()\n * ```\n *\n * @exampleResponse Override type of object response\n * ```js\n * let x: typeof data // MyType | null\n * ```\n */\n returns<NewResult>(): PostgrestTransformBuilder<\n ClientOptions,\n Schema,\n Row,\n CheckMatchingArrayTypes<Result, NewResult>,\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n > {\n return this as unknown as PostgrestTransformBuilder<\n ClientOptions,\n Schema,\n Row,\n CheckMatchingArrayTypes<Result, NewResult>,\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n >\n }\n\n /**\n * Set the maximum number of rows that can be affected by the query.\n * Only available in PostgREST v13+ and only works with PATCH and DELETE methods.\n *\n * @param rows - The maximum number of rows that can be affected\n *\n * @category Database\n * @subcategory Using modifiers\n */\n maxAffected(rows: number): MaxAffectedEnabled<ClientOptions['PostgrestVersion']> extends true\n ? // TODO: update the RPC case to only work on RPC that returns SETOF rows\n Method extends 'PATCH' | 'DELETE' | 'RPC'\n ? this\n : InvalidMethodError<'maxAffected method only available on update or delete'>\n : InvalidMethodError<'maxAffected method only available on postgrest 13+'> {\n this.headers.append('Prefer', 'handling=strict')\n this.headers.append('Prefer', `max-affected=${rows}`)\n return this as unknown as MaxAffectedEnabled<ClientOptions['PostgrestVersion']> extends true\n ? Method extends 'PATCH' | 'DELETE' | 'RPC'\n ? this\n : InvalidMethodError<'maxAffected method only available on update or delete'>\n : InvalidMethodError<'maxAffected method only available on postgrest 13+'>\n }\n}\n","import PostgrestTransformBuilder from './PostgrestTransformBuilder'\nimport { JsonPathToAccessor, JsonPathToType } from './select-query-parser/utils'\nimport { ClientServerOptions, GenericSchema } from './types/common/common'\n\ntype FilterOperator =\n | 'eq'\n | 'neq'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'like'\n | 'ilike'\n | 'is'\n | 'isdistinct'\n | 'in'\n | 'cs'\n | 'cd'\n | 'sl'\n | 'sr'\n | 'nxl'\n | 'nxr'\n | 'adj'\n | 'ov'\n | 'fts'\n | 'plfts'\n | 'phfts'\n | 'wfts'\n | 'match'\n | 'imatch'\n\nexport type IsStringOperator<Path extends string> = Path extends `${string}->>${string}`\n ? true\n : false\n\nconst PostgrestReservedCharsRegexp = new RegExp('[,()]')\n\n// Match relationship filters with `table.column` syntax and resolve underlying\n// column value. If not matched, fallback to generic type.\n// TODO: Validate the relationship itself ala select-query-parser. Currently we\n// assume that all tables have valid relationships to each other, despite\n// nonexistent foreign keys.\ntype ResolveFilterValue<\n Schema extends GenericSchema,\n Row extends Record<string, unknown>,\n ColumnName extends string,\n> = ColumnName extends `${infer RelationshipTable}.${infer Remainder}`\n ? Remainder extends `${infer _}.${infer _}`\n ? ResolveFilterValue<Schema, Row, Remainder>\n : ResolveFilterRelationshipValue<Schema, RelationshipTable, Remainder>\n : ColumnName extends keyof Row\n ? Row[ColumnName]\n : // If the column selection is a jsonpath like `data->value` or `data->>value` we attempt to match\n // the expected type with the parsed custom json type\n IsStringOperator<ColumnName> extends true\n ? string\n : JsonPathToType<Row, JsonPathToAccessor<ColumnName>> extends infer JsonPathValue\n ? JsonPathValue extends never\n ? never\n : JsonPathValue\n : never\n\ntype ResolveFilterRelationshipValue<\n Schema extends GenericSchema,\n RelationshipTable extends string,\n RelationshipColumn extends string,\n> = Schema['Tables'] & Schema['Views'] extends infer TablesAndViews\n ? RelationshipTable extends keyof TablesAndViews\n ? 'Row' extends keyof TablesAndViews[RelationshipTable]\n ? RelationshipColumn extends keyof TablesAndViews[RelationshipTable]['Row']\n ? TablesAndViews[RelationshipTable]['Row'][RelationshipColumn]\n : unknown\n : unknown\n : unknown\n : never\n\nexport type InvalidMethodError<S extends string> = { Error: S }\n\ntype NonNullableColumn<T extends Record<string, unknown>, Col extends string> = Col extends keyof T\n ? { [K in keyof T]: K extends Col ? NonNullable<T[K]> : T[K] }\n : T\n\ntype NarrowResultColumn<T, Col extends string> = T extends (infer Item)[]\n ? Item extends Record<string, unknown>\n ? Col extends keyof Item\n ? { [K in keyof Item]: K extends Col ? NonNullable<Item[K]> : Item[K] }[]\n : T\n : T\n : T extends Record<string, unknown>\n ? Col extends keyof T\n ? { [K in keyof T]: K extends Col ? NonNullable<T[K]> : T[K] }\n : T\n : T\n\nexport default class PostgrestFilterBuilder<\n ClientOptions extends ClientServerOptions,\n Schema extends GenericSchema,\n Row extends Record<string, unknown>,\n Result,\n RelationName = unknown,\n Relationships = unknown,\n Method = unknown,\n ThrowOnError extends boolean = false,\n> extends PostgrestTransformBuilder<\n ClientOptions,\n Schema,\n Row,\n Result,\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n> {\n throwOnError(): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Row,\n Result,\n RelationName,\n Relationships,\n Method,\n true\n > {\n return super.throwOnError() as PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Row,\n Result,\n RelationName,\n Relationships,\n Method,\n true\n >\n }\n\n /**\n * Match only rows where `column` is equal to `value`.\n *\n * To check if the value of `column` is NULL, you should use `.is()` instead.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .eq('name', 'Leia')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 2,\n * \"name\": \"Leia\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n eq<ColumnName extends string>(\n column: ColumnName extends keyof Row\n ? ColumnName\n : ColumnName extends `${string}.${string}` | `${string}->${string}`\n ? ColumnName\n : string extends ColumnName\n ? string\n : keyof Row,\n value: ResolveFilterValue<Schema, Row, ColumnName> extends never\n ? NonNullable<unknown>\n : ResolveFilterValue<Schema, Row, ColumnName> extends infer ResolvedFilterValue\n ? NonNullable<ResolvedFilterValue>\n : never\n ): this {\n this.url.searchParams.append(column as string, `eq.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` is not equal to `value`.\n *\n * This filter does not include rows where `column` is `NULL`. To match null\n * values, use `.is(column, null)` instead.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .neq('name', 'Leia')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * },\n * {\n * \"id\": 3,\n * \"name\": \"Han\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n neq<ColumnName extends string>(\n column: ColumnName extends keyof Row\n ? ColumnName\n : ColumnName extends `${string}.${string}` | `${string}->${string}`\n ? ColumnName\n : string extends ColumnName\n ? string\n : keyof Row,\n value: ResolveFilterValue<Schema, Row, ColumnName> extends never\n ? unknown\n : ResolveFilterValue<Schema, Row, ColumnName> extends infer Resolved\n ? Resolved\n : never\n ): this {\n this.url.searchParams.append(column as string, `neq.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` is greater than `value`.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription With `select()`\n * When using [reserved words](https://www.postgresql.org/docs/current/sql-keywords-appendix.html) for column names you need\n * to add double quotes e.g. `.gt('\"order\"', 2)`\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .gt('id', 2)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 3,\n * \"name\": \"Han\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n gt<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n gt(column: string, value: unknown): this\n gt(column: string, value: unknown): this {\n this.url.searchParams.append(column, `gt.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` is greater than or equal to `value`.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .gte('id', 2)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 2,\n * \"name\": \"Leia\"\n * },\n * {\n * \"id\": 3,\n * \"name\": \"Han\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n gte<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n gte(column: string, value: unknown): this\n gte(column: string, value: unknown): this {\n this.url.searchParams.append(column, `gte.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` is less than `value`.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .lt('id', 2)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n lt<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n lt(column: string, value: unknown): this\n lt(column: string, value: unknown): this {\n this.url.searchParams.append(column, `lt.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` is less than or equal to `value`.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .lte('id', 2)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * },\n * {\n * \"id\": 2,\n * \"name\": \"Leia\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n lte<ColumnName extends string & keyof Row>(column: ColumnName, value: Row[ColumnName]): this\n lte(column: string, value: unknown): this\n lte(column: string, value: unknown): this {\n this.url.searchParams.append(column, `lte.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches `pattern` case-sensitively.\n *\n * @param column - The column to filter on\n * @param pattern - The pattern to match with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .like('name', '%Lu%')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n like<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n like(column: string, pattern: string): this\n like(column: string, pattern: string): this {\n this.url.searchParams.append(column, `like.${pattern}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches all of `patterns` case-sensitively.\n *\n * @param column - The column to filter on\n * @param patterns - The patterns to match with\n *\n * @category Database\n * @subcategory Using filters\n */\n likeAllOf<ColumnName extends string & keyof Row>(\n column: ColumnName,\n patterns: readonly string[]\n ): this\n likeAllOf(column: string, patterns: readonly string[]): this\n likeAllOf(column: string, patterns: readonly string[]): this {\n this.url.searchParams.append(column, `like(all).{${patterns.join(',')}}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches any of `patterns` case-sensitively.\n *\n * @param column - The column to filter on\n * @param patterns - The patterns to match with\n *\n * @category Database\n * @subcategory Using filters\n */\n likeAnyOf<ColumnName extends string & keyof Row>(\n column: ColumnName,\n patterns: readonly string[]\n ): this\n likeAnyOf(column: string, patterns: readonly string[]): this\n likeAnyOf(column: string, patterns: readonly string[]): this {\n this.url.searchParams.append(column, `like(any).{${patterns.join(',')}}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches `pattern` case-insensitively.\n *\n * @param column - The column to filter on\n * @param pattern - The pattern to match with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .ilike('name', '%lu%')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Luke\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n ilike<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n ilike(column: string, pattern: string): this\n ilike(column: string, pattern: string): this {\n this.url.searchParams.append(column, `ilike.${pattern}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches all of `patterns` case-insensitively.\n *\n * @param column - The column to filter on\n * @param patterns - The patterns to match with\n *\n * @category Database\n * @subcategory Using filters\n */\n ilikeAllOf<ColumnName extends string & keyof Row>(\n column: ColumnName,\n patterns: readonly string[]\n ): this\n ilikeAllOf(column: string, patterns: readonly string[]): this\n ilikeAllOf(column: string, patterns: readonly string[]): this {\n this.url.searchParams.append(column, `ilike(all).{${patterns.join(',')}}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches any of `patterns` case-insensitively.\n *\n * @param column - The column to filter on\n * @param patterns - The patterns to match with\n *\n * @category Database\n * @subcategory Using filters\n */\n ilikeAnyOf<ColumnName extends string & keyof Row>(\n column: ColumnName,\n patterns: readonly string[]\n ): this\n ilikeAnyOf(column: string, patterns: readonly string[]): this\n ilikeAnyOf(column: string, patterns: readonly string[]): this {\n this.url.searchParams.append(column, `ilike(any).{${patterns.join(',')}}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches the PostgreSQL regex `pattern`\n * case-sensitively (using the `~` operator).\n *\n * @param column - The column to filter on\n * @param pattern - The PostgreSQL regular expression pattern to match with\n */\n regexMatch<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n regexMatch(column: string, pattern: string): this\n regexMatch(column: string, pattern: string): this {\n this.url.searchParams.append(column, `match.${pattern}`)\n return this\n }\n\n /**\n * Match only rows where `column` matches the PostgreSQL regex `pattern`\n * case-insensitively (using the `~*` operator).\n *\n * @param column - The column to filter on\n * @param pattern - The PostgreSQL regular expression pattern to match with\n */\n regexIMatch<ColumnName extends string & keyof Row>(column: ColumnName, pattern: string): this\n regexIMatch(column: string, pattern: string): this\n regexIMatch(column: string, pattern: string): this {\n this.url.searchParams.append(column, `imatch.${pattern}`)\n return this\n }\n\n /**\n * Match only rows where `column` IS `value`.\n *\n * For non-boolean columns, this is only relevant for checking if the value of\n * `column` is NULL by setting `value` to `null`.\n *\n * For boolean columns, you can also set `value` to `true` or `false` and it\n * will behave the same way as `.eq()`.\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription Checking for nullness, true or false\n * Using the `eq()` filter doesn't work when filtering for `null`.\n *\n * Instead, you need to use `is()`.\n *\n * @example Checking for nullness, true or false\n * ```ts\n * const { data, error } = await supabase\n * .from('countries')\n * .select()\n * .is('name', null)\n * ```\n *\n * @exampleSql Checking for nullness, true or false\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n *\n * insert into\n * countries (id, name)\n * values\n * (1, 'null'),\n * (2, null);\n * ```\n *\n * @exampleResponse Checking for nullness, true or false\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 2,\n * \"name\": \"null\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n is<ColumnName extends string & keyof Row>(\n column: ColumnName,\n value: Row[ColumnName] & (boolean | null)\n ): this\n is(column: string, value: boolean | null): this\n is(column: string, value: boolean | null): this {\n this.url.searchParams.append(column, `is.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` IS DISTINCT FROM `value`.\n *\n * Unlike `.neq()`, this treats `NULL` as a comparable value. Two `NULL` values\n * are considered equal (not distinct), and comparing `NULL` with any non-NULL\n * value returns true (distinct).\n *\n * @param column - The column to filter on\n * @param value - The value to filter with\n */\n isDistinct<ColumnName extends string>(\n column: ColumnName,\n value: ResolveFilterValue<Schema, Row, ColumnName> extends never\n ? unknown\n : ResolveFilterValue<Schema, Row, ColumnName> extends infer ResolvedFilterValue\n ? ResolvedFilterValue\n : never\n ): this {\n this.url.searchParams.append(column, `isdistinct.${value}`)\n return this\n }\n\n /**\n * Match only rows where `column` is included in the `values` array.\n *\n * @param column - The column to filter on\n * @param values - The values array to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .in('name', ['Leia', 'Han'])\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 2,\n * \"name\": \"Leia\"\n * },\n * {\n * \"id\": 3,\n * \"name\": \"Han\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n in<ColumnName extends string>(\n column: ColumnName,\n values: ReadonlyArray<\n ResolveFilterValue<Schema, Row, ColumnName> extends never\n ? unknown\n : // We want to infer the type before wrapping it into a `NonNullable` to avoid too deep\n // type resolution error\n ResolveFilterValue<Schema, Row, ColumnName> extends infer ResolvedFilterValue\n ? ResolvedFilterValue\n : // We should never enter this case as all the branches are covered above\n never\n >\n ): this {\n const cleanedValues = Array.from(new Set(values))\n .map((s) => {\n // handle postgrest reserved characters\n // https://postgrest.org/en/v7.0.0/api.html#reserved-characters\n if (typeof s === 'string' && PostgrestReservedCharsRegexp.test(s)) return `\"${s}\"`\n else return `${s}`\n })\n .join(',')\n this.url.searchParams.append(column, `in.(${cleanedValues})`)\n return this\n }\n\n /**\n * Match only rows where `column` is NOT included in the `values` array.\n *\n * @param column - The column to filter on\n * @param values - The values array to filter with\n */\n notIn<ColumnName extends string>(\n column: ColumnName,\n values: ReadonlyArray<\n ResolveFilterValue<Schema, Row, ColumnName> extends never\n ? unknown\n : ResolveFilterValue<Schema, Row, ColumnName> extends infer ResolvedFilterValue\n ? ResolvedFilterValue\n : never\n >\n ): this {\n const cleanedValues = Array.from(new Set(values))\n .map((s) => {\n // handle postgrest reserved characters\n // https://postgrest.org/en/v7.0.0/api.html#reserved-characters\n if (typeof s === 'string' && PostgrestReservedCharsRegexp.test(s)) return `\"${s}\"`\n else return `${s}`\n })\n .join(',')\n this.url.searchParams.append(column, `not.in.(${cleanedValues})`)\n return this\n }\n\n /**\n * Only relevant for jsonb, array, and range columns. Match only rows where\n * `column` contains every element appearing in `value`.\n *\n * @param column - The jsonb, array, or range column to filter on\n * @param value - The jsonb, array, or range value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example On array columns\n * ```ts\n * const { data, error } = await supabase\n * .from('issues')\n * .select()\n * .contains('tags', ['is:open', 'priority:low'])\n * ```\n *\n * @exampleSql On array columns\n * ```sql\n * create table\n * issues (\n * id int8 primary key,\n * title text,\n * tags text[]\n * );\n *\n * insert into\n * issues (id, title, tags)\n * values\n * (1, 'Cache invalidation is not working', array['is:open', 'severity:high', 'priority:low']),\n * (2, 'Use better names', array['is:open', 'severity:low', 'priority:medium']);\n * ```\n *\n * @exampleResponse On array columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"title\": \"Cache invalidation is not working\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription On range columns\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example On range columns\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .contains('during', '[2000-01-01 13:00, 2000-01-01 13:30)')\n * ```\n *\n * @exampleSql On range columns\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse On range columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"room_name\": \"Emerald\",\n * \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example On `jsonb` columns\n * ```ts\n * const { data, error } = await supabase\n * .from('users')\n * .select('name')\n * .contains('address', { postcode: 90210 })\n * ```\n *\n * @exampleSql On `jsonb` columns\n * ```sql\n * create table\n * users (\n * id int8 primary key,\n * name text,\n * address jsonb\n * );\n *\n * insert into\n * users (id, name, address)\n * values\n * (1, 'Michael', '{ \"postcode\": 90210, \"street\": \"Melrose Place\" }'),\n * (2, 'Jane', '{}');\n * ```\n *\n * @exampleResponse On `jsonb` columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Michael\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n contains<ColumnName extends string & keyof Row>(\n column: ColumnName,\n value: string | ReadonlyArray<Row[ColumnName]> | Record<string, unknown>\n ): this\n contains(column: string, value: string | readonly unknown[] | Record<string, unknown>): this\n contains(column: string, value: string | readonly unknown[] | Record<string, unknown>): this {\n if (typeof value === 'string') {\n // range types can be inclusive '[', ']' or exclusive '(', ')' so just\n // keep it simple and accept a string\n this.url.searchParams.append(column, `cs.${value}`)\n } else if (Array.isArray(value)) {\n // array\n this.url.searchParams.append(column, `cs.{${value.join(',')}}`)\n } else {\n // json\n this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`)\n }\n return this\n }\n\n /**\n * Only relevant for jsonb, array, and range columns. Match only rows where\n * every element appearing in `column` is contained by `value`.\n *\n * @param column - The jsonb, array, or range column to filter on\n * @param value - The jsonb, array, or range value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example On array columns\n * ```ts\n * const { data, error } = await supabase\n * .from('classes')\n * .select('name')\n * .containedBy('days', ['monday', 'tuesday', 'wednesday', 'friday'])\n * ```\n *\n * @exampleSql On array columns\n * ```sql\n * create table\n * classes (\n * id int8 primary key,\n * name text,\n * days text[]\n * );\n *\n * insert into\n * classes (id, name, days)\n * values\n * (1, 'Chemistry', array['monday', 'friday']),\n * (2, 'History', array['monday', 'wednesday', 'thursday']);\n * ```\n *\n * @exampleResponse On array columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Chemistry\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription On range columns\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example On range columns\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .containedBy('during', '[2000-01-01 00:00, 2000-01-01 23:59)')\n * ```\n *\n * @exampleSql On range columns\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse On range columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"room_name\": \"Emerald\",\n * \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example On `jsonb` columns\n * ```ts\n * const { data, error } = await supabase\n * .from('users')\n * .select('name')\n * .containedBy('address', {})\n * ```\n *\n * @exampleSql On `jsonb` columns\n * ```sql\n * create table\n * users (\n * id int8 primary key,\n * name text,\n * address jsonb\n * );\n *\n * insert into\n * users (id, name, address)\n * values\n * (1, 'Michael', '{ \"postcode\": 90210, \"street\": \"Melrose Place\" }'),\n * (2, 'Jane', '{}');\n * ```\n *\n * @exampleResponse On `jsonb` columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Jane\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n *\n * ```\n */\n containedBy<ColumnName extends string & keyof Row>(\n column: ColumnName,\n value: string | ReadonlyArray<Row[ColumnName]> | Record<string, unknown>\n ): this\n containedBy(column: string, value: string | readonly unknown[] | Record<string, unknown>): this\n containedBy(column: string, value: string | readonly unknown[] | Record<string, unknown>): this {\n if (typeof value === 'string') {\n // range\n this.url.searchParams.append(column, `cd.${value}`)\n } else if (Array.isArray(value)) {\n // array\n this.url.searchParams.append(column, `cd.{${value.join(',')}}`)\n } else {\n // json\n this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`)\n }\n return this\n }\n\n /**\n * Only relevant for range columns. Match only rows where every element in\n * `column` is greater than any element in `range`.\n *\n * @param column - The range column to filter on\n * @param range - The range to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription With `select()`\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .rangeGt('during', '[2000-01-02 08:00, 2000-01-02 09:00)')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 2,\n * \"room_name\": \"Topaz\",\n * \"during\": \"[\\\"2000-01-02 09:00:00\\\",\\\"2000-01-02 10:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n *\n * ```\n */\n rangeGt<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeGt(column: string, range: string): this\n rangeGt(column: string, range: string): this {\n this.url.searchParams.append(column, `sr.${range}`)\n return this\n }\n\n /**\n * Only relevant for range columns. Match only rows where every element in\n * `column` is either contained in `range` or greater than any element in\n * `range`.\n *\n * @param column - The range column to filter on\n * @param range - The range to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription With `select()`\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .rangeGte('during', '[2000-01-02 08:30, 2000-01-02 09:30)')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 2,\n * \"room_name\": \"Topaz\",\n * \"during\": \"[\\\"2000-01-02 09:00:00\\\",\\\"2000-01-02 10:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n *\n * ```\n */\n rangeGte<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeGte(column: string, range: string): this\n rangeGte(column: string, range: string): this {\n this.url.searchParams.append(column, `nxl.${range}`)\n return this\n }\n\n /**\n * Only relevant for range columns. Match only rows where every element in\n * `column` is less than any element in `range`.\n *\n * @param column - The range column to filter on\n * @param range - The range to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription With `select()`\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .rangeLt('during', '[2000-01-01 15:00, 2000-01-01 16:00)')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"room_name\": \"Emerald\",\n * \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n rangeLt<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeLt(column: string, range: string): this\n rangeLt(column: string, range: string): this {\n this.url.searchParams.append(column, `sl.${range}`)\n return this\n }\n\n /**\n * Only relevant for range columns. Match only rows where every element in\n * `column` is either contained in `range` or less than any element in\n * `range`.\n *\n * @param column - The range column to filter on\n * @param range - The range to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription With `select()`\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .rangeLte('during', '[2000-01-01 14:00, 2000-01-01 16:00)')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"room_name\": \"Emerald\",\n * \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n *\n * ```\n */\n rangeLte<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeLte(column: string, range: string): this\n rangeLte(column: string, range: string): this {\n this.url.searchParams.append(column, `nxr.${range}`)\n return this\n }\n\n /**\n * Only relevant for range columns. Match only rows where `column` is\n * mutually exclusive to `range` and there can be no element between the two\n * ranges.\n *\n * @param column - The range column to filter on\n * @param range - The range to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @exampleDescription With `select()`\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .rangeAdjacent('during', '[2000-01-01 12:00, 2000-01-01 13:00)')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"room_name\": \"Emerald\",\n * \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n rangeAdjacent<ColumnName extends string & keyof Row>(column: ColumnName, range: string): this\n rangeAdjacent(column: string, range: string): this\n rangeAdjacent(column: string, range: string): this {\n this.url.searchParams.append(column, `adj.${range}`)\n return this\n }\n\n /**\n * Only relevant for array and range columns. Match only rows where\n * `column` and `value` have an element in common.\n *\n * @param column - The array or range column to filter on\n * @param value - The array or range value to filter with\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example On array columns\n * ```ts\n * const { data, error } = await supabase\n * .from('issues')\n * .select('title')\n * .overlaps('tags', ['is:closed', 'severity:high'])\n * ```\n *\n * @exampleSql On array columns\n * ```sql\n * create table\n * issues (\n * id int8 primary key,\n * title text,\n * tags text[]\n * );\n *\n * insert into\n * issues (id, title, tags)\n * values\n * (1, 'Cache invalidation is not working', array['is:open', 'severity:high', 'priority:low']),\n * (2, 'Use better names', array['is:open', 'severity:low', 'priority:medium']);\n * ```\n *\n * @exampleResponse On array columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"title\": \"Cache invalidation is not working\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription On range columns\n * Postgres supports a number of [range\n * types](https://www.postgresql.org/docs/current/rangetypes.html). You\n * can filter on range columns using the string representation of range\n * values.\n *\n * @example On range columns\n * ```ts\n * const { data, error } = await supabase\n * .from('reservations')\n * .select()\n * .overlaps('during', '[2000-01-01 12:45, 2000-01-01 13:15)')\n * ```\n *\n * @exampleSql On range columns\n * ```sql\n * create table\n * reservations (\n * id int8 primary key,\n * room_name text,\n * during tsrange\n * );\n *\n * insert into\n * reservations (id, room_name, during)\n * values\n * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),\n * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)');\n * ```\n *\n * @exampleResponse On range columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"room_name\": \"Emerald\",\n * \"during\": \"[\\\"2000-01-01 13:00:00\\\",\\\"2000-01-01 15:00:00\\\")\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n overlaps<ColumnName extends string & keyof Row>(\n column: ColumnName,\n value: string | ReadonlyArray<Row[ColumnName]>\n ): this\n overlaps(column: string, value: string | readonly unknown[]): this\n overlaps(column: string, value: string | readonly unknown[]): this {\n if (typeof value === 'string') {\n // range\n this.url.searchParams.append(column, `ov.${value}`)\n } else {\n // array\n this.url.searchParams.append(column, `ov.{${value.join(',')}}`)\n }\n return this\n }\n\n /**\n * Only relevant for text and tsvector columns. Match only rows where\n * `column` matches the query string in `query`.\n *\n * @param column - The text or tsvector column to filter on\n * @param query - The query text to match with\n * @param options - Named parameters\n * @param options.config - The text search configuration to use\n * @param options.type - Change how the `query` text is interpreted\n *\n * @category Database\n * @subcategory Using filters\n *\n * @remarks\n * - For more information, see [Postgres full text search](/docs/guides/database/full-text-search).\n *\n * @example Text search\n * ```ts\n * const result = await supabase\n * .from(\"texts\")\n * .select(\"content\")\n * .textSearch(\"content\", `'eggs' & 'ham'`, {\n * config: \"english\",\n * });\n * ```\n *\n * @exampleSql Text search\n * ```sql\n * create table texts (\n * id bigint\n * primary key\n * generated always as identity,\n * content text\n * );\n *\n * insert into texts (content) values\n * ('Four score and seven years ago'),\n * ('The road goes ever on and on'),\n * ('Green eggs and ham')\n * ;\n * ```\n *\n * @exampleResponse Text search\n * ```json\n * {\n * \"data\": [\n * {\n * \"content\": \"Green eggs and ham\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Basic normalization\n * Uses PostgreSQL's `plainto_tsquery` function.\n *\n * @example Basic normalization\n * ```ts\n * const { data, error } = await supabase\n * .from('quotes')\n * .select('catchphrase')\n * .textSearch('catchphrase', `'fat' & 'cat'`, {\n * type: 'plain',\n * config: 'english'\n * })\n * ```\n *\n * @exampleDescription Full normalization\n * Uses PostgreSQL's `phraseto_tsquery` function.\n *\n * @example Full normalization\n * ```ts\n * const { data, error } = await supabase\n * .from('quotes')\n * .select('catchphrase')\n * .textSearch('catchphrase', `'fat' & 'cat'`, {\n * type: 'phrase',\n * config: 'english'\n * })\n * ```\n *\n * @exampleDescription Websearch\n * Uses PostgreSQL's `websearch_to_tsquery` function.\n * This function will never raise syntax errors, which makes it possible to use raw user-supplied input for search, and can be used\n * with advanced operators.\n *\n * - `unquoted text`: text not inside quote marks will be converted to terms separated by & operators, as if processed by plainto_tsquery.\n * - `\"quoted text\"`: text inside quote marks will be converted to terms separated by `<->` operators, as if processed by phraseto_tsquery.\n * - `OR`: the word “or” will be converted to the | operator.\n * - `-`: a dash will be converted to the ! operator.\n *\n * @example Websearch\n * ```ts\n * const { data, error } = await supabase\n * .from('quotes')\n * .select('catchphrase')\n * .textSearch('catchphrase', `'fat or cat'`, {\n * type: 'websearch',\n * config: 'english'\n * })\n * ```\n */\n textSearch<ColumnName extends string & keyof Row>(\n column: ColumnName,\n query: string,\n options?: { config?: string; type?: 'plain' | 'phrase' | 'websearch' }\n ): this\n textSearch(\n column: string,\n query: string,\n options?: { config?: string; type?: 'plain' | 'phrase' | 'websearch' }\n ): this\n textSearch(\n column: string,\n query: string,\n { config, type }: { config?: string; type?: 'plain' | 'phrase' | 'websearch' } = {}\n ): this {\n let typePart = ''\n if (type === 'plain') {\n typePart = 'pl'\n } else if (type === 'phrase') {\n typePart = 'ph'\n } else if (type === 'websearch') {\n typePart = 'w'\n }\n const configPart = config === undefined ? '' : `(${config})`\n this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`)\n return this\n }\n\n /**\n * Match only rows where each column in `query` keys is equal to its\n * associated value. Shorthand for multiple `.eq()`s.\n *\n * @param query - The object to filter with, with column names as keys mapped\n * to their filter values\n *\n * @category Database\n * @subcategory Using filters\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * .match({ id: 2, name: 'Leia' })\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Leia\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n match<ColumnName extends string & keyof Row>(query: Record<ColumnName, Row[ColumnName]>): this\n match(query: Record<string, unknown>): this\n match(query: Record<string, unknown>): this {\n Object.entries(query)\n // columns with `undefined` value needs to be filtered out, otherwise it'll\n // show up as `?column=eq.undefined`\n .filter(([_, value]) => value !== undefined)\n .forEach(([column, value]) => {\n this.url.searchParams.append(column, `eq.${value}`)\n })\n return this\n }\n\n /**\n * Match only rows which doesn't satisfy the filter.\n *\n * Unlike most filters, `opearator` and `value` are used as-is and need to\n * follow [PostgREST\n * syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n * to make sure they are properly sanitized.\n *\n * @param column - The column to filter on\n * @param operator - The operator to be negated to filter with, following\n * PostgREST syntax\n * @param value - The value to filter with, following PostgREST syntax\n *\n * @category Database\n * @subcategory Using filters\n */\n not<ColumnName extends string & keyof Row>(\n column: ColumnName,\n operator: 'is',\n value: null\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n NonNullableColumn<Row, ColumnName>,\n NarrowResultColumn<Result, ColumnName>,\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n > &\n this\n not<ColumnName extends string & keyof Row>(\n column: ColumnName,\n operator: FilterOperator,\n value: Row[ColumnName]\n ): this\n not(column: string, operator: string, value: unknown): this\n /**\n * Match only rows which doesn't satisfy the filter.\n *\n * Unlike most filters, `opearator` and `value` are used as-is and need to\n * follow [PostgREST\n * syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n * to make sure they are properly sanitized.\n *\n * @param column - The column to filter on\n * @param operator - The operator to be negated to filter with, following\n * PostgREST syntax\n * @param value - The value to filter with, following PostgREST syntax\n *\n * @category Database\n * @subcategory Using filters\n *\n * @remarks\n * not() expects you to use the raw PostgREST syntax for the filter values.\n *\n * ```ts\n * .not('id', 'in', '(5,6,7)') // Use `()` for `in` filter\n * .not('arraycol', 'cs', '{\"a\",\"b\"}') // Use `cs` for `contains()`, `{}` for array values\n * ```\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('countries')\n * .select()\n * .not('name', 'is', null)\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n *\n * insert into\n * countries (id, name)\n * values\n * (1, 'null'),\n * (2, null);\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"null\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n *\n * ```\n */\n not(\n column: string,\n operator: string,\n value: unknown\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n any,\n any,\n RelationName,\n Relationships,\n Method,\n ThrowOnError\n > &\n this {\n this.url.searchParams.append(column, `not.${operator}.${value}`)\n return this as any\n }\n\n /**\n * Match only rows which satisfy at least one of the filters.\n *\n * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST\n * syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n * to make sure it's properly sanitized.\n *\n * It's currently not possible to do an `.or()` filter across multiple tables.\n *\n * @param filters - The filters to use, following PostgREST syntax\n * @param options - Named parameters\n * @param options.referencedTable - Set this to filter on referenced tables\n * instead of the parent table\n * @param options.foreignTable - Deprecated, use `referencedTable` instead\n *\n * @category Database\n * @subcategory Using filters\n *\n * @remarks\n * or() expects you to use the raw PostgREST syntax for the filter names and values.\n *\n * ```ts\n * .or('id.in.(5,6,7), arraycol.cs.{\"a\",\"b\"}') // Use `()` for `in` filter, `{}` for array values and `cs` for `contains()`.\n * .or('id.in.(5,6,7), arraycol.cd.{\"a\",\"b\"}') // Use `cd` for `containedBy()`\n * ```\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * .or('id.eq.2,name.eq.Han')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Leia\"\n * },\n * {\n * \"name\": \"Han\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example Use `or` with `and`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * .or('id.gt.3,and(id.eq.1,name.eq.Luke)')\n * ```\n *\n * @exampleSql Use `or` with `and`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse Use `or` with `and`\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Luke\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example Use `or` on referenced tables\n * ```ts\n * const { data, error } = await supabase\n * .from('orchestral_sections')\n * .select(`\n * name,\n * instruments!inner (\n * name\n * )\n * `)\n * .or('section_id.eq.1,name.eq.guzheng', { referencedTable: 'instruments' })\n * ```\n *\n * @exampleSql Use `or` on referenced tables\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 2, 'flute'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse Use `or` on referenced tables\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"strings\",\n * \"instruments\": [\n * {\n * \"name\": \"violin\"\n * }\n * ]\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n or(\n filters: string,\n {\n foreignTable,\n referencedTable = foreignTable,\n }: { foreignTable?: string; referencedTable?: string } = {}\n ): this {\n const key = referencedTable ? `${referencedTable}.or` : 'or'\n this.url.searchParams.append(key, `(${filters})`)\n return this\n }\n\n /**\n * Match only rows which satisfy the filter. This is an escape hatch - you\n * should use the specific filter methods wherever possible.\n *\n * Unlike most filters, `opearator` and `value` are used as-is and need to\n * follow [PostgREST\n * syntax](https://postgrest.org/en/stable/api.html#operators). You also need\n * to make sure they are properly sanitized.\n *\n * @param column - The column to filter on\n * @param operator - The operator to filter with, following PostgREST syntax\n * @param value - The value to filter with, following PostgREST syntax\n *\n * @category Database\n * @subcategory Using filters\n *\n * @remarks\n * filter() expects you to use the raw PostgREST syntax for the filter values.\n *\n * ```ts\n * .filter('id', 'in', '(5,6,7)') // Use `()` for `in` filter\n * .filter('arraycol', 'cs', '{\"a\",\"b\"}') // Use `cs` for `contains()`, `{}` for array values\n * ```\n *\n * @example With `select()`\n * ```ts\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * .filter('name', 'in', '(\"Han\",\"Yoda\")')\n * ```\n *\n * @exampleSql With `select()`\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse With `select()`\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 3,\n * \"name\": \"Han\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example On a referenced table\n * ```ts\n * const { data, error } = await supabase\n * .from('orchestral_sections')\n * .select(`\n * name,\n * instruments!inner (\n * name\n * )\n * `)\n * .filter('instruments.name', 'eq', 'flute')\n * ```\n *\n * @exampleSql On a referenced table\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 2, 'flute'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse On a referenced table\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"woodwinds\",\n * \"instruments\": [\n * {\n * \"name\": \"flute\"\n * }\n * ]\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n filter<ColumnName extends string & keyof Row>(\n column: ColumnName,\n operator: `${'' | 'not.'}${FilterOperator}`,\n value: unknown\n ): this\n filter(column: string, operator: string, value: unknown): this\n filter(column: string, operator: string, value: unknown): this {\n this.url.searchParams.append(column, `${operator}.${value}`)\n return this\n }\n}\n","import PostgrestFilterBuilder from './PostgrestFilterBuilder'\nimport { GetResult } from './select-query-parser/result'\nimport {\n ClientServerOptions,\n Fetch,\n GenericSchema,\n GenericTable,\n GenericView,\n} from './types/common/common'\nimport { RejectExcessProperties } from './types/types'\n\nexport default class PostgrestQueryBuilder<\n ClientOptions extends ClientServerOptions,\n Schema extends GenericSchema,\n Relation extends GenericTable | GenericView,\n RelationName = unknown,\n Relationships = Relation extends { Relationships: infer R } ? R : unknown,\n> {\n url: URL\n headers: Headers\n schema?: string\n signal?: AbortSignal\n fetch?: Fetch\n urlLengthLimit: number\n\n /**\n * Enable or disable automatic retries for transient errors.\n * When enabled, idempotent requests (GET/HEAD/OPTIONS) that fail with network\n * errors or HTTP 503/520 responses are automatically retried with exponential\n * backoff (1s, 2s, 4s, up to 3 attempts). Defaults to `true` when not specified.\n */\n retry?: boolean\n\n /**\n * Creates a query builder scoped to a Postgres table or view.\n *\n * @category Database\n *\n * @param url - The URL for the query\n * @param options - Named parameters\n * @param options.headers - Custom headers\n * @param options.schema - Postgres schema to use\n * @param options.fetch - Custom fetch implementation\n * @param options.urlLengthLimit - Maximum URL length before warning\n * @param options.retry - Enable automatic retries for transient errors (default: true)\n *\n * @example Using supabase-js (recommended)\n * ```ts\n * import { createClient } from '@supabase/supabase-js'\n *\n * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n * const { data, error } = await supabase.from('users').select('*')\n * ```\n *\n * @example Standalone import for bundle-sensitive environments\n * ```ts\n * import { PostgrestQueryBuilder } from '@supabase/postgrest-js'\n *\n * const query = new PostgrestQueryBuilder(\n * new URL('https://xyzcompany.supabase.co/rest/v1/users'),\n * { headers: { apikey: 'your-publishable-key' }, retry: true }\n * )\n * ```\n */\n constructor(\n url: URL,\n {\n headers = {},\n schema,\n fetch,\n urlLengthLimit = 8000,\n retry,\n }: {\n headers?: HeadersInit\n schema?: string\n fetch?: Fetch\n urlLengthLimit?: number\n retry?: boolean\n }\n ) {\n this.url = url\n this.headers = new Headers(headers)\n this.schema = schema\n this.fetch = fetch\n this.urlLengthLimit = urlLengthLimit\n this.retry = retry\n }\n\n /**\n * Clone URL and headers to prevent shared state between operations.\n */\n private cloneRequestState(): { url: URL; headers: Headers } {\n return {\n url: new URL(this.url.toString()),\n headers: new Headers(this.headers),\n }\n }\n\n /**\n * Perform a SELECT query on the table or view.\n *\n * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName`\n *\n * @param options - Named parameters\n *\n * @param options.head - When set to `true`, `data` will not be returned.\n * Useful if you only need the count.\n *\n * @param options.count - Count algorithm to use to count rows in the table or view.\n *\n * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n * hood.\n *\n * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n * statistics under the hood.\n *\n * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n * numbers.\n *\n * @remarks\n * When using `count` with `.range()` or `.limit()`, the returned `count` is the total number of rows\n * that match your filters, not the number of rows in the current page. Use this to build pagination UI.\n \n * - By default, Supabase projects return a maximum of 1,000 rows. This setting can be changed in your project's [API settings](/dashboard/project/_/settings/api). It's recommended that you keep it low to limit the payload size of accidental or malicious requests. You can use `range()` queries to paginate through your data.\n * - `select()` can be combined with [Filters](/docs/reference/javascript/using-filters)\n * - `select()` can be combined with [Modifiers](/docs/reference/javascript/using-modifiers)\n * - `apikey` is a reserved keyword if you're using the [Supabase Platform](/docs/guides/platform) and [should be avoided as a column name](https://github.com/supabase/supabase/issues/5465). *\n * @category Database\n *\n * @example Getting your data\n * ```js\n * const { data, error } = await supabase\n * .from('characters')\n * .select()\n * ```\n *\n * @exampleSql Getting your data\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Harry'),\n * (2, 'Frodo'),\n * (3, 'Katniss');\n * ```\n *\n * @exampleResponse Getting your data\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Harry\"\n * },\n * {\n * \"id\": 2,\n * \"name\": \"Frodo\"\n * },\n * {\n * \"id\": 3,\n * \"name\": \"Katniss\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Handling errors\n * The most useful field on a Postgres error is usually `hint` — when the database knows the fix, it puts the literal SQL there. For example, a permission-denied error (`code: '42501'`) arrives with a `hint` like `\"Grant the required privileges to the current role with: GRANT SELECT ON public.characters TO anon;\"`. Log the full `error` object so the hint isn't hidden behind `error.message`.\n *\n * @example Handling errors\n * ```js\n * const { data, error } = await supabase.from('characters').select()\n * if (error) {\n * // Logs the full error: message, code, details, and hint.\n * console.error(error)\n * return\n * }\n * ```\n *\n * @exampleResponse Handling errors\n * ```json\n * {\n * \"error\": {\n * \"code\": \"42501\",\n * \"details\": null,\n * \"hint\": \"Grant the required privileges to the current role with: GRANT SELECT ON public.characters TO anon;\",\n * \"message\": \"permission denied for table characters\"\n * },\n * \"status\": 401,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @example Selecting specific columns\n * ```js\n * const { data, error } = await supabase\n * .from('characters')\n * .select('name')\n * ```\n *\n * @exampleSql Selecting specific columns\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Frodo'),\n * (2, 'Harry'),\n * (3, 'Katniss');\n * ```\n *\n * @exampleResponse Selecting specific columns\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Frodo\"\n * },\n * {\n * \"name\": \"Harry\"\n * },\n * {\n * \"name\": \"Katniss\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Query referenced tables\n * If your database has foreign key relationships, you can query related tables too.\n *\n * @example Query referenced tables\n * ```js\n * const { data, error } = await supabase\n * .from('orchestral_sections')\n * .select(`\n * name,\n * instruments (\n * name\n * )\n * `)\n * ```\n *\n * @exampleSql Query referenced tables\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 2, 'flute'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse Query referenced tables\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"strings\",\n * \"instruments\": [\n * {\n * \"name\": \"violin\"\n * }\n * ]\n * },\n * {\n * \"name\": \"woodwinds\",\n * \"instruments\": [\n * {\n * \"name\": \"flute\"\n * }\n * ]\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Query referenced tables with spaces in their names\n * If your table name contains spaces, you must use double quotes in the `select` statement to reference the table.\n *\n * @example Query referenced tables with spaces in their names\n * ```js\n * const { data, error } = await supabase\n * .from('orchestral sections')\n * .select(`\n * name,\n * \"musical instruments\" (\n * name\n * )\n * `)\n * ```\n *\n * @exampleSql Query referenced tables with spaces in their names\n * ```sql\n * create table\n * \"orchestral sections\" (id int8 primary key, name text);\n * create table\n * \"musical instruments\" (\n * id int8 primary key,\n * section_id int8 not null references \"orchestral sections\",\n * name text\n * );\n *\n * insert into\n * \"orchestral sections\" (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * \"musical instruments\" (id, section_id, name)\n * values\n * (1, 2, 'flute'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse Query referenced tables with spaces in their names\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"strings\",\n * \"musical instruments\": [\n * {\n * \"name\": \"violin\"\n * }\n * ]\n * },\n * {\n * \"name\": \"woodwinds\",\n * \"musical instruments\": [\n * {\n * \"name\": \"flute\"\n * }\n * ]\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Query referenced tables through a join table\n * If you're in a situation where your tables are **NOT** directly\n * related, but instead are joined by a _join table_, you can still use\n * the `select()` method to query the related data. The join table needs\n * to have the foreign keys as part of its composite primary key.\n *\n * @example Query referenced tables through a join table\n * ```ts\n * const { data, error } = await supabase\n * .from('users')\n * .select(`\n * name,\n * teams (\n * name\n * )\n * `)\n * \n * ```\n *\n * @exampleSql Query referenced tables through a join table\n * ```sql\n * create table\n * users (\n * id int8 primary key,\n * name text\n * );\n * create table\n * teams (\n * id int8 primary key,\n * name text\n * );\n * -- join table\n * create table\n * users_teams (\n * user_id int8 not null references users,\n * team_id int8 not null references teams,\n * -- both foreign keys must be part of a composite primary key\n * primary key (user_id, team_id)\n * );\n *\n * insert into\n * users (id, name)\n * values\n * (1, 'Kiran'),\n * (2, 'Evan');\n * insert into\n * teams (id, name)\n * values\n * (1, 'Green'),\n * (2, 'Blue');\n * insert into\n * users_teams (user_id, team_id)\n * values\n * (1, 1),\n * (1, 2),\n * (2, 2);\n * ```\n *\n * @exampleResponse Query referenced tables through a join table\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"Kiran\",\n * \"teams\": [\n * {\n * \"name\": \"Green\"\n * },\n * {\n * \"name\": \"Blue\"\n * }\n * ]\n * },\n * {\n * \"name\": \"Evan\",\n * \"teams\": [\n * {\n * \"name\": \"Blue\"\n * }\n * ]\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * \n * ```\n *\n * @exampleDescription Query the same referenced table multiple times\n * If you need to query the same referenced table twice, use the name of the\n * joined column to identify which join to use. You can also give each\n * column an alias.\n *\n * @example Query the same referenced table multiple times\n * ```ts\n * const { data, error } = await supabase\n * .from('messages')\n * .select(`\n * content,\n * from:sender_id(name),\n * to:receiver_id(name)\n * `)\n *\n * // To infer types, use the name of the table (in this case `users`) and\n * // the name of the foreign key constraint.\n * const { data, error } = await supabase\n * .from('messages')\n * .select(`\n * content,\n * from:users!messages_sender_id_fkey(name),\n * to:users!messages_receiver_id_fkey(name)\n * `)\n * ```\n *\n * @exampleSql Query the same referenced table multiple times\n * ```sql\n * create table\n * users (id int8 primary key, name text);\n *\n * create table\n * messages (\n * sender_id int8 not null references users,\n * receiver_id int8 not null references users,\n * content text\n * );\n *\n * insert into\n * users (id, name)\n * values\n * (1, 'Kiran'),\n * (2, 'Evan');\n *\n * insert into\n * messages (sender_id, receiver_id, content)\n * values\n * (1, 2, '👋');\n * ```\n * ```\n *\n * @exampleResponse Query the same referenced table multiple times\n * ```json\n * {\n * \"data\": [\n * {\n * \"content\": \"👋\",\n * \"from\": {\n * \"name\": \"Kiran\"\n * },\n * \"to\": {\n * \"name\": \"Evan\"\n * }\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Query nested foreign tables through a join table\n * You can use the result of a joined table to gather data in\n * another foreign table. With multiple references to the same foreign\n * table you must specify the column on which to conduct the join.\n *\n * @example Query nested foreign tables through a join table\n * ```ts\n * const { data, error } = await supabase\n * .from('games')\n * .select(`\n * game_id:id,\n * away_team:teams!games_away_team_fkey (\n * users (\n * id,\n * name\n * )\n * )\n * `)\n * \n * ```\n *\n * @exampleSql Query nested foreign tables through a join table\n * ```sql\n * ```sql\n * create table\n * users (\n * id int8 primary key,\n * name text\n * );\n * create table\n * teams (\n * id int8 primary key,\n * name text\n * );\n * -- join table\n * create table\n * users_teams (\n * user_id int8 not null references users,\n * team_id int8 not null references teams,\n *\n * primary key (user_id, team_id)\n * );\n * create table\n * games (\n * id int8 primary key,\n * home_team int8 not null references teams,\n * away_team int8 not null references teams,\n * name text\n * );\n *\n * insert into users (id, name)\n * values\n * (1, 'Kiran'),\n * (2, 'Evan');\n * insert into\n * teams (id, name)\n * values\n * (1, 'Green'),\n * (2, 'Blue');\n * insert into\n * users_teams (user_id, team_id)\n * values\n * (1, 1),\n * (1, 2),\n * (2, 2);\n * insert into\n * games (id, home_team, away_team, name)\n * values\n * (1, 1, 2, 'Green vs Blue'),\n * (2, 2, 1, 'Blue vs Green');\n * ```\n *\n * @exampleResponse Query nested foreign tables through a join table\n * ```json\n * {\n * \"data\": [\n * {\n * \"game_id\": 1,\n * \"away_team\": {\n * \"users\": [\n * {\n * \"id\": 1,\n * \"name\": \"Kiran\"\n * },\n * {\n * \"id\": 2,\n * \"name\": \"Evan\"\n * }\n * ]\n * }\n * },\n * {\n * \"game_id\": 2,\n * \"away_team\": {\n * \"users\": [\n * {\n * \"id\": 1,\n * \"name\": \"Kiran\"\n * }\n * ]\n * }\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * \n * ```\n *\n * @exampleDescription Filtering through referenced tables\n * If the filter on a referenced table's column is not satisfied, the referenced\n * table returns `[]` or `null` but the parent table is not filtered out.\n * If you want to filter out the parent table rows, use the `!inner` hint\n *\n * @example Filtering through referenced tables\n * ```ts\n * const { data, error } = await supabase\n * .from('instruments')\n * .select('name, orchestral_sections(*)')\n * .eq('orchestral_sections.name', 'percussion')\n * ```\n *\n * @exampleSql Filtering through referenced tables\n * ```sql\n * create table\n * orchestral_sections (id int8 primary key, name text);\n * create table\n * instruments (\n * id int8 primary key,\n * section_id int8 not null references orchestral_sections,\n * name text\n * );\n *\n * insert into\n * orchestral_sections (id, name)\n * values\n * (1, 'strings'),\n * (2, 'woodwinds');\n * insert into\n * instruments (id, section_id, name)\n * values\n * (1, 2, 'flute'),\n * (2, 1, 'violin');\n * ```\n *\n * @exampleResponse Filtering through referenced tables\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"flute\",\n * \"orchestral_sections\": null\n * },\n * {\n * \"name\": \"violin\",\n * \"orchestral_sections\": null\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Querying referenced table with count\n * You can get the number of rows in a related table by using the\n * **count** property.\n *\n * @example Querying referenced table with count\n * ```ts\n * const { data, error } = await supabase\n * .from('orchestral_sections')\n * .select(`*, instruments(count)`)\n * ```\n *\n * @exampleSql Querying referenced table with count\n * ```sql\n * create table orchestral_sections (\n * \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n * \"name\" text\n * );\n *\n * create table characters (\n * \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n * \"name\" text,\n * \"section_id\" \"uuid\" references public.orchestral_sections on delete cascade\n * );\n *\n * with section as (\n * insert into orchestral_sections (name)\n * values ('strings') returning id\n * )\n * insert into instruments (name, section_id) values\n * ('violin', (select id from section)),\n * ('viola', (select id from section)),\n * ('cello', (select id from section)),\n * ('double bass', (select id from section));\n * ```\n *\n * @exampleResponse Querying referenced table with count\n * ```json\n * [\n * {\n * \"id\": \"693694e7-d993-4360-a6d7-6294e325d9b6\",\n * \"name\": \"strings\",\n * \"instruments\": [\n * {\n * \"count\": 4\n * }\n * ]\n * }\n * ]\n * ```\n *\n * @exampleDescription Querying with count option\n * You can get the number of rows by using the\n * [count](/docs/reference/javascript/select#parameters) option.\n *\n * @example Querying with count option\n * ```ts\n * const { count, error } = await supabase\n * .from('characters')\n * .select('*', { count: 'exact', head: true })\n * ```\n *\n * @exampleSql Querying with count option\n * ```sql\n * create table\n * characters (id int8 primary key, name text);\n *\n * insert into\n * characters (id, name)\n * values\n * (1, 'Luke'),\n * (2, 'Leia'),\n * (3, 'Han');\n * ```\n *\n * @exampleResponse Querying with count option\n * ```json\n * {\n * \"count\": 3,\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Querying JSON data\n * You can select and filter data inside of\n * [JSON](/docs/guides/database/json) columns. Postgres offers some\n * [operators](/docs/guides/database/json#query-the-jsonb-data) for\n * querying JSON data.\n *\n * @example Querying JSON data\n * ```ts\n * const { data, error } = await supabase\n * .from('users')\n * .select(`\n * id, name,\n * address->city\n * `)\n * ```\n *\n * @exampleSql Querying JSON data\n * ```sql\n * create table\n * users (\n * id int8 primary key,\n * name text,\n * address jsonb\n * );\n *\n * insert into\n * users (id, name, address)\n * values\n * (1, 'Frodo', '{\"city\":\"Hobbiton\"}');\n * ```\n *\n * @exampleResponse Querying JSON data\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Frodo\",\n * \"city\": \"Hobbiton\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Querying referenced table with inner join\n * If you don't want to return the referenced table contents, you can leave the parenthesis empty.\n * Like `.select('name, orchestral_sections!inner()')`.\n *\n * @example Querying referenced table with inner join\n * ```ts\n * const { data, error } = await supabase\n * .from('instruments')\n * .select('name, orchestral_sections!inner(name)')\n * .eq('orchestral_sections.name', 'woodwinds')\n * .limit(1)\n * ```\n *\n * @exampleSql Querying referenced table with inner join\n * ```sql\n * create table orchestral_sections (\n * \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n * \"name\" text\n * );\n *\n * create table instruments (\n * \"id\" \"uuid\" primary key default \"extensions\".\"uuid_generate_v4\"() not null,\n * \"name\" text,\n * \"section_id\" \"uuid\" references public.orchestral_sections on delete cascade\n * );\n *\n * with section as (\n * insert into orchestral_sections (name)\n * values ('woodwinds') returning id\n * )\n * insert into instruments (name, section_id) values\n * ('flute', (select id from section)),\n * ('clarinet', (select id from section)),\n * ('bassoon', (select id from section)),\n * ('piccolo', (select id from section));\n * ```\n *\n * @exampleResponse Querying referenced table with inner join\n * ```json\n * {\n * \"data\": [\n * {\n * \"name\": \"flute\",\n * \"orchestral_sections\": {\"name\": \"woodwinds\"}\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Switching schemas per query\n * In addition to setting the schema during initialization, you can also switch schemas on a per-query basis.\n * Make sure you've set up your [database privileges and API settings](/docs/guides/api/using-custom-schemas).\n *\n * @example Switching schemas per query\n * ```ts\n * const { data, error } = await supabase\n * .schema('myschema')\n * .from('mytable')\n * .select()\n * ```\n *\n * @exampleSql Switching schemas per query\n * ```sql\n * create schema myschema;\n *\n * create table myschema.mytable (\n * id uuid primary key default gen_random_uuid(),\n * data text\n * );\n *\n * insert into myschema.mytable (data) values ('mydata');\n * ```\n *\n * @exampleResponse Switching schemas per query\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": \"4162e008-27b0-4c0f-82dc-ccaeee9a624d\",\n * \"data\": \"mydata\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n select<\n Query extends string = '*',\n ResultOne = GetResult<\n Schema,\n Relation['Row'],\n RelationName,\n Relationships,\n Query,\n ClientOptions\n >,\n >(\n columns?: Query,\n options?: {\n head?: boolean\n count?: 'exact' | 'planned' | 'estimated' | (string & {})\n }\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n ResultOne[],\n RelationName,\n Relationships,\n 'GET'\n > {\n const { head = false, count } = options ?? {}\n\n const method = head ? 'HEAD' : 'GET'\n // Remove whitespaces except when quoted\n let quoted = false\n const cleanedColumns = (columns ?? '*')\n .split('')\n .map((c) => {\n if (/\\s/.test(c) && !quoted) {\n return ''\n }\n if (c === '\"') {\n quoted = !quoted\n }\n return c\n })\n .join('')\n\n const { url, headers } = this.cloneRequestState()\n url.searchParams.set('select', cleanedColumns)\n\n if (count) {\n headers.append('Prefer', `count=${count}`)\n }\n\n return new PostgrestFilterBuilder({\n method,\n url,\n headers,\n schema: this.schema,\n fetch: this.fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n\n /**\n * Perform an INSERT into the table or view.\n *\n * By default, inserted rows are not returned. To return it, chain the call\n * with `.select()`.\n *\n * @param values - The values to insert. Pass an object to insert a single row\n * or an array to insert multiple rows.\n *\n * @param options - Named parameters\n *\n * @param options.count - Count algorithm to use to count inserted rows.\n *\n * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n * hood.\n *\n * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n * statistics under the hood.\n *\n * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n * numbers.\n *\n * @param options.defaultToNull - Make missing fields default to `null`.\n * Otherwise, use the default value for the column. Only applies for bulk\n * inserts.\n *\n * @category Database\n *\n * @example Create a record\n * ```ts\n * const { error } = await supabase\n * .from('countries')\n * .insert({ id: 1, name: 'Mordor' })\n * ```\n *\n * @exampleSql Create a record\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n * ```\n *\n * @exampleResponse Create a record\n * ```json\n * {\n * \"status\": 201,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @exampleDescription Handling errors\n * `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT INSERT ON public.countries TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n *\n * @example Handling errors\n * ```js\n * const { error } = await supabase.from('countries').insert({ id: 1, name: 'Mordor' })\n * if (error) console.error(error)\n * ```\n *\n * @example Create a record and return it\n * ```ts\n * const { data, error } = await supabase\n * .from('countries')\n * .insert({ id: 1, name: 'Mordor' })\n * .select()\n * ```\n *\n * @exampleSql Create a record and return it\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n * ```\n *\n * @exampleResponse Create a record and return it\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Mordor\"\n * }\n * ],\n * \"status\": 201,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @exampleDescription Bulk create\n * A bulk create operation is handled in a single transaction.\n * If any of the inserts fail, none of the rows are inserted.\n *\n * @example Bulk create\n * ```ts\n * const { error } = await supabase\n * .from('countries')\n * .insert([\n * { id: 1, name: 'Mordor' },\n * { id: 1, name: 'The Shire' },\n * ])\n * ```\n *\n * @exampleSql Bulk create\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n * ```\n *\n * @exampleResponse Bulk create\n * ```json\n * {\n * \"error\": {\n * \"code\": \"23505\",\n * \"details\": \"Key (id)=(1) already exists.\",\n * \"hint\": null,\n * \"message\": \"duplicate key value violates unique constraint \\\"countries_pkey\\\"\"\n * },\n * \"status\": 409,\n * \"statusText\": \"\"\n * }\n * ```\n */\n insert<Row extends Relation extends { Insert: unknown } ? Relation['Insert'] : never>(\n values:\n | RejectExcessProperties<\n Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n Row\n >\n | RejectExcessProperties<\n Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n Row\n >[],\n {\n count,\n defaultToNull = true,\n }: {\n count?: 'exact' | 'planned' | 'estimated' | (string & {})\n defaultToNull?: boolean\n } = {}\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n null,\n RelationName,\n Relationships,\n 'POST'\n > {\n const method = 'POST'\n const { url, headers } = this.cloneRequestState()\n\n if (count) {\n headers.append('Prefer', `count=${count}`)\n }\n if (!defaultToNull) {\n headers.append('Prefer', `missing=default`)\n }\n\n if (Array.isArray(values)) {\n const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), [] as string[])\n if (columns.length > 0) {\n const uniqueColumns = [...new Set(columns)].map((column) => `\"${column}\"`)\n url.searchParams.set('columns', uniqueColumns.join(','))\n }\n }\n\n return new PostgrestFilterBuilder({\n method,\n url,\n headers,\n schema: this.schema,\n body: values,\n fetch: this.fetch ?? fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n\n /**\n * Perform an UPSERT on the table or view. Depending on the column(s) passed\n * to `onConflict`, `.upsert()` allows you to perform the equivalent of\n * `.insert()` if a row with the corresponding `onConflict` columns doesn't\n * exist, or if it does exist, perform an alternative action depending on\n * `ignoreDuplicates`.\n *\n * By default, upserted rows are not returned. To return it, chain the call\n * with `.select()`.\n *\n * @param values - The values to upsert with. Pass an object to upsert a\n * single row or an array to upsert multiple rows.\n *\n * @param options - Named parameters\n *\n * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how\n * duplicate rows are determined. Two rows are duplicates if all the\n * `onConflict` columns are equal.\n *\n * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If\n * `false`, duplicate rows are merged with existing rows.\n *\n * @param options.count - Count algorithm to use to count upserted rows.\n *\n * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n * hood.\n *\n * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n * statistics under the hood.\n *\n * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n * numbers.\n *\n * @param options.defaultToNull - Make missing fields default to `null`.\n * Otherwise, use the default value for the column. This only applies when\n * inserting new rows, not when merging with existing rows under\n * `ignoreDuplicates: false`. This also only applies when doing bulk upserts.\n *\n * @example Upsert a single row using a unique key\n * ```ts\n * // Upserting a single row, overwriting based on the 'username' unique column\n * const { data, error } = await supabase\n * .from('users')\n * .upsert({ username: 'supabot' }, { onConflict: 'username' })\n *\n * // Example response:\n * // {\n * // data: [\n * // { id: 4, message: 'bar', username: 'supabot' }\n * // ],\n * // error: null\n * // }\n * ```\n *\n * @example Upsert with conflict resolution and exact row counting\n * ```ts\n * // Upserting and returning exact count\n * const { data, error, count } = await supabase\n * .from('users')\n * .upsert(\n * {\n * id: 3,\n * message: 'foo',\n * username: 'supabot'\n * },\n * {\n * onConflict: 'username',\n * count: 'exact'\n * }\n * )\n *\n * // Example response:\n * // {\n * // data: [\n * // {\n * // id: 42,\n * // handle: \"saoirse\",\n * // display_name: \"Saoirse\"\n * // }\n * // ],\n * // count: 1,\n * // error: null\n * // }\n * ```\n *\n * @category Database\n *\n * @remarks\n * - Primary keys must be included in `values` to use upsert.\n *\n * @example Upsert your data\n * ```ts\n * const { data, error } = await supabase\n * .from('instruments')\n * .upsert({ id: 1, name: 'piano' })\n * .select()\n * ```\n *\n * @exampleSql Upsert your data\n * ```sql\n * create table\n * instruments (id int8 primary key, name text);\n *\n * insert into\n * instruments (id, name)\n * values\n * (1, 'harpsichord');\n * ```\n *\n * @exampleResponse Upsert your data\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"piano\"\n * }\n * ],\n * \"status\": 201,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @exampleDescription Handling errors\n * `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT INSERT, UPDATE ON public.instruments TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n *\n * @example Handling errors\n * ```js\n * const { data, error } = await supabase.from('instruments').upsert({ id: 1, name: 'piano' }).select()\n * if (error) console.error(error)\n * ```\n *\n * @example Bulk Upsert your data\n * ```ts\n * const { data, error } = await supabase\n * .from('instruments')\n * .upsert([\n * { id: 1, name: 'piano' },\n * { id: 2, name: 'harp' },\n * ])\n * .select()\n * ```\n *\n * @exampleSql Bulk Upsert your data\n * ```sql\n * create table\n * instruments (id int8 primary key, name text);\n *\n * insert into\n * instruments (id, name)\n * values\n * (1, 'harpsichord');\n * ```\n *\n * @exampleResponse Bulk Upsert your data\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"piano\"\n * },\n * {\n * \"id\": 2,\n * \"name\": \"harp\"\n * }\n * ],\n * \"status\": 201,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @exampleDescription Upserting into tables with constraints\n * In the following query, `upsert()` implicitly uses the `id`\n * (primary key) column to determine conflicts. If there is no existing\n * row with the same `id`, `upsert()` inserts a new row, which\n * will fail in this case as there is already a row with `handle` `\"saoirse\"`.\n * Using the `onConflict` option, you can instruct `upsert()` to use\n * another column with a unique constraint to determine conflicts.\n *\n * @example Upserting into tables with constraints\n * ```ts\n * const { data, error } = await supabase\n * .from('users')\n * .upsert({ id: 42, handle: 'saoirse', display_name: 'Saoirse' })\n * .select()\n * ```\n *\n * @exampleSql Upserting into tables with constraints\n * ```sql\n * create table\n * users (\n * id int8 generated by default as identity primary key,\n * handle text not null unique,\n * display_name text\n * );\n *\n * insert into\n * users (id, handle, display_name)\n * values\n * (1, 'saoirse', null);\n * ```\n *\n * @exampleResponse Upserting into tables with constraints\n * ```json\n * {\n * \"error\": {\n * \"code\": \"23505\",\n * \"details\": \"Key (handle)=(saoirse) already exists.\",\n * \"hint\": null,\n * \"message\": \"duplicate key value violates unique constraint \\\"users_handle_key\\\"\"\n * },\n * \"status\": 409,\n * \"statusText\": \"\"\n * }\n * ```\n */\n\n upsert<Row extends Relation extends { Insert: unknown } ? Relation['Insert'] : never>(\n values:\n | RejectExcessProperties<\n Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n Row\n >\n | RejectExcessProperties<\n Relation extends { Insert: unknown } ? Relation['Insert'] : never,\n Row\n >[],\n {\n onConflict,\n ignoreDuplicates = false,\n count,\n defaultToNull = true,\n }: {\n onConflict?: string\n ignoreDuplicates?: boolean\n count?: 'exact' | 'planned' | 'estimated' | (string & {})\n defaultToNull?: boolean\n } = {}\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n null,\n RelationName,\n Relationships,\n 'POST'\n > {\n const method = 'POST'\n const { url, headers } = this.cloneRequestState()\n\n headers.append('Prefer', `resolution=${ignoreDuplicates ? 'ignore' : 'merge'}-duplicates`)\n\n if (onConflict !== undefined) url.searchParams.set('on_conflict', onConflict)\n if (count) {\n headers.append('Prefer', `count=${count}`)\n }\n if (!defaultToNull) {\n headers.append('Prefer', 'missing=default')\n }\n\n if (Array.isArray(values)) {\n const columns = values.reduce((acc, x) => acc.concat(Object.keys(x)), [] as string[])\n if (columns.length > 0) {\n const uniqueColumns = [...new Set(columns)].map((column) => `\"${column}\"`)\n url.searchParams.set('columns', uniqueColumns.join(','))\n }\n }\n\n return new PostgrestFilterBuilder({\n method,\n url,\n headers,\n schema: this.schema,\n body: values,\n fetch: this.fetch ?? fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n\n /**\n * Perform an UPDATE on the table or view.\n *\n * By default, updated rows are not returned. To return it, chain the call\n * with `.select()` after filters.\n *\n * @param values - The values to update with\n *\n * @param options - Named parameters\n *\n * @param options.count - Count algorithm to use to count updated rows.\n *\n * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n * hood.\n *\n * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n * statistics under the hood.\n *\n * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n * numbers.\n *\n * @category Database\n *\n * @remarks\n * - `update()` should always be combined with [Filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to update.\n *\n * @example Updating your data\n * ```ts\n * const { error } = await supabase\n * .from('instruments')\n * .update({ name: 'piano' })\n * .eq('id', 1)\n * ```\n *\n * @exampleSql Updating your data\n * ```sql\n * create table\n * instruments (id int8 primary key, name text);\n *\n * insert into\n * instruments (id, name)\n * values\n * (1, 'harpsichord');\n * ```\n *\n * @exampleResponse Updating your data\n * ```json\n * {\n * \"status\": 204,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @exampleDescription Handling errors\n * `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT UPDATE ON public.instruments TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n *\n * @example Handling errors\n * ```js\n * const { error } = await supabase.from('instruments').update({ name: 'piano' }).eq('id', 1)\n * if (error) console.error(error)\n * ```\n *\n * @example Update a record and return it\n * ```ts\n * const { data, error } = await supabase\n * .from('instruments')\n * .update({ name: 'piano' })\n * .eq('id', 1)\n * .select()\n * ```\n *\n * @exampleSql Update a record and return it\n * ```sql\n * create table\n * instruments (id int8 primary key, name text);\n *\n * insert into\n * instruments (id, name)\n * values\n * (1, 'harpsichord');\n * ```\n *\n * @exampleResponse Update a record and return it\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"piano\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Updating JSON data\n * Postgres offers some\n * [operators](/docs/guides/database/json#query-the-jsonb-data) for\n * working with JSON data. Currently, it is only possible to update the entire JSON document.\n *\n * @example Updating JSON data\n * ```ts\n * const { data, error } = await supabase\n * .from('users')\n * .update({\n * address: {\n * street: 'Melrose Place',\n * postcode: 90210\n * }\n * })\n * .eq('address->postcode', 90210)\n * .select()\n * ```\n *\n * @exampleSql Updating JSON data\n * ```sql\n * create table\n * users (\n * id int8 primary key,\n * name text,\n * address jsonb\n * );\n *\n * insert into\n * users (id, name, address)\n * values\n * (1, 'Michael', '{ \"postcode\": 90210 }');\n * ```\n *\n * @exampleResponse Updating JSON data\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Michael\",\n * \"address\": {\n * \"street\": \"Melrose Place\",\n * \"postcode\": 90210\n * }\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n update<Row extends Relation extends { Update: unknown } ? Relation['Update'] : never>(\n values: RejectExcessProperties<\n Relation extends { Update: unknown } ? Relation['Update'] : never,\n Row\n >,\n {\n count,\n }: {\n count?: 'exact' | 'planned' | 'estimated' | (string & {})\n } = {}\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n null,\n RelationName,\n Relationships,\n 'PATCH'\n > {\n const method = 'PATCH'\n const { url, headers } = this.cloneRequestState()\n\n if (count) {\n headers.append('Prefer', `count=${count}`)\n }\n\n return new PostgrestFilterBuilder({\n method,\n url,\n headers,\n schema: this.schema,\n body: values,\n fetch: this.fetch ?? fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n\n /**\n * Perform a DELETE on the table or view.\n *\n * By default, deleted rows are not returned. To return it, chain the call\n * with `.select()` after filters.\n *\n * @param options - Named parameters\n *\n * @param options.count - Count algorithm to use to count deleted rows.\n *\n * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n * hood.\n *\n * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n * statistics under the hood.\n *\n * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n * numbers.\n *\n * @category Database\n *\n * @remarks\n * - `delete()` should always be combined with [filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to delete.\n * - If you use `delete()` with filters and you have\n * [RLS](/docs/learn/auth-deep-dive/auth-row-level-security) enabled, only\n * rows visible through `SELECT` policies are deleted. Note that by default\n * no rows are visible, so you need at least one `SELECT`/`ALL` policy that\n * makes the rows visible.\n * - When using `delete().in()`, specify an array of values to target multiple rows with a single query. This is particularly useful for batch deleting entries that share common criteria, such as deleting users by their IDs. Ensure that the array you provide accurately represents all records you intend to delete to avoid unintended data removal.\n *\n * @example Delete a single record\n * ```ts\n * const response = await supabase\n * .from('countries')\n * .delete()\n * .eq('id', 1)\n * ```\n *\n * @exampleSql Delete a single record\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n *\n * insert into\n * countries (id, name)\n * values\n * (1, 'Mordor');\n * ```\n *\n * @exampleResponse Delete a single record\n * ```json\n * {\n * \"status\": 204,\n * \"statusText\": \"\"\n * }\n * ```\n *\n * @exampleDescription Handling errors\n * `error.hint` from Postgres often contains the actionable fix (e.g. `\"Grant the required privileges to the current role with: GRANT DELETE ON public.countries TO anon;\"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`.\n *\n * @example Handling errors\n * ```js\n * const { error } = await supabase.from('countries').delete().eq('id', 1)\n * if (error) console.error(error)\n * ```\n *\n * @example Delete a record and return it\n * ```ts\n * const { data, error } = await supabase\n * .from('countries')\n * .delete()\n * .eq('id', 1)\n * .select()\n * ```\n *\n * @exampleSql Delete a record and return it\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n *\n * insert into\n * countries (id, name)\n * values\n * (1, 'Mordor');\n * ```\n *\n * @exampleResponse Delete a record and return it\n * ```json\n * {\n * \"data\": [\n * {\n * \"id\": 1,\n * \"name\": \"Mordor\"\n * }\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example Delete multiple records\n * ```ts\n * const response = await supabase\n * .from('countries')\n * .delete()\n * .in('id', [1, 2, 3])\n * ```\n *\n * @exampleSql Delete multiple records\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n *\n * insert into\n * countries (id, name)\n * values\n * (1, 'Rohan'), (2, 'The Shire'), (3, 'Mordor');\n * ```\n *\n * @exampleResponse Delete multiple records\n * ```json\n * {\n * \"status\": 204,\n * \"statusText\": \"\"\n * }\n * ```\n */\n delete({\n count,\n }: {\n count?: 'exact' | 'planned' | 'estimated' | (string & {})\n } = {}): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n Relation['Row'],\n null,\n RelationName,\n Relationships,\n 'DELETE'\n > {\n const method = 'DELETE'\n const { url, headers } = this.cloneRequestState()\n\n if (count) {\n headers.append('Prefer', `count=${count}`)\n }\n\n return new PostgrestFilterBuilder({\n method,\n url,\n headers,\n schema: this.schema,\n fetch: this.fetch ?? fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n}\n","import PostgrestQueryBuilder from './PostgrestQueryBuilder'\nimport PostgrestFilterBuilder from './PostgrestFilterBuilder'\nimport { Fetch, GenericSchema, ClientServerOptions } from './types/common/common'\nimport { GetRpcFunctionFilterBuilderByArgs } from './types/common/rpc'\nimport PostgrestError from './PostgrestError'\nimport { fetchWithRetry } from './fetchWithRetry'\nimport {\n PostgrestOpenApiSpec,\n PostgrestResponseFailure,\n PostgrestSingleResponse,\n} from './types/types'\n\n/**\n * Build the error for a failed OpenAPI request. PostgREST answers with a JSON\n * error object when it produced the failure itself; proxies and disabled\n * OpenAPI output answer with plain text or an empty body, in which case the\n * body (or, failing that, the status text) becomes the message.\n */\nfunction toOpenApiError(body: string, statusText: string): PostgrestError {\n try {\n const parsed = JSON.parse(body)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return new PostgrestError({\n message: String(parsed.message ?? body),\n details: parsed.details ?? '',\n hint: parsed.hint ?? '',\n code: parsed.code ?? '',\n })\n }\n } catch {\n // Not JSON; fall through to the plain-text message.\n }\n return new PostgrestError({ message: body || statusText, details: '', hint: '', code: '' })\n}\n\n/**\n * Build the response for a request that yielded no readable body: the fetch\n * itself rejected (no status is known, so it is 0), or the body stream failed\n * while being read (the response status is preserved).\n */\nfunction toTransportFailure(\n cause: unknown,\n status: number,\n statusText: string\n): PostgrestResponseFailure {\n const err = cause as { name?: string; message?: string } | null | undefined\n return {\n success: false,\n error: new PostgrestError({\n message: `${err?.name ?? 'FetchError'}: ${err?.message}`,\n details: '',\n hint: '',\n code: '',\n }),\n data: null,\n count: null,\n status,\n statusText,\n }\n}\n\n/**\n * PostgREST client.\n *\n * @typeParam Database - Types for the schema from the [type\n * generator](https://supabase.com/docs/reference/javascript/next/typescript-support)\n *\n * @typeParam SchemaName - Postgres schema to switch to. Must be a string\n * literal, the same one passed to the constructor. If the schema is not\n * `\"public\"`, this must be supplied manually.\n */\nexport default class PostgrestClient<\n Database = any,\n ClientOptions extends ClientServerOptions = Database extends {\n __InternalSupabase: infer I extends ClientServerOptions\n }\n ? I\n : {},\n SchemaName extends string & keyof Omit<Database, '__InternalSupabase'> =\n 'public' extends keyof Omit<Database, '__InternalSupabase'>\n ? 'public'\n : string & keyof Omit<Database, '__InternalSupabase'>,\n Schema extends GenericSchema = Omit<\n Database,\n '__InternalSupabase'\n >[SchemaName] extends GenericSchema\n ? Omit<Database, '__InternalSupabase'>[SchemaName]\n : any,\n> {\n url: string\n headers: Headers\n schemaName?: SchemaName\n fetch?: Fetch\n urlLengthLimit: number\n\n // Retry configuration - enabled by default\n retry?: boolean\n\n // TODO: Add back shouldThrowOnError once we figure out the typings\n /**\n * Creates a PostgREST client.\n *\n * @param url - URL of the PostgREST endpoint\n * @param options - Named parameters\n * @param options.headers - Custom headers\n * @param options.schema - Postgres schema to switch to\n * @param options.fetch - Custom fetch\n * @param options.timeout - Optional timeout in milliseconds for all requests. When set, requests will automatically abort after this duration to prevent indefinite hangs.\n * @param options.urlLengthLimit - Maximum URL length in characters before warnings/errors are triggered. Defaults to 8000.\n * @param options.retry - Enable or disable automatic retries for transient errors.\n * When enabled, idempotent requests (GET, HEAD, OPTIONS) that fail with network\n * errors or HTTP 503/520 responses will be automatically retried up to 3 times\n * with exponential backoff (1s, 2s, 4s). Defaults to `true`.\n * @example Using supabase-js (recommended)\n * ```ts\n * import { createClient } from '@supabase/supabase-js'\n *\n * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')\n * const { data, error } = await supabase.from('profiles').select('*')\n * ```\n *\n * @category Database\n *\n * @remarks\n * - A `timeout` option (in milliseconds) can be set to automatically abort requests that take too long.\n * - A `urlLengthLimit` option (default: 8000) can be set to control when URL length warnings are included in error messages for aborted requests.\n *\n * @example Standalone import for bundle-sensitive environments\n * ```ts\n * import { PostgrestClient } from '@supabase/postgrest-js'\n *\n * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', {\n * headers: { apikey: 'your-publishable-key' },\n * schema: 'public',\n * timeout: 30000, // 30 second timeout\n * })\n * ```\n */\n constructor(\n url: string,\n {\n headers = {},\n schema,\n fetch,\n timeout,\n urlLengthLimit = 8000,\n retry,\n }: {\n headers?: HeadersInit\n schema?: SchemaName\n fetch?: Fetch\n timeout?: number\n urlLengthLimit?: number\n retry?: boolean\n } = {}\n ) {\n this.url = url\n this.headers = new Headers(headers)\n this.schemaName = schema\n this.urlLengthLimit = urlLengthLimit\n\n const originalFetch = fetch ?? globalThis.fetch\n\n // Wrap fetch with timeout if specified\n if (timeout !== undefined && timeout > 0) {\n this.fetch = (input, init) => {\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n // Merge abort signals if one already exists\n const existingSignal = init?.signal\n if (existingSignal) {\n // If the existing signal is already aborted, use it directly\n if (existingSignal.aborted) {\n clearTimeout(timeoutId)\n return originalFetch(input, init)\n }\n\n // Listen to existing signal and abort our controller too\n const abortHandler = () => {\n clearTimeout(timeoutId)\n controller.abort()\n }\n existingSignal.addEventListener('abort', abortHandler, { once: true })\n\n return originalFetch(input, {\n ...init,\n signal: controller.signal,\n }).finally(() => {\n clearTimeout(timeoutId)\n existingSignal.removeEventListener('abort', abortHandler)\n })\n }\n\n return originalFetch(input, {\n ...init,\n signal: controller.signal,\n }).finally(() => clearTimeout(timeoutId))\n }\n } else {\n this.fetch = originalFetch\n }\n this.retry = retry\n }\n /**\n * Perform a query on a table or a view.\n *\n * @param relation - The table or view name to query\n *\n * @category Database\n */\n from<\n TableName extends string & keyof Schema['Tables'],\n Table extends Schema['Tables'][TableName],\n >(relation: TableName): PostgrestQueryBuilder<ClientOptions, Schema, Table, TableName>\n from<ViewName extends string & keyof Schema['Views'], View extends Schema['Views'][ViewName]>(\n relation: ViewName\n ): PostgrestQueryBuilder<ClientOptions, Schema, View, ViewName>\n from(\n relation: (string & keyof Schema['Tables']) | (string & keyof Schema['Views'])\n ): PostgrestQueryBuilder<ClientOptions, Schema, any, any> {\n if (!relation || typeof relation !== 'string' || relation.trim() === '') {\n throw new Error('Invalid relation name: relation must be a non-empty string.')\n }\n\n const url = new URL(`${this.url}/${relation}`)\n return new PostgrestQueryBuilder(url, {\n headers: new Headers(this.headers),\n schema: this.schemaName,\n fetch: this.fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n\n /**\n * Select a schema to query or perform an function (rpc) call.\n *\n * The schema needs to be on the list of exposed schemas inside Supabase.\n *\n * @param schema - The schema to query\n *\n * @category Database\n */\n schema<DynamicSchema extends string & keyof Omit<Database, '__InternalSupabase'>>(\n schema: DynamicSchema\n ): PostgrestClient<\n Database,\n ClientOptions,\n DynamicSchema,\n Database[DynamicSchema] extends GenericSchema ? Database[DynamicSchema] : any\n > {\n return new PostgrestClient(this.url, {\n headers: this.headers,\n schema,\n fetch: this.fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n\n /**\n * Fetch the OpenAPI description PostgREST publishes for this client's schema.\n *\n * The document lists only the tables, views and functions the caller's role\n * holds privileges on; PostgREST applies that filtering server-side. The\n * schema is the one this client was created with, so call `.schema()` first\n * to describe a different one. Transient failures are retried according to\n * the client's `retry` option, like any other idempotent request.\n *\n * @example\n * ```ts\n * const { data, error } = await supabase.getOpenApiSpec()\n * ```\n *\n * @example Describe a schema other than the client default\n * ```ts\n * const { data, error } = await supabase.schema('billing').getOpenApiSpec()\n * ```\n *\n * @category Database\n */\n async getOpenApiSpec(): Promise<PostgrestSingleResponse<PostgrestOpenApiSpec>> {\n const headers = new Headers(this.headers)\n headers.set('Accept', 'application/openapi+json')\n if (this.schemaName) {\n headers.set('Accept-Profile', this.schemaName)\n }\n\n // Headers reach the fetch implementation as a plain object, as in\n // PostgrestBuilder: React Native's XHR-based fetch drops headers that are\n // supplied as a Headers instance.\n const requestHeaders: Record<string, string> = {}\n headers.forEach((value, key) => {\n requestHeaders[key] = value\n })\n\n const fetchImpl = this.fetch ?? globalThis.fetch\n let res: Response\n try {\n res = await fetchWithRetry(\n fetchImpl,\n `${this.url}/`,\n { method: 'GET', headers: requestHeaders },\n this.retry ?? true\n )\n } catch (fetchError) {\n return toTransportFailure(fetchError, 0, '')\n }\n\n let body: string\n try {\n body = await res.text()\n } catch (readError) {\n return toTransportFailure(readError, res.status, res.statusText)\n }\n\n if (res.ok) {\n try {\n return {\n success: true,\n error: null,\n data: JSON.parse(body) as PostgrestOpenApiSpec,\n count: null,\n status: res.status,\n statusText: res.statusText,\n }\n } catch {\n // A 2xx status does not guarantee a JSON body; report it like a failure.\n }\n }\n\n return {\n success: false,\n error: toOpenApiError(body, res.statusText),\n data: null,\n count: null,\n status: res.status,\n statusText: res.statusText,\n }\n }\n\n /**\n * Perform a function call.\n *\n * @param fn - The function name to call\n * @param args - The arguments to pass to the function call\n * @param options - Named parameters\n * @param options.head - When set to `true`, `data` will not be returned.\n * Useful if you only need the count.\n * @param options.get - When set to `true`, the function will be called with\n * read-only access mode.\n * @param options.count - Count algorithm to use to count rows returned by the\n * function. Only applicable for [set-returning\n * functions](https://www.postgresql.org/docs/current/functions-srf.html).\n *\n * `\"exact\"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the\n * hood.\n *\n * `\"planned\"`: Approximated but fast count algorithm. Uses the Postgres\n * statistics under the hood.\n *\n * `\"estimated\"`: Uses exact count for low numbers and planned count for high\n * numbers.\n *\n * @example\n * ```ts\n * // For cross-schema functions where type inference fails, use overrideTypes:\n * const { data } = await supabase\n * .schema('schema_b')\n * .rpc('function_a', {})\n * .overrideTypes<{ id: string; user_id: string }[]>()\n * ```\n *\n * @category Database\n *\n * @example Call a Postgres function without arguments\n * ```ts\n * const { data, error } = await supabase.rpc('hello_world')\n * ```\n *\n * @exampleSql Call a Postgres function without arguments\n * ```sql\n * create function hello_world() returns text as $$\n * select 'Hello world';\n * $$ language sql;\n * ```\n *\n * @exampleResponse Call a Postgres function without arguments\n * ```json\n * {\n * \"data\": \"Hello world\",\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example Call a Postgres function with arguments\n * ```ts\n * const { data, error } = await supabase.rpc('echo', { say: '👋' })\n * ```\n *\n * @exampleSql Call a Postgres function with arguments\n * ```sql\n * create function echo(say text) returns text as $$\n * select say;\n * $$ language sql;\n * ```\n *\n * @exampleResponse Call a Postgres function with arguments\n * ```json\n * {\n * \"data\": \"👋\",\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n *\n * ```\n *\n * @exampleDescription Bulk processing\n * You can process large payloads by passing in an array as an argument.\n *\n * @example Bulk processing\n * ```ts\n * const { data, error } = await supabase.rpc('add_one_each', { arr: [1, 2, 3] })\n * ```\n *\n * @exampleSql Bulk processing\n * ```sql\n * create function add_one_each(arr int[]) returns int[] as $$\n * select array_agg(n + 1) from unnest(arr) as n;\n * $$ language sql;\n * ```\n *\n * @exampleResponse Bulk processing\n * ```json\n * {\n * \"data\": [\n * 2,\n * 3,\n * 4\n * ],\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @exampleDescription Call a Postgres function with filters\n * Postgres functions that return tables can also be combined with [Filters](/docs/reference/javascript/using-filters) and [Modifiers](/docs/reference/javascript/using-modifiers).\n *\n * @example Call a Postgres function with filters\n * ```ts\n * const { data, error } = await supabase\n * .rpc('list_stored_countries')\n * .eq('id', 1)\n * .single()\n * ```\n *\n * @exampleSql Call a Postgres function with filters\n * ```sql\n * create table\n * countries (id int8 primary key, name text);\n *\n * insert into\n * countries (id, name)\n * values\n * (1, 'Rohan'),\n * (2, 'The Shire');\n *\n * create function list_stored_countries() returns setof countries as $$\n * select * from countries;\n * $$ language sql;\n * ```\n *\n * @exampleResponse Call a Postgres function with filters\n * ```json\n * {\n * \"data\": {\n * \"id\": 1,\n * \"name\": \"Rohan\"\n * },\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n *\n * @example Call a read-only Postgres function\n * ```ts\n * const { data, error } = await supabase.rpc('hello_world', undefined, { get: true })\n * ```\n *\n * @exampleSql Call a read-only Postgres function\n * ```sql\n * create function hello_world() returns text as $$\n * select 'Hello world';\n * $$ language sql;\n * ```\n *\n * @exampleResponse Call a read-only Postgres function\n * ```json\n * {\n * \"data\": \"Hello world\",\n * \"status\": 200,\n * \"statusText\": \"OK\"\n * }\n * ```\n */\n rpc<\n FnName extends string & keyof Schema['Functions'],\n Args extends Schema['Functions'][FnName]['Args'] = never,\n FilterBuilder extends GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args> =\n GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args>,\n >(\n fn: FnName,\n args: Args = {} as Args,\n {\n head = false,\n get = false,\n count,\n }: {\n head?: boolean\n get?: boolean\n count?: 'exact' | 'planned' | 'estimated' | (string & {})\n } = {}\n ): PostgrestFilterBuilder<\n ClientOptions,\n Schema,\n FilterBuilder['Row'],\n FilterBuilder['Result'],\n FilterBuilder['RelationName'],\n FilterBuilder['Relationships'],\n 'RPC'\n > {\n let method: 'HEAD' | 'GET' | 'POST'\n const url = new URL(`${this.url}/rpc/${fn}`)\n let body: unknown | undefined\n // objects/arrays-of-objects can't be serialized to URL params, use POST + return=minimal instead\n const _isObject = (v: unknown): boolean =>\n v !== null && typeof v === 'object' && (!Array.isArray(v) || v.some(_isObject))\n const _hasObjectArg = head && Object.values(args as object).some(_isObject)\n if (_hasObjectArg) {\n method = 'POST'\n body = args\n } else if (head || get) {\n method = head ? 'HEAD' : 'GET'\n Object.entries(args)\n // params with undefined value needs to be filtered out, otherwise it'll\n // show up as `?param=undefined`\n .filter(([_, value]) => value !== undefined)\n // array values need special syntax\n .map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`])\n .forEach(([name, value]) => {\n url.searchParams.append(name, value)\n })\n } else {\n method = 'POST'\n body = args\n }\n\n const headers = new Headers(this.headers)\n if (_hasObjectArg) {\n headers.set('Prefer', count ? `count=${count},return=minimal` : 'return=minimal')\n } else if (count) {\n headers.set('Prefer', `count=${count}`)\n }\n\n return new PostgrestFilterBuilder({\n method,\n url,\n headers,\n schema: this.schemaName,\n body,\n fetch: this.fetch ?? fetch,\n urlLengthLimit: this.urlLengthLimit,\n retry: this.retry,\n })\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n 'debug' | 'verbose' | 'info' | 'warn' | 'error' | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * Canonical client and platform error codes emitted by Firebase SQL operations.\n *\n * @remarks\n * {@link FirebaseSqlError.code} is typed as `string` because errors with\n * `category === 'sql-postgrest'` preserve raw PostgreSQL SQLSTATE codes (such as `'23505'` for\n * unique-constraint violations or `'42501'` for insufficient privilege) and PostgREST `PGRST*`\n * codes (such as `'PGRST116'` when `.single()` or `.maybeSingle()` row-count expectations fail).\n * Client (`'sql-client'`) and non-PostgREST (`'sql-platform'`) errors emit values from\n * `FirebaseSqlErrorCode` (see runtime constants in {@link (Code:variable) | Code}).\n *\n * @example\n * Type-annotate a helper handling client and platform error codes:\n * ```ts\n * import { Code, type FirebaseSqlErrorCode } from 'firebase/sql';\n *\n * function isAuthFailure(code: FirebaseSqlErrorCode | string): boolean {\n * return code === Code.UNAUTHORIZED;\n * }\n * ```\n *\n * @public\n */\nexport type FirebaseSqlErrorCode =\n | 'other'\n | 'already-initialized'\n | 'not-initialized'\n | 'not-supported'\n | 'invalid-argument'\n | 'partial-error'\n | 'unauthorized';\n\n/**\n * Alias for {@link FirebaseSqlErrorCode}.\n *\n * @example\n * Reference `Code` as both a type and a runtime constant map:\n * ```ts\n * import { Code } from 'firebase/sql';\n *\n * const expected: Code = Code.NOT_INITIALIZED;\n * ```\n *\n * @public\n */\nexport type Code = FirebaseSqlErrorCode;\n\n/**\n * Frozen map of canonical client and platform error code constants.\n *\n * @remarks\n * Compare against `error.code` when handling `'sql-client'` and `'sql-platform'` errors.\n *\n * `Code.INVALID_ARGUMENT` (`'invalid-argument'`): missing `projectId`, `serviceId`, or `location`,\n * invalid `port`, dot-segment resource name (`'.'` or `'..'`), disallowed HTTP header, or HTTP 400\n * non-PostgREST gateway rejection.\n *\n * `Code.NOT_INITIALIZED` (`'not-initialized'`): operation called or settled after {@link terminate}\n * or `deleteApp()`.\n *\n * `Code.NOT_SUPPORTED` (`'not-supported'`): global `fetch` unavailable in runtime (`'sql-client'`),\n * or HTTP 501 / `UNIMPLEMENTED` gateway rejection (`'sql-platform'`).\n *\n * `Code.UNAUTHORIZED` (`'unauthorized'`): emitted for `'sql-platform'` HTTP 401/403 or\n * `UNAUTHENTICATED` / `PERMISSION_DENIED` gateway, IAM, or App Check rejections. PostgreSQL and\n * PostgREST privilege errors preserve SQLSTATE `'42501'` or `'PGRST*'` under `'sql-postgrest'`, and\n * client-side Auth `getToken()` failures map to `Code.OTHER` under `'sql-client'`.\n *\n * `Code.OTHER` (`'other'`): network failure, aborted request, circular JSON request body,\n * client-side Auth token retrieval failure (`res.status === 0`, `'sql-client'`), or unmapped\n * `'sql-platform'` response (such as HTTP 502/504 or unparseable 2xx body).\n *\n * `Code.ALREADY_INITIALIZED` (`'already-initialized'`) and `Code.PARTIAL_ERROR` (`'partial-error'`):\n * reserved error codes.\n *\n * @example\n * Branch on client and platform error codes:\n * ```ts\n * import { Code } from 'firebase/sql';\n *\n * const res = await sql.from('events').select('id, title');\n * if (!res.success && res.error.code === Code.UNAUTHORIZED) {\n * console.error('Sign in or check App Check configuration:', res.error.message);\n * }\n * ```\n *\n * @public\n */\nexport const Code = Object.freeze({\n OTHER: 'other' as const satisfies FirebaseSqlErrorCode,\n ALREADY_INITIALIZED:\n 'already-initialized' as const satisfies FirebaseSqlErrorCode,\n NOT_INITIALIZED: 'not-initialized' as const satisfies FirebaseSqlErrorCode,\n NOT_SUPPORTED: 'not-supported' as const satisfies FirebaseSqlErrorCode,\n INVALID_ARGUMENT: 'invalid-argument' as const satisfies FirebaseSqlErrorCode,\n PARTIAL_ERROR: 'partial-error' as const satisfies FirebaseSqlErrorCode,\n UNAUTHORIZED: 'unauthorized' as const satisfies FirebaseSqlErrorCode\n});\n\n/**\n * Origin tier discriminator identifying which layer produced a {@link FirebaseSqlError}.\n *\n * @remarks\n * {@link FirebaseSqlError.category} is typed as `string` at compile time, while SDK-generated\n * errors emit one of three values.\n *\n * `'sql-client'`: local SDK validation, missing `fetch`, network drop, `AbortSignal` cancellation,\n * circular JSON body, Auth `getToken()` rejection, or terminated client (`error.status` is\n * `undefined`, while {@link OperationBase.status | OperationFailure.status} is `0`).\n *\n * `'sql-platform'`: any HTTP failure response whose body is not a PostgREST error envelope—typically\n * a Google Cloud gateway, IAM, or App Check rejection, but also proxy or gateway errors (such as\n * HTTP 502 or 504), body-less `HEAD` failures, or `2xx` responses with unparseable JSON bodies. Do\n * not assume the request had no effect on the server.\n *\n * `'sql-postgrest'`: PostgREST or PostgreSQL database execution failure (`code` contains a\n * PostgreSQL SQLSTATE or PostgREST `PGRST*` code).\n *\n * @example\n * Inspect an error category in a telemetry helper:\n * ```ts\n * import { Code, FirebaseSqlErrorCategory, type FirebaseSqlError } from 'firebase/sql';\n *\n * function describeOrigin(err: FirebaseSqlError): FirebaseSqlErrorCategory | 'custom' {\n * if (\n * err.category === FirebaseSqlErrorCategory.SQL_CLIENT ||\n * err.category === FirebaseSqlErrorCategory.SQL_PLATFORM ||\n * err.category === FirebaseSqlErrorCategory.SQL_POSTGREST\n * ) {\n * if (err.category === FirebaseSqlErrorCategory.SQL_CLIENT && err.code === Code.OTHER) {\n * // Transport/abort failure: an in-flight write may or may not have reached the server.\n * }\n * return err.category;\n * }\n * return 'custom';\n * }\n * ```\n *\n * @public\n */\nexport type FirebaseSqlErrorCategory =\n 'sql-postgrest' | 'sql-platform' | 'sql-client';\n\n/**\n * Frozen map of {@link (FirebaseSqlErrorCategory:type) | FirebaseSqlErrorCategory} constants for discriminating error origin tiers.\n *\n * @example\n * Distinguish PostgreSQL errors from gateway or client failures:\n * ```ts\n * import { FirebaseSqlErrorCategory } from 'firebase/sql';\n *\n * const res = await sql.from('events').select('id, code');\n * if (!res.success && res.error.category === FirebaseSqlErrorCategory.SQL_POSTGREST) {\n * console.error('Database error SQLSTATE/PGRST:', res.error.code, res.error.hint);\n * }\n * ```\n *\n * @public\n */\nexport const FirebaseSqlErrorCategory = Object.freeze({\n SQL_POSTGREST: 'sql-postgrest' as const satisfies FirebaseSqlErrorCategory,\n SQL_PLATFORM: 'sql-platform' as const satisfies FirebaseSqlErrorCategory,\n SQL_CLIENT: 'sql-client' as const satisfies FirebaseSqlErrorCategory\n});\n\n/**\n * Plain JSON-serializable object returned by {@link FirebaseSqlError.toJSON}.\n *\n * @example\n * Serialize a `FirebaseSqlError` for structured telemetry:\n * ```ts\n * import type { SerializedFirebaseSqlError } from 'firebase/sql';\n *\n * const res = await sql.from('events').select('id');\n * if (!res.success) {\n * const payload: SerializedFirebaseSqlError = res.error.toJSON();\n * console.error(JSON.stringify(payload));\n * }\n * ```\n *\n * @public\n */\nexport interface SerializedFirebaseSqlError {\n /**\n * Error class name (`'FirebaseSqlError'`).\n * @internal\n */\n name: string;\n /** PostgREST/PostgreSQL wire code (`'sql-postgrest'`) or {@link FirebaseSqlErrorCode} (`'sql-platform'` / `'sql-client'`). */\n code: string;\n /** Human-readable error message. */\n message: string;\n /** Origin tier (`'sql-postgrest'`, `'sql-platform'`, or `'sql-client'`). */\n category: string;\n /** Optional diagnostic detail (server-supplied, JSON-serialized structured details, or client error stack / cause chain on `'sql-client'` errors). */\n details?: string | undefined;\n /** Optional remediation hint (from PostgreSQL/PostgREST, or client-generated abort / header / URL-length hints on `'sql-client'` errors). */\n hint?: string | undefined;\n /** HTTP status code when an HTTP response was received; omitted (`undefined`) for local/network `'sql-client'` errors. */\n status?: number | undefined;\n}\n\n/**\n * Structured error class returned in {@link OperationFailure.error} or thrown synchronously / via {@link Builder.throwOnError}.\n *\n * @remarks\n * Extends `FirebaseError` from `@firebase/util`. Inspect {@link FirebaseSqlError.category},\n * {@link FirebaseSqlError.code}, {@link FirebaseSqlError.details}, and {@link FirebaseSqlError.hint}\n * together—PostgreSQL and PostgREST frequently populate `hint` and `details` with the exact column,\n * constraint, or SQL grant needed to fix a failing query (and `'sql-client'` errors may populate\n * them with client error stacks, `Caused by` chains, or cancellation/URL-length hints). See\n * {@link (Code:variable) | Code} for client and platform error codes and\n * {@link (FirebaseSqlErrorCategory:variable) | FirebaseSqlErrorCategory} for origin tiers.\n *\n * @example\n * Inspect error origin category, code, details, and hint:\n * ```ts\n * import { Code, FirebaseSqlErrorCategory } from 'firebase/sql';\n *\n * const res = await sql.from('events').select('id, title');\n * if (!res.success) {\n * const { category, code, message, details, hint, status } = res.error;\n * if (category === FirebaseSqlErrorCategory.SQL_POSTGREST && code === '42501') {\n * console.error('Database privilege error:', message, hint);\n * } else if (code === Code.UNAUTHORIZED) {\n * console.error('Auth or App Check rejected:', status, details);\n * }\n * }\n * ```\n *\n * @public\n */\nexport class FirebaseSqlError extends FirebaseError {\n /**\n * Error class name (`'FirebaseSqlError'`).\n * @internal\n */\n readonly name: string = 'FirebaseSqlError';\n /** PostgREST/PostgreSQL wire code (`'23505'`, `'PGRST116'`, etc.) or {@link FirebaseSqlErrorCode}. */\n readonly code: string;\n /** Origin tier (`'sql-postgrest'`, `'sql-platform'`, or `'sql-client'`; typed as `string` at compile time). */\n readonly category: string;\n /** Optional diagnostic explanation (server-supplied, JSON-serialized structured payload, or client error stack / cause chain on `'sql-client'` errors). */\n readonly details?: string | undefined;\n /** Optional actionable remediation hint (from PostgreSQL/PostgREST, or client-generated on `'sql-client'` errors). */\n readonly hint?: string | undefined;\n /** HTTP status code when an HTTP response was received (`undefined` for `'sql-client'` errors, where {@link OperationBase.status | OperationFailure.status} is `0`). */\n readonly status?: number | undefined;\n\n /**\n * Constructs a new `FirebaseSqlError` instance.\n *\n * @param code - PostgREST/SQLSTATE error code or {@link FirebaseSqlErrorCode} literal stored on `error.code`.\n * @param message - Human-readable failure description stored on `error.message`.\n * @param category - Origin tier identifier (see {@link (FirebaseSqlErrorCategory:variable) | FirebaseSqlErrorCategory}).\n * @param details - Server-supplied diagnostic detail string, JSON-serialized structured details, or client error stack; `undefined` when absent.\n * @param hint - Server-supplied remediation or URL-length hint; `undefined` when absent.\n * @param status - HTTP response status code, or `undefined` for client-side errors (stored verbatim without runtime validation).\n */\n constructor(\n code: string,\n message: string,\n category: string,\n details?: string | undefined,\n hint?: string | undefined,\n status?: number | undefined\n ) {\n super(code, message);\n this.code = code;\n this.category = category;\n this.details = details;\n this.hint = hint;\n this.status = status;\n\n // Ensure the instanceof operator works as expected on subclasses of Error.\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types\n // and https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget\n Object.setPrototypeOf(this, FirebaseSqlError.prototype);\n }\n\n /**\n * Serializes this error into a plain JSON-compatible object omitting `undefined` optional fields.\n *\n * @returns Plain {@link SerializedFirebaseSqlError} snapshot suitable for structured logging.\n *\n * @example\n * Convert a `FirebaseSqlError` to JSON:\n * ```ts\n * const res = await sql.from('venues').select('id').eq('slug', 'missing').single();\n * if (!res.success) {\n * console.error(JSON.stringify(res.error.toJSON()));\n * }\n * ```\n */\n toJSON(): SerializedFirebaseSqlError {\n const serialized: SerializedFirebaseSqlError = {\n name: this.name,\n code: this.code,\n message: this.message,\n category: this.category\n };\n if (this.details !== undefined) {\n serialized.details = this.details;\n }\n if (this.hint !== undefined) {\n serialized.hint = this.hint;\n }\n if (this.status !== undefined) {\n serialized.status = this.status;\n }\n return serialized;\n }\n\n /** @internal */\n toString(): string {\n const detailsText = this.details ? ` (details: ${this.details})` : '';\n const hintText = this.hint ? ` (hint: ${this.hint})` : '';\n return `${this.name}[code=${this.code}]: ${this.message}${detailsText}${hintText}`.trim();\n }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Code,\n FirebaseSqlError,\n FirebaseSqlErrorCategory,\n type FirebaseSqlErrorCode\n} from './error';\nimport type { MapPostgrestError } from './state';\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\n}\n\nfunction normalizeNonEmptyString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction normalizeDetails(details: unknown): string | undefined {\n const stringDetails = normalizeNonEmptyString(details);\n if (stringDetails !== undefined) {\n return stringDetails;\n }\n // PostgREST PGRST201 (ambiguous embedding) and Google OnePlatform RPC errors\n // emit structured object/array details rather than strings.\n if (typeof details === 'object' && details !== null) {\n return JSON.stringify(details);\n }\n return undefined;\n}\n\nfunction normalizeHint(hint: unknown): string | undefined {\n return normalizeNonEmptyString(hint);\n}\n\nfunction mapPlatformStatusToCode(\n status: number,\n rpcStatus?: unknown\n): FirebaseSqlErrorCode {\n if (\n status === 401 ||\n status === 403 ||\n rpcStatus === 'UNAUTHENTICATED' ||\n rpcStatus === 'PERMISSION_DENIED'\n ) {\n return Code.UNAUTHORIZED;\n }\n if (status === 400 || rpcStatus === 'INVALID_ARGUMENT') {\n return Code.INVALID_ARGUMENT;\n }\n if (status === 501 || rpcStatus === 'UNIMPLEMENTED') {\n return Code.NOT_SUPPORTED;\n }\n return Code.OTHER;\n}\n\n/**\n * Maps low-level transport and PostgREST HTTP failures into canonical `FirebaseSqlError` instances.\n *\n * Cross-Platform Architecture Note (see go/fsql-postgrest-sdk):\n * All Firebase SQL client platforms (Web/JS, Android/Kotlin, Apple/Swift, Flutter/Dart) communicate\n * with the same Google Cloud PostgREST backend behind Google's ESF gateway and encounter three\n * identical tiers of error responses:\n *\n * 1. `SQL_CLIENT`: Local client or network transport failures (offline, network drops, client termination\n * via `NOT_INITIALIZED`, or invalid client configuration).\n * 2. `SQL_PLATFORM`: Google OnePlatform / ESF pre-adapter JSON envelopes (`{ error: { code, message, status, details } }`)\n * emitted by Google Cloud infrastructure before reaching PostgREST (e.g. invalid App Check token,\n * IAM authentication/permission rejections, quota limits).\n * 3. `POSTGREST`: PostgREST JSON envelopes (`{ code, message, details, hint }`) containing PostgREST\n * error codes or PostgreSQL SQLSTATE codes (`23505` uniqueness violation, `42P01` undefined table, etc.)\n * mapped to canonical `Code.*` values.\n *\n * @internal\n */\nexport const mapPostgrestFailureToFirebaseSqlError: MapPostgrestError = (\n rawError,\n status,\n statusText\n) => {\n if (rawError instanceof FirebaseSqlError) {\n return rawError;\n }\n\n const normalizedStatus = status > 0 ? status : undefined;\n\n if (status === 0) {\n const message =\n isPlainRecord(rawError) &&\n typeof rawError.message === 'string' &&\n rawError.message.length > 0\n ? rawError.message\n : rawError instanceof Error && rawError.message.length > 0\n ? rawError.message\n : typeof rawError === 'string' && rawError.length > 0\n ? rawError\n : 'Network request failed.';\n const details = isPlainRecord(rawError)\n ? normalizeDetails(rawError.details)\n : rawError instanceof Error\n ? normalizeDetails(rawError.stack)\n : undefined;\n const hint = isPlainRecord(rawError)\n ? normalizeHint(rawError.hint)\n : undefined;\n return new FirebaseSqlError(\n Code.OTHER,\n message,\n FirebaseSqlErrorCategory.SQL_CLIENT,\n details,\n hint\n );\n }\n\n const envelopeCandidate =\n Array.isArray(rawError) && rawError.length === 1 ? rawError[0] : rawError;\n\n // Google OnePlatform / ESF pre-adapter rejections wrap errors under a top-level\n // `error` envelope (`{ error: { code, message, status, details } }` or single-element\n // array `[{ error: { ... } }]`), which @supabase/postgrest-js leaves nested via raw JSON.parse.\n if (\n isPlainRecord(envelopeCandidate) &&\n isPlainRecord(envelopeCandidate.error)\n ) {\n const inner = envelopeCandidate.error;\n const code = mapPlatformStatusToCode(status, inner.status);\n const message =\n typeof inner.message === 'string' && inner.message.length > 0\n ? inner.message\n : statusText || `HTTP Error ${status}`;\n return new FirebaseSqlError(\n code,\n message,\n FirebaseSqlErrorCategory.SQL_PLATFORM,\n normalizeDetails(inner.details),\n normalizeHint(inner.hint),\n normalizedStatus\n );\n }\n\n if (\n isPlainRecord(rawError) &&\n typeof rawError.error === 'string' &&\n rawError.error.length > 0\n ) {\n const message =\n typeof rawError.error_description === 'string' &&\n rawError.error_description.length > 0\n ? rawError.error_description\n : typeof rawError.message === 'string' && rawError.message.length > 0\n ? rawError.message\n : rawError.error;\n return new FirebaseSqlError(\n mapPlatformStatusToCode(status, rawError.status),\n message,\n FirebaseSqlErrorCategory.SQL_PLATFORM,\n normalizeDetails(rawError.details),\n normalizeHint(rawError.hint),\n normalizedStatus\n );\n }\n\n if (\n isPlainRecord(rawError) &&\n typeof rawError.code === 'string' &&\n rawError.code.length > 0 &&\n typeof rawError.status !== 'string'\n ) {\n const message =\n typeof rawError.message === 'string' && rawError.message.length > 0\n ? rawError.message\n : statusText || rawError.code;\n return new FirebaseSqlError(\n rawError.code,\n message,\n FirebaseSqlErrorCategory.SQL_POSTGREST,\n normalizeDetails(rawError.details),\n normalizeHint(rawError.hint),\n normalizedStatus\n );\n }\n\n const fallbackMessage =\n isPlainRecord(rawError) &&\n typeof rawError.message === 'string' &&\n rawError.message.length > 0\n ? rawError.message\n : typeof rawError === 'string' && rawError.length > 0\n ? rawError\n : statusText || `HTTP Error ${status}`;\n const fallbackDetails = isPlainRecord(rawError)\n ? normalizeDetails(rawError.details)\n : Array.isArray(rawError)\n ? normalizeDetails(rawError)\n : undefined;\n const fallbackHint = isPlainRecord(rawError)\n ? normalizeHint(rawError.hint)\n : undefined;\n\n return new FirebaseSqlError(\n mapPlatformStatusToCode(\n status,\n isPlainRecord(rawError) ? rawError.status : undefined\n ),\n fallbackMessage,\n FirebaseSqlErrorCategory.SQL_PLATFORM,\n fallbackDetails,\n fallbackHint,\n normalizedStatus\n );\n};\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nexport let SDK_VERSION = '';\n\n/**\n * SDK_VERSION should be set before any database instance is created\n * @internal\n */\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AppCheckTokenResult } from '@firebase/app-check-interop-types';\nimport { FirebaseAuthTokenData } from '@firebase/auth-interop-types';\n\nimport {\n Code,\n FirebaseSqlError,\n FirebaseSqlErrorCategory\n} from '../core/error';\nimport { SDK_VERSION } from '../core/version';\n\n/**\n * Lowercased HTTP header keys used by transport for authorization, telemetry, etc.\n * @internal\n */\nexport type FirebaseHeaders = Lowercase<\n | 'x-goog-api-client'\n | 'x-client-version'\n | 'x-firebase-gmpid'\n | 'x-firebase-auth-token'\n | 'x-firebase-appcheck'\n>;\n\n/**\n * Lowercased HTTP Header keys used by transport for authorization, telemetry, etc.\n * @internal\n */\nexport const FirebaseHeaders = Object.freeze({\n GOOG_API_CLIENT: 'x-goog-api-client' as const satisfies FirebaseHeaders,\n CLIENT_VERSION: 'x-client-version' as const satisfies FirebaseHeaders,\n FIREBASE_GMPID: 'x-firebase-gmpid' as const satisfies FirebaseHeaders,\n FIREBASE_AUTH_TOKEN:\n 'x-firebase-auth-token' as const satisfies FirebaseHeaders,\n FIREBASE_APPCHECK: 'x-firebase-appcheck' as const satisfies FirebaseHeaders\n});\n\n/**\n * Lowercased HTTP header keys forbidden for FSQL SDK.\n * Keep in sync with go/firebasesql:sdk:headers.\n */\nconst FORBIDDEN_HEADERS = [\n 'x-firebase-sqlconnect-affinity',\n 'x-goog-request-params',\n 'x-firebase-client',\n 'x-firebase-client-log-type',\n 'authorization'\n] as const;\n\n/** @internal */\nexport const LOWERCASE_DISALLOWED_HEADER_KEYS: ReadonlySet<string> =\n new Set<string>([...Object.values(FirebaseHeaders), ...FORBIDDEN_HEADERS]);\n\n/**\n * Returns the {@linkcode FirebaseHeaders.GOOG_API_CLIENT | 'x-goog-api-client'} header value.\n * @internal\n */\nexport function getGoogApiClientValue(): string {\n return 'gl-js/ fire/' + SDK_VERSION;\n}\n\n/**\n * Validates that the given header name is not a protected header key (case-insensitive).\n * @throws `FirebaseSqlError` with `Code.INVALID_ARGUMENT` and\n * `FirebaseSqlErrorCategory.SQL_CLIENT` if the header name is a protected\n * header key.\n * @internal\n */\nexport function validateHeaderName(name: string): string {\n // Coerce to a string exactly once. Header validation is a security boundary\n // guarding protected wire headers (e.g. auth and telemetry). Single coercion\n // prevents untyped JS callers from bypassing validation with stateful\n // toString() / [Symbol.toPrimitive] objects that return an allowed name\n // during validation and a forbidden name when applied downstream.\n const headerName = String(name);\n if (LOWERCASE_DISALLOWED_HEADER_KEYS.has(headerName.trim().toLowerCase())) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n `Cannot set protected header ${headerName}.`,\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n return headerName;\n}\n\n/**\n * Validates that the given headers do not contain any protected header keys (case-insensitive).\n * @throws `FirebaseSqlError` with `Code.INVALID_ARGUMENT` and\n * `FirebaseSqlErrorCategory.SQL_CLIENT` if the headers contain any protected\n * header keys.\n * @internal\n */\nexport function validateHeaders(\n headers?: Record<string, string> | undefined\n): void {\n if (!headers) {\n return;\n }\n for (const key of Object.keys(headers)) {\n validateHeaderName(key);\n }\n}\n\n/**\n * Merges headers from any valid `HeadersInit` source into a target `Headers` instance.\n * Normalizes across `Headers` instances, plain records, and tuple arrays using the standard\n * `Headers` constructor.\n *\n * @param target - The destination `Headers` instance to mutate.\n * @param source - Source headers in any valid `HeadersInit` format.\n * @returns The mutated `target` `Headers` instance for convenient chaining.\n * @internal\n */\nexport function mergeHeadersInit(\n target: Headers,\n source?: HeadersInit\n): Headers {\n if (source) {\n new Headers(source).forEach((value, key) => {\n target.set(key, value);\n });\n }\n return target;\n}\n\n/**\n * Resolves and normalizes wire-level request headers from request init options,\n * telemetry, and SDK auth / App Check providers.\n * @internal\n */\nexport function resolveRequestHeaders(\n authToken: FirebaseAuthTokenData | null,\n appCheckToken: AppCheckTokenResult | null,\n init?: RequestInit,\n _appId?: string\n): Record<string, string> {\n const headers = new Headers();\n\n mergeHeadersInit(headers, init?.headers);\n\n for (const key of FORBIDDEN_HEADERS) {\n headers.delete(key);\n }\n\n // Firebase token headers\n // user-supplied authorization headers are overwritten\n if (authToken?.accessToken) {\n headers.set(FirebaseHeaders.FIREBASE_AUTH_TOKEN, authToken.accessToken);\n } else {\n headers.delete(FirebaseHeaders.FIREBASE_AUTH_TOKEN);\n }\n\n if (appCheckToken?.token) {\n headers.set(FirebaseHeaders.FIREBASE_APPCHECK, appCheckToken.token);\n } else {\n headers.delete(FirebaseHeaders.FIREBASE_APPCHECK);\n }\n\n // Telemetry headers\n headers.set(FirebaseHeaders.GOOG_API_CLIENT, getGoogApiClientValue());\n headers.set(FirebaseHeaders.CLIENT_VERSION, 'web/' + SDK_VERSION);\n if (_appId !== undefined) {\n headers.set(FirebaseHeaders.FIREBASE_GMPID, _appId);\n } else {\n headers.delete(FirebaseHeaders.FIREBASE_GMPID);\n }\n\n // Normalize headers\n const headersRecord: Record<string, string> = {};\n headers.forEach((value, key) => {\n headersRecord[key] = value;\n });\n return headersRecord;\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { validateHeaders } from '../network/headers';\n\nimport { FirebaseSqlErrorCategory, Code, FirebaseSqlError } from './error';\n\n/**\n * Connection and routing configuration for a {@link FirebaseSql} service client instance\n * initialized via {@link (getSql:1) | getSql()}.\n *\n * @remarks\n * Passed to {@link (getSql:1) | getSql()}, which validates `serviceId`, `location`, `port`, and\n * protected `headers` keys, creates a deep frozen copy, and resolves the PostgREST endpoint URL as\n * `{http|https}://{host}[:{port}]/v1/projects/{projectId}/locations/{location}/services/{serviceId}/postgrest`.\n *\n * Instance caching: {@link (getSql:1) | getSql()} deduplicates instances by `(app, resolvedUrl, schemaName)`.\n * Different `headers` objects passed with an already-initialized `(app, resolvedUrl, schemaName)`\n * reuse the cached {@link FirebaseSql} instance and its original `headers`; use\n * {@link Builder.setHeader} for per-request header overrides. See {@link (getSql:1) | getSql()} for\n * client initialization and error rules.\n *\n * @example\n * Configure settings using the default schema:\n * ```ts\n * import type { SqlServiceSettings } from 'firebase/sql';\n *\n * const settings: SqlServiceSettings = {\n * serviceId: 'events-db',\n * location: 'us-central1'\n * };\n * ```\n *\n * @example\n * Configure settings targeting a non-default PostgreSQL schema:\n * ```ts\n * import type { SqlServiceSettings } from 'firebase/sql';\n *\n * const analyticsSettings: SqlServiceSettings = {\n * serviceId: 'events-db',\n * location: 'us-central1',\n * schemaName: 'analytics'\n * };\n * ```\n *\n * @public\n */\nexport interface SqlServiceSettings {\n /**\n * Target PostgreSQL schema exposed by PostgREST (for example, `'analytics'`).\n *\n * @remarks\n * Defaults to `undefined`. When specified, sends `Accept-Profile: <schemaName>` on `GET` and\n * `HEAD` requests and `Content-Profile: <schemaName>` on `POST`, `PATCH`, and `DELETE` mutations.\n * Omitting `schemaName` (or passing `undefined`) omits profile headers and uses the server's\n * default exposed schema, so specifying `'public'` is unnecessary when `'public'` is the default\n * schema.\n *\n * Do not pass an empty string `''`—it sends an empty profile header that PostgREST rejects with\n * HTTP `406` (`'PGRST106'`). Must be a valid HTTP header value (Latin-1 characters with no CR or\n * LF); otherwise awaiting any builder on the client rejects with a `TypeError` when setting the\n * profile header. Note that omitting `schemaName` and passing an explicit `schemaName` string\n * produce distinct cached {@link FirebaseSql} instances.\n */\n schemaName?: string | undefined;\n\n /**\n * Static custom HTTP headers included on every outgoing request from this client instance.\n *\n * @remarks\n * Defaults to `undefined`. Do not use for authentication or App Check tokens (`Authorization`,\n * `x-firebase-auth-token`, `x-firebase-appcheck`) or reserved Firebase telemetry and routing\n * headers (`x-goog-api-client`, `x-client-version`, `x-firebase-gmpid`, `x-firebase-client`,\n * `x-firebase-client-log-type`, `x-goog-request-params`, `x-firebase-sqlconnect-affinity`).\n * Supplying any protected header key (case-insensitive) causes {@link (getSql:1) | getSql()} to\n * throw {@link FirebaseSqlError} (`invalid-argument`). Every header name and value must also be a\n * valid HTTP header accepted by the Fetch `Headers` constructor (no spaces in header names, no\n * CR/LF, and Latin-1 characters only), or {@link (getSql:1) | getSql()} throws a `TypeError`\n * synchronously when creating a new client (if a client is already cached for the same endpoint\n * and `schemaName`, `getSql()` returns the cached client and ignores `settings.headers`).\n * Firebase Auth and App Check tokens are attached automatically when configured on\n * the bound `FirebaseApp`.\n *\n * Excluded from the {@link (getSql:1) | getSql()} instance cache key; use {@link Builder.setHeader}\n * for request-scoped headers.\n */\n headers?: Record<string, string> | undefined;\n\n /**\n * Non-empty Firebase SQL service identifier within the Firebase project (for example, `'events-db'`).\n *\n * @remarks\n * Required. Passing an empty string causes {@link (getSql:1) | getSql()} to throw\n * {@link FirebaseSqlError} (`invalid-argument`). Percent-encoded when constructing the\n * `/services/{serviceId}/postgrest` URL path.\n */\n serviceId: string;\n\n /**\n * Non-empty Google Cloud region hosting the Firebase SQL service (for example, `'us-central1'`).\n *\n * @remarks\n * Required. Passing an empty string causes {@link (getSql:1) | getSql()} to throw\n * {@link FirebaseSqlError} (`invalid-argument`). Percent-encoded when constructing the\n * `/locations/{location}/` URL path.\n */\n location: string;\n\n /**\n * Custom endpoint hostname (without protocol or path) overriding the default Firebase SQL service host.\n *\n * @remarks\n * Defaults to `'firebasedataconnect.googleapis.com'`. Must be a bare hostname (optionally\n * `host:port`) with no scheme or path. Only values rejected by the WHATWG `URL` parser when\n * prefixed with `https://` (such as `''`) cause {@link (getSql:1) | getSql()} to throw a\n * `TypeError`; passing a scheme or path is not rejected and silently produces a wrong endpoint\n * (for example, `'http://example.com'` resolves to hostname `'http'`, and any path segment is\n * overwritten).\n */\n host?: string | undefined;\n\n /**\n * Custom TCP port number appended to the resolved service endpoint URL.\n *\n * @remarks\n * Defaults to `undefined`. When provided, must be an integer between `1` and `65535` inclusive;\n * non-integers or out-of-range values cause {@link (getSql:1) | getSql()} to throw\n * {@link FirebaseSqlError} (`invalid-argument`).\n */\n port?: number | undefined;\n\n /**\n * Controls whether requests use `https:` (`true` or `undefined`) or `http:` (`false`).\n *\n * @remarks\n * Defaults to `true`. Omitting `sslEnabled` and setting `sslEnabled: true` resolve to the same\n * `https:` endpoint and share the same cached {@link FirebaseSql} instance.\n */\n sslEnabled?: boolean | undefined;\n}\n\n/**\n * Creates a mutable deep copy of a {@link SqlServiceSettings} object, cloning nested `headers` if present.\n *\n * @remarks\n * When to use: cloning a frozen `sql.settings` object (returned by {@link FirebaseSql.settings})\n * to derive configuration for another {@link FirebaseSql} instance (such as targeting a different\n * `schemaName` or `serviceId`).\n *\n * Behavior and side effects: pure synchronous clone with no network I/O or validation. Unlike\n * `sql.settings`, the returned object and its `headers` map are unfrozen and safe to mutate before\n * passing to {@link (getSql:1) | getSql()}.\n *\n * @param settings - Source {@link SqlServiceSettings} object to clone.\n * @returns A new mutable {@link SqlServiceSettings} object with an independent copy of `headers`.\n *\n * @example\n * Derive a secondary schema client from existing settings:\n * ```ts\n * import { copySqlServiceSettings, getSql } from 'firebase/sql';\n *\n * const sql = getSql({ serviceId: 'events-db', location: 'us-central1' });\n * const analyticsSettings = copySqlServiceSettings(sql.settings);\n * analyticsSettings.schemaName = 'analytics';\n *\n * const analyticsSql = getSql(sql.app, analyticsSettings);\n * ```\n *\n * @public\n */\nexport function copySqlServiceSettings(\n settings: SqlServiceSettings\n): SqlServiceSettings {\n const settingsCopy: SqlServiceSettings = Object.assign({}, settings);\n if (settings.headers !== undefined) {\n settingsCopy.headers = Object.assign({}, settings.headers);\n }\n return settingsCopy;\n}\n\n/**\n * Freezes a deep copy of the `SqlServiceSettings`.\n * @internal\n */\nexport function freezeSqlServiceSettings(\n settings: SqlServiceSettings\n): SqlServiceSettings {\n const settingsCopy = copySqlServiceSettings(settings);\n if (settingsCopy.headers !== undefined) {\n Object.freeze(settingsCopy.headers);\n }\n return Object.freeze(settingsCopy);\n}\n\n/**\n * Validates that the provided port is a valid TCP port number.\n *\n * @throws `FirebaseSqlError` with `Code.INVALID_ARGUMENT` and `FirebaseSqlErrorCategory.SQL_CLIENT` if port is invalid.\n */\nfunction validatePort(port: unknown): void {\n if (port === undefined) {\n return;\n }\n if (\n typeof port !== 'number' ||\n !Number.isInteger(port) ||\n port < 1 ||\n port > 65535\n ) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n `Port must be a valid integer between 1 and 65535 if provided. Received: ${String(port)}.`,\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n}\n\n/**\n * Validates required `SqlServiceSettings` fields.\n *\n * @returns a deep, frozen copy of the settings.\n * @throws `FirebaseSqlError` with `Code.INVALID_ARGUMENT` and `FirebaseSqlErrorCategory.SQL_CLIENT` if required fields are missing or invalid.\n * @internal\n */\nexport function validateSqlServiceSettings(\n settings: SqlServiceSettings\n): SqlServiceSettings {\n if (!settings) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n 'SqlServiceSettings must be provided.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (!settings.serviceId) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n 'serviceId is required.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (!settings.location) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n 'location is required.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n validatePort(settings.port);\n validateHeaders(settings.headers);\n return freezeSqlServiceSettings(settings);\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** @internal */\nexport const FIREBASE_SQL_COMPONENT_NAME = 'firebase-sql';\n\n/** @internal */\nexport const FIREBASE_SQL_PACKAGE_NAME = '@firebase/sql';\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from './core/version';\nimport { FIREBASE_SQL_PACKAGE_NAME } from './util/constants';\n\n/** @internal */\nexport const logger = new Logger(FIREBASE_SQL_PACKAGE_NAME);\n\nexport function getLogLevel(): LogLevelString {\n return LogLevel[logger.logLevel].toLowerCase() as LogLevelString;\n}\nexport function setLogLevel(logLevel: LogLevelString): void {\n logger.setLogLevel(logLevel);\n}\nexport function logDebug(msg: string): void {\n logger.debug(`Firebase SQL (${SDK_VERSION}): ${msg}`);\n}\n\nexport function logError(msg: string): void {\n logger.error(`Firebase SQL (${SDK_VERSION}): ${msg}`);\n}\n\n/**\n * The App Check \"placeholder\" token, i.e. base64 of `{\"error\":\"UNKNOWN_ERROR\"}`,\n * sent when App Check fails to obtain a real token.\n * See `formatDummyToken(defaultTokenErrorData)` in `@firebase/app-check`.\n */\nconst PLACEHOLDER_APP_CHECK_TOKEN = 'eyJlcnJvciI6IlVOS05PV05fRVJST1IifQ==';\n\n/**\n * Returns a partially redacted access token, keeping only a short prefix and\n * suffix so that tokens can be correlated in logs without exposing them.\n * @internal\n */\nexport function redactToken(token: string | null): string {\n if (token === null) {\n return 'null';\n }\n if (token === PLACEHOLDER_APP_CHECK_TOKEN) {\n return `${token} (the \"placeholder\" App Check token)`;\n }\n if (token.length < 30) {\n return '<redacted>';\n }\n return `${token.slice(0, 6)}<redacted>${token.slice(-6)}`;\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Name, Provider } from '@firebase/component';\n\nimport { logError } from '../../logger';\n\n/**\n * Options for retrieving a token.\n *\n * {@linkcode forceRefresh} - if true, forces a token refresh from the underlying service. If no token\n * is available in the underlying service, null will be returned.\n *\n * @internal\n */\nexport interface TokenOptions {\n forceRefresh?: boolean;\n}\n\n/**\n * Common token provider interface for SQL client access token providers.\n * @internal\n */\nexport interface TokenProvider<TToken, TListener> {\n getToken(options?: TokenOptions): Promise<TToken | null>;\n addTokenChangeListener(listener: TListener): void;\n removeTokenChangeListener(listener: TListener): void;\n terminate(): void;\n}\n\n/**\n * Abstract base class managing token retrieval lifecycle, in-flight deduplication,\n * delayed component initialization, and listener registration.\n * @internal\n */\nexport abstract class AbstractTokenProvider<\n Token,\n Component,\n Listener,\n ComponentName extends Name = Name\n> implements TokenProvider<Token, Listener> {\n protected component: Component | undefined;\n /** Promise to dedupe concurrent in-flight getToken() requests */\n private activeGetTokenPromise?: Promise<Token | null> | undefined = undefined;\n /** Promise to dedupe concurrent in-flight getToken({ forceRefresh: true }) requests */\n private activeForceRefreshPromise?: Promise<Token | null> | undefined =\n undefined;\n /** Resolver to settle active inFlightGetToken early when a concurrent force-refresh returns */\n private resolveActiveGetTokenPromise?:\n ((token: Token | null) => void) | undefined = undefined;\n\n /** Unsubscribe callback to release onInit listener from the provider */\n private onInitUnsubscribe?: (() => void) | undefined = undefined;\n\n /**\n * Array of token change listeners registered on this provider.\n * Used to cleanup listeners when the instance is deleted.\n */\n private activeListeners: Listener[] = [];\n /** Array of token change listeners queued to be registered on this provider once it initializes. */\n private queuedListeners: Listener[] = [];\n\n /**\n * @param provider Provider for a Firebase service component\n * @param serverAppToken Static token from a Firebase Server App\n */\n constructor(\n protected readonly provider: Provider<ComponentName> | undefined,\n protected readonly serverAppToken?: string | undefined\n ) {\n this.component =\n (provider?.getImmediate({ optional: true }) as Component) ?? undefined;\n if (!this.component) {\n this.onInitUnsubscribe = provider?.onInit(component => {\n this.component = component as Component;\n const n = this.queuedListeners.length;\n for (let i = 0; i < n; i++) {\n const oldestListener = this.queuedListeners.shift();\n oldestListener && this.addTokenChangeListener(oldestListener);\n }\n this.cancelOnInit();\n });\n }\n }\n\n /**\n * Retrieves the token, deduplicating concurrent in-flight requests.\n *\n * NOTE: Calls {@linkcode requestToken()} which provides the {@linkcode serverAppToken} token if one was provided and no token is available from the\n * underlying service (and `TokenOptions.forceRefresh === false`).\n *\n * {@linkcode TokenOptions.forceRefresh} - if true, forces a token refresh from the underlying service. If no token\n * is available in the underlying service, null will be returned.\n */\n getToken(\n options: TokenOptions = { forceRefresh: false }\n ): Promise<Token | null> {\n if (!this.activeForceRefreshPromise && options.forceRefresh) {\n const forcedPromise = this.requestToken(options)\n .then(token => {\n this.resolveActiveGetTokenPromise?.(token);\n return token;\n })\n .finally(() => {\n if (this.activeForceRefreshPromise === forcedPromise) {\n this.activeForceRefreshPromise = undefined;\n }\n });\n this.activeForceRefreshPromise = forcedPromise;\n }\n if (this.activeForceRefreshPromise) {\n return this.activeForceRefreshPromise;\n }\n\n if (!this.activeGetTokenPromise) {\n const unforcedPromise = new Promise<Token | null>((resolve, reject) => {\n this.resolveActiveGetTokenPromise = resolve;\n this.requestToken(options).then(resolve, reject);\n }).finally(() => {\n if (this.activeGetTokenPromise === unforcedPromise) {\n this.activeGetTokenPromise = undefined;\n this.resolveActiveGetTokenPromise = undefined;\n }\n });\n this.activeGetTokenPromise = unforcedPromise;\n }\n return this.activeGetTokenPromise;\n }\n\n /**\n * Invoke the underlying service to fetch a token.\n * Allows for delayed initialization.\n */\n private requestToken(\n options: TokenOptions = { forceRefresh: false }\n ): Promise<Token | null> {\n if (this.component) {\n return this.fetchToken(this.component, options);\n }\n\n if (!this.provider) {\n if (this.serverAppToken && !options.forceRefresh) {\n return Promise.resolve(this.convertServerAppToken(this.serverAppToken));\n }\n return Promise.resolve(null);\n }\n\n return new Promise<Token | null>((resolve, reject) => {\n // Support delayed initialization. This allows our customers to initialize\n // the Firebase SQL SDK before initializing Auth or AppCheck and ensures that\n // all requests are authenticated if a token becomes available before the timeout expires.\n setTimeout(() => {\n if (this.component) {\n this.requestToken(options).then(resolve, reject);\n } else if (this.serverAppToken && !options.forceRefresh) {\n resolve(this.convertServerAppToken(this.serverAppToken));\n } else {\n resolve(null);\n }\n }, 0);\n });\n }\n\n /**\n * Invoke the underlying service component to add a token change listener. If the service is not\n * yet initialized, the listener is buffered and added once the service initializes.\n *\n * NOTE: Does NOT filter out duplicate listeners.\n */\n addTokenChangeListener(listener: Listener): void {\n if (this.component) {\n try {\n this.activeListeners.push(listener);\n this.addListener(this.component, listener);\n } catch (err) {\n this.activeListeners.pop();\n logError(err instanceof Error ? err.message : String(err));\n }\n } else {\n this.queuedListeners.push(listener);\n }\n }\n\n /**\n * Invoke the underlying service component to remove a token change listener. If the service is not\n * yet initialized, the listener is removed from the pending buffer.\n */\n removeTokenChangeListener(listener: Listener): void {\n if (this.component) {\n try {\n removeFirstOccurrenceFromList(listener, this.activeListeners);\n this.removeListener(this.component, listener);\n } catch (err) {\n logError(err instanceof Error ? err.message : String(err));\n }\n }\n removeFirstOccurrenceFromList(listener, this.queuedListeners);\n }\n\n /**\n * Convert the Firebase Server App token to the appropriate token type.\n */\n protected abstract convertServerAppToken(token: string): Token;\n\n /**\n * Get token from underlying service component\n */\n protected abstract fetchToken(\n component: Component,\n options: TokenOptions\n ): Promise<Token | null>;\n\n /**\n * Add a token change listener to the underlying service component\n */\n protected abstract addListener(\n component: Component,\n listener: Listener\n ): void;\n\n /**\n * Remove an added token change listener from the underlying service component\n */\n protected abstract removeListener(\n component: Component,\n listener: Listener\n ): void;\n\n /**\n * Cleans up any pending initialization callbacks.\n * @internal\n */\n protected cancelOnInit(): void {\n this.onInitUnsubscribe?.();\n this.onInitUnsubscribe = undefined;\n this.queuedListeners = [];\n }\n\n /**\n * Terminates the `TokenProvider` instance. Cleans up any outstanding resources.\n * @internal\n */\n terminate(): void {\n this.cancelOnInit();\n [...this.activeListeners].forEach(listener =>\n this.removeTokenChangeListener(listener)\n );\n }\n}\n\n/**\n * Removes the first occurrence of an item from the list.\n * @internal\n */\nfunction removeFirstOccurrenceFromList<Element>(\n item: Element,\n list: Element[]\n): boolean {\n const index = list.indexOf(item);\n if (index !== -1) {\n list.splice(index, 1);\n }\n return index !== -1;\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\nimport {\n AppCheckInternalComponentName,\n AppCheckTokenListener,\n AppCheckTokenResult,\n FirebaseAppCheckInternal\n} from '@firebase/app-check-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport {\n AbstractTokenProvider,\n TokenOptions,\n TokenProvider\n} from './AbstractTokenProvider';\n\n/** @internal */\nexport interface AppCheckTokenProvider extends TokenProvider<\n AppCheckTokenResult,\n AppCheckTokenListener\n> {}\n\n/**\n * App Check Provider backed by the `@firebase/app-check-interop-types` component\n * or a `FirebaseServerApp` static `appCheckToken`.\n * @internal\n */\nexport class AppCheckProvider\n extends AbstractTokenProvider<\n AppCheckTokenResult,\n FirebaseAppCheckInternal,\n AppCheckTokenListener,\n AppCheckInternalComponentName\n >\n implements AppCheckTokenProvider\n{\n constructor(\n app: FirebaseApp,\n appCheckInternalProvider:\n Provider<AppCheckInternalComponentName> | undefined\n ) {\n const serverAppToken = _isFirebaseServerApp(app)\n ? app.settings.appCheckToken\n : undefined;\n super(appCheckInternalProvider, serverAppToken);\n }\n\n protected convertServerAppToken(token: string): AppCheckTokenResult {\n return { token };\n }\n\n protected fetchToken(\n component: FirebaseAppCheckInternal,\n options: TokenOptions = { forceRefresh: false }\n ): Promise<AppCheckTokenResult | null> {\n return component.getToken(options.forceRefresh);\n }\n\n protected addListener(\n component: FirebaseAppCheckInternal,\n listener: AppCheckTokenListener\n ): void {\n component.addTokenListener(listener);\n }\n\n protected removeListener(\n component: FirebaseAppCheckInternal,\n listener: AppCheckTokenListener\n ): void {\n component.removeTokenListener(listener);\n }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName,\n FirebaseAuthTokenData\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\nimport { logDebug, logError } from '../../logger';\n\nimport {\n AbstractTokenProvider,\n TokenOptions,\n TokenProvider\n} from './AbstractTokenProvider';\n\n/** @internal */\nexport interface FirebaseAuthTokenProvider extends TokenProvider<\n FirebaseAuthTokenData,\n AuthTokenListener\n> {\n getAuth(): FirebaseAuthInternal | undefined;\n}\n\n/** @internal */\nexport type AuthTokenListener = (token: string | null) => void;\n\n/**\n * Auth Token Provider backed by the `@firebase/auth-interop-types` component\n * or a `FirebaseServerApp` static `authIdToken`.\n * @internal\n */\nexport class FirebaseAuthProvider\n extends AbstractTokenProvider<\n FirebaseAuthTokenData,\n FirebaseAuthInternal,\n AuthTokenListener,\n FirebaseAuthInternalName\n >\n implements FirebaseAuthTokenProvider\n{\n constructor(\n app: FirebaseApp,\n authInternalProvider: Provider<FirebaseAuthInternalName> | undefined\n ) {\n const serverAppToken = _isFirebaseServerApp(app)\n ? app.settings.authIdToken\n : undefined;\n super(authInternalProvider, serverAppToken);\n }\n\n getAuth(): FirebaseAuthInternal | undefined {\n return this.component;\n }\n\n protected convertServerAppToken(token: string): FirebaseAuthTokenData {\n return { accessToken: token };\n }\n\n protected fetchToken(\n component: FirebaseAuthInternal,\n options: TokenOptions = { forceRefresh: false }\n ): Promise<FirebaseAuthTokenData | null> {\n return component.getToken(options.forceRefresh).catch((error: unknown) => {\n if (\n error &&\n typeof error === 'object' &&\n 'code' in error &&\n error.code === 'auth/token-not-initialized'\n ) {\n logDebug(\n 'Got auth/token-not-initialized error. Treating as null token.'\n );\n return null;\n }\n const errorMsg = error instanceof Error ? error.message : String(error);\n logError('Error received when attempting to retrieve token: ' + errorMsg);\n return Promise.reject(error);\n });\n }\n\n protected addListener(\n component: FirebaseAuthInternal,\n listener: AuthTokenListener\n ): void {\n component.addAuthTokenListener(listener);\n }\n\n protected removeListener(\n component: FirebaseAuthInternal,\n listener: AuthTokenListener\n ): void {\n component.removeAuthTokenListener(listener);\n }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseAuthTokenData } from '@firebase/auth-interop-types';\nimport { decode, isCloudWorkstation } from '@firebase/util';\n\nimport {\n Code,\n FirebaseSqlError,\n FirebaseSqlErrorCategory\n} from '../core/error';\nimport { SqlServiceSettings } from '../core/settings';\nimport type {\n BuilderExecutionTracker,\n CreateBuilderFetch,\n SqlClientState\n} from '../core/state';\nimport { AppCheckTokenProvider } from '../core/tokenProviders/AppCheckTokenProvider';\nimport { FirebaseAuthTokenProvider } from '../core/tokenProviders/FirebaseAuthTokenProvider';\n\nimport { Fetch, getFetch } from './fetch';\nimport { FirebaseHeaders, resolveRequestHeaders } from './headers';\n\n/**\n * Extracts the user UID from an Auth ID token's `sub` claim.\n *\n * The \"sub\" claim is documented to be \"a non-empty string and must be the uid of the user or device\"\n * (see http://goo.gle/4oGjEQt). Extracting the UID directly from the cryptographic token avoids race\n * conditions where the auth manager's current UID may have changed since the token was issued.\n *\n * @internal\n */\nexport function getAuthUidFromToken(\n token: string | null | undefined\n): string | null {\n if (!token) {\n return null;\n }\n try {\n const parts = token.split('.');\n if (parts.length !== 3) {\n return null;\n }\n const claims = decode(token).claims;\n const sub = claims?.sub;\n return typeof sub === 'string' && sub.length > 0 ? sub : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Normalizes an AbortSignal abort reason or thrown error into a standard AbortError,\n * preserving any existing FirebaseSqlError, AbortError, or TimeoutError.\n *\n * @internal\n */\nexport function toAbortError(signal: AbortSignal, thrown?: unknown): Error {\n const reason: unknown = thrown !== undefined ? thrown : signal.reason;\n if (\n reason instanceof Error &&\n (reason.name === 'AbortError' ||\n reason.name === 'TimeoutError' ||\n reason instanceof FirebaseSqlError)\n ) {\n return reason;\n }\n const message =\n reason instanceof Error\n ? reason.message\n : typeof reason === 'string'\n ? reason\n : 'This operation was aborted';\n const error = new Error(message);\n error.name = 'AbortError';\n return error;\n}\n\n/**\n * Composes two AbortSignals into a single effective AbortSignal.\n *\n * @internal\n */\nexport function composeSignals(\n signal1: AbortSignal | undefined,\n signal2: AbortSignal | undefined\n): { signal: AbortSignal | undefined; cleanup: () => void } {\n if (!signal1) {\n return { signal: signal2, cleanup: () => {} };\n }\n if (!signal2) {\n return { signal: signal1, cleanup: () => {} };\n }\n if (signal1.aborted) {\n return { signal: signal1, cleanup: () => {} };\n }\n if (signal2.aborted) {\n return { signal: signal2, cleanup: () => {} };\n }\n\n if (typeof AbortSignal.any === 'function') {\n return {\n signal: AbortSignal.any([signal1, signal2]),\n cleanup: () => {}\n };\n }\n\n const controller = new AbortController();\n const onAbort1 = (): void => controller.abort(signal1.reason);\n const onAbort2 = (): void => controller.abort(signal2.reason);\n signal1.addEventListener('abort', onAbort1, { once: true });\n signal2.addEventListener('abort', onAbort2, { once: true });\n\n const cleanup = (): void => {\n signal1.removeEventListener('abort', onAbort1);\n signal2.removeEventListener('abort', onAbort2);\n };\n return { signal: controller.signal, cleanup };\n}\n\n/**\n * Interface defining the external API of the transport layer.\n * @internal\n */\nexport interface FirebaseSqlTransportInterface {\n readonly settings?: SqlServiceSettings;\n\n /**\n * Constructs and executes an FSQL HTTP request, and returns the response.\n */\n invokePostgrestOperation(\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response>;\n\n /**\n * Returns a standard `fetch` implementation bound to this transport instance,\n * optionally tracking `FirebaseSqlError` instances on `tracker.clientError` and\n * throwing `AbortError` to immediately short-circuit PostgREST retries.\n */\n toFetch(tracker?: BuilderExecutionTracker): typeof fetch;\n}\n\n/**\n * Configuration options for FirebaseSqlTransport.\n * @internal\n */\nexport interface FirebaseSqlTransportOptions {\n settings?: SqlServiceSettings;\n appId?: string | undefined;\n authTokenProvider?: FirebaseAuthTokenProvider | undefined;\n appCheckTokenProvider?: AppCheckTokenProvider | undefined;\n terminationSignal?: AbortSignal | undefined;\n state?: SqlClientState | undefined;\n}\n\n/**\n * HTTP transport layer for Firebase SQL.\n * @internal\n */\nexport class FirebaseSqlTransport implements FirebaseSqlTransportInterface {\n readonly settings?: SqlServiceSettings;\n protected _appId?: string;\n // TODO: Update _isUsingEmulator if we add emulator support in the future.\n protected _isUsingEmulator = false;\n protected authProvider?: FirebaseAuthTokenProvider;\n protected appCheckProvider?: AppCheckTokenProvider;\n protected _terminationSignal?: AbortSignal;\n protected _state?: SqlClientState;\n\n constructor(options: FirebaseSqlTransportOptions = {}) {\n this.settings = options.settings;\n this._appId = options.appId;\n this.authProvider = options.authTokenProvider;\n this.appCheckProvider = options.appCheckTokenProvider;\n this._terminationSignal = options.terminationSignal;\n this._state = options.state;\n }\n\n /**\n * Constructs and executes an FSQL HTTP request, and returns the response.\n */\n async invokePostgrestOperation(\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response> {\n if (this._state && this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.toString()\n : input.url;\n\n const authProvider =\n this._state?.active?.authTokenProvider ?? this.authProvider;\n const appCheckProvider =\n this._state?.active?.appCheckTokenProvider ?? this.appCheckProvider;\n const appId = this._state?.active?.appId ?? this._appId;\n const terminationSignal =\n this._state?.terminationSignal ?? this._terminationSignal;\n\n if (terminationSignal?.aborted) {\n throw toAbortError(terminationSignal);\n }\n\n const inputSignal =\n init?.signal !== undefined\n ? (init.signal ?? undefined)\n : typeof Request !== 'undefined' && input instanceof Request\n ? input.signal\n : undefined;\n\n const { signal: effectiveSignal, cleanup } = composeSignals(\n inputSignal,\n terminationSignal\n );\n\n const isRequest =\n typeof Request !== 'undefined' && input instanceof Request;\n let mergedHeadersInit: HeadersInit | undefined = init?.headers;\n if (isRequest) {\n if (init?.headers === undefined) {\n mergedHeadersInit = input.headers;\n } else {\n const combined = new Headers(input.headers);\n new Headers(init.headers).forEach((value, key) => {\n combined.set(key, value);\n });\n mergedHeadersInit = combined;\n }\n }\n\n const mergedInit: RequestInit = {\n ...(isRequest\n ? {\n method: input.method,\n body: input.body,\n mode: input.mode,\n credentials: input.credentials,\n cache: input.cache,\n redirect: input.redirect,\n referrer: input.referrer,\n integrity: input.integrity\n }\n : undefined),\n ...init,\n headers: mergedHeadersInit\n };\n\n try {\n const fetchImpl = getFetch();\n\n let authToken: FirebaseAuthTokenData | null = null;\n let appCheckToken: { token: string } | null = null;\n\n try {\n const [authData, appCheckData] = await Promise.all([\n authProvider\n ? authProvider.getToken({ forceRefresh: false })\n : Promise.resolve(null),\n appCheckProvider\n ? appCheckProvider\n .getToken({ forceRefresh: false })\n .catch(() => null)\n : Promise.resolve(null)\n ]);\n authToken = authData;\n appCheckToken = appCheckData;\n } catch (err) {\n if (this._state && this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (effectiveSignal?.aborted) {\n throw toAbortError(effectiveSignal, err);\n }\n throw err;\n }\n\n if (this._state && this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (effectiveSignal?.aborted) {\n throw toAbortError(effectiveSignal);\n }\n\n const headers = resolveRequestHeaders(\n authToken,\n appCheckToken,\n mergedInit,\n appId\n );\n const requestInit = this.buildRequestInit(\n mergedInit,\n headers,\n url,\n effectiveSignal\n );\n const initialUid = getAuthUidFromToken(authToken?.accessToken);\n const canReplayBody = !(\n typeof ReadableStream !== 'undefined' &&\n (requestInit.body instanceof ReadableStream ||\n (isRequest && init?.body === undefined && input.bodyUsed))\n );\n\n return await fetchImpl(url, requestInit)\n .then(async response => {\n if (this._state && this._state.active === null) {\n if (typeof response.body?.cancel === 'function') {\n await response.body.cancel().catch(() => {});\n }\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (\n response.status === 401 &&\n authToken &&\n canReplayBody &&\n authProvider\n ) {\n return this.refreshAuthAndRefetch(\n fetchImpl,\n url,\n requestInit,\n headers,\n authToken,\n response,\n initialUid,\n authProvider\n );\n }\n return response;\n })\n .catch(async err => {\n if (this._state && this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (effectiveSignal?.aborted) {\n throw toAbortError(effectiveSignal, err);\n }\n throw err;\n });\n } finally {\n cleanup();\n }\n }\n\n /**\n * Constructs the final `RequestInit` configuration by merging caller-supplied init options\n * and normalized headers, while applying Cloud Workstation credentials if applicable.\n */\n private buildRequestInit(\n init: RequestInit | undefined,\n headers: Record<string, string>,\n requestUrl: string,\n signal?: AbortSignal | undefined\n ): RequestInit {\n const requestInit: RequestInit = Object.assign({}, init, { headers });\n if (signal !== undefined) {\n requestInit.signal = signal;\n }\n\n // Forward workstation auth cookies when targeting an emulator host in\n // Cloud Workstations, where forwarded ports require cookie auth.\n if (\n isCloudWorkstation(requestUrl) &&\n this._isUsingEmulator &&\n !requestInit.credentials\n ) {\n requestInit.credentials = 'include';\n }\n\n return requestInit;\n }\n\n /**\n * Force-refreshes the Firebase Auth token and retries the request once if a new token was\n * successfully obtained.\n */\n private async refreshAuthAndRefetch(\n fetchImpl: Fetch,\n requestUrl: string,\n requestInit: RequestInit,\n headers: Record<string, string>,\n currentToken: FirebaseAuthTokenData,\n originalResponse: Response,\n initialUid: string | null,\n authProvider: FirebaseAuthTokenProvider\n ): Promise<Response> {\n if (!authProvider) {\n return originalResponse;\n }\n\n const signal = requestInit.signal;\n if (signal?.aborted) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n throw toAbortError(signal);\n }\n\n if (this._state && this._state.active === null) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n\n // Check cached token first to avoid redundant Auth network trips if another\n // concurrent request already refreshed the token in the background.\n let refreshedToken: FirebaseAuthTokenData | null = null;\n try {\n refreshedToken = await authProvider\n .getToken({ forceRefresh: false })\n .then(data => data ?? null)\n .catch(() => null);\n\n if (signal?.aborted) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n throw toAbortError(signal);\n }\n\n if (this._state && this._state.active === null) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n\n if (\n !refreshedToken?.accessToken ||\n refreshedToken.accessToken === currentToken.accessToken\n ) {\n refreshedToken = await authProvider\n .getToken({ forceRefresh: true })\n .then(data => data ?? null)\n .catch(() => null);\n }\n } catch (err) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n if (this._state && this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (signal?.aborted) {\n throw toAbortError(signal, err);\n }\n throw err;\n }\n\n if (signal?.aborted) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n throw toAbortError(signal);\n }\n\n if (this._state && this._state.active === null) {\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n\n if (\n refreshedToken?.accessToken &&\n refreshedToken.accessToken !== currentToken.accessToken\n ) {\n const refreshedUid = getAuthUidFromToken(refreshedToken.accessToken);\n if (initialUid !== null && refreshedUid !== initialUid) {\n return originalResponse;\n }\n\n // Cancel original response body ReadableStream if it exists\n if (typeof originalResponse.body?.cancel === 'function') {\n await originalResponse.body.cancel().catch(() => {});\n }\n const retryHeaders: Record<string, string> = Object.assign({}, headers);\n retryHeaders[FirebaseHeaders.FIREBASE_AUTH_TOKEN] =\n refreshedToken.accessToken;\n const retryRequestInit: RequestInit = Object.assign({}, requestInit, {\n headers: retryHeaders\n });\n return fetchImpl(requestUrl, retryRequestInit);\n }\n return originalResponse;\n }\n\n /**\n * Returns a standard `fetch` implementation bound to this transport instance,\n * optionally tracking `FirebaseSqlError` instances on `tracker.clientError` and\n * throwing `AbortError` to immediately short-circuit PostgREST retries.\n */\n toFetch(tracker?: BuilderExecutionTracker): typeof fetch {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response> => {\n try {\n return await this.invokePostgrestOperation(input, init);\n } catch (err) {\n const errorToTrack =\n this._state && this._state.active === null\n ? new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n )\n : err instanceof FirebaseSqlError\n ? err\n : null;\n\n if (tracker && errorToTrack) {\n tracker.clientError = errorToTrack;\n const abortError = new Error(errorToTrack.message);\n abortError.name = 'AbortError';\n throw abortError;\n }\n throw err;\n }\n };\n }\n}\n\n/** @internal */\nexport const createBuilderFetch: CreateBuilderFetch = (state, tracker) => {\n const transport = new FirebaseSqlTransport({ state });\n return transport.toFetch(tracker);\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { jsonEval } from './json';\n\ninterface Claims {\n [key: string]: {};\n}\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const decode = function (token: string): DecodedToken {\n let header = {},\n claims: Claims = {},\n data = {},\n signature = '';\n\n try {\n const parts = token.split('.');\n header = jsonEval(base64Decode(parts[0]) || '') as object;\n claims = jsonEval(base64Decode(parts[1]) || '') as Claims;\n signature = parts[2];\n data = claims['d'] || {};\n delete claims['d'];\n } catch (e) {}\n\n return {\n header,\n claims,\n data,\n signature\n };\n};\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidTimestamp = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n const now: number = Math.floor(new Date().getTime() / 1000);\n let validSince: number = 0,\n validUntil: number = 0;\n\n if (typeof claims === 'object') {\n if (claims.hasOwnProperty('nbf')) {\n validSince = claims['nbf'] as number;\n } else if (claims.hasOwnProperty('iat')) {\n validSince = claims['iat'] as number;\n }\n\n if (claims.hasOwnProperty('exp')) {\n validUntil = claims['exp'] as number;\n } else {\n // token will expire after 24h by default\n validUntil = validSince + 86400;\n }\n }\n\n return (\n !!now &&\n !!validSince &&\n !!validUntil &&\n now >= validSince &&\n now <= validUntil\n );\n};\n\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const issuedAtTime = function (token: string): number | null {\n const claims: Claims = decode(token).claims;\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n return claims['iat'] as number;\n }\n return null;\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isValidFormat = function (token: string): boolean {\n const decoded = decode(token),\n claims = decoded.claims;\n\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\n};\n\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n */\nexport const isAdmin = function (token: string): boolean {\n const claims: Claims = decode(token).claims;\n return typeof claims === 'object' && claims['admin'] === true;\n};\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseSqlErrorCategory,\n Code,\n FirebaseSqlError\n} from '../core/error';\n\n/** @internal */\nexport type Fetch = typeof fetch;\n\n/**\n * Retrieves the fetch implementation to use for a Firebase SQL network request.\n *\n * `globalThis.fetch` is read on every call (rather than captured once when this\n * module is loaded) so that replacing or stubbing the global, for example with\n * `vi.stubGlobal('fetch', ...)` in tests, takes effect regardless of module load\n * order.\n *\n * @returns The current `globalThis.fetch` function.\n * @throws `FirebaseSqlError` if no fetch implementation is available.\n * @internal\n */\nexport function getFetch(): Fetch {\n const fetchImpl: Fetch | undefined = globalThis.fetch;\n if (!fetchImpl) {\n throw new FirebaseSqlError(\n Code.NOT_SUPPORTED,\n 'No Fetch implementation detected in the current environment.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n return fetchImpl;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Checks whether host is a cloud workstation or not.\n * @public\n */\nexport function isCloudWorkstation(url: string): boolean {\n // `isCloudWorkstation` is called without protocol in certain connect*Emulator functions\n // In HTTP request builders, it's called with the protocol.\n // If called with protocol prefix, it's a valid URL, so we extract the hostname\n // If called without, we assume the string is the hostname.\n try {\n const host =\n url.startsWith('http://') || url.startsWith('https://')\n ? new URL(url).hostname\n : url;\n return host.endsWith('.cloudworkstations.dev');\n } catch {\n return false;\n }\n}\n\n/**\n * Makes a fetch request to the given server.\n * Mostly used for forwarding cookies in Firebase Studio.\n * @public\n */\nexport async function pingServer(endpoint: string): Promise<boolean> {\n const result = await fetch(endpoint, {\n credentials: 'include'\n });\n return result.ok;\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SqlServiceSettings } from '../core/settings';\n\n/** @internal */\nexport const PROD_HOST = 'firebasedataconnect.googleapis.com';\n\n/**\n * Builds the resolved PostgREST endpoint URL for a given SQL service configuration.\n * Assumes settings have been validated!\n *\n * @throws TypeError if the hostname + protocol combination is invalid for the URL constructor.\n * @internal\n */\nexport function resolvePostgrestUrl(\n settings: SqlServiceSettings,\n projectId: string\n): string {\n const protocol = settings.sslEnabled === false ? 'http' : 'https';\n const host = settings.host ?? PROD_HOST;\n const url = new URL(`${protocol}://${host}`);\n\n if (settings.port !== undefined) {\n url.port = String(settings.port);\n }\n\n const encodedProjectId = encodeURIComponent(projectId);\n const encodedLocation = encodeURIComponent(settings.location);\n const encodedServiceId = encodeURIComponent(settings.serviceId);\n url.pathname = `/v1/projects/${encodedProjectId}/locations/${encodedLocation}/services/${encodedServiceId}/postgrest`;\n\n return url.toString();\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PostgrestFilterBuilder } from '@supabase/postgrest-js';\n\nimport {\n Code,\n FirebaseSqlError,\n FirebaseSqlErrorCategory\n} from '../../core/error';\nimport type {\n BuilderExecutionTracker,\n CreateBuilderFetch,\n MapPostgrestError,\n SqlClientState\n} from '../../core/state';\nimport type {\n UntypedClientOptions,\n UntypedSchema\n} from '../../core/untypedSchema';\nimport { validateHeaderName } from '../../network/headers';\nimport type {\n Builder,\n CheckMatchingArrayTypes,\n ContainsNull,\n IsValidResultOverride,\n MergePartialResult,\n OperationFailure,\n OperationResult,\n OperationSuccess\n} from '../Builder';\nimport type {\n FilterBuilder,\n FilterOperator,\n FilterOrOptions,\n FilterTextSearchOptions,\n NarrowResultColumn\n} from '../FilterBuilder';\nimport type {\n InvalidMethodError,\n TransformBuilder,\n TransformExplainOptions,\n TransformLimitOptions,\n TransformOrderOptions,\n TransformRangeOptions\n} from '../TransformBuilder';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type AnyPostgrestFilterBuilder =\n | PostgrestFilterBuilder<any, any, any, any, any>\n | PostgrestFilterBuilder<\n UntypedClientOptions,\n UntypedSchema,\n never,\n any,\n any,\n any,\n any,\n any\n >;\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nexport class FilterBuilderImpl<T, Method = unknown> implements FilterBuilder<\n T,\n Method,\n false\n> {\n private readonly _delegate: AnyPostgrestFilterBuilder;\n private readonly _state: Readonly<SqlClientState>;\n private readonly _createFetch: CreateBuilderFetch;\n private readonly _mapError: MapPostgrestError;\n private _shouldThrowOnError = false;\n\n constructor(\n delegate: AnyPostgrestFilterBuilder,\n state: Readonly<SqlClientState>,\n createFetch: CreateBuilderFetch,\n mapError: MapPostgrestError\n ) {\n this._delegate = delegate;\n this._state = state;\n this._createFetch = createFetch;\n this._mapError = mapError;\n }\n\n throwOnError(): FilterBuilder<T, Method, true> {\n // Keep _delegate in its default shouldThrowOnError = false mode so `await this._delegate`\n // always resolves with HTTP status/statusText intact instead of throwing a PostgrestError\n // that discards them, allowing _execute() to map all errors to FirebaseSqlError first.\n this._shouldThrowOnError = true;\n return this as unknown as FilterBuilder<T, Method, true>;\n }\n\n stripNulls(): this {\n // Delegate without catching so synchronous validation errors (e.g. `.csv().stripNulls()`)\n // propagate unwrapped as raw Error instances matching @supabase/postgrest-js.\n // `void` is used across synchronous builder mutations because PostgrestFilterBuilder is a lazy\n // PromiseLike that only executes when `.then()` is invoked, satisfying no-floating-promises.\n void this._delegate.stripNulls();\n return this;\n }\n\n setHeader(name: string, value: string): this {\n const headerName = validateHeaderName(name);\n void this._delegate.setHeader(headerName, value);\n return this;\n }\n\n retry(enabled: boolean): this {\n void this._delegate.retry(enabled);\n return this;\n }\n\n returns<NewResult>(): TransformBuilder<\n CheckMatchingArrayTypes<T, NewResult>,\n Method,\n false\n > {\n void this._delegate.returns();\n return this as unknown as TransformBuilder<\n CheckMatchingArrayTypes<T, NewResult>,\n Method,\n false\n >;\n }\n\n overrideTypes<\n NewResult,\n Options extends {\n merge?: boolean | undefined;\n } = {\n merge: true;\n }\n >(): Builder<\n IsValidResultOverride<T, NewResult, false, false> extends true\n ? ContainsNull<T> extends true\n ? MergePartialResult<NewResult, NonNullable<T>, Options> | null\n : MergePartialResult<NewResult, T, Options>\n : CheckMatchingArrayTypes<T, NewResult>,\n false\n > {\n void this._delegate.overrideTypes();\n return this as unknown as Builder<\n IsValidResultOverride<T, NewResult, false, false> extends true\n ? ContainsNull<T> extends true\n ? MergePartialResult<NewResult, NonNullable<T>, Options> | null\n : MergePartialResult<NewResult, T, Options>\n : CheckMatchingArrayTypes<T, NewResult>,\n false\n >;\n }\n\n select(\n columns?: string | undefined\n ): FilterBuilder<\n Method extends 'RPC'\n ? unknown extends T\n ? T\n : T extends readonly unknown[]\n ? Array<Record<string, unknown>>\n : Record<string, unknown>\n : Array<Record<string, unknown>>,\n Method,\n false\n > {\n void this._delegate.select(columns);\n return this as unknown as FilterBuilder<\n Method extends 'RPC'\n ? unknown extends T\n ? T\n : T extends readonly unknown[]\n ? Array<Record<string, unknown>>\n : Record<string, unknown>\n : Array<Record<string, unknown>>,\n Method,\n false\n >;\n }\n\n order(\n column: string,\n options?: Readonly<TransformOrderOptions> | undefined\n ): this {\n void this._delegate.order(column, options);\n return this;\n }\n\n limit(\n rows: number,\n options?: Readonly<TransformLimitOptions> | undefined\n ): this {\n void this._delegate.limit(rows, options);\n return this;\n }\n\n range(\n from: number,\n to: number,\n options?: Readonly<TransformRangeOptions> | undefined\n ): this {\n void this._delegate.range(from, to, options);\n return this;\n }\n\n abortSignal(signal: AbortSignal): this {\n void this._delegate.abortSignal(signal);\n return this;\n }\n\n single<\n ResultOne = unknown extends T\n ? Record<string, unknown>\n : T extends ReadonlyArray<infer R>\n ? R\n : never\n >(): Builder<ResultOne, false> {\n void this._delegate.single();\n return this as unknown as Builder<ResultOne, false>;\n }\n\n maybeSingle<\n ResultOne = unknown extends T\n ? Record<string, unknown>\n : T extends ReadonlyArray<infer R>\n ? R\n : never\n >(): Builder<ResultOne | null, false> {\n void this._delegate.maybeSingle();\n return this as unknown as Builder<ResultOne | null, false>;\n }\n\n csv(): Builder<string, false> {\n void this._delegate.csv();\n return this as unknown as Builder<string, false>;\n }\n\n geojson(): Builder<Record<string, unknown>, false> {\n void this._delegate.geojson();\n return this as unknown as Builder<Record<string, unknown>, false>;\n }\n\n explain(\n options?: Readonly<TransformExplainOptions> | undefined\n ): Builder<Array<Record<string, unknown>>, false> | Builder<string, false> {\n void this._delegate.explain(options);\n return this as unknown as\n Builder<Array<Record<string, unknown>>, false> | Builder<string, false>;\n }\n\n rollback(): this {\n void this._delegate.rollback();\n return this;\n }\n\n maxAffected(\n rows: number\n ): Method extends 'PATCH' | 'DELETE' | 'RPC'\n ? this\n : InvalidMethodError<'maxAffected method only available on update or delete'> {\n void this._delegate.maxAffected(rows);\n return this as unknown as Method extends 'PATCH' | 'DELETE' | 'RPC'\n ? this\n : InvalidMethodError<'maxAffected method only available on update or delete'>;\n }\n\n eq(column: string, value: NonNullable<unknown>): this {\n void this._delegate.eq(column, value);\n return this;\n }\n\n neq(column: string, value: unknown): this {\n void this._delegate.neq(column, value);\n return this;\n }\n\n gt(column: string, value: unknown): this {\n void this._delegate.gt(column, value);\n return this;\n }\n\n gte(column: string, value: unknown): this {\n void this._delegate.gte(column, value);\n return this;\n }\n\n lt(column: string, value: unknown): this {\n void this._delegate.lt(column, value);\n return this;\n }\n\n lte(column: string, value: unknown): this {\n void this._delegate.lte(column, value);\n return this;\n }\n\n like(column: string, pattern: string): this {\n void this._delegate.like(column, pattern);\n return this;\n }\n\n likeAllOf(column: string, patterns: readonly string[]): this {\n void this._delegate.likeAllOf(column, patterns);\n return this;\n }\n\n likeAnyOf(column: string, patterns: readonly string[]): this {\n void this._delegate.likeAnyOf(column, patterns);\n return this;\n }\n\n ilike(column: string, pattern: string): this {\n void this._delegate.ilike(column, pattern);\n return this;\n }\n\n ilikeAllOf(column: string, patterns: readonly string[]): this {\n void this._delegate.ilikeAllOf(column, patterns);\n return this;\n }\n\n ilikeAnyOf(column: string, patterns: readonly string[]): this {\n void this._delegate.ilikeAnyOf(column, patterns);\n return this;\n }\n\n regexMatch(column: string, pattern: string): this {\n void this._delegate.regexMatch(column, pattern);\n return this;\n }\n\n regexIMatch(column: string, pattern: string): this {\n void this._delegate.regexIMatch(column, pattern);\n return this;\n }\n\n is(column: string, value: boolean | null): this {\n void this._delegate.is(column, value);\n return this;\n }\n\n isDistinct(column: string, value: unknown): this {\n void this._delegate.isDistinct(column, value);\n return this;\n }\n\n in(column: string, values: readonly unknown[]): this {\n void this._delegate.in(column, values);\n return this;\n }\n\n notIn(column: string, values: readonly unknown[]): this {\n void this._delegate.notIn(column, values);\n return this;\n }\n\n contains<\n Value extends object & {\n readonly [K in keyof Value]: unknown;\n } & {\n readonly [Symbol.iterator]?: never;\n } = Record<string, unknown>\n >(column: string, value: string | readonly unknown[] | Value): this {\n void this._delegate.contains(\n column,\n value as string | readonly unknown[] | Record<string, unknown>\n );\n return this;\n }\n\n containedBy<\n Value extends object & {\n readonly [K in keyof Value]: unknown;\n } & {\n readonly [Symbol.iterator]?: never;\n } = Record<string, unknown>\n >(column: string, value: string | readonly unknown[] | Value): this {\n void this._delegate.containedBy(\n column,\n value as string | readonly unknown[] | Record<string, unknown>\n );\n return this;\n }\n\n rangeGt(column: string, range: string): this {\n void this._delegate.rangeGt(column, range);\n return this;\n }\n\n rangeGte(column: string, range: string): this {\n void this._delegate.rangeGte(column, range);\n return this;\n }\n\n rangeLt(column: string, range: string): this {\n void this._delegate.rangeLt(column, range);\n return this;\n }\n\n rangeLte(column: string, range: string): this {\n void this._delegate.rangeLte(column, range);\n return this;\n }\n\n rangeAdjacent(column: string, range: string): this {\n void this._delegate.rangeAdjacent(column, range);\n return this;\n }\n\n overlaps(column: string, value: string | readonly unknown[]): this {\n void this._delegate.overlaps(column, value);\n return this;\n }\n\n textSearch(\n column: string,\n query: string,\n options?: Readonly<FilterTextSearchOptions> | undefined\n ): this {\n void this._delegate.textSearch(column, query, options);\n return this;\n }\n\n match<\n Query extends object & {\n readonly [K in keyof Query]: unknown;\n } & {\n readonly [Symbol.iterator]?: never;\n } = Record<string, unknown>\n >(query: Query): this {\n void this._delegate.match(query as Record<string, unknown>);\n return this;\n }\n\n not<ColumnName extends string>(\n column: ColumnName,\n operator: 'is',\n value: null\n ): FilterBuilder<NarrowResultColumn<T, ColumnName>, Method, false> & this;\n not(\n column: string,\n operator: FilterOperator | (string & {}),\n value: unknown\n ): this;\n not<ColumnName extends string>(\n column: ColumnName,\n operator: FilterOperator | (string & {}),\n value: unknown\n ):\n | (FilterBuilder<NarrowResultColumn<T, ColumnName>, Method, false> & this)\n | this {\n void this._delegate.not(column, operator, value);\n return this as unknown as FilterBuilder<\n NarrowResultColumn<T, ColumnName>,\n Method,\n false\n > &\n this;\n }\n\n or(filters: string, options?: Readonly<FilterOrOptions> | undefined): this {\n void this._delegate.or(filters, options);\n return this;\n }\n\n filter(\n column: string,\n operator: `${'' | 'not.'}${FilterOperator}` | (string & {}),\n value: unknown\n ): this {\n void this._delegate.filter(column, operator, value);\n return this;\n }\n\n then<TResult1 = OperationResult<T>, TResult2 = never>(\n onfulfilled?:\n | ((value: OperationResult<T>) => TResult1 | PromiseLike<TResult1>)\n | null\n | undefined,\n onrejected?:\n ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined\n ): PromiseLike<TResult1 | TResult2> {\n const result = this._execute();\n return onfulfilled || onrejected\n ? result.then(onfulfilled, onrejected)\n : (result as PromiseLike<TResult1 | TResult2>);\n }\n\n private _fail(\n error: FirebaseSqlError,\n status: number,\n statusText: string\n ): OperationResult<T> {\n if (this._shouldThrowOnError) {\n throw error;\n }\n const failure: OperationFailure = {\n success: false,\n error,\n data: null,\n count: null,\n status,\n statusText\n };\n return failure;\n }\n\n private _execute(): PromiseLike<OperationResult<T>> {\n // Bind a fresh per-execution tracker synchronously before invoking `this._delegate.then(...)`.\n // PostgrestFilterBuilder snapshots `this.fetch` synchronously on entry before yielding microtasks.\n // Dynamic per-execution binding ensures concurrent executions of the same builder instance\n // (e.g. `Promise.all([query, query])`) each receive an isolated `BuilderExecutionTracker`\n // closure, preventing cross-talk between concurrent error/success attributions.\n const tracker: BuilderExecutionTracker = { clientError: null };\n Reflect.set(\n this._delegate,\n 'fetch',\n this._createFetch(this._state, tracker)\n );\n try {\n return this._delegate.then(raw => {\n // Re-check state.active and tracker.clientError after _delegate settles in case terminate()\n // was called in-flight or the transport recorded a pre-flight/token error and aborted fetchWithRetry.\n if (this._state.active === null) {\n return this._fail(\n new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'FirebaseSql instance has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n ),\n 0,\n ''\n );\n }\n\n if (tracker.clientError !== null) {\n return this._fail(tracker.clientError, 0, '');\n }\n\n // @supabase/postgrest-js sets `success: error === null` after `JSON.parse(body)`,\n // so non-2xx responses with a `\"null\"` JSON body arrive with `raw.success === true`\n // and `raw.error === null` (whereas empty `404` rewrites normalize status to `200`/`204`).\n if (\n !raw.success ||\n raw.error !== null ||\n raw.status < 200 ||\n raw.status >= 300\n ) {\n return this._fail(\n this._mapError(raw.error, raw.status, raw.statusText),\n raw.status,\n raw.statusText\n );\n }\n\n const success: OperationSuccess<T> = {\n success: true,\n error: null,\n data: raw.data as T,\n count: raw.count,\n status: raw.status,\n statusText: raw.statusText\n };\n return success;\n });\n } finally {\n Reflect.set(this._delegate, 'fetch', undefined);\n }\n }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PostgrestQueryBuilder } from '@supabase/postgrest-js';\n\nimport type {\n CreateBuilderFetch,\n MapPostgrestError,\n SqlClientState\n} from '../../core/state';\nimport type {\n UntypedClientOptions,\n UntypedSchema,\n UntypedTable\n} from '../../core/untypedSchema';\nimport type { FilterBuilder } from '../FilterBuilder';\nimport type {\n NonIterable,\n QueryBuilder,\n QueryDeleteOptions,\n QueryInsertOptions,\n QuerySelectOptions,\n QueryUpdateOptions,\n QueryUpsertOptions\n} from '../QueryBuilder';\n\nimport {\n type AnyPostgrestFilterBuilder,\n FilterBuilderImpl\n} from './FilterBuilderImpl';\n\nexport class QueryBuilderImpl implements QueryBuilder {\n private readonly _delegate: PostgrestQueryBuilder<\n UntypedClientOptions,\n UntypedSchema,\n UntypedTable\n >;\n private readonly _state: Readonly<SqlClientState>;\n private readonly _createFetch: CreateBuilderFetch;\n private readonly _mapError: MapPostgrestError;\n\n constructor(\n delegate: PostgrestQueryBuilder<\n UntypedClientOptions,\n UntypedSchema,\n UntypedTable\n >,\n state: Readonly<SqlClientState>,\n createFetch: CreateBuilderFetch,\n mapError: MapPostgrestError\n ) {\n this._delegate = delegate;\n this._state = state;\n this._createFetch = createFetch;\n this._mapError = mapError;\n }\n\n private _wrap<T, Method>(\n delegate: AnyPostgrestFilterBuilder\n ): FilterBuilder<T, Method> {\n return new FilterBuilderImpl<T, Method>(\n delegate,\n this._state,\n this._createFetch,\n this._mapError\n );\n }\n\n select(\n columns?: string | undefined,\n options?: Readonly<QuerySelectOptions> | undefined\n ): FilterBuilder<Array<Record<string, unknown>>, 'GET'> {\n return this._wrap(this._delegate.select(columns, options));\n }\n\n insert<\n Row extends NonIterable<\n object & {\n readonly [K in keyof Row]: unknown;\n }\n > = Record<string, unknown>\n >(\n values: Row | readonly Row[],\n options?: Readonly<QueryInsertOptions> | undefined\n ): FilterBuilder<null, 'POST'> {\n return this._wrap(\n this._delegate.insert(\n values as Record<string, unknown> | Array<Record<string, unknown>>,\n options\n )\n );\n }\n\n upsert<\n Row extends NonIterable<\n object & {\n readonly [K in keyof Row]: unknown;\n }\n > = Record<string, unknown>\n >(\n values: Row | readonly Row[],\n options?: Readonly<QueryUpsertOptions> | undefined\n ): FilterBuilder<null, 'POST'> {\n return this._wrap(\n this._delegate.upsert(\n values as Record<string, unknown> | Array<Record<string, unknown>>,\n options\n )\n );\n }\n\n update<\n Row extends NonIterable<\n object & {\n readonly [K in keyof Row]: unknown;\n }\n > = Record<string, unknown>\n >(\n values: Row,\n options?: Readonly<QueryUpdateOptions> | undefined\n ): FilterBuilder<null, 'PATCH'> {\n return this._wrap(\n this._delegate.update(values as Record<string, unknown>, options)\n );\n }\n\n delete(\n options?: Readonly<QueryDeleteOptions> | undefined\n ): FilterBuilder<null, 'DELETE'> {\n return this._wrap(this._delegate.delete(options));\n }\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FirebaseApp,\n getApp,\n _getProvider,\n _removeServiceInstance\n} from '@firebase/app';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\nimport { PostgrestClient } from '@supabase/postgrest-js';\n\nimport {\n Code,\n FirebaseSqlError,\n FirebaseSqlErrorCategory\n} from '../core/error';\nimport { mapPostgrestFailureToFirebaseSqlError } from '../core/errorMapper';\nimport {\n SqlServiceSettings,\n validateSqlServiceSettings\n} from '../core/settings';\nimport type { SqlClientState } from '../core/state';\nimport { AppCheckProvider } from '../core/tokenProviders/AppCheckTokenProvider';\nimport { FirebaseAuthProvider } from '../core/tokenProviders/FirebaseAuthTokenProvider';\nimport type {\n UntypedClientOptions,\n UntypedDatabase,\n UntypedSchema\n} from '../core/untypedSchema';\nimport { logDebug } from '../logger';\nimport { createBuilderFetch } from '../network/transport';\nimport { FIREBASE_SQL_COMPONENT_NAME } from '../util/constants';\nimport { resolvePostgrestUrl } from '../util/url';\n\nimport type { FilterBuilder } from './FilterBuilder';\nimport { FilterBuilderImpl } from './impl/FilterBuilderImpl';\nimport { QueryBuilderImpl } from './impl/QueryBuilderImpl';\nimport type { QueryBuilder, QueryCountStrategy } from './QueryBuilder';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n [FIREBASE_SQL_COMPONENT_NAME]: FirebaseSql;\n }\n}\n\n/**\n * HTTP method and row-counting options for {@link FirebaseSql.rpc}.\n *\n * @example\n * Configure read-only `GET` execution with exact row counting:\n * ```ts\n * import type { FirebaseSqlRpcOptions } from 'firebase/sql';\n *\n * const rpcOptions: FirebaseSqlRpcOptions = {\n * get: true,\n * count: 'exact'\n * };\n * ```\n *\n * @public\n */\nexport interface FirebaseSqlRpcOptions {\n /**\n * Sends an HTTP `HEAD` request to retrieve response headers and `count` without a response body (`data` resolves to `null`).\n *\n * @remarks\n * Defaults to `false`. Takes precedence over `get` when both are `true`.\n *\n * Parameters are serialized as URL query parameters unless any parameter value is a non-null\n * object (including plain objects, `Date`, `Map`, or an array containing an object), in which\n * case the client falls back to `POST` with `Prefer: return=minimal` because object arguments\n * cannot be encoded as PostgREST URL parameters. That `POST` fallback executes the function in a\n * read-write transaction on PostgREST and disables automatic `GET`/`HEAD` retries.\n *\n * Because `HEAD` responses carry no body, an HTTP `404` (for example, an unknown function) is\n * normalized to `status: 204` with `success: true` and `count: null`, and other `HEAD` failures\n * carry no PostgREST error code; treat `count === null` as a failed count when `count` was requested.\n */\n head?: boolean | undefined;\n\n /**\n * Calls the PostgreSQL function via HTTP `GET` with arguments encoded in the URL query string.\n *\n * @remarks\n * Defaults to `false`.\n *\n * When to use: invoking `IMMUTABLE` or `STABLE` read-only PostgreSQL functions with primitive or\n * flat-array arguments so automatic transient-error retries (`retry(true)`) apply.\n *\n * Do not use for functions that perform `INSERT`, `UPDATE`, or `DELETE` side effects or accept\n * nested JSON object parameters; omit `get` (or pass `false`) so arguments are sent in a `POST`\n * JSON body. Arguments with `undefined` values are omitted from the query string, top-level\n * arrays are formatted unquoted as `{a,b}` (`{value.join(',')}`), and all other non-array values\n * are stringified via `String(value)` (pass ISO strings via `date.toISOString()`, never raw `Date`).\n */\n get?: boolean | undefined;\n\n /**\n * Row-counting strategy sent via the `Prefer: count=<strategy>` header for set-returning (`RETURNS SETOF` / `RETURNS TABLE`) functions.\n *\n * @remarks\n * Defaults to `undefined`. Only the exact lowercase literals `'exact'` (full `COUNT(*)` scan),\n * `'planned'` (PostgreSQL planner estimate), and `'estimated'` (exact for small result sets,\n * planner estimate above PostgREST's threshold) populate `result.count` on\n * {@link OperationSuccess}; other strings are sent verbatim in `Prefer` while `result.count`\n * remains `null`.\n */\n count?: QueryCountStrategy | undefined;\n}\n\n/**\n * Service client bound to a `FirebaseApp` and a specific Firebase SQL PostgREST endpoint.\n *\n * @remarks\n * Do not instantiate directly: obtain instances via {@link (getSql:1) | getSql()}, which validates\n * settings and deduplicates clients per `(app, resolvedEndpoint, schemaName)`. `FirebaseSql` does\n * not expose a `.schema(name)` method—configure `schemaName` in {@link SqlServiceSettings} when\n * calling {@link (getSql:1) | getSql()} (or clone `sql.settings` via {@link copySqlServiceSettings}\n * to create a client for another schema). See {@link terminate} for shutting down a client and\n * evicting it from the app registry.\n *\n * Automatically attaches Firebase Authentication ID tokens (`x-firebase-auth-token`, with a single\n * automatic token refresh and retry on HTTP 401 when the authenticated UID is unchanged) and\n * Firebase App Check tokens (`x-firebase-appcheck`) when those services are registered on `app`\n * (including static `authIdToken` and `appCheckToken` credentials configured on a `FirebaseServerApp`\n * via `initializeServerApp`). If App Check cannot obtain a real token, it resolves with a\n * placeholder dummy token sent in `x-firebase-appcheck` (which the backend rejects when App Check\n * is enforced; `x-firebase-appcheck` is omitted only if the App Check provider itself rejects).\n * Auth `getToken()` rejections fail the request. When Auth or App Check has not finished\n * initializing yet, the SDK waits one macrotask (`setTimeout(..., 0)`) for initialization and\n * attaches the token if available; otherwise the request is sent without that token.\n *\n * @example\n * Query a table and invoke a stored function using a `FirebaseSql` client:\n * ```ts\n * import { getSql, type FirebaseSql } from 'firebase/sql';\n *\n * const sql: FirebaseSql = getSql({\n * serviceId: 'events-db',\n * location: 'us-central1'\n * });\n *\n * const venuesRes = await sql.from('venues').select('id, slug, name, city');\n * const seatsRes = await sql\n * .rpc('remaining_seats', { target_event_id: '6ba7b810-9dad-11d1-80b4-00c04fd430c8' }, { get: true })\n * .returns<number>();\n *\n * if (venuesRes.success && seatsRes.success) {\n * console.log(venuesRes.data.length, seatsRes.data);\n * }\n * ```\n *\n * @public\n */\nexport class FirebaseSql {\n /** @internal */\n readonly _postgrestUrl: string;\n\n /** @internal */\n private readonly _state: SqlClientState;\n\n private readonly _terminationController = new AbortController();\n\n private readonly _postgrestClient: PostgrestClient<\n UntypedDatabase,\n UntypedClientOptions,\n string,\n UntypedSchema\n >;\n\n /**\n * Should only be called by {@link (getSql:1) | getSql()}, after validating inputs.\n * @internal\n */\n constructor(\n /** The bound {@link @firebase/app#FirebaseApp} instance. */\n readonly app: FirebaseApp,\n /** Deeply frozen copy of the validated {@link SqlServiceSettings} used by this client. */\n readonly settings: SqlServiceSettings,\n /** @internal */\n readonly _instanceIdentifier: string,\n /** @internal */\n authInternalProvider: Provider<FirebaseAuthInternalName>,\n /** @internal */\n appCheckInternalProvider: Provider<AppCheckInternalComponentName>\n ) {\n this._postgrestUrl = resolvePostgrestUrl(\n this.settings,\n app.options.projectId!\n );\n\n this._state = {\n active: {\n appId: app.options.appId,\n authTokenProvider: new FirebaseAuthProvider(app, authInternalProvider),\n appCheckTokenProvider: new AppCheckProvider(\n app,\n appCheckInternalProvider\n )\n },\n terminationSignal: this._terminationController.signal\n };\n\n // PostgrestClient is deliberately instantiated without a static `fetch` option.\n // Instead, `createBuilderFetch` is passed down to query/filter builders, which\n // bind an execution-isolated `fetch` dynamically on each query execution to ensure\n // concurrent executions of the same builder instance do not share a single\n // `BuilderExecutionTracker` closure.\n this._postgrestClient = new PostgrestClient(this._postgrestUrl, {\n headers: this.settings.headers,\n schema: this.settings.schemaName\n });\n }\n\n /** @internal */\n _delete(): Promise<void> {\n if (this._state.active !== null) {\n const active = this._state.active;\n this._state.active = null;\n this._terminationController.abort(\n new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'The Firebase SQL client has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n )\n );\n active.appCheckTokenProvider.terminate();\n active.authTokenProvider.terminate();\n _removeServiceInstance(\n this.app,\n FIREBASE_SQL_COMPONENT_NAME,\n this._instanceIdentifier\n );\n }\n return Promise.resolve();\n }\n\n // Encode table and RPC names so `/`, `?`, `#`, and dot-segments cannot traverse out of\n // `/postgrest` or inject query parameters on the shared `firebasedataconnect.googleapis.com`\n // origin (deviating from `PostgrestClient`'s raw URL interpolation while leaving blank\n // `from('')` inputs untouched so `@supabase/postgrest-js`'s raw `Error` still propagates).\n private _encodeResourceSegment(\n segment: string,\n preserveBlank: boolean\n ): string {\n if (segment === '.' || segment === '..') {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n `Invalid resource name \"${segment}\".`,\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n if (\n typeof segment !== 'string' ||\n segment.length === 0 ||\n (preserveBlank && segment.trim() === '')\n ) {\n return segment;\n }\n return encodeURIComponent(segment);\n }\n\n /**\n * Creates a reusable {@link QueryBuilder} scoped to a PostgreSQL table, view, or materialized view.\n *\n * @remarks\n * When to use: starting any `SELECT`, `INSERT`, `UPSERT`, `UPDATE`, or `DELETE` chain against a\n * relation in the client's configured PostgreSQL schema (`settings.schemaName`, or the server\n * default schema). See {@link QueryBuilder} for available SQL verbs.\n *\n * Do not use for calling stored functions or procedures (use {@link FirebaseSql.rpc} instead),\n * passing `<Row>` type generics (`sql.from<EventRow>('events')` is not supported; apply\n * {@link Builder.returns} or {@link Builder.overrideTypes} later in the chain), or\n * schema-qualifying `table` as `'analytics.events'` (`table` is URI-encoded as a single path\n * segment; configure `schemaName: 'analytics'` in {@link (getSql:1) | getSql()} instead).\n *\n * Preconditions: this `FirebaseSql` instance must not have been terminated via {@link terminate}\n * or `deleteApp()`.\n *\n * Behavior and side effects: synchronous and performs no network I/O. The returned\n * {@link QueryBuilder} clones URL and header state on each verb call (`select`, `insert`, etc.),\n * so a single `sql.from('events')` reference can be safely stored and reused across concurrent\n * queries. Special URI characters (`/`, `?`, `#`) in `table` are percent-encoded to prevent path\n * traversal.\n *\n * @param table - Non-empty PostgreSQL table or view name (must not be `'.'`, `'..'`, or blank/whitespace).\n * @returns A stateless {@link QueryBuilder} for starting SQL verb chains on `table`.\n *\n * @throws {@link FirebaseSqlError} (`not-initialized`, category `'sql-client'`)\n * Thrown synchronously when called after {@link terminate} or `deleteApp()`. Obtain a fresh\n * client via {@link (getSql:1) | getSql()}.\n * @throws {@link FirebaseSqlError} (`invalid-argument`, category `'sql-client'`)\n * Thrown synchronously when `table` is `'.'` or `'..'`. Pass a valid PostgreSQL relation identifier.\n * @throws `Error`\n * Thrown synchronously when `table` is empty (`''`) or whitespace-only. Provide a non-blank table\n * or view name.\n *\n * @example\n * Reuse a table `QueryBuilder` across concurrent `Promise.all` reads:\n * ```ts\n * const eventsTable = sql.from('events');\n *\n * const [featuredRes, countRes] = await Promise.all([\n * eventsTable.select('id, code, title').eq('is_featured', true),\n * eventsTable.select('*', { head: true, count: 'exact' }).eq('status', 'published')\n * ]);\n *\n * if (featuredRes.success && countRes.success) {\n * console.log(featuredRes.data.length, countRes.count);\n * }\n * ```\n *\n * @example\n * Perform CRUD operations against a shared table reference:\n * ```ts\n * const registrationsTable = sql.from('registrations');\n *\n * const created = await registrationsTable\n * .insert({\n * event_id: '6ba7b810-9dad-11d1-80b4-00c04fd430c8',\n * user_uid: 'uid_carol',\n * attendee_email: 'carol@example.com'\n * })\n * .select('id')\n * .single()\n * .returns<{ id: string }>();\n *\n * if (created.success) {\n * const checkInRes = await registrationsTable\n * .update({ checked_in_at: '2026-10-15T15:55:00Z' })\n * .eq('id', created.data.id);\n * if (!checkInRes.success) {\n * console.error('Check-in update failed:', checkInRes.error.message);\n * }\n * }\n * ```\n *\n * @public\n */\n from(table: string): QueryBuilder {\n if (this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'FirebaseSql instance has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n const delegate = this._postgrestClient.from(\n this._encodeResourceSegment(table, true)\n );\n return new QueryBuilderImpl(\n delegate,\n this._state,\n createBuilderFetch,\n mapPostgrestFailureToFirebaseSqlError\n );\n }\n\n /**\n * Creates a lazy {@link FilterBuilder} that invokes a PostgreSQL stored function or procedure (`RPC`).\n *\n * @remarks\n * When to use: calling custom server-side SQL or PL/pgSQL functions—including multi-statement\n * transactional workflows, server-side aggregations (`remaining_seats`), or set-returning\n * functions (`RETURNS SETOF` / `RETURNS TABLE` such as `list_events_by_city`) whose output rows\n * need further PostgREST filtering, ordering, or pagination.\n *\n * Do not use for standard single-table CRUD operations; prefer {@link FirebaseSql.from}.\n *\n * Preconditions: this `FirebaseSql` instance must not have been terminated via {@link terminate}\n * or `deleteApp()`. `Args` must be a plain non-iterable key-value object matching the PostgreSQL\n * function's named parameter names (arrays cannot be passed as the top-level `params` argument;\n * wrap array parameters inside an object key, such as `{ target_tags: ['firebase', 'ai'] }`).\n *\n * Behavior and side effects: builder progression is `FirebaseSql -> FilterBuilder<unknown, 'RPC', false>`.\n * No HTTP request is sent until the returned builder is `await`ed or `.then()` is invoked. Each\n * `await` or `.then()` call sends a new HTTP request (results are not cached); awaiting the same\n * `rpc()` builder twice executes the function twice and duplicates side effects for write\n * functions, so await each mutation RPC builder at most once.\n *\n * Defaults to `POST /rpc/{fn}` with JSON body `params ?? {}` (omit `params` for zero-argument\n * functions: `sql.rpc('fn')`). Set `options.get: true` in {@link FirebaseSqlRpcOptions} for\n * read-only functions to use `GET` with query parameters (enabling automatic transient-error\n * retries). Functions declared `RETURNS void` resolve with HTTP `204` and `data: null`.\n *\n * Untyped `data` defaults to `unknown`. `<Args>` types input `params` only—chain\n * {@link TransformBuilder.returns | .returns()} (or {@link Builder.returns} after `.single()` /\n * `.maybeSingle()`) to assign a full static return type to `result.data`, or chain\n * {@link Builder.overrideTypes | .overrideTypes()} when partially refining fields on a typed row.\n *\n * For set-returning functions (`RETURNS SETOF` / `RETURNS TABLE`), you can chain\n * {@link FilterBuilder} filters (`.eq()`, `.overlaps()`), {@link TransformBuilder} modifiers\n * (`.select()`, `.order()`, `.limit()`, `.single()`, `.maxAffected()`), and {@link Builder}\n * modifiers before awaiting.\n *\n * Error handling: resolves to {@link OperationFailure} (`{ success: false, error: FirebaseSqlError }`)\n * on HTTP, PostgREST (`'sql-postgrest'`, such as `'PGRST202'` when function signature or parameter\n * names do not match), gateway (`'sql-platform'`), or network (`'sql-client'`) failures. Chain\n * {@link Builder.throwOnError} to reject with {@link FirebaseSqlError} instead.\n *\n * @typeParam Args - Non-iterable object mapping PostgreSQL function parameter names to values.\n * @param fn - PostgreSQL function name in the active schema (must not be `'.'` or `'..'`; special URI characters are percent-encoded).\n * @param params - Named arguments object passed to the PostgreSQL function. In `POST` mode, serialized with `JSON.stringify` (`bigint` values serialize via `.toString()`, `undefined` properties and functions are omitted, `NaN`/`Infinity` serialize as `null`, `Date` serializes to ISO-8601, and circular references resolve at `await` time as `res.status === 0`, `res.error.category === 'sql-client'`, `res.error.code === 'other'`).\n * @param options - HTTP verb (`get`, `head`) and `count` configuration. See {@link FirebaseSqlRpcOptions}.\n * @returns A lazy {@link FilterBuilder} with untyped result `unknown` and method tag `'RPC'`.\n *\n * @throws {@link FirebaseSqlError} (`not-initialized`, category `'sql-client'`)\n * Thrown synchronously when called after {@link terminate} or `deleteApp()`. Re-initialize a\n * client with {@link (getSql:1) | getSql()}.\n * @throws {@link FirebaseSqlError} (`invalid-argument`, category `'sql-client'`)\n * Thrown synchronously when `fn` is `'.'` or `'..'`. Pass a valid PostgreSQL function name.\n *\n * @example\n * Full RPC verb chain on a set-returning function (`RETURNS SETOF events`):\n * ```ts\n * interface EventRow {\n * id: string;\n * venue_id: string | null;\n * code: string;\n * title: string;\n * status: 'draft' | 'published' | 'cancelled' | 'archived';\n * is_featured: boolean;\n * ticket_price: number;\n * tags: string[];\n * metadata: Record<string, unknown>;\n * schedule: string;\n * created_at: string;\n * }\n *\n * const cityEvents = await sql\n * .rpc('list_events_by_city', { target_city: 'Seattle' }, { get: true, count: 'exact' })\n * .eq('status', 'published')\n * .overlaps('tags', ['firebase', 'postgres'])\n * .order('ticket_price', { ascending: true })\n * .limit(10)\n * .returns<EventRow[]>();\n *\n * if (!cityEvents.success) {\n * console.error(cityEvents.error.code, cityEvents.error.hint);\n * } else {\n * console.log(`Showing ${cityEvents.data.length} of ${cityEvents.count} events`);\n * }\n * ```\n *\n * @example\n * Scalar read-only RPC returning a primitive value (`{ get: true }`):\n * ```ts\n * const seatsRes = await sql\n * .rpc(\n * 'remaining_seats',\n * { target_event_id: '6ba7b810-9dad-11d1-80b4-00c04fd430c8' },\n * { get: true }\n * )\n * .returns<number>();\n *\n * if (seatsRes.success) {\n * console.log('Remaining seats:', seatsRes.data);\n * }\n * ```\n *\n * @example\n * Set-returning RPC sent via default `POST` JSON body with `.throwOnError()`:\n * ```ts\n * const { data } = await sql\n * .rpc('list_events_by_city', { target_city: 'San Francisco' })\n * .select('id, code, title')\n * .returns<Array<{ id: string; code: string; title: string }>>()\n * .throwOnError();\n * ```\n *\n * @example\n * Count-only `HEAD` RPC check (`data` resolves to `null`):\n * ```ts\n * const headRes = await sql.rpc(\n * 'list_events_by_city',\n * { target_city: 'Seattle' },\n * { head: true, count: 'exact' }\n * );\n *\n * if (headRes.success && headRes.count !== null) {\n * console.log('Matching Seattle events:', headRes.count);\n * }\n * ```\n *\n * @public\n */\n rpc<\n Args extends object & {\n readonly [K in keyof Args]: unknown;\n } & {\n readonly [Symbol.iterator]?: never;\n } = Record<string, unknown>\n >(\n fn: string,\n params?: Args | undefined,\n options?: Readonly<FirebaseSqlRpcOptions> | undefined\n ): FilterBuilder<unknown, 'RPC'> {\n if (this._state.active === null) {\n throw new FirebaseSqlError(\n Code.NOT_INITIALIZED,\n 'FirebaseSql instance has been terminated.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n const delegate = this._postgrestClient.rpc(\n this._encodeResourceSegment(fn, false),\n params as Record<string, unknown> | undefined,\n options\n );\n return new FilterBuilderImpl<unknown, 'RPC'>(\n delegate,\n this._state,\n createBuilderFetch,\n mapPostgrestFailureToFirebaseSqlError\n );\n }\n}\n\n/**\n * Returns the cached or newly initialized {@link FirebaseSql} client bound to the default\n * {@link @firebase/app#FirebaseApp} and the specified {@link SqlServiceSettings}.\n *\n * @remarks\n * When to use: standard single-app setups where `initializeApp({ projectId, ... })` has already\n * been called for the default Firebase app.\n *\n * Do not use in multi-app environments targeting a named secondary `FirebaseApp` (pass `app`\n * explicitly via {@link (getSql:2) | getSql(app, settings)}) or when varying `settings.headers` on\n * the same `(serviceId, location, schemaName)` expecting separate clients (cached instances ignore\n * subsequent `settings.headers`; use {@link Builder.setHeader} for per-request headers or call\n * {@link terminate} first).\n *\n * Preconditions: the default `FirebaseApp` must be initialized via `initializeApp(...)` with a\n * non-empty `options.projectId`.\n *\n * Behavior and side effects: synchronous, performs no network I/O, deep-clones and freezes\n * `settings`, and caches the resulting {@link FirebaseSql} instance on the default app keyed by\n * `(resolvedEndpointUrl, schemaName)`. Note that if `settings.host` contains a scheme or path (such\n * as `'http://example.com'`), it does not throw—it resolves to the unintended hostname `'http'` and\n * overwrites the path, so always pass a bare hostname.\n *\n * @param settings - Required service connection settings (`serviceId` and `location` are mandatory). See {@link SqlServiceSettings}.\n * @returns The cached or newly created {@link FirebaseSql} client instance.\n *\n * @throws `FirebaseError` (`app/no-app`)\n * Thrown when no default `FirebaseApp` has been initialized. Call `initializeApp({ projectId: '...' })`\n * before calling `getSql(settings)`.\n * @throws {@link FirebaseSqlError} (`invalid-argument`, category `'sql-client'`)\n * Thrown when `settings` is missing, `serviceId` or `location` is empty, `port` is outside\n * `1..65535` or non-integer, `headers` contains a protected header key, or `app.options.projectId`\n * is missing/empty. Supply non-empty `projectId`, `serviceId`, and `location`, an integer `port` in\n * `1..65535`, and remove disallowed auth/telemetry headers.\n * @throws `TypeError`\n * Thrown synchronously when `settings.host` is rejected by the WHATWG `URL` parser (such as `''`)\n * or, when creating a new client, when `settings.headers` contains an invalid HTTP header name or\n * value (for example, spaces in a header name, CR/LF, or non-Latin-1 characters; cached clients\n * return before `Headers` construction). Note that a scheme or path in `settings.host` is not\n * rejected by `URL` and silently produces a wrong endpoint.\n *\n * @example\n * Initialize Firebase SQL using the default schema:\n * ```ts\n * import { initializeApp } from 'firebase/app';\n * import { getSql } from 'firebase/sql';\n *\n * initializeApp({\n * apiKey: 'YOUR_API_KEY',\n * appId: 'YOUR_APP_ID',\n * projectId: 'my-firebase-project'\n * });\n *\n * const sql = getSql({\n * serviceId: 'events-db',\n * location: 'us-central1'\n * });\n * ```\n *\n * @example\n * Initialize Firebase SQL targeting a non-default schema:\n * ```ts\n * import { getSql } from 'firebase/sql';\n *\n * const analyticsSql = getSql({\n * serviceId: 'events-db',\n * location: 'us-central1',\n * schemaName: 'analytics'\n * });\n * ```\n *\n * @public\n */\nexport function getSql(settings: SqlServiceSettings): FirebaseSql;\n\n/**\n * Returns the cached or newly initialized {@link FirebaseSql} client bound to the given\n * {@link @firebase/app#FirebaseApp} and {@link SqlServiceSettings}.\n *\n * @remarks\n * When to use: binding to a specific `FirebaseApp` instance (including named secondary apps or\n * `FirebaseServerApp` instances created via `initializeServerApp`) or maintaining explicit\n * dependency injection of `app`.\n *\n * Preconditions: `app.options.projectId` must be a non-empty string.\n *\n * Behavior and side effects: synchronous, performs no network I/O, deep-clones and freezes\n * `settings`, and caches the {@link FirebaseSql} instance on `app` keyed by\n * `(resolvedEndpointUrl, schemaName)` (`settings.headers` is excluded from the cache key; use\n * {@link Builder.setHeader} for per-operation headers, or {@link terminate} to evict the cached\n * instance). Note that passing a scheme or path in `settings.host` does not throw and silently\n * produces a wrong endpoint (for example, `'http://example.com'` resolves to hostname `'http'`).\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance whose `projectId`, Auth, and App Check providers will be used.\n * @param settings - Required service connection settings (`serviceId` and `location` are mandatory). See {@link SqlServiceSettings}.\n * @returns The cached or newly created {@link FirebaseSql} client instance for `app`.\n *\n * @throws {@link FirebaseSqlError} (`invalid-argument`, category `'sql-client'`)\n * Thrown when `app` is not an object with an `options` property (note that passing `undefined` as\n * `app` falls back to the default app via `getApp()`, which throws `FirebaseError` `app/no-app` if\n * no default app exists), `app.options.projectId` is missing/empty, `settings`, `serviceId`, or\n * `location` is missing/empty, `port` is not an integer in `1..65535`, or `headers` includes a\n * protected header name.\n * @throws `TypeError`\n * Thrown synchronously when `settings.host` is rejected by the WHATWG `URL` parser (such as `''`)\n * or, when creating a new client, when `settings.headers` contains an invalid HTTP header name or\n * value (for example, spaces in a header name, CR/LF, or non-Latin-1 characters; cached clients\n * return before `Headers` construction).\n *\n * @example\n * Initialize Firebase SQL with an explicit `FirebaseApp` using the default schema:\n * ```ts\n * import { initializeApp } from 'firebase/app';\n * import { getSql } from 'firebase/sql';\n *\n * const app = initializeApp({\n * apiKey: 'YOUR_API_KEY',\n * appId: 'YOUR_APP_ID',\n * projectId: 'my-firebase-project'\n * });\n *\n * const sql = getSql(app, {\n * serviceId: 'events-db',\n * location: 'us-central1'\n * });\n * ```\n *\n * @example\n * Initialize Firebase SQL with an explicit `FirebaseApp` targeting a non-default schema:\n * ```ts\n * import { getApp } from 'firebase/app';\n * import { getSql } from 'firebase/sql';\n *\n * const app = getApp();\n *\n * const analyticsSql = getSql(app, {\n * serviceId: 'events-db',\n * location: 'us-central1',\n * schemaName: 'analytics'\n * });\n * ```\n *\n * @public\n */\nexport function getSql(\n app: FirebaseApp,\n settings: SqlServiceSettings\n): FirebaseSql;\n\nexport function getSql(\n appOrSettings: FirebaseApp | SqlServiceSettings,\n settingsArg?: SqlServiceSettings\n): FirebaseSql {\n let app: FirebaseApp;\n let rawSettings: SqlServiceSettings;\n\n if (settingsArg === undefined) {\n app = getApp();\n rawSettings = appOrSettings as SqlServiceSettings;\n } else {\n if (appOrSettings === undefined) {\n app = getApp();\n } else if (\n !appOrSettings ||\n typeof appOrSettings !== 'object' ||\n !('options' in appOrSettings)\n ) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n 'First argument passed to getSql() must be a FirebaseApp or SqlServiceSettings instance.',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n } else {\n app = appOrSettings;\n }\n rawSettings = settingsArg;\n }\n\n const validatedSettings = validateSqlServiceSettings(rawSettings);\n\n if (\n typeof app.options?.projectId !== 'string' ||\n app.options.projectId.length === 0\n ) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n 'Project ID must be provided in FirebaseApp options. Did you pass in a proper projectId to initializeApp?',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n\n const instanceIdentifier = getInstanceIdentifier(\n validatedSettings,\n app.options.projectId\n );\n const provider = _getProvider(app, FIREBASE_SQL_COMPONENT_NAME);\n\n if (provider.isInitialized(instanceIdentifier)) {\n logDebug(\n 'Re-using cached instance (NOTE: custom headers set on the original FSQL client are RE-USED when that client is re-used from the instance cache. Creating multiple FSQL clients with the same settings and app, but different headers, is NOT supported. Instead, use .setHeaders() while building an operation chain to set custom headers for that specific operation.)'\n );\n return provider.getImmediate({ identifier: instanceIdentifier });\n }\n\n logDebug('Creating new Firebase SQL instance');\n return provider.initialize({\n instanceIdentifier,\n options: validatedSettings\n });\n}\n\n/**\n * Terminates a {@link FirebaseSql} client, aborts any in-flight HTTP requests, cancels pending\n * Auth and App Check initialization subscriptions, and evicts the instance from its `FirebaseApp`\n * component cache.\n *\n * @remarks\n * When to use: tearing down a client during test cleanup, user session isolation, or before\n * re-initializing a client with updated `headers` for the same `(app, serviceId, location, schemaName)`\n * via {@link (getSql:1) | getSql()}.\n *\n * Behavior and side effects: idempotent—calling `terminate(sql)` repeatedly on an\n * already-terminated instance resolves immediately without side effects and will not evict a newer\n * client created afterward via {@link (getSql:1) | getSql()}.\n *\n * After termination, calling `sql.from()` or `sql.rpc()` throws {@link FirebaseSqlError}\n * (`not-initialized`) synchronously. Pre-existing builders created before `terminate(sql)` continue\n * chaining synchronously without throwing, but awaiting them (or any request already in flight)\n * settles with {@link FirebaseSqlError} (`not-initialized`, category `'sql-client'`).\n *\n * @param sql - The {@link FirebaseSql} client instance to terminate.\n * @returns A `Promise` that resolves immediately after the instance is marked terminated, pending initialization subscriptions are cancelled, and the instance is removed from the registry.\n *\n * @example\n * Terminate a client and create a fresh instance:\n * ```ts\n * import { getSql, terminate } from 'firebase/sql';\n *\n * const sql = getSql({ serviceId: 'events-db', location: 'us-central1' });\n * await terminate(sql);\n *\n * // Subsequent getSql() call creates a brand-new active instance\n * const nextSql = getSql({ serviceId: 'events-db', location: 'us-central1' });\n * ```\n *\n * @example\n * Handle `Code.NOT_INITIALIZED` on builders created before termination:\n * ```ts\n * import { Code, getSql, terminate } from 'firebase/sql';\n *\n * const sql = getSql({ serviceId: 'events-db', location: 'us-central1' });\n * const pendingQuery = sql.from('events').select('id, title');\n *\n * await terminate(sql);\n *\n * const res = await pendingQuery;\n * if (!res.success && res.error.code === Code.NOT_INITIALIZED) {\n * console.warn('Client was terminated before query executed.');\n * }\n * ```\n *\n * @public\n */\nexport function terminate(sql: FirebaseSql): Promise<void> {\n return sql._delete();\n}\n\n/**\n * Computes a deterministic JSON instance identifier string.\n * Assumes settings have been validated!\n * @internal\n */\nexport function getInstanceIdentifier(\n settings: SqlServiceSettings,\n projectId: string\n): string {\n const resolvedUrl = resolvePostgrestUrl(settings, projectId);\n return JSON.stringify({\n resolvedUrl,\n schemaName: settings.schemaName\n });\n}\n","/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from '../package.json';\n\nimport { FirebaseSql, getInstanceIdentifier } from './api/FirebaseSql';\nimport { FirebaseSqlErrorCategory, Code, FirebaseSqlError } from './core/error';\nimport { SqlServiceSettings } from './core/settings';\nimport { setSDKVersion } from './core/version';\nimport { FIREBASE_SQL_COMPONENT_NAME } from './util/constants';\n\n/**\n * Registers the `@firebase/sql` service component and SDK version with Firebase App.\n *\n * @param variant - Optional SDK build variant identifier.\n * @internal\n */\nexport function registerSql(variant?: string): void {\n setSDKVersion(SDK_VERSION);\n _registerComponent(\n new Component(\n FIREBASE_SQL_COMPONENT_NAME,\n (container, { instanceIdentifier, options }) => {\n const settings = options as SqlServiceSettings;\n const app = container.getProvider('app').getImmediate()!;\n const authProvider = container.getProvider('auth-internal');\n const appCheckProvider = container.getProvider('app-check-internal');\n if (\n typeof app.options?.projectId !== 'string' ||\n app.options.projectId.length === 0\n ) {\n throw new FirebaseSqlError(\n Code.INVALID_ARGUMENT,\n 'Project ID must be provided in FirebaseApp options. Did you pass in a proper projectId to initializeApp?',\n FirebaseSqlErrorCategory.SQL_CLIENT\n );\n }\n const id =\n instanceIdentifier ??\n getInstanceIdentifier(settings, app.options.projectId);\n return new FirebaseSql(\n app,\n settings,\n id,\n authProvider,\n appCheckProvider\n );\n },\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n registerVersion(name, version, variant);\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * PostgREST-compatible SQL client SDK (`firebase/sql`) for querying PostgreSQL databases\n * hosted on Firebase SQL with automatic Firebase Authentication and App Check integration.\n *\n * @remarks\n * Application import path: install `firebase` and import from `firebase/sql` (do not import\n * `@firebase/sql` directly in application code).\n *\n * Builder state machine and chain order: queries and mutations progress through five stages (the\n * entry client and four lazy TypeScript builder interfaces): (1) {@link FirebaseSql}, the entry client exposing\n * `sql.from(table)` and `sql.rpc(fn, params, options)`; (2) {@link QueryBuilder}, the SQL table\n * verb selector (`select`, `insert`, `upsert`, `update`, `delete`); (3) {@link FilterBuilder}, row\n * filters (`eq`, `in`, `gte`, `contains`, `or`, `not`, and related operators);\n * (4) {@link TransformBuilder}, ordering, pagination, post-mutation `select()`, server preferences\n * (`maxAffected`, `rollback`), cancellation (`abortSignal`), full-type narrowing (`returns`), and\n * cardinality/format modifiers (`single`, `maybeSingle`, `csv`, `geojson`, `explain`); and\n * (5) {@link Builder}, static result-type overrides (`returns`, `overrideTypes`), `stripNulls`,\n * `setHeader`, `retry`, `throwOnError`, and `PromiseLike` execution (`await`).\n *\n * Always apply {@link FilterBuilder} predicates before calling `.returns()`, and apply all\n * {@link FilterBuilder} and {@link TransformBuilder} methods before calling `.single()`,\n * `.maybeSingle()`, `.csv()`, `.geojson()`, `.explain()`, or `.overrideTypes()`, because those\n * methods narrow the static return type to {@link Builder}. Each `await` or `.then()` sends a new\n * HTTP request (results are never cached), so await each mutation builder at most once.\n *\n * Untyped defaults and type narrowing: {@link (getSql:1) | getSql()} and {@link FirebaseSql.from}\n * do not accept `<Database>` or `<Row>` generics, and there is no `sql.schema()` method (pass\n * `schemaName` in {@link SqlServiceSettings} to {@link (getSql:1) | getSql()} instead). Table\n * `select()` defaults `data` to `Array<Record<string, unknown>>`; `insert()`, `upsert()`,\n * `update()`, and `delete()` default `data` to `null` unless `.select()` is chained; and `rpc()`\n * defaults `data` to `unknown` (its `<Args>` generic types input parameters only). Chain\n * `.returns<Row[]>()` (or `.single().returns<Row>()` / `.returns<T>()` on `rpc()`) to assign a full\n * static TypeScript type to `data`, and use `.overrideTypes<PartialRow>()` when partially\n * overriding or refining specific fields on an already-typed builder.\n *\n * Result envelope vs. throwing mode: by default, `await builder` resolves to\n * {@link OperationResult} (`{ success: true, data, count, error: null, status, statusText }` or\n * `{ success: false, data: null, count: null, error: FirebaseSqlError, status, statusText }`) for\n * HTTP, PostgREST, platform, and network failures (note that a `settings.schemaName` containing\n * invalid HTTP header characters rejects with a `TypeError` when setting the profile header).\n * Narrow via `if (!res.success)` or `const { data, error } = await ...; if (error)`—never narrow\n * with `if (!data)` when `data` can legitimately be `null` (such as `.maybeSingle()`, `head: true`,\n * or mutations without `.select()`). Chain {@link Builder.throwOnError | .throwOnError()} to reject\n * with {@link FirebaseSqlError} on failure and narrow the resolved envelope to\n * {@link OperationSuccess} (still destructure `const { data } = await query.throwOnError()`, as it\n * resolves `{ data, count, status, statusText, success: true, error: null }`, not raw `T`).\n *\n * Example conventions and reference schema: code examples across this package assume an initialized\n * client `const sql = getSql({ serviceId: 'events-db', location: 'us-central1' });` unless client\n * initialization is shown explicitly, and share three PostgreSQL tables plus two stored functions:\n * `venues(id uuid PK, slug text UNIQUE, name text, city text, capacity int4, coords geography(Point, 4326))`,\n * `events(id uuid PK, venue_id uuid FK NULL, code text UNIQUE, title text, status text DEFAULT 'draft', is_featured bool DEFAULT false, ticket_price numeric, tags text[], metadata jsonb, schedule tstzrange, search_doc tsvector, created_at timestamptz DEFAULT now())`,\n * `registrations(id uuid PK, event_id uuid FK, user_uid text, attendee_email text, role text DEFAULT 'attendee', checked_in_at timestamptz NULL, UNIQUE (event_id, attendee_email))`,\n * `remaining_seats(target_event_id uuid) RETURNS int4`, and\n * `list_events_by_city(target_city text) RETURNS SETOF events`.\n *\n * @packageDocumentation\n */\n\n/**\n * @license\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerSql } from './register';\n\nexport * from './api';\n\nregisterSql();\n"],"names":["base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","this","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","Error","init_","byteToCharMap","output","i","length","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","push","join","encodeString","btoa","str","out","p","c","charCodeAt","stringToByteArray","decodeString","bytes","pos","c1","String","fromCharCode","c2","u","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","DecodeBase64StringError","constructor","name","base64Decode","e","console","error","FirebaseError","code","message","customData","super","Object","setPrototypeOf","prototype","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","replaceTemplate","ptr","result","start","indexOf","substring","end","key","value","fullMessage","jsonEval","JSON","parse","Component","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","callback","InstantiationMode","ComponentType","PostgrestError","context","details","hint","toJSON","getRetryDelay","attemptIndex","Math","min","RETRYABLE_STATUS_CODES","RETRYABLE_METHODS","sleep","ms","signal","Promise","resolve","aborted","id","setTimeout","removeEventListener","onAbort","clearTimeout","addEventListener","shouldRetry","method","status","attemptCount","retryEnabled","includes","async","fetchWithRetry","fetchImpl","url","request","headers: Record<string, string>","headers","res: Response","res","body","fetchError: any","fetchError","_request$signal","delay","retryAfterHeader","_res$headers$get","_res$headers","get","max","parseInt","text","PostgrestBuilder","builder","shouldThrowOnError","Headers","schema","_builder$shouldThrowO","isMaybeSingle","_builder$isMaybeSingl","shouldStripNulls","_builder$shouldStripN","urlLengthLimit","_builder$urlLengthLim","_builder$retry","retry","fetch","throwOnError","stripNulls","setHeader","set","enabled","then","onfulfilled","onrejected","currentAccept","_fetch","_this","forEach","toString","stringify","_","processResponse","executeWithRetry","catch","errorDetails","cause","causeMessage","_cause$message","causeCode","_cause$code","_fetchError$name","_cause$name","stack","_fetchError$stack","urlLength","success","_fetchError$name2","count","statusText","count: number | null","ok","_this$headers$get","_unused","countHeader","_this$headers$get2","match","contentRange","split","_objectSpread2","_error$hint","_unused2","returns","overrideTypes","PostgrestTransformBuilder","select","columns","quoted","cleanedColumns","map","test","searchParams","append","order","column","ascending","nullsFirst","foreignTable","referencedTable","existingOrder","limit","rows","range","from","to","keyOffset","keyLimit","abortSignal","single","maybeSingle","csv","geojson","explain","analyze","verbose","settings","buffers","wal","format","options","filter","Boolean","forMediatype","rollback","maxAffected","PostgrestReservedCharsRegexp","RegExp","PostgrestFilterBuilder","eq","neq","gt","gte","lt","lte","like","pattern","likeAllOf","patterns","likeAnyOf","ilike","ilikeAllOf","ilikeAnyOf","regexMatch","regexIMatch","is","isDistinct","values","cleanedValues","Set","s","notIn","contains","containedBy","rangeGt","rangeGte","rangeLt","rangeLte","rangeAdjacent","overlaps","textSearch","query","config","typePart","configPart","entries","not","operator","or","filters","PostgrestQueryBuilder","fetch$1","cloneRequestState","URL","head","insert","defaultToNull","reduce","acc","x","concat","keys","uniqueColumns","_this$fetch","upsert","onConflict","ignoreDuplicates","_this$fetch2","update","_this$fetch3","_this$fetch4","toOpenApiError","parsed","_parsed$message","_parsed$details","_parsed$hint","_parsed$code","toTransportFailure","err","_err$name","LogLevel","PostgrestClient","timeout","schemaName","originalFetch","globalThis","init","controller","AbortController","timeoutId","abort","existingSignal","abortHandler","once","finally","relation","trim","getOpenApiSpec","requestHeaders: Record<string, string>","requestHeaders","body: string","_this$retry","readError","rpc","fn","args","method: 'HEAD' | 'GET' | 'POST'","body: unknown | undefined","_isObject","v","some","_hasObjectArg","levelStringToEnum","debug","DEBUG","VERBOSE","info","INFO","warn","WARN","ERROR","silent","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","instance","logType","logLevel","now","Date","toISOString","Code","freeze","OTHER","ALREADY_INITIALIZED","NOT_INITIALIZED","NOT_SUPPORTED","INVALID_ARGUMENT","PARTIAL_ERROR","UNAUTHORIZED","FirebaseSqlErrorCategory","SQL_POSTGREST","SQL_PLATFORM","SQL_CLIENT","FirebaseSqlError","category","serialized","undefined","detailsText","hintText","isPlainRecord","proto","getPrototypeOf","normalizeNonEmptyString","normalizeDetails","stringDetails","normalizeHint","mapPlatformStatusToCode","rpcStatus","mapPostgrestFailureToFirebaseSqlError","rawError","normalizedStatus","envelopeCandidate","inner","error_description","fallbackMessage","fallbackDetails","fallbackHint","SDK_VERSION","FirebaseHeaders","GOOG_API_CLIENT","CLIENT_VERSION","FIREBASE_GMPID","FIREBASE_AUTH_TOKEN","FIREBASE_APPCHECK","FORBIDDEN_HEADERS","LOWERCASE_DISALLOWED_HEADER_KEYS","validateHeaderName","headerName","has","toLowerCase","resolveRequestHeaders","authToken","appCheckToken","_appId","mergeHeadersInit","target","source","delete","accessToken","token","getGoogApiClientValue","headersRecord","copySqlServiceSettings","settingsCopy","assign","validateSqlServiceSettings","serviceId","location","validatePort","port","Number","isInteger","validateHeaders","freezeSqlServiceSettings","FIREBASE_SQL_COMPONENT_NAME","logger","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","log","logDebug","msg","logError","AbstractTokenProvider","provider","serverAppToken","activeGetTokenPromise","activeForceRefreshPromise","resolveActiveGetTokenPromise","onInitUnsubscribe","activeListeners","queuedListeners","component","getImmediate","optional","onInit","n","oldestListener","shift","addTokenChangeListener","cancelOnInit","getToken","forceRefresh","forcedPromise","requestToken","unforcedPromise","reject","fetchToken","convertServerAppToken","listener","addListener","pop","removeTokenChangeListener","removeFirstOccurrenceFromList","removeListener","terminate","item","list","index","splice","AppCheckProvider","app","appCheckInternalProvider","_isFirebaseServerApp","addTokenListener","removeTokenListener","FirebaseAuthProvider","authInternalProvider","authIdToken","getAuth","addAuthTokenListener","removeAuthTokenListener","getAuthUidFromToken","claims","header","signature","parts","decode","sub","toAbortError","thrown","reason","FirebaseSqlTransport","_isUsingEmulator","appId","authProvider","authTokenProvider","appCheckProvider","appCheckTokenProvider","_terminationSignal","terminationSignal","_state","state","invokePostgrestOperation","active","inputSignal","Request","effectiveSignal","cleanup","composeSignals","signal1","signal2","AbortSignal","any","onAbort1","onAbort2","isRequest","mergedHeadersInit","combined","mergedInit","credentials","cache","redirect","referrer","integrity","getFetch","authData","appCheckData","all","requestInit","buildRequestInit","initialUid","canReplayBody","ReadableStream","bodyUsed","response","cancel","refreshAuthAndRefetch","requestUrl","isCloudWorkstation","startsWith","hostname","endsWith","currentToken","originalResponse","refreshedToken","refreshedUid","retryHeaders","toFetch","tracker","errorToTrack","clientError","abortError","createBuilderFetch","resolvePostgrestUrl","projectId","protocol","sslEnabled","host","encodedProjectId","encodeURIComponent","encodedLocation","encodedServiceId","pathname","FilterBuilderImpl","delegate","createFetch","mapError","_shouldThrowOnError","_delegate","_createFetch","_mapError","in","_execute","_fail","Reflect","raw","QueryBuilderImpl","_wrap","FirebaseSql","_instanceIdentifier","_terminationController","_postgrestUrl","_postgrestClient","_delete","_removeServiceInstance","_encodeResourceSegment","segment","preserveBlank","table","params","getSql","appOrSettings","settingsArg","rawSettings","getApp","validatedSettings","instanceIdentifier","getInstanceIdentifier","_getProvider","isInitialized","identifier","initialize","sql","resolvedUrl","registerSql","variant","setSDKVersion","version","_registerComponent","container","getProvider","registerVersion"],"mappings":"wKAiBA,MA0FaA,EAAiB,CAI5BC,eAAgB,KAKhBC,eAAgB,KAMhBC,sBAAuB,KAMvBC,sBAAuB,KAMvBC,kBACE,iEAKF,gBAAIC,GACF,OAAOC,KAAKF,kBAAoB,KAClC,EAKA,wBAAIG,GACF,OAAOD,KAAKF,kBAAoB,KAClC,EASAI,mBAAoC,mBAATC,KAW3B,eAAAC,CAAgBC,EAA8BC,GAC5C,IAAKC,MAAMC,QAAQH,GACjB,MAAMI,MAAM,iDAGdT,KAAKU,QAEL,MAAMC,EAAgBL,EAClBN,KAAKJ,sBACLI,KAAKN,eAEHkB,EAAS,GAEf,IAAK,IAAIC,EAAI,EAAGA,EAAIR,EAAMS,OAAQD,GAAK,EAAG,CACxC,MAAME,EAAQV,EAAMQ,GACdG,EAAYH,EAAI,EAAIR,EAAMS,OAC1BG,EAAQD,EAAYX,EAAMQ,EAAI,GAAK,EACnCK,EAAYL,EAAI,EAAIR,EAAMS,OAC1BK,EAAQD,EAAYb,EAAMQ,EAAI,GAAK,EAEnCO,EAAWL,GAAS,EACpBM,GAAqB,EAARN,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