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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
import PostgrestQueryBuilder from './PostgrestQueryBuilder'
import PostgrestFilterBuilder from './PostgrestFilterBuilder'
import { Fetch, GenericSchema, ClientServerOptions } from './types/common/common'
import { GetRpcFunctionFilterBuilderByArgs } from './types/common/rpc'
import PostgrestError from './PostgrestError'
import { fetchWithRetry } from './fetchWithRetry'
import {
  PostgrestOpenApiSpec,
  PostgrestResponseFailure,
  PostgrestSingleResponse,
} from './types/types'

/**
 * Build the error for a failed OpenAPI request. PostgREST answers with a JSON
 * error object when it produced the failure itself; proxies and disabled
 * OpenAPI output answer with plain text or an empty body, in which case the
 * body (or, failing that, the status text) becomes the message.
 */
function toOpenApiError(body: string, statusText: string): PostgrestError {
  try {
    const parsed = JSON.parse(body)
    if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
      return new PostgrestError({
        message: String(parsed.message ?? body),
        details: parsed.details ?? '',
        hint: parsed.hint ?? '',
        code: parsed.code ?? '',
      })
    }
  } catch {
    // Not JSON; fall through to the plain-text message.
  }
  return new PostgrestError({ message: body || statusText, details: '', hint: '', code: '' })
}

/**
 * Build the response for a request that yielded no readable body: the fetch
 * itself rejected (no status is known, so it is 0), or the body stream failed
 * while being read (the response status is preserved).
 */
function toTransportFailure(
  cause: unknown,
  status: number,
  statusText: string
): PostgrestResponseFailure {
  const err = cause as { name?: string; message?: string } | null | undefined
  return {
    success: false,
    error: new PostgrestError({
      message: `${err?.name ?? 'FetchError'}: ${err?.message}`,
      details: '',
      hint: '',
      code: '',
    }),
    data: null,
    count: null,
    status,
    statusText,
  }
}

/**
 * PostgREST client.
 *
 * @typeParam Database - Types for the schema from the [type
 * generator](https://supabase.com/docs/reference/javascript/next/typescript-support)
 *
 * @typeParam SchemaName - Postgres schema to switch to. Must be a string
 * literal, the same one passed to the constructor. If the schema is not
 * `"public"`, this must be supplied manually.
 */
export default class PostgrestClient<
  Database = any,
  ClientOptions extends ClientServerOptions = Database extends {
    __InternalSupabase: infer I extends ClientServerOptions
  }
    ? I
    : {},
  SchemaName extends string & keyof Omit<Database, '__InternalSupabase'> =
    'public' extends keyof Omit<Database, '__InternalSupabase'>
      ? 'public'
      : string & keyof Omit<Database, '__InternalSupabase'>,
  Schema extends GenericSchema = Omit<
    Database,
    '__InternalSupabase'
  >[SchemaName] extends GenericSchema
    ? Omit<Database, '__InternalSupabase'>[SchemaName]
    : any,
> {
  url: string
  headers: Headers
  schemaName?: SchemaName
  fetch?: Fetch
  urlLengthLimit: number

  // Retry configuration - enabled by default
  retry?: boolean

  // TODO: Add back shouldThrowOnError once we figure out the typings
  /**
   * Creates a PostgREST client.
   *
   * @param url - URL of the PostgREST endpoint
   * @param options - Named parameters
   * @param options.headers - Custom headers
   * @param options.schema - Postgres schema to switch to
   * @param options.fetch - Custom fetch
   * @param options.timeout - Optional timeout in milliseconds for all requests. When set, requests will automatically abort after this duration to prevent indefinite hangs.
   * @param options.urlLengthLimit - Maximum URL length in characters before warnings/errors are triggered. Defaults to 8000.
   * @param options.retry - Enable or disable automatic retries for transient errors.
   *   When enabled, idempotent requests (GET, HEAD, OPTIONS) that fail with network
   *   errors or HTTP 503/520 responses will be automatically retried up to 3 times
   *   with exponential backoff (1s, 2s, 4s). Defaults to `true`.
   * @example Using supabase-js (recommended)
   * ```ts
   * import { createClient } from '@supabase/supabase-js'
   *
   * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key')
   * const { data, error } = await supabase.from('profiles').select('*')
   * ```
   *
   * @category Database
   *
   * @remarks
   * - A `timeout` option (in milliseconds) can be set to automatically abort requests that take too long.
   * - A `urlLengthLimit` option (default: 8000) can be set to control when URL length warnings are included in error messages for aborted requests.
   *
   * @example Standalone import for bundle-sensitive environments
   * ```ts
   * import { PostgrestClient } from '@supabase/postgrest-js'
   *
   * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', {
   *   headers: { apikey: 'your-publishable-key' },
   *   schema: 'public',
   *   timeout: 30000, // 30 second timeout
   * })
   * ```
   */
  constructor(
    url: string,
    {
      headers = {},
      schema,
      fetch,
      timeout,
      urlLengthLimit = 8000,
      retry,
    }: {
      headers?: HeadersInit
      schema?: SchemaName
      fetch?: Fetch
      timeout?: number
      urlLengthLimit?: number
      retry?: boolean
    } = {}
  ) {
    this.url = url
    this.headers = new Headers(headers)
    this.schemaName = schema
    this.urlLengthLimit = urlLengthLimit

    const originalFetch = fetch ?? globalThis.fetch

    // Wrap fetch with timeout if specified
    if (timeout !== undefined && timeout > 0) {
      this.fetch = (input, init) => {
        const controller = new AbortController()
        const timeoutId = setTimeout(() => controller.abort(), timeout)

        // Merge abort signals if one already exists
        const existingSignal = init?.signal
        if (existingSignal) {
          // If the existing signal is already aborted, use it directly
          if (existingSignal.aborted) {
            clearTimeout(timeoutId)
            return originalFetch(input, init)
          }

          // Listen to existing signal and abort our controller too
          const abortHandler = () => {
            clearTimeout(timeoutId)
            controller.abort()
          }
          existingSignal.addEventListener('abort', abortHandler, { once: true })

          return originalFetch(input, {
            ...init,
            signal: controller.signal,
          }).finally(() => {
            clearTimeout(timeoutId)
            existingSignal.removeEventListener('abort', abortHandler)
          })
        }

        return originalFetch(input, {
          ...init,
          signal: controller.signal,
        }).finally(() => clearTimeout(timeoutId))
      }
    } else {
      this.fetch = originalFetch
    }
    this.retry = retry
  }
  /**
   * Perform a query on a table or a view.
   *
   * @param relation - The table or view name to query
   *
   * @category Database
   */
  from<
    TableName extends string & keyof Schema['Tables'],
    Table extends Schema['Tables'][TableName],
  >(relation: TableName): PostgrestQueryBuilder<ClientOptions, Schema, Table, TableName>
  from<ViewName extends string & keyof Schema['Views'], View extends Schema['Views'][ViewName]>(
    relation: ViewName
  ): PostgrestQueryBuilder<ClientOptions, Schema, View, ViewName>
  from(
    relation: (string & keyof Schema['Tables']) | (string & keyof Schema['Views'])
  ): PostgrestQueryBuilder<ClientOptions, Schema, any, any> {
    if (!relation || typeof relation !== 'string' || relation.trim() === '') {
      throw new Error('Invalid relation name: relation must be a non-empty string.')
    }

    const url = new URL(`${this.url}/${relation}`)
    return new PostgrestQueryBuilder(url, {
      headers: new Headers(this.headers),
      schema: this.schemaName,
      fetch: this.fetch,
      urlLengthLimit: this.urlLengthLimit,
      retry: this.retry,
    })
  }

  /**
   * Select a schema to query or perform an function (rpc) call.
   *
   * The schema needs to be on the list of exposed schemas inside Supabase.
   *
   * @param schema - The schema to query
   *
   * @category Database
   */
  schema<DynamicSchema extends string & keyof Omit<Database, '__InternalSupabase'>>(
    schema: DynamicSchema
  ): PostgrestClient<
    Database,
    ClientOptions,
    DynamicSchema,
    Database[DynamicSchema] extends GenericSchema ? Database[DynamicSchema] : any
  > {
    return new PostgrestClient(this.url, {
      headers: this.headers,
      schema,
      fetch: this.fetch,
      urlLengthLimit: this.urlLengthLimit,
      retry: this.retry,
    })
  }

  /**
   * Fetch the OpenAPI description PostgREST publishes for this client's schema.
   *
   * The document lists only the tables, views and functions the caller's role
   * holds privileges on; PostgREST applies that filtering server-side. The
   * schema is the one this client was created with, so call `.schema()` first
   * to describe a different one. Transient failures are retried according to
   * the client's `retry` option, like any other idempotent request.
   *
   * @example
   * ```ts
   * const { data, error } = await supabase.getOpenApiSpec()
   * ```
   *
   * @example Describe a schema other than the client default
   * ```ts
   * const { data, error } = await supabase.schema('billing').getOpenApiSpec()
   * ```
   *
   * @category Database
   */
  async getOpenApiSpec(): Promise<PostgrestSingleResponse<PostgrestOpenApiSpec>> {
    const headers = new Headers(this.headers)
    headers.set('Accept', 'application/openapi+json')
    if (this.schemaName) {
      headers.set('Accept-Profile', this.schemaName)
    }

    // Headers reach the fetch implementation as a plain object, as in
    // PostgrestBuilder: React Native's XHR-based fetch drops headers that are
    // supplied as a Headers instance.
    const requestHeaders: Record<string, string> = {}
    headers.forEach((value, key) => {
      requestHeaders[key] = value
    })

    const fetchImpl = this.fetch ?? globalThis.fetch
    let res: Response
    try {
      res = await fetchWithRetry(
        fetchImpl,
        `${this.url}/`,
        { method: 'GET', headers: requestHeaders },
        this.retry ?? true
      )
    } catch (fetchError) {
      return toTransportFailure(fetchError, 0, '')
    }

    let body: string
    try {
      body = await res.text()
    } catch (readError) {
      return toTransportFailure(readError, res.status, res.statusText)
    }

    if (res.ok) {
      try {
        return {
          success: true,
          error: null,
          data: JSON.parse(body) as PostgrestOpenApiSpec,
          count: null,
          status: res.status,
          statusText: res.statusText,
        }
      } catch {
        // A 2xx status does not guarantee a JSON body; report it like a failure.
      }
    }

    return {
      success: false,
      error: toOpenApiError(body, res.statusText),
      data: null,
      count: null,
      status: res.status,
      statusText: res.statusText,
    }
  }

  /**
   * Perform a function call.
   *
   * @param fn - The function name to call
   * @param args - The arguments to pass to the function call
   * @param options - Named parameters
   * @param options.head - When set to `true`, `data` will not be returned.
   * Useful if you only need the count.
   * @param options.get - When set to `true`, the function will be called with
   * read-only access mode.
   * @param options.count - Count algorithm to use to count rows returned by the
   * function. Only applicable for [set-returning
   * functions](https://www.postgresql.org/docs/current/functions-srf.html).
   *
   * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the
   * hood.
   *
   * `"planned"`: Approximated but fast count algorithm. Uses the Postgres
   * statistics under the hood.
   *
   * `"estimated"`: Uses exact count for low numbers and planned count for high
   * numbers.
   *
   * @example
   * ```ts
   * // For cross-schema functions where type inference fails, use overrideTypes:
   * const { data } = await supabase
   *   .schema('schema_b')
   *   .rpc('function_a', {})
   *   .overrideTypes<{ id: string; user_id: string }[]>()
   * ```
   *
   * @category Database
   *
   * @example Call a Postgres function without arguments
   * ```ts
   * const { data, error } = await supabase.rpc('hello_world')
   * ```
   *
   * @exampleSql Call a Postgres function without arguments
   * ```sql
   * create function hello_world() returns text as $$
   *   select 'Hello world';
   * $$ language sql;
   * ```
   *
   * @exampleResponse Call a Postgres function without arguments
   * ```json
   * {
   *   "data": "Hello world",
   *   "status": 200,
   *   "statusText": "OK"
   * }
   * ```
   *
   * @example Call a Postgres function with arguments
   * ```ts
   * const { data, error } = await supabase.rpc('echo', { say: '👋' })
   * ```
   *
   * @exampleSql Call a Postgres function with arguments
   * ```sql
   * create function echo(say text) returns text as $$
   *   select say;
   * $$ language sql;
   * ```
   *
   * @exampleResponse Call a Postgres function with arguments
   * ```json
   *   {
   *     "data": "👋",
   *     "status": 200,
   *     "statusText": "OK"
   *   }
   *
   * ```
   *
   * @exampleDescription Bulk processing
   * You can process large payloads by passing in an array as an argument.
   *
   * @example Bulk processing
   * ```ts
   * const { data, error } = await supabase.rpc('add_one_each', { arr: [1, 2, 3] })
   * ```
   *
   * @exampleSql Bulk processing
   * ```sql
   * create function add_one_each(arr int[]) returns int[] as $$
   *   select array_agg(n + 1) from unnest(arr) as n;
   * $$ language sql;
   * ```
   *
   * @exampleResponse Bulk processing
   * ```json
   * {
   *   "data": [
   *     2,
   *     3,
   *     4
   *   ],
   *   "status": 200,
   *   "statusText": "OK"
   * }
   * ```
   *
   * @exampleDescription Call a Postgres function with filters
   * Postgres functions that return tables can also be combined with [Filters](/docs/reference/javascript/using-filters) and [Modifiers](/docs/reference/javascript/using-modifiers).
   *
   * @example Call a Postgres function with filters
   * ```ts
   * const { data, error } = await supabase
   *   .rpc('list_stored_countries')
   *   .eq('id', 1)
   *   .single()
   * ```
   *
   * @exampleSql Call a Postgres function with filters
   * ```sql
   * create table
   *   countries (id int8 primary key, name text);
   *
   * insert into
   *   countries (id, name)
   * values
   *   (1, 'Rohan'),
   *   (2, 'The Shire');
   *
   * create function list_stored_countries() returns setof countries as $$
   *   select * from countries;
   * $$ language sql;
   * ```
   *
   * @exampleResponse Call a Postgres function with filters
   * ```json
   * {
   *   "data": {
   *     "id": 1,
   *     "name": "Rohan"
   *   },
   *   "status": 200,
   *   "statusText": "OK"
   * }
   * ```
   *
   * @example Call a read-only Postgres function
   * ```ts
   * const { data, error } = await supabase.rpc('hello_world', undefined, { get: true })
   * ```
   *
   * @exampleSql Call a read-only Postgres function
   * ```sql
   * create function hello_world() returns text as $$
   *   select 'Hello world';
   * $$ language sql;
   * ```
   *
   * @exampleResponse Call a read-only Postgres function
   * ```json
   * {
   *   "data": "Hello world",
   *   "status": 200,
   *   "statusText": "OK"
   * }
   * ```
   */
  rpc<
    FnName extends string & keyof Schema['Functions'],
    Args extends Schema['Functions'][FnName]['Args'] = never,
    FilterBuilder extends GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args> =
      GetRpcFunctionFilterBuilderByArgs<Schema, FnName, Args>,
  >(
    fn: FnName,
    args: Args = {} as Args,
    {
      head = false,
      get = false,
      count,
    }: {
      head?: boolean
      get?: boolean
      count?: 'exact' | 'planned' | 'estimated' | (string & {})
    } = {}
  ): PostgrestFilterBuilder<
    ClientOptions,
    Schema,
    FilterBuilder['Row'],
    FilterBuilder['Result'],
    FilterBuilder['RelationName'],
    FilterBuilder['Relationships'],
    'RPC'
  > {
    let method: 'HEAD' | 'GET' | 'POST'
    const url = new URL(`${this.url}/rpc/${fn}`)
    let body: unknown | undefined
    // objects/arrays-of-objects can't be serialized to URL params, use POST + return=minimal instead
    const _isObject = (v: unknown): boolean =>
      v !== null && typeof v === 'object' && (!Array.isArray(v) || v.some(_isObject))
    const _hasObjectArg = head && Object.values(args as object).some(_isObject)
    if (_hasObjectArg) {
      method = 'POST'
      body = args
    } else if (head || get) {
      method = head ? 'HEAD' : 'GET'
      Object.entries(args)
        // params with undefined value needs to be filtered out, otherwise it'll
        // show up as `?param=undefined`
        .filter(([_, value]) => value !== undefined)
        // array values need special syntax
        .map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(',')}}` : `${value}`])
        .forEach(([name, value]) => {
          url.searchParams.append(name, value)
        })
    } else {
      method = 'POST'
      body = args
    }

    const headers = new Headers(this.headers)
    if (_hasObjectArg) {
      headers.set('Prefer', count ? `count=${count},return=minimal` : 'return=minimal')
    } else if (count) {
      headers.set('Prefer', `count=${count}`)
    }

    return new PostgrestFilterBuilder({
      method,
      url,
      headers,
      schema: this.schemaName,
      body,
      fetch: this.fetch ?? fetch,
      urlLengthLimit: this.urlLengthLimit,
      retry: this.retry,
    })
  }
}