@omnara/sdk 0.1.42 → 0.1.44

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.
package/README.md CHANGED
@@ -28,6 +28,104 @@ const client = createOmnaraClient({
28
28
 
29
29
  Requires Node.js 22 or later.
30
30
 
31
+ ### Retries and deadlines
32
+
33
+ Clients created with `createOmnaraClient` retry temporary network failures and HTTP
34
+ 408, 429, 500, 502, 503, and 504 responses up to twice. The SDK only retries reads
35
+ and writes whose API contract guarantees replay safety. Other writes get one
36
+ attempt. It uses exponential backoff with jitter and honors `Retry-After`; a
37
+ server wait longer than 60 seconds returns the error so your application can
38
+ schedule a later attempt.
39
+
40
+ ```ts
41
+ import { bearerToken, createOmnaraClient, sdk } from '@omnara/sdk'
42
+
43
+ const client = createOmnaraClient({
44
+ auth: bearerToken('your-api-key'),
45
+ maxRetries: 2, // Retries after the first attempt; 0 disables them.
46
+ timeoutMs: 30_000, // Total budget for one SDK call; 0 (the default) means no deadline.
47
+ })
48
+
49
+ await sdk.createAgentInput({
50
+ client,
51
+ path: { orgID, projectID, agentID },
52
+ body: { content_blocks: [{ type: 'text', text: 'Hello' }] },
53
+ headers: { 'Idempotency-Key': durableJobID },
54
+ maxRetries: 0, // Both settings can be overridden for one call.
55
+ timeoutMs: 5_000,
56
+ signal: controller.signal,
57
+ })
58
+ ```
59
+
60
+ For endpoints accepting `Idempotency-Key`, the SDK generates a key when none was
61
+ supplied. Every attempt within that call uses the same key, body, and authenticated
62
+ request. Separate SDK calls get separate keys. Supply your own stable key when
63
+ repeating a job across calls or process restarts. A key cannot make an endpoint
64
+ replay-safe unless that endpoint supports it. The SDK rejects `Idempotency-Key`
65
+ in client-wide headers: each logical operation needs its own key.
66
+
67
+ Replay safety protects an operation's effect, not its response: a retried write
68
+ can return a conflict such as `409 tool_call_already_completed` after a lost
69
+ success response.
70
+
71
+ `timeoutMs` includes authentication, response parsing, and retry waits. If the
72
+ next wait cannot fit, the SDK returns the last API error immediately. Expiring
73
+ during a request raises a `TimeoutError`; caller cancellation preserves
74
+ `signal.reason`. Both settings must be non-negative integers; `timeoutMs` must
75
+ fit a 32-bit timer. The `throwOnError: false` response modes still apply.
76
+
77
+ Authentication, serialization, and interceptors run once per logical call, not
78
+ once per attempt. If a validator changes the method, route template, or base URL,
79
+ or an interceptor changes the constructed request's method or URL, the SDK makes
80
+ one attempt because the original replay contract no longer applies.
81
+ Clearing the client's request interceptors also disables retries.
82
+ Header changes and clones that preserve the destination remain retryable.
83
+ A custom `fetch` still sees each attempt. Retries stop at the
84
+ fetch boundary: a failure while reading or parsing a JSON response body is
85
+ returned without another attempt. Streamed request bodies and `parseAs: 'stream'`
86
+ requests are not retried. For a successfully returned stream, including automatic
87
+ parsing, the request deadline does not limit subsequent body reads; use `signal`
88
+ to cancel them. HTTP error-body parsing remains covered by the deadline.
89
+ `openAgentEventStream` owns its reconnection policy.
90
+ The lower-level generated `sdk.streamEvents` uses its `sse*` options
91
+ instead of `maxRetries` and `timeoutMs`.
92
+
93
+ Pass your configured `client` to generated functions and TanStack options. Calls
94
+ without one use a shared default client with `maxRetries: 0` and `timeoutMs: 0`.
95
+ Per-call retry and deadline options still apply. The shared client returns raw
96
+ errors without `ApiError` mapping. When enabling SDK retries with TanStack Query,
97
+ set `retry: false` to avoid multiplying attempts; query refetches on reconnect
98
+ remain independent of transport retries.
99
+
100
+ ### Request observations
101
+
102
+ An optional `onRequestComplete` callback receives one local summary per SDK call,
103
+ including its total duration, fetch attempts, time spent waiting between attempts,
104
+ final HTTP status when available, and promise settlement. It can be set on the
105
+ client or overridden per call:
106
+
107
+ ```ts
108
+ import { bearerToken, createOmnaraClient } from '@omnara/sdk'
109
+
110
+ const client = createOmnaraClient({
111
+ auth: bearerToken('your-api-key'),
112
+ onRequestComplete(observation) {
113
+ localMetrics.record(observation)
114
+ },
115
+ })
116
+ ```
117
+
118
+ `outcome` is `returned`, `threw`, `canceled`, or `timeout`. A nonthrowing HTTP
119
+ failure has outcome `returned`, so inspect `status` as well. `operation` contains
120
+ a known API method and route template, or `unknown`; summaries never
121
+ contain resolved URLs, identifiers, credentials, or request/response payloads.
122
+ For raw streams, the summary ends when the SDK returns the stream; subsequent
123
+ body consumption is outside the request observation.
124
+
125
+ Keep callbacks cheap: they run synchronously at settlement, their promises are
126
+ not awaited, and thrown errors or rejected promises cannot affect the request.
127
+ The SDK does not export observations over the network or install telemetry.
128
+
31
129
  ## Documentation
32
130
 
33
131
  The [quickstart](https://docs.omnara.com/quickstart) shows how to launch an agent with the SDK. See also the [Omnara docs](https://docs.omnara.com) and the [GitHub repository](https://github.com/omnara-ai/omnara).
package/dist/browser.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
- ApiError
3
- } from "./chunk-6YKVAVCM.js";
4
- import "./chunk-NZCMY3BC.js";
5
- import "./chunk-WM4BXMLD.js";
2
+ ApiError,
3
+ createOmnaraClient
4
+ } from "./chunk-HFFDN2XF.js";
5
+ import "./chunk-BUM22BVJ.js";
6
6
 
7
7
  // src/browser.ts
8
8
  import * as z from "zod";
@@ -70,9 +70,7 @@ async function authJSON(path, body) {
70
70
  if (!response.ok) throw await ApiError.fromResponse(response);
71
71
  }
72
72
  async function listAuthConnectors() {
73
- const response = await fetch("/api/auth/connectors", { credentials: "include" });
74
- if (!response.ok) throw await ApiError.fromResponse(response);
75
- const data = zAuthConnectorsResponse.parse(await response.json());
73
+ const data = await readBrowserJSON("/api/auth/connectors", zAuthConnectorsResponse);
76
74
  return data.connectors.map((connector) => ({
77
75
  slug: connector.slug,
78
76
  kind: connector.kind,
@@ -81,16 +79,15 @@ async function listAuthConnectors() {
81
79
  }));
82
80
  }
83
81
  async function fetchWebConfig() {
84
- const response = await fetch("/api/web-config", { credentials: "include" });
85
- if (!response.ok) throw await ApiError.fromResponse(response);
86
- const data = zWebConfigResponse.parse(await response.json());
82
+ const data = await readBrowserJSON("/api/web-config", zWebConfigResponse);
87
83
  return { billingURL: data.billing_url, apiURL: data.api_url, publicURL: data.public_url };
88
84
  }
89
85
  async function pendingDeviceAuth(userCode) {
90
86
  const params = new URLSearchParams({ user_code: userCode });
91
- const response = await fetch(`/api/auth/device/pending?${params}`, { credentials: "include" });
92
- if (!response.ok) throw await ApiError.fromResponse(response);
93
- const data = zDeviceAuthPendingResponse.parse(await response.json());
87
+ const data = await readBrowserJSON(
88
+ `/api/auth/device/pending?${params}`,
89
+ zDeviceAuthPendingResponse
90
+ );
94
91
  return {
95
92
  clientName: data.client_name,
96
93
  tokenName: data.token_name,
@@ -98,6 +95,18 @@ async function pendingDeviceAuth(userCode) {
98
95
  expiresAt: data.expires_at
99
96
  };
100
97
  }
98
+ async function readBrowserJSON(url, schema) {
99
+ const data = await createOmnaraClient({
100
+ baseUrl: globalThis.location.origin,
101
+ credentials: "include"
102
+ }).get({
103
+ url,
104
+ responseStyle: "data",
105
+ throwOnError: true,
106
+ parseAs: "json"
107
+ });
108
+ return schema.parse(data);
109
+ }
101
110
  async function approveDeviceAuth(userCode) {
102
111
  await authJSON("/api/auth/device/approve", { user_code: userCode });
103
112
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/browser.ts"],"sourcesContent":["import * as z from 'zod'\n\nimport type { AuthStrategy } from './auth'\nimport { ApiError } from './errors'\n\nconst SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])\n\nexport interface DeviceAuthPending {\n clientName: string\n tokenName: string\n createdAt: string\n expiresAt: string\n}\n\nexport interface AuthConnector {\n slug: string\n kind: string\n displayName: string\n loginURL: string\n}\n\nexport interface WebConfig {\n billingURL?: string\n apiURL?: string\n publicURL?: string\n}\n\ntype AuthRequestBody = Record<string, string | undefined>\n\nconst zAuthConnectorsResponse = z.object({\n connectors: z.array(\n z.object({\n slug: z.string(),\n kind: z.string(),\n display_name: z.string(),\n login_url: z.string(),\n }),\n ),\n})\n\nconst zWebConfigResponse = z.object({\n billing_url: z.string().optional(),\n api_url: z.string().optional(),\n public_url: z.string().optional(),\n})\n\nconst zDeviceAuthPendingResponse = z.object({\n client_name: z.string(),\n token_name: z.string(),\n created_at: z.string(),\n expires_at: z.string(),\n})\n\nfunction cookieValue(name: string): string | undefined {\n const prefix = `${name}=`\n const raw = document.cookie\n .split(';')\n .map((cookie) => cookie.trim())\n .find((cookie) => cookie.startsWith(prefix))\n ?.slice(prefix.length)\n if (!raw) return undefined\n try {\n return decodeURIComponent(raw)\n } catch {\n return undefined\n }\n}\n\nfunction csrfToken(): string | undefined {\n return cookieValue('__Host-omnara_csrf') ?? cookieValue('omnara_csrf')\n}\n\nexport function getLastUsedAuthMethod(): string | undefined {\n return cookieValue('omnara_last_login_method')\n}\n\nexport function cookieCsrf(): AuthStrategy {\n return {\n authenticate(request) {\n if (!SAFE_METHODS.has(request.method.toUpperCase())) {\n const token = csrfToken()\n if (token) request.headers.set('X-Omnara-Csrf', token)\n }\n },\n }\n}\n\nasync function authJSON(path: string, body?: AuthRequestBody): Promise<void> {\n const headers: Record<string, string> = {}\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json'\n }\n const token = csrfToken()\n if (token) headers['X-Omnara-Csrf'] = token\n const response = await fetch(path, {\n method: 'POST',\n credentials: 'include',\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n })\n if (!response.ok) throw await ApiError.fromResponse(response)\n}\n\nexport async function listAuthConnectors(): Promise<AuthConnector[]> {\n const response = await fetch('/api/auth/connectors', { credentials: 'include' })\n if (!response.ok) throw await ApiError.fromResponse(response)\n const data = zAuthConnectorsResponse.parse(await response.json())\n return data.connectors.map((connector) => ({\n slug: connector.slug,\n kind: connector.kind,\n displayName: connector.display_name,\n loginURL: connector.login_url,\n }))\n}\n\nexport async function fetchWebConfig(): Promise<WebConfig> {\n const response = await fetch('/api/web-config', { credentials: 'include' })\n if (!response.ok) throw await ApiError.fromResponse(response)\n const data = zWebConfigResponse.parse(await response.json())\n return { billingURL: data.billing_url, apiURL: data.api_url, publicURL: data.public_url }\n}\n\nexport async function pendingDeviceAuth(userCode: string): Promise<DeviceAuthPending> {\n const params = new URLSearchParams({ user_code: userCode })\n const response = await fetch(`/api/auth/device/pending?${params}`, { credentials: 'include' })\n if (!response.ok) throw await ApiError.fromResponse(response)\n const data = zDeviceAuthPendingResponse.parse(await response.json())\n return {\n clientName: data.client_name,\n tokenName: data.token_name,\n createdAt: data.created_at,\n expiresAt: data.expires_at,\n }\n}\n\nexport async function approveDeviceAuth(userCode: string): Promise<void> {\n await authJSON('/api/auth/device/approve', { user_code: userCode })\n}\n\nexport async function denyDeviceAuth(userCode: string): Promise<void> {\n await authJSON('/api/auth/device/deny', { user_code: userCode })\n}\n\nexport async function sessionLogin(email: string, password: string): Promise<void> {\n await authJSON('/api/auth/login', { email, password })\n}\n\nexport async function sessionLogout(): Promise<void> {\n await authJSON('/api/auth/logout')\n}\n\nexport async function requestSignup(email: string, returnTo?: string): Promise<void> {\n await authJSON('/api/auth/signup', { email, return_to: returnTo })\n}\n\nexport async function completeEmailVerification(\n token: string,\n password: string,\n displayName: string,\n): Promise<void> {\n await authJSON('/api/auth/email/verify', {\n token,\n password,\n display_name: displayName.trim() || undefined,\n })\n}\n\nexport async function requestPasswordReset(email: string): Promise<void> {\n await authJSON('/api/auth/password/reset/request', { email })\n}\n\nexport async function completePasswordReset(token: string, password: string): Promise<void> {\n await authJSON('/api/auth/password/reset', { token, password })\n}\n\nexport interface OAuthAuthorizePending {\n clientId: string\n clientName: string\n clientUri?: string\n redirectUri: string\n redirectHost: string\n loopback: boolean\n resource: string\n scope: string\n}\n\nconst zOAuthAuthorizePendingResponse = z.object({\n client_id: z.string(),\n client_name: z.string(),\n client_uri: z.string(),\n redirect_uri: z.string(),\n redirect_host: z.string(),\n loopback: z.boolean(),\n resource: z.string(),\n scope: z.string().optional(),\n})\n\nconst zOAuthAuthorizeRedirectResponse = z.object({ redirect_url: z.string().min(1) })\n\nconst zOAuthAuthorizeErrorResponse = z.object({\n error: z.string().min(1),\n error_description: z.string().optional(),\n redirect_url: z.string().optional(),\n})\n\nexport class OAuthAuthorizeError extends Error {\n readonly code: string\n readonly redirectUrl?: string\n\n constructor(code: string, description: string | undefined, redirectUrl: string | undefined) {\n super(description ?? code)\n this.name = 'OAuthAuthorizeError'\n this.code = code\n this.redirectUrl = redirectUrl\n }\n}\n\nasync function oauthAuthorizeFailure(response: Response): Promise<Error> {\n const text = await response.text()\n try {\n const parsed = zOAuthAuthorizeErrorResponse.parse(JSON.parse(text))\n return new OAuthAuthorizeError(parsed.error, parsed.error_description, parsed.redirect_url)\n } catch {\n return await ApiError.fromResponse(\n new Response(text, { status: response.status, headers: response.headers }),\n )\n }\n}\n\nexport async function pendingOAuthAuthorization(query: string): Promise<OAuthAuthorizePending> {\n const response = await fetch(`/api/auth/oauth/authorize/pending${query}`, {\n credentials: 'include',\n })\n if (!response.ok) throw await oauthAuthorizeFailure(response)\n const data = zOAuthAuthorizePendingResponse.parse(await response.json())\n return {\n clientId: data.client_id,\n clientName: data.client_name,\n clientUri: data.client_uri || undefined,\n redirectUri: data.redirect_uri,\n redirectHost: data.redirect_host,\n loopback: data.loopback,\n resource: data.resource,\n scope: data.scope ?? '',\n }\n}\n\nasync function oauthAuthorizeDecision(path: string, query: string): Promise<string> {\n const headers = new Headers({ 'Content-Type': 'application/json' })\n const token = csrfToken()\n if (token) headers.set('X-Omnara-Csrf', token)\n const response = await fetch(path, {\n method: 'POST',\n credentials: 'include',\n headers,\n body: JSON.stringify({ query }),\n })\n if (!response.ok) throw await oauthAuthorizeFailure(response)\n return zOAuthAuthorizeRedirectResponse.parse(await response.json()).redirect_url\n}\n\nexport function approveOAuthAuthorization(query: string): Promise<string> {\n return oauthAuthorizeDecision('/api/auth/oauth/authorize/approve', query)\n}\n\nexport function denyOAuthAuthorization(query: string): Promise<string> {\n return oauthAuthorizeDecision('/api/auth/oauth/authorize/deny', query)\n}\n"],"mappings":";;;;;;;AAAA,YAAY,OAAO;AAKnB,IAAM,eAAe,oBAAI,IAAI,CAAC,OAAO,QAAQ,SAAS,CAAC;AAwBvD,I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Q,UAAU;AACxB,MAAI,MAAO,SAAQ,IAAI,iBAAiB,KAAK;AAC7C,QAAM,WAAW,MAAM,MAAM,MAAM;AAAA,IACjC,QAAQ;AAAA,IACR,aAAa;AAAA,IACb;AAAA,IACA,MAAM,KAAK,UAAU,EAAE,MAAM,CAAC;AAAA,EAChC,CAAC;AACD,MAAI,CAAC,SAAS,GAAI,OAAM,MAAM,sBAAsB,QAAQ;AAC5D,SAAO,gCAAgC,MAAM,MAAM,SAAS,KAAK,CAAC,EAAE;AACtE;AAEO,SAAS,0BAA0B,OAAgC;AACxE,SAAO,uBAAuB,qCAAqC,KAAK;AAC1E;AAEO,SAAS,uBAAuB,OAAgC;AACrE,SAAO,uBAAuB,kCAAkC,KAAK;AACvE;","names":[]}
1
+ {"version":3,"sources":["../src/browser.ts"],"sourcesContent":["import * as z from 'zod'\n\nimport type { AuthStrategy } from './auth'\nimport { createOmnaraClient } from './client'\nimport { ApiError } from './errors'\n\nconst SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])\n\nexport interface DeviceAuthPending {\n clientName: string\n tokenName: string\n createdAt: string\n expiresAt: string\n}\n\nexport interface AuthConnector {\n slug: string\n kind: string\n displayName: string\n loginURL: string\n}\n\nexport interface WebConfig {\n billingURL?: string\n apiURL?: string\n publicURL?: string\n}\n\ntype AuthRequestBody = Record<string, string | undefined>\n\nconst zAuthConnectorsResponse = z.object({\n connectors: z.array(\n z.object({\n slug: z.string(),\n kind: z.string(),\n display_name: z.string(),\n login_url: z.string(),\n }),\n ),\n})\n\nconst zWebConfigResponse = z.object({\n billing_url: z.string().optional(),\n api_url: z.string().optional(),\n public_url: z.string().optional(),\n})\n\nconst zDeviceAuthPendingResponse = z.object({\n client_name: z.string(),\n token_name: z.string(),\n created_at: z.string(),\n expires_at: z.string(),\n})\n\nfunction cookieValue(name: string): string | undefined {\n const prefix = `${name}=`\n const raw = document.cookie\n .split(';')\n .map((cookie) => cookie.trim())\n .find((cookie) => cookie.startsWith(prefix))\n ?.slice(prefix.length)\n if (!raw) return undefined\n try {\n return decodeURIComponent(raw)\n } catch {\n return undefined\n }\n}\n\nfunction csrfToken(): string | undefined {\n return cookieValue('__Host-omnara_csrf') ?? cookieValue('omnara_csrf')\n}\n\nexport function getLastUsedAuthMethod(): string | undefined {\n return cookieValue('omnara_last_login_method')\n}\n\nexport function cookieCsrf(): AuthStrategy {\n return {\n authenticate(request) {\n if (!SAFE_METHODS.has(request.method.toUpperCase())) {\n const token = csrfToken()\n if (token) request.headers.set('X-Omnara-Csrf', token)\n }\n },\n }\n}\n\nasync function authJSON(path: string, body?: AuthRequestBody): Promise<void> {\n const headers: Record<string, string> = {}\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json'\n }\n const token = csrfToken()\n if (token) headers['X-Omnara-Csrf'] = token\n const response = await fetch(path, {\n method: 'POST',\n credentials: 'include',\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n })\n if (!response.ok) throw await ApiError.fromResponse(response)\n}\n\nexport async function listAuthConnectors(): Promise<AuthConnector[]> {\n const data = await readBrowserJSON('/api/auth/connectors', zAuthConnectorsResponse)\n return data.connectors.map((connector) => ({\n slug: connector.slug,\n kind: connector.kind,\n displayName: connector.display_name,\n loginURL: connector.login_url,\n }))\n}\n\nexport async function fetchWebConfig(): Promise<WebConfig> {\n const data = await readBrowserJSON('/api/web-config', zWebConfigResponse)\n return { billingURL: data.billing_url, apiURL: data.api_url, publicURL: data.public_url }\n}\n\nexport async function pendingDeviceAuth(userCode: string): Promise<DeviceAuthPending> {\n const params = new URLSearchParams({ user_code: userCode })\n const data = await readBrowserJSON(\n `/api/auth/device/pending?${params}`,\n zDeviceAuthPendingResponse,\n )\n return {\n clientName: data.client_name,\n tokenName: data.token_name,\n createdAt: data.created_at,\n expiresAt: data.expires_at,\n }\n}\n\nasync function readBrowserJSON<T>(url: string, schema: z.ZodType<T>): Promise<T> {\n const data = await createOmnaraClient({\n baseUrl: globalThis.location.origin,\n credentials: 'include',\n }).get({\n url,\n responseStyle: 'data',\n throwOnError: true,\n parseAs: 'json',\n })\n return schema.parse(data)\n}\n\nexport async function approveDeviceAuth(userCode: string): Promise<void> {\n await authJSON('/api/auth/device/approve', { user_code: userCode })\n}\n\nexport async function denyDeviceAuth(userCode: string): Promise<void> {\n await authJSON('/api/auth/device/deny', { user_code: userCode })\n}\n\nexport async function sessionLogin(email: string, password: string): Promise<void> {\n await authJSON('/api/auth/login', { email, password })\n}\n\nexport async function sessionLogout(): Promise<void> {\n await authJSON('/api/auth/logout')\n}\n\nexport async function requestSignup(email: string, returnTo?: string): Promise<void> {\n await authJSON('/api/auth/signup', { email, return_to: returnTo })\n}\n\nexport async function completeEmailVerification(\n token: string,\n password: string,\n displayName: string,\n): Promise<void> {\n await authJSON('/api/auth/email/verify', {\n token,\n password,\n display_name: displayName.trim() || undefined,\n })\n}\n\nexport async function requestPasswordReset(email: string): Promise<void> {\n await authJSON('/api/auth/password/reset/request', { email })\n}\n\nexport async function completePasswordReset(token: string, password: string): Promise<void> {\n await authJSON('/api/auth/password/reset', { token, password })\n}\n\nexport interface OAuthAuthorizePending {\n clientId: string\n clientName: string\n clientUri?: string\n redirectUri: string\n redirectHost: string\n loopback: boolean\n resource: string\n scope: string\n}\n\nconst zOAuthAuthorizePendingResponse = z.object({\n client_id: z.string(),\n client_name: z.string(),\n client_uri: z.string(),\n redirect_uri: z.string(),\n redirect_host: z.string(),\n loopback: z.boolean(),\n resource: z.string(),\n scope: z.string().optional(),\n})\n\nconst zOAuthAuthorizeRedirectResponse = z.object({ redirect_url: z.string().min(1) })\n\nconst zOAuthAuthorizeErrorResponse = z.object({\n error: z.string().min(1),\n error_description: z.string().optional(),\n redirect_url: z.string().optional(),\n})\n\nexport class OAuthAuthorizeError extends Error {\n readonly code: string\n readonly redirectUrl?: string\n\n constructor(code: string, description: string | undefined, redirectUrl: string | undefined) {\n super(description ?? code)\n this.name = 'OAuthAuthorizeError'\n this.code = code\n this.redirectUrl = redirectUrl\n }\n}\n\nasync function oauthAuthorizeFailure(response: Response): Promise<Error> {\n const text = await response.text()\n try {\n const parsed = zOAuthAuthorizeErrorResponse.parse(JSON.parse(text))\n return new OAuthAuthorizeError(parsed.error, parsed.error_description, parsed.redirect_url)\n } catch {\n return await ApiError.fromResponse(\n new Response(text, { status: response.status, headers: response.headers }),\n )\n }\n}\n\nexport async function pendingOAuthAuthorization(query: string): Promise<OAuthAuthorizePending> {\n const response = await fetch(`/api/auth/oauth/authorize/pending${query}`, {\n credentials: 'include',\n })\n if (!response.ok) throw await oauthAuthorizeFailure(response)\n const data = zOAuthAuthorizePendingResponse.parse(await response.json())\n return {\n clientId: data.client_id,\n clientName: data.client_name,\n clientUri: data.client_uri || undefined,\n redirectUri: data.redirect_uri,\n redirectHost: data.redirect_host,\n loopback: data.loopback,\n resource: data.resource,\n scope: data.scope ?? '',\n }\n}\n\nasync function oauthAuthorizeDecision(path: string, query: string): Promise<string> {\n const headers = new Headers({ 'Content-Type': 'application/json' })\n const token = csrfToken()\n if (token) headers.set('X-Omnara-Csrf', token)\n const response = await fetch(path, {\n method: 'POST',\n credentials: 'include',\n headers,\n body: JSON.stringify({ query }),\n })\n if (!response.ok) throw await oauthAuthorizeFailure(response)\n return zOAuthAuthorizeRedirectResponse.parse(await response.json()).redirect_url\n}\n\nexport function approveOAuthAuthorization(query: string): Promise<string> {\n return oauthAuthorizeDecision('/api/auth/oauth/authorize/approve', query)\n}\n\nexport function denyOAuthAuthorization(query: string): Promise<string> {\n return oauthAuthorizeDecision('/api/auth/oauth/authorize/deny', query)\n}\n"],"mappings":";;;;;;;AAAA,YAAY,OAAO;AAMnB,IAAM,eAAe,oBAAI,IAAI,CAAC,OAAO,QAAQ,SAAS,CAAC;AAwBvD,IAAM,0BAA4B,SAAO;AAAA,EACvC,YAAc;AAAA,IACV,SAAO;AAAA,MACP,MAAQ,SAAO;AAAA,MACf,MAAQ,SAAO;AAAA,MACf,cAAgB,SAAO;AAAA,MACvB,WAAa,SAAO;AAAA,IACtB,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