@orth/sdk 0.5.1 → 0.7.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,38 @@
1
+ # Changelog
2
+
3
+ ## 0.7.0
4
+
5
+ ### Added
6
+
7
+ - `searchId` on `run()`: the `searchId` of the search that led to the call,
8
+ so Orthogonal can link the two. Optional; the server ignores a bad one.
9
+
10
+ ## 0.6.0
11
+
12
+ The SDK is now built and published from Orthogonal's monorepo.
13
+
14
+ ### Changed
15
+
16
+ - Calls go to `https://www.orthogonal.com` by default (was `https://api.orth.sh`,
17
+ which serves the same API). `baseUrl` or `ORTH_API_URL` picks another host.
18
+ - `RunResponse` describes what `/v1/run` answers: `priceCents`, `requestId`,
19
+ `billing` and `data`. `price` is optional; `/v1/run` sends it only on a dry run.
20
+
21
+ ### Added
22
+
23
+ - `method` on `run()`, for endpoints that take more than one HTTP method.
24
+ - `idempotencyKey` on `run()`: a retry with the same key runs and bills once.
25
+ - `baseUrl` on the constructor.
26
+ - `VERSION` export.
27
+
28
+ ### Fixed
29
+
30
+ - A non-JSON error answer (such as a gateway's HTML page) throws
31
+ `OrthogonalRunError` with its status and text instead of a JSON parse error.
32
+ - The `User-Agent` header carries the real SDK version.
33
+ - The 401 and 402 error messages link to the current account pages.
34
+
35
+ ## 0.5.1 and earlier
36
+
37
+ Released from the orthogonal-sh/orthogonal-typescript repository. 0.5.2 and
38
+ 0.5.3 changed only the README and were never published.
package/README.md CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  # Orthogonal SDK
4
4
 
5
- **Call any API on the [Orthogonal](https://orthogonal.com) platform from TypeScript — one client, one balance.**
5
+ **TypeScript SDK for calling APIs on the [Orthogonal](https://orthogonal.com) platform.**
6
6
 
7
- Reach hundreds of production APIs through a single client and a single credit balance. No per-provider signups, keys, or contracts — authentication, routing, and billing are handled for you.
7
+ Call any API on the Orthogonal platform through one client and one credit balance — authentication, routing, and billing are handled for you.
8
8
 
9
9
  [![npm version](https://img.shields.io/npm/v/@orth/sdk.svg?logo=npm&color=cb3837)](https://www.npmjs.com/package/@orth/sdk)
10
10
  [![npm downloads](https://img.shields.io/npm/dm/@orth/sdk.svg?color=cb3837)](https://www.npmjs.com/package/@orth/sdk)
@@ -29,7 +29,7 @@ Reach hundreds of production APIs through a single client and a single credit ba
29
29
 
30
30
  ## Why Orthogonal
31
31
 
32
- Orthogonal is a marketplace of production APIs behind one account and one balance:
32
+ Orthogonal puts a catalog of APIs behind one account and one balance:
33
33
 
34
34
  - **One integration** — call any API on the platform through a single `run()` method.
35
35
  - **Pay per use** — a single credit balance instead of juggling dozens of provider subscriptions.
@@ -38,7 +38,7 @@ Orthogonal is a marketplace of production APIs behind one account and one balanc
38
38
 
39
39
  ## Installation
40
40
 
41
- Requires **Node.js 18+**.
41
+ Requires **Node.js 18+** (or any runtime with `fetch`).
42
42
 
43
43
  ```bash
44
44
  npm install @orth/sdk
@@ -57,14 +57,15 @@ const orthogonal = new Orthogonal({
57
57
  const res = await orthogonal.run({
58
58
  api: "tavily",
59
59
  path: "/search",
60
- query: { query: "latest AI news" },
60
+ method: "POST",
61
+ body: { query: "latest AI news" },
61
62
  });
62
63
 
63
- console.log(res.data); // the upstream API's response
64
- console.log(res.price); // amount charged, e.g. "0.01"
64
+ console.log(res.data); // the upstream API's response
65
+ console.log(res.priceCents); // what the call cost, in US cents
65
66
  ```
66
67
 
67
- Get an API key from your [Orthogonal dashboard](https://orthogonal.com/dashboard).
68
+ Get an API key at [Account → Keys](https://www.orthogonal.com/account/keys).
68
69
 
69
70
  ## Authentication
70
71
 
@@ -102,6 +103,33 @@ const res = await orthogonal.run({
102
103
  });
103
104
  ```
104
105
 
106
+ ### Retry safely
107
+
108
+ Pass one `idempotencyKey` per logical call. A retry with the same key runs and
109
+ bills once; if the first attempt completed, the retry fails with status 409.
110
+
111
+ ```typescript
112
+ const res = await orthogonal.run({
113
+ api: "tavily",
114
+ path: "/search",
115
+ method: "POST",
116
+ body: { query: "latest AI news" },
117
+ idempotencyKey: crypto.randomUUID(),
118
+ });
119
+ ```
120
+
121
+ ### Another host
122
+
123
+ `baseUrl` (or the `ORTH_API_URL` environment variable, which the CLI reads
124
+ too) points the client at another Orthogonal deployment, e.g. a local server:
125
+
126
+ ```typescript
127
+ const orthogonal = new Orthogonal({
128
+ apiKey: process.env.ORTHOGONAL_API_KEY!,
129
+ baseUrl: "http://localhost:3000",
130
+ });
131
+ ```
132
+
105
133
  ### Custom headers
106
134
 
107
135
  Headers passed to the constructor are sent on every request:
@@ -146,6 +174,7 @@ On a contract violation the `orthogonal` hint tells you exactly what to fix —
146
174
  | --- | --- | --- |
147
175
  | `apiKey` | `string` | **Required.** Your Orthogonal API key (`orth_live_…` / `orth_test_…`). |
148
176
  | `headers` | `Record<string, string>` | Optional headers sent on every request. |
177
+ | `baseUrl` | `string` | Optional host. Default: `ORTH_API_URL`, else `https://www.orthogonal.com`. |
149
178
 
150
179
  ### `orthogonal.run(options)` → `Promise<RunResponse>`
151
180
 
@@ -153,15 +182,19 @@ On a contract violation the `orthogonal` hint tells you exactly what to fix —
153
182
  | --- | --- | --- |
154
183
  | `api` | `string` | **Required.** The API slug (e.g. `"tavily"`). |
155
184
  | `path` | `string` | **Required.** The endpoint path (e.g. `"/search"`). |
185
+ | `method` | `string` | HTTP method, when the endpoint takes more than one (e.g. `"POST"`). |
156
186
  | `query` | `Record<string, unknown>` | Query parameters. |
157
- | `body` | `Record<string, unknown>` | Request body for POST/PUT/PATCH. |
187
+ | `body` | `unknown` | Request body for POST/PUT/PATCH. |
188
+ | `idempotencyKey` | `string` | One per logical call; a retry with the same key runs and bills once. |
158
189
 
159
190
  **`RunResponse`**
160
191
 
161
192
  | Field | Type | Description |
162
193
  | --- | --- | --- |
163
194
  | `success` | `boolean` | Whether the call succeeded. |
164
- | `price` | `string` | Amount charged in USD (e.g. `"0.01"`). |
195
+ | `priceCents` | `number` | What the call cost, in US cents. |
196
+ | `requestId` | `string` | The call's id. |
197
+ | `billing` | `unknown` | Who paid and how much. |
165
198
  | `data` | `unknown` | The upstream API's response. |
166
199
 
167
200
  ### `OrthogonalRunError`
@@ -180,7 +213,8 @@ The package ships with type definitions and both ESM and CommonJS builds — no
180
213
 
181
214
  ## Related
182
215
 
183
- - **[`@orth/cli`](https://www.npmjs.com/package/@orth/cli)** — the Orthogonal command-line tool for discovering and calling APIs from your terminal.
216
+ - **[`@orth/cli`](https://www.npmjs.com/package/@orth/cli)** — the Orthogonal command-line tool.
217
+ - **[`orth`](https://pypi.org/project/orth/)** — the official Python SDK.
184
218
 
185
219
  ## License
186
220
 
@@ -0,0 +1,159 @@
1
+ /** Kept equal to package.json by tests/requests.test.ts. */
2
+ export const VERSION = "0.7.0";
3
+ const DEFAULT_BASE_URL = "https://www.orthogonal.com";
4
+ /** The host to call: the option, else ORTH_API_URL where a process exists. */
5
+ function resolveBaseUrl(baseUrl) {
6
+ // Browsers and edge runtimes have no process; read it without Node's types.
7
+ const env = globalThis
8
+ .process?.env;
9
+ const fromEnv = env?.ORTH_API_URL;
10
+ return (baseUrl || fromEnv || DEFAULT_BASE_URL)
11
+ .replace(/\/+$/, "")
12
+ .replace(/\/v1$/, "");
13
+ }
14
+ /**
15
+ * Coerce an error payload into a human-readable string.
16
+ *
17
+ * Upstream providers surface errors as structured objects (e.g. People Data Labs
18
+ * returns `{type: [...], message: "..."}`). Passing those to `new Error()` coerces
19
+ * to `"[object Object]"`, which is useless to SDK consumers. We prefer the most
20
+ * specific string field when present, and fall back to JSON so callers can still
21
+ * see the full payload.
22
+ */
23
+ function formatError(raw, status) {
24
+ if (raw == null)
25
+ return `Request failed with status ${status}`;
26
+ if (typeof raw === "string") {
27
+ return raw.length > 0 ? raw : `Request failed with status ${status}`;
28
+ }
29
+ if (typeof raw === "object") {
30
+ const obj = raw;
31
+ // Only use .message / .error if they are non-empty strings; otherwise fall
32
+ // through to JSON.stringify so callers still see the full payload.
33
+ if (typeof obj.message === "string" && obj.message.length > 0)
34
+ return obj.message;
35
+ if (typeof obj.error === "string" && obj.error.length > 0)
36
+ return obj.error;
37
+ try {
38
+ const json = JSON.stringify(raw);
39
+ // "{}" / "[]" / "null" aren't useful; fall back to the status message.
40
+ if (json && json !== "{}" && json !== "[]" && json !== "null")
41
+ return json;
42
+ return `Request failed with status ${status}`;
43
+ }
44
+ catch {
45
+ return `Request failed with status ${status}`;
46
+ }
47
+ }
48
+ return String(raw);
49
+ }
50
+ /**
51
+ * Error thrown by {@link Orthogonal.run} on a non-2xx response.
52
+ *
53
+ * Extends `Error` (so existing `catch (e) { e.message }` keeps working) but also
54
+ * carries the structured server payload. On a contract violation the API returns
55
+ * an `_orthogonal` self-correction hint (expected schema, unexpected/missing
56
+ * fields, numeric bounds) — exposed here as `orthogonal` so an agent can fix the
57
+ * request and retry instead of only seeing the terse message.
58
+ */
59
+ export class OrthogonalRunError extends Error {
60
+ constructor(message, opts) {
61
+ super(message);
62
+ this.name = "OrthogonalRunError";
63
+ this.status = opts.status;
64
+ this.orthogonal = opts.orthogonal;
65
+ this.responseBody = opts.responseBody;
66
+ // Restore the prototype chain for instanceof across the compiled target.
67
+ Object.setPrototypeOf(this, OrthogonalRunError.prototype);
68
+ }
69
+ }
70
+ /**
71
+ * Orthogonal SDK client
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * import Orthogonal from "@orth/sdk";
76
+ *
77
+ * const orthogonal = new Orthogonal({
78
+ * apiKey: process.env.ORTHOGONAL_API_KEY
79
+ * });
80
+ *
81
+ * const response = await orthogonal.run({
82
+ * api: "andi",
83
+ * path: "/api/v1/search",
84
+ * query: { q: "hello world" }
85
+ * });
86
+ *
87
+ * console.log(response.data);
88
+ * ```
89
+ */
90
+ export class Orthogonal {
91
+ constructor(config) {
92
+ if (!config.apiKey) {
93
+ throw new Error("Orthogonal API key is required");
94
+ }
95
+ this.apiKey = config.apiKey;
96
+ this.customHeaders = config.headers || {};
97
+ this.baseUrl = resolveBaseUrl(config.baseUrl);
98
+ }
99
+ /**
100
+ * Call any API on the Orthogonal platform
101
+ */
102
+ async run(options) {
103
+ const { api, path, method, query, body, idempotencyKey, searchId } = options;
104
+ const response = await fetch(`${this.baseUrl}/v1/run`, {
105
+ method: "POST",
106
+ headers: {
107
+ Authorization: `Bearer ${this.apiKey}`,
108
+ "Content-Type": "application/json",
109
+ "User-Agent": `@orth/sdk/${VERSION}`,
110
+ "X-Orthogonal-Source": "sdk",
111
+ ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
112
+ ...this.customHeaders,
113
+ },
114
+ body: JSON.stringify({ api, path, method, query, body, searchId }),
115
+ });
116
+ // A proxy or gateway error can answer with HTML: keep its text.
117
+ const text = await response.text();
118
+ let data;
119
+ try {
120
+ data = text ? JSON.parse(text) : {};
121
+ }
122
+ catch {
123
+ data = { error: text.slice(0, 500) };
124
+ }
125
+ if (!response.ok) {
126
+ const orthogonal = data?._orthogonal;
127
+ // Provide helpful error messages for common cases
128
+ if (response.status === 401) {
129
+ throw new OrthogonalRunError("Invalid API key. Create one at https://www.orthogonal.com/account/keys", { status: 401, orthogonal, responseBody: data });
130
+ }
131
+ if (response.status === 402) {
132
+ // 402 now covers several distinct cases: insufficient credits, a per-key
133
+ // daily spend limit, and an account-wide daily spend limit. Surface the
134
+ // server's specific message when it provided one so callers know which
135
+ // applies. We test `rawError` directly (not formatError's output) so a
136
+ // real message that happens to start with "Request failed" isn't mistaken
137
+ // for the no-message fallback.
138
+ const rawError = data.data?.error || data.error;
139
+ const hasServerMessage = rawError !== undefined && rawError !== null && rawError !== "";
140
+ throw new OrthogonalRunError(hasServerMessage
141
+ ? formatError(rawError, response.status)
142
+ : "Insufficient credits. Add credits at https://www.orthogonal.com/account/add-funds", { status: 402, orthogonal, responseBody: data });
143
+ }
144
+ // Check for nested error in data.error (e.g., from target API). Use `||`
145
+ // (not `??`) so that falsy values like `""` still fall through the chain
146
+ // to the status-based fallback inside `formatError`.
147
+ const rawError = data.data?.error || data.error;
148
+ const errorMessage = formatError(rawError, response.status);
149
+ throw new OrthogonalRunError(errorMessage, {
150
+ status: response.status,
151
+ orthogonal,
152
+ responseBody: data,
153
+ });
154
+ }
155
+ return data;
156
+ }
157
+ }
158
+ // Default export
159
+ export default Orthogonal;
@@ -0,0 +1 @@
1
+ {"type":"module"}
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,37 +1,6 @@
1
- /**
2
- * Configuration options for the Orthogonal client
3
- */
4
- interface OrthogonalConfig {
5
- /** Your Orthogonal API key (starts with orth_live_ or orth_test_) */
6
- apiKey: string;
7
- /** Custom headers to include in all requests */
8
- headers?: Record<string, string>;
9
- }
10
- /**
11
- * Options for the run() method
12
- */
13
- interface RunOptions {
14
- /** The API slug (e.g., "andi", "weather-api") */
15
- api: string;
16
- /** The endpoint path (e.g., "/api/v1/search") */
17
- path: string;
18
- /** Query parameters to pass to the endpoint */
19
- query?: Record<string, unknown>;
20
- /** Request body for POST/PUT/PATCH requests */
21
- body?: Record<string, unknown>;
22
- }
23
- /**
24
- * Response from the run() method
25
- */
26
- interface RunResponse {
27
- /** Whether the request was successful */
28
- success: boolean;
29
- /** The price paid in USD (e.g., "0.01") */
30
- price: string;
31
- /** The response data from the target API */
32
- data: unknown;
33
- }
34
-
1
+ import type { OrthogonalConfig, RunOptions, RunResponse } from "./types";
2
+ /** Kept equal to package.json by tests/requests.test.ts. */
3
+ export declare const VERSION = "0.7.0";
35
4
  /**
36
5
  * Error thrown by {@link Orthogonal.run} on a non-2xx response.
37
6
  *
@@ -41,7 +10,7 @@ interface RunResponse {
41
10
  * fields, numeric bounds) — exposed here as `orthogonal` so an agent can fix the
42
11
  * request and retry instead of only seeing the terse message.
43
12
  */
44
- declare class OrthogonalRunError extends Error {
13
+ export declare class OrthogonalRunError extends Error {
45
14
  /** HTTP status of the failed response. */
46
15
  status: number;
47
16
  /** The API's `_orthogonal` self-correction hint, when present. */
@@ -74,14 +43,15 @@ declare class OrthogonalRunError extends Error {
74
43
  * console.log(response.data);
75
44
  * ```
76
45
  */
77
- declare class Orthogonal {
46
+ export declare class Orthogonal {
78
47
  private apiKey;
79
48
  private customHeaders;
49
+ private baseUrl;
80
50
  constructor(config: OrthogonalConfig);
81
51
  /**
82
52
  * Call any API on the Orthogonal platform
83
53
  */
84
54
  run(options: RunOptions): Promise<RunResponse>;
85
55
  }
86
-
87
- export { Orthogonal, type OrthogonalConfig, OrthogonalRunError, type RunOptions, type RunResponse, Orthogonal as default };
56
+ export type * from "./types";
57
+ export default Orthogonal;
package/dist/index.js CHANGED
@@ -1,117 +1,164 @@
1
1
  "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- Orthogonal: () => Orthogonal,
24
- OrthogonalRunError: () => OrthogonalRunError,
25
- default: () => index_default
26
- });
27
- module.exports = __toCommonJS(index_exports);
28
- var VERSION = "0.1.0";
29
- var BASE_URL = "https://api.orth.sh";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Orthogonal = exports.OrthogonalRunError = exports.VERSION = void 0;
4
+ /** Kept equal to package.json by tests/requests.test.ts. */
5
+ exports.VERSION = "0.7.0";
6
+ const DEFAULT_BASE_URL = "https://www.orthogonal.com";
7
+ /** The host to call: the option, else ORTH_API_URL where a process exists. */
8
+ function resolveBaseUrl(baseUrl) {
9
+ // Browsers and edge runtimes have no process; read it without Node's types.
10
+ const env = globalThis
11
+ .process?.env;
12
+ const fromEnv = env?.ORTH_API_URL;
13
+ return (baseUrl || fromEnv || DEFAULT_BASE_URL)
14
+ .replace(/\/+$/, "")
15
+ .replace(/\/v1$/, "");
16
+ }
17
+ /**
18
+ * Coerce an error payload into a human-readable string.
19
+ *
20
+ * Upstream providers surface errors as structured objects (e.g. People Data Labs
21
+ * returns `{type: [...], message: "..."}`). Passing those to `new Error()` coerces
22
+ * to `"[object Object]"`, which is useless to SDK consumers. We prefer the most
23
+ * specific string field when present, and fall back to JSON so callers can still
24
+ * see the full payload.
25
+ */
30
26
  function formatError(raw, status) {
31
- if (raw == null) return `Request failed with status ${status}`;
32
- if (typeof raw === "string") {
33
- return raw.length > 0 ? raw : `Request failed with status ${status}`;
34
- }
35
- if (typeof raw === "object") {
36
- const obj = raw;
37
- if (typeof obj.message === "string" && obj.message.length > 0) return obj.message;
38
- if (typeof obj.error === "string" && obj.error.length > 0) return obj.error;
39
- try {
40
- const json = JSON.stringify(raw);
41
- if (json && json !== "{}" && json !== "[]" && json !== "null") return json;
42
- return `Request failed with status ${status}`;
43
- } catch {
44
- return `Request failed with status ${status}`;
27
+ if (raw == null)
28
+ return `Request failed with status ${status}`;
29
+ if (typeof raw === "string") {
30
+ return raw.length > 0 ? raw : `Request failed with status ${status}`;
31
+ }
32
+ if (typeof raw === "object") {
33
+ const obj = raw;
34
+ // Only use .message / .error if they are non-empty strings; otherwise fall
35
+ // through to JSON.stringify so callers still see the full payload.
36
+ if (typeof obj.message === "string" && obj.message.length > 0)
37
+ return obj.message;
38
+ if (typeof obj.error === "string" && obj.error.length > 0)
39
+ return obj.error;
40
+ try {
41
+ const json = JSON.stringify(raw);
42
+ // "{}" / "[]" / "null" aren't useful; fall back to the status message.
43
+ if (json && json !== "{}" && json !== "[]" && json !== "null")
44
+ return json;
45
+ return `Request failed with status ${status}`;
46
+ }
47
+ catch {
48
+ return `Request failed with status ${status}`;
49
+ }
45
50
  }
46
- }
47
- return String(raw);
51
+ return String(raw);
48
52
  }
49
- var OrthogonalRunError = class _OrthogonalRunError extends Error {
50
- constructor(message, opts) {
51
- super(message);
52
- this.name = "OrthogonalRunError";
53
- this.status = opts.status;
54
- this.orthogonal = opts.orthogonal;
55
- this.responseBody = opts.responseBody;
56
- Object.setPrototypeOf(this, _OrthogonalRunError.prototype);
57
- }
58
- };
59
- var Orthogonal = class {
60
- constructor(config) {
61
- if (!config.apiKey) {
62
- throw new Error("Orthogonal API key is required");
53
+ /**
54
+ * Error thrown by {@link Orthogonal.run} on a non-2xx response.
55
+ *
56
+ * Extends `Error` (so existing `catch (e) { e.message }` keeps working) but also
57
+ * carries the structured server payload. On a contract violation the API returns
58
+ * an `_orthogonal` self-correction hint (expected schema, unexpected/missing
59
+ * fields, numeric bounds) — exposed here as `orthogonal` so an agent can fix the
60
+ * request and retry instead of only seeing the terse message.
61
+ */
62
+ class OrthogonalRunError extends Error {
63
+ constructor(message, opts) {
64
+ super(message);
65
+ this.name = "OrthogonalRunError";
66
+ this.status = opts.status;
67
+ this.orthogonal = opts.orthogonal;
68
+ this.responseBody = opts.responseBody;
69
+ // Restore the prototype chain for instanceof across the compiled target.
70
+ Object.setPrototypeOf(this, OrthogonalRunError.prototype);
63
71
  }
64
- this.apiKey = config.apiKey;
65
- this.customHeaders = config.headers || {};
66
- }
67
- /**
68
- * Call any API on the Orthogonal platform
69
- */
70
- async run(options) {
71
- const { api, path, query, body } = options;
72
- const response = await fetch(`${BASE_URL}/v1/run`, {
73
- method: "POST",
74
- headers: {
75
- Authorization: `Bearer ${this.apiKey}`,
76
- "Content-Type": "application/json",
77
- "User-Agent": `@orth/sdk/${VERSION}`,
78
- "X-Orthogonal-Source": "sdk",
79
- ...this.customHeaders
80
- },
81
- body: JSON.stringify({ api, path, query, body })
82
- });
83
- const data = await response.json();
84
- if (!response.ok) {
85
- const orthogonal = data?._orthogonal;
86
- if (response.status === 401) {
87
- throw new OrthogonalRunError(
88
- "Invalid API key. Visit https://orthogonal.com to get one!",
89
- { status: 401, orthogonal, responseBody: data }
90
- );
91
- }
92
- if (response.status === 402) {
93
- const rawError2 = data.data?.error || data.error;
94
- const hasServerMessage = rawError2 !== void 0 && rawError2 !== null && rawError2 !== "";
95
- throw new OrthogonalRunError(
96
- hasServerMessage ? formatError(rawError2, response.status) : "Insufficient credits. Top up your balance at https://www.orthogonal.com/dashboard/balance",
97
- { status: 402, orthogonal, responseBody: data }
98
- );
99
- }
100
- const rawError = data.data?.error || data.error;
101
- const errorMessage = formatError(rawError, response.status);
102
- throw new OrthogonalRunError(errorMessage, {
103
- status: response.status,
104
- orthogonal,
105
- responseBody: data
106
- });
72
+ }
73
+ exports.OrthogonalRunError = OrthogonalRunError;
74
+ /**
75
+ * Orthogonal SDK client
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * import Orthogonal from "@orth/sdk";
80
+ *
81
+ * const orthogonal = new Orthogonal({
82
+ * apiKey: process.env.ORTHOGONAL_API_KEY
83
+ * });
84
+ *
85
+ * const response = await orthogonal.run({
86
+ * api: "andi",
87
+ * path: "/api/v1/search",
88
+ * query: { q: "hello world" }
89
+ * });
90
+ *
91
+ * console.log(response.data);
92
+ * ```
93
+ */
94
+ class Orthogonal {
95
+ constructor(config) {
96
+ if (!config.apiKey) {
97
+ throw new Error("Orthogonal API key is required");
98
+ }
99
+ this.apiKey = config.apiKey;
100
+ this.customHeaders = config.headers || {};
101
+ this.baseUrl = resolveBaseUrl(config.baseUrl);
107
102
  }
108
- return data;
109
- }
110
- };
111
- var index_default = Orthogonal;
112
- // Annotate the CommonJS export names for ESM import in node:
113
- 0 && (module.exports = {
114
- Orthogonal,
115
- OrthogonalRunError
116
- });
117
- //# sourceMappingURL=index.js.map
103
+ /**
104
+ * Call any API on the Orthogonal platform
105
+ */
106
+ async run(options) {
107
+ const { api, path, method, query, body, idempotencyKey, searchId } = options;
108
+ const response = await fetch(`${this.baseUrl}/v1/run`, {
109
+ method: "POST",
110
+ headers: {
111
+ Authorization: `Bearer ${this.apiKey}`,
112
+ "Content-Type": "application/json",
113
+ "User-Agent": `@orth/sdk/${exports.VERSION}`,
114
+ "X-Orthogonal-Source": "sdk",
115
+ ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
116
+ ...this.customHeaders,
117
+ },
118
+ body: JSON.stringify({ api, path, method, query, body, searchId }),
119
+ });
120
+ // A proxy or gateway error can answer with HTML: keep its text.
121
+ const text = await response.text();
122
+ let data;
123
+ try {
124
+ data = text ? JSON.parse(text) : {};
125
+ }
126
+ catch {
127
+ data = { error: text.slice(0, 500) };
128
+ }
129
+ if (!response.ok) {
130
+ const orthogonal = data?._orthogonal;
131
+ // Provide helpful error messages for common cases
132
+ if (response.status === 401) {
133
+ throw new OrthogonalRunError("Invalid API key. Create one at https://www.orthogonal.com/account/keys", { status: 401, orthogonal, responseBody: data });
134
+ }
135
+ if (response.status === 402) {
136
+ // 402 now covers several distinct cases: insufficient credits, a per-key
137
+ // daily spend limit, and an account-wide daily spend limit. Surface the
138
+ // server's specific message when it provided one so callers know which
139
+ // applies. We test `rawError` directly (not formatError's output) so a
140
+ // real message that happens to start with "Request failed" isn't mistaken
141
+ // for the no-message fallback.
142
+ const rawError = data.data?.error || data.error;
143
+ const hasServerMessage = rawError !== undefined && rawError !== null && rawError !== "";
144
+ throw new OrthogonalRunError(hasServerMessage
145
+ ? formatError(rawError, response.status)
146
+ : "Insufficient credits. Add credits at https://www.orthogonal.com/account/add-funds", { status: 402, orthogonal, responseBody: data });
147
+ }
148
+ // Check for nested error in data.error (e.g., from target API). Use `||`
149
+ // (not `??`) so that falsy values like `""` still fall through the chain
150
+ // to the status-based fallback inside `formatError`.
151
+ const rawError = data.data?.error || data.error;
152
+ const errorMessage = formatError(rawError, response.status);
153
+ throw new OrthogonalRunError(errorMessage, {
154
+ status: response.status,
155
+ orthogonal,
156
+ responseBody: data,
157
+ });
158
+ }
159
+ return data;
160
+ }
161
+ }
162
+ exports.Orthogonal = Orthogonal;
163
+ // Default export
164
+ exports.default = Orthogonal;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Configuration options for the Orthogonal client
3
+ */
4
+ export interface OrthogonalConfig {
5
+ /** Your Orthogonal API key (starts with orth_live_ or orth_test_) */
6
+ apiKey: string;
7
+ /** Custom headers to include in all requests */
8
+ headers?: Record<string, string>;
9
+ /**
10
+ * The Orthogonal host to call. Default: ORTH_API_URL when set, else
11
+ * https://www.orthogonal.com.
12
+ */
13
+ baseUrl?: string;
14
+ }
15
+ /**
16
+ * Options for the run() method
17
+ */
18
+ export interface RunOptions {
19
+ /** The API slug (e.g., "andi", "weather-api") */
20
+ api: string;
21
+ /** The endpoint path (e.g., "/api/v1/search") */
22
+ path: string;
23
+ /** The HTTP method, when the endpoint takes more than one (e.g., "POST") */
24
+ method?: string;
25
+ /** Query parameters to pass to the endpoint */
26
+ query?: Record<string, unknown>;
27
+ /** Request body for POST/PUT/PATCH requests */
28
+ body?: unknown;
29
+ /**
30
+ * One per logical call: a retry with the same key runs and bills once
31
+ * (sent as the Idempotency-Key header).
32
+ */
33
+ idempotencyKey?: string;
34
+ /**
35
+ * The `searchId` of the search (/v1/search, MCP search) that led to this
36
+ * call. Optional: it links the call to that search, and the server ignores
37
+ * a missing or malformed one.
38
+ */
39
+ searchId?: string;
40
+ }
41
+ /**
42
+ * Response from the run() method
43
+ */
44
+ export interface RunResponse {
45
+ /** Whether the request was successful */
46
+ success: boolean;
47
+ /** What the call cost, in US cents (e.g., 1 for $0.01) */
48
+ priceCents?: number;
49
+ /** The price as text (e.g., "$0.01"), on answers that carry it */
50
+ price?: string;
51
+ /** The call's id: keep it to look the call up or to report it */
52
+ requestId?: string;
53
+ /** Who paid and how much, as the server reports it */
54
+ billing?: unknown;
55
+ /** The response data from the target API */
56
+ data: unknown;
57
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,27 +1,26 @@
1
1
  {
2
2
  "name": "@orth/sdk",
3
- "version": "0.5.1",
3
+ "version": "0.7.0",
4
4
  "description": "TypeScript SDK to call any API on the Orthogonal platform",
5
5
  "main": "dist/index.js",
6
- "module": "dist/index.mjs",
7
6
  "types": "dist/index.d.ts",
8
7
  "exports": {
9
8
  ".": {
10
9
  "types": "./dist/index.d.ts",
11
- "import": "./dist/index.mjs",
10
+ "import": "./dist/esm/index.js",
12
11
  "require": "./dist/index.js"
13
12
  }
14
13
  },
15
14
  "files": [
16
15
  "dist",
17
16
  "README.md",
17
+ "CHANGELOG.md",
18
18
  "LICENSE"
19
19
  ],
20
20
  "sideEffects": false,
21
21
  "scripts": {
22
- "build": "tsup",
23
- "test": "vitest",
24
- "prepublishOnly": "npm run build"
22
+ "build": "node ../../scripts/local-run.mjs heavy sh -c \"rm -rf dist && tsc -p tsconfig.json && tsc -p tsconfig.esm.json && echo {\\\\\\\"type\\\\\\\":\\\\\\\"module\\\\\\\"} > dist/esm/package.json\"",
23
+ "test": "node ../../scripts/local-run.mjs heavy vitest run"
25
24
  },
26
25
  "keywords": [
27
26
  "orthogonal",
@@ -35,19 +34,22 @@
35
34
  "license": "MIT",
36
35
  "repository": {
37
36
  "type": "git",
38
- "url": "https://github.com/orthogonal-sh/orthogonal-typescript.git"
37
+ "url": "git+https://github.com/orthogonal-sh/mono-repo.git",
38
+ "directory": "packages/sdk"
39
39
  },
40
- "homepage": "https://orthogonal.sh",
40
+ "homepage": "https://www.orthogonal.com",
41
41
  "bugs": {
42
- "url": "https://github.com/orthogonal-sh/orthogonal-typescript/issues"
42
+ "url": "https://github.com/orthogonal-sh/mono-repo/issues"
43
43
  },
44
44
  "engines": {
45
45
  "node": ">=18"
46
46
  },
47
47
  "devDependencies": {
48
- "tsup": "^8.0.0",
49
- "tsx": "^4.21.0",
50
- "typescript": "^5.0.0",
51
- "vitest": "^1.0.0"
48
+ "typescript": "^7.0.2",
49
+ "vitest": "^5.1.0"
50
+ },
51
+ "private": false,
52
+ "publishConfig": {
53
+ "access": "public"
52
54
  }
53
55
  }
package/dist/index.d.mts DELETED
@@ -1,87 +0,0 @@
1
- /**
2
- * Configuration options for the Orthogonal client
3
- */
4
- interface OrthogonalConfig {
5
- /** Your Orthogonal API key (starts with orth_live_ or orth_test_) */
6
- apiKey: string;
7
- /** Custom headers to include in all requests */
8
- headers?: Record<string, string>;
9
- }
10
- /**
11
- * Options for the run() method
12
- */
13
- interface RunOptions {
14
- /** The API slug (e.g., "andi", "weather-api") */
15
- api: string;
16
- /** The endpoint path (e.g., "/api/v1/search") */
17
- path: string;
18
- /** Query parameters to pass to the endpoint */
19
- query?: Record<string, unknown>;
20
- /** Request body for POST/PUT/PATCH requests */
21
- body?: Record<string, unknown>;
22
- }
23
- /**
24
- * Response from the run() method
25
- */
26
- interface RunResponse {
27
- /** Whether the request was successful */
28
- success: boolean;
29
- /** The price paid in USD (e.g., "0.01") */
30
- price: string;
31
- /** The response data from the target API */
32
- data: unknown;
33
- }
34
-
35
- /**
36
- * Error thrown by {@link Orthogonal.run} on a non-2xx response.
37
- *
38
- * Extends `Error` (so existing `catch (e) { e.message }` keeps working) but also
39
- * carries the structured server payload. On a contract violation the API returns
40
- * an `_orthogonal` self-correction hint (expected schema, unexpected/missing
41
- * fields, numeric bounds) — exposed here as `orthogonal` so an agent can fix the
42
- * request and retry instead of only seeing the terse message.
43
- */
44
- declare class OrthogonalRunError extends Error {
45
- /** HTTP status of the failed response. */
46
- status: number;
47
- /** The API's `_orthogonal` self-correction hint, when present. */
48
- orthogonal?: unknown;
49
- /** The full parsed response body. */
50
- responseBody?: unknown;
51
- constructor(message: string, opts: {
52
- status: number;
53
- orthogonal?: unknown;
54
- responseBody?: unknown;
55
- });
56
- }
57
- /**
58
- * Orthogonal SDK client
59
- *
60
- * @example
61
- * ```typescript
62
- * import Orthogonal from "@orth/sdk";
63
- *
64
- * const orthogonal = new Orthogonal({
65
- * apiKey: process.env.ORTHOGONAL_API_KEY
66
- * });
67
- *
68
- * const response = await orthogonal.run({
69
- * api: "andi",
70
- * path: "/api/v1/search",
71
- * query: { q: "hello world" }
72
- * });
73
- *
74
- * console.log(response.data);
75
- * ```
76
- */
77
- declare class Orthogonal {
78
- private apiKey;
79
- private customHeaders;
80
- constructor(config: OrthogonalConfig);
81
- /**
82
- * Call any API on the Orthogonal platform
83
- */
84
- run(options: RunOptions): Promise<RunResponse>;
85
- }
86
-
87
- export { Orthogonal, type OrthogonalConfig, OrthogonalRunError, type RunOptions, type RunResponse, Orthogonal as default };
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { OrthogonalConfig, RunOptions, RunResponse } from \"./types\";\n\nconst VERSION = \"0.1.0\";\nconst BASE_URL = \"https://api.orth.sh\";\n\n/**\n * Coerce an error payload into a human-readable string.\n *\n * Upstream providers surface errors as structured objects (e.g. People Data Labs\n * returns `{type: [...], message: \"...\"}`). Passing those to `new Error()` coerces\n * to `\"[object Object]\"`, which is useless to SDK consumers. We prefer the most\n * specific string field when present, and fall back to JSON so callers can still\n * see the full payload.\n */\nfunction formatError(raw: unknown, status: number): string {\n if (raw == null) return `Request failed with status ${status}`;\n if (typeof raw === \"string\") {\n return raw.length > 0 ? raw : `Request failed with status ${status}`;\n }\n if (typeof raw === \"object\") {\n const obj = raw as Record<string, unknown>;\n // Only use .message / .error if they are non-empty strings; otherwise fall\n // through to JSON.stringify so callers still see the full payload.\n if (typeof obj.message === \"string\" && obj.message.length > 0) return obj.message;\n if (typeof obj.error === \"string\" && obj.error.length > 0) return obj.error;\n try {\n const json = JSON.stringify(raw);\n // \"{}\" / \"[]\" / \"null\" aren't useful; fall back to the status message.\n if (json && json !== \"{}\" && json !== \"[]\" && json !== \"null\") return json;\n return `Request failed with status ${status}`;\n } catch {\n return `Request failed with status ${status}`;\n }\n }\n return String(raw);\n}\n\n/**\n * Error thrown by {@link Orthogonal.run} on a non-2xx response.\n *\n * Extends `Error` (so existing `catch (e) { e.message }` keeps working) but also\n * carries the structured server payload. On a contract violation the API returns\n * an `_orthogonal` self-correction hint (expected schema, unexpected/missing\n * fields, numeric bounds) — exposed here as `orthogonal` so an agent can fix the\n * request and retry instead of only seeing the terse message.\n */\nexport class OrthogonalRunError extends Error {\n /** HTTP status of the failed response. */\n status: number;\n /** The API's `_orthogonal` self-correction hint, when present. */\n orthogonal?: unknown;\n /** The full parsed response body. */\n responseBody?: unknown;\n\n constructor(\n message: string,\n opts: { status: number; orthogonal?: unknown; responseBody?: unknown },\n ) {\n super(message);\n this.name = \"OrthogonalRunError\";\n this.status = opts.status;\n this.orthogonal = opts.orthogonal;\n this.responseBody = opts.responseBody;\n // Restore the prototype chain for instanceof across the compiled target.\n Object.setPrototypeOf(this, OrthogonalRunError.prototype);\n }\n}\n\n/**\n * Orthogonal SDK client\n *\n * @example\n * ```typescript\n * import Orthogonal from \"@orth/sdk\";\n *\n * const orthogonal = new Orthogonal({\n * apiKey: process.env.ORTHOGONAL_API_KEY\n * });\n *\n * const response = await orthogonal.run({\n * api: \"andi\",\n * path: \"/api/v1/search\",\n * query: { q: \"hello world\" }\n * });\n *\n * console.log(response.data);\n * ```\n */\nexport class Orthogonal {\n private apiKey: string;\n private customHeaders: Record<string, string>;\n\n constructor(config: OrthogonalConfig) {\n if (!config.apiKey) {\n throw new Error(\"Orthogonal API key is required\");\n }\n this.apiKey = config.apiKey;\n this.customHeaders = config.headers || {};\n }\n\n /**\n * Call any API on the Orthogonal platform\n */\n async run(options: RunOptions): Promise<RunResponse> {\n const { api, path, query, body } = options;\n\n const response = await fetch(`${BASE_URL}/v1/run`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n \"User-Agent\": `@orth/sdk/${VERSION}`,\n \"X-Orthogonal-Source\": \"sdk\",\n ...this.customHeaders,\n },\n body: JSON.stringify({ api, path, query, body }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n const orthogonal = (data as any)?._orthogonal;\n // Provide helpful error messages for common cases\n if (response.status === 401) {\n throw new OrthogonalRunError(\n \"Invalid API key. Visit https://orthogonal.com to get one!\",\n { status: 401, orthogonal, responseBody: data },\n );\n }\n if (response.status === 402) {\n // 402 now covers several distinct cases: insufficient credits, a per-key\n // daily spend limit, and an account-wide daily spend limit. Surface the\n // server's specific message when it provided one so callers know which\n // applies. We test `rawError` directly (not formatError's output) so a\n // real message that happens to start with \"Request failed\" isn't mistaken\n // for the no-message fallback.\n const rawError = data.data?.error || data.error;\n const hasServerMessage =\n rawError !== undefined && rawError !== null && rawError !== \"\";\n throw new OrthogonalRunError(\n hasServerMessage\n ? formatError(rawError, response.status)\n : \"Insufficient credits. Top up your balance at https://www.orthogonal.com/dashboard/balance\",\n { status: 402, orthogonal, responseBody: data },\n );\n }\n // Check for nested error in data.error (e.g., from target API). Use `||`\n // (not `??`) so that falsy values like `\"\"` still fall through the chain\n // to the status-based fallback inside `formatError`.\n const rawError = data.data?.error || data.error;\n const errorMessage = formatError(rawError, response.status);\n throw new OrthogonalRunError(errorMessage, {\n status: response.status,\n orthogonal,\n responseBody: data,\n });\n }\n\n return data as RunResponse;\n }\n}\n\n// Export types\nexport * from \"./types\";\n\n// Default export\nexport default Orthogonal;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,IAAM,UAAU;AAChB,IAAM,WAAW;AAWjB,SAAS,YAAY,KAAc,QAAwB;AACzD,MAAI,OAAO,KAAM,QAAO,8BAA8B,MAAM;AAC5D,MAAI,OAAO,QAAQ,UAAU;AAC3B,WAAO,IAAI,SAAS,IAAI,MAAM,8BAA8B,MAAM;AAAA,EACpE;AACA,MAAI,OAAO,QAAQ,UAAU;AAC3B,UAAM,MAAM;AAGZ,QAAI,OAAO,IAAI,YAAY,YAAY,IAAI,QAAQ,SAAS,EAAG,QAAO,IAAI;AAC1E,QAAI,OAAO,IAAI,UAAU,YAAY,IAAI,MAAM,SAAS,EAAG,QAAO,IAAI;AACtE,QAAI;AACF,YAAM,OAAO,KAAK,UAAU,GAAG;AAE/B,UAAI,QAAQ,SAAS,QAAQ,SAAS,QAAQ,SAAS,OAAQ,QAAO;AACtE,aAAO,8BAA8B,MAAM;AAAA,IAC7C,QAAQ;AACN,aAAO,8BAA8B,MAAM;AAAA,IAC7C;AAAA,EACF;AACA,SAAO,OAAO,GAAG;AACnB;AAWO,IAAM,qBAAN,MAAM,4BAA2B,MAAM;AAAA,EAQ5C,YACE,SACA,MACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,KAAK;AACnB,SAAK,aAAa,KAAK;AACvB,SAAK,eAAe,KAAK;AAEzB,WAAO,eAAe,MAAM,oBAAmB,SAAS;AAAA,EAC1D;AACF;AAsBO,IAAM,aAAN,MAAiB;AAAA,EAItB,YAAY,QAA0B;AACpC,QAAI,CAAC,OAAO,QAAQ;AAClB,YAAM,IAAI,MAAM,gCAAgC;AAAA,IAClD;AACA,SAAK,SAAS,OAAO;AACrB,SAAK,gBAAgB,OAAO,WAAW,CAAC;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,IAAI,SAA2C;AACnD,UAAM,EAAE,KAAK,MAAM,OAAO,KAAK,IAAI;AAEnC,UAAM,WAAW,MAAM,MAAM,GAAG,QAAQ,WAAW;AAAA,MACjD,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,eAAe,UAAU,KAAK,MAAM;AAAA,QACpC,gBAAgB;AAAA,QAChB,cAAc,aAAa,OAAO;AAAA,QAClC,uBAAuB;AAAA,QACvB,GAAG,KAAK;AAAA,MACV;AAAA,MACA,MAAM,KAAK,UAAU,EAAE,KAAK,MAAM,OAAO,KAAK,CAAC;AAAA,IACjD,CAAC;AAED,UAAM,OAAO,MAAM,SAAS,KAAK;AAEjC,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,aAAc,MAAc;AAElC,UAAI,SAAS,WAAW,KAAK;AAC3B,cAAM,IAAI;AAAA,UACR;AAAA,UACA,EAAE,QAAQ,KAAK,YAAY,cAAc,KAAK;AAAA,QAChD;AAAA,MACF;AACA,UAAI,SAAS,WAAW,KAAK;AAO3B,cAAMA,YAAW,KAAK,MAAM,SAAS,KAAK;AAC1C,cAAM,mBACJA,cAAa,UAAaA,cAAa,QAAQA,cAAa;AAC9D,cAAM,IAAI;AAAA,UACR,mBACI,YAAYA,WAAU,SAAS,MAAM,IACrC;AAAA,UACJ,EAAE,QAAQ,KAAK,YAAY,cAAc,KAAK;AAAA,QAChD;AAAA,MACF;AAIA,YAAM,WAAW,KAAK,MAAM,SAAS,KAAK;AAC1C,YAAM,eAAe,YAAY,UAAU,SAAS,MAAM;AAC1D,YAAM,IAAI,mBAAmB,cAAc;AAAA,QACzC,QAAQ,SAAS;AAAA,QACjB;AAAA,QACA,cAAc;AAAA,MAChB,CAAC;AAAA,IACH;AAEA,WAAO;AAAA,EACT;AACF;AAMA,IAAO,gBAAQ;","names":["rawError"]}
package/dist/index.mjs DELETED
@@ -1,91 +0,0 @@
1
- // src/index.ts
2
- var VERSION = "0.1.0";
3
- var BASE_URL = "https://api.orth.sh";
4
- function formatError(raw, status) {
5
- if (raw == null) return `Request failed with status ${status}`;
6
- if (typeof raw === "string") {
7
- return raw.length > 0 ? raw : `Request failed with status ${status}`;
8
- }
9
- if (typeof raw === "object") {
10
- const obj = raw;
11
- if (typeof obj.message === "string" && obj.message.length > 0) return obj.message;
12
- if (typeof obj.error === "string" && obj.error.length > 0) return obj.error;
13
- try {
14
- const json = JSON.stringify(raw);
15
- if (json && json !== "{}" && json !== "[]" && json !== "null") return json;
16
- return `Request failed with status ${status}`;
17
- } catch {
18
- return `Request failed with status ${status}`;
19
- }
20
- }
21
- return String(raw);
22
- }
23
- var OrthogonalRunError = class _OrthogonalRunError extends Error {
24
- constructor(message, opts) {
25
- super(message);
26
- this.name = "OrthogonalRunError";
27
- this.status = opts.status;
28
- this.orthogonal = opts.orthogonal;
29
- this.responseBody = opts.responseBody;
30
- Object.setPrototypeOf(this, _OrthogonalRunError.prototype);
31
- }
32
- };
33
- var Orthogonal = class {
34
- constructor(config) {
35
- if (!config.apiKey) {
36
- throw new Error("Orthogonal API key is required");
37
- }
38
- this.apiKey = config.apiKey;
39
- this.customHeaders = config.headers || {};
40
- }
41
- /**
42
- * Call any API on the Orthogonal platform
43
- */
44
- async run(options) {
45
- const { api, path, query, body } = options;
46
- const response = await fetch(`${BASE_URL}/v1/run`, {
47
- method: "POST",
48
- headers: {
49
- Authorization: `Bearer ${this.apiKey}`,
50
- "Content-Type": "application/json",
51
- "User-Agent": `@orth/sdk/${VERSION}`,
52
- "X-Orthogonal-Source": "sdk",
53
- ...this.customHeaders
54
- },
55
- body: JSON.stringify({ api, path, query, body })
56
- });
57
- const data = await response.json();
58
- if (!response.ok) {
59
- const orthogonal = data?._orthogonal;
60
- if (response.status === 401) {
61
- throw new OrthogonalRunError(
62
- "Invalid API key. Visit https://orthogonal.com to get one!",
63
- { status: 401, orthogonal, responseBody: data }
64
- );
65
- }
66
- if (response.status === 402) {
67
- const rawError2 = data.data?.error || data.error;
68
- const hasServerMessage = rawError2 !== void 0 && rawError2 !== null && rawError2 !== "";
69
- throw new OrthogonalRunError(
70
- hasServerMessage ? formatError(rawError2, response.status) : "Insufficient credits. Top up your balance at https://www.orthogonal.com/dashboard/balance",
71
- { status: 402, orthogonal, responseBody: data }
72
- );
73
- }
74
- const rawError = data.data?.error || data.error;
75
- const errorMessage = formatError(rawError, response.status);
76
- throw new OrthogonalRunError(errorMessage, {
77
- status: response.status,
78
- orthogonal,
79
- responseBody: data
80
- });
81
- }
82
- return data;
83
- }
84
- };
85
- var index_default = Orthogonal;
86
- export {
87
- Orthogonal,
88
- OrthogonalRunError,
89
- index_default as default
90
- };
91
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { OrthogonalConfig, RunOptions, RunResponse } from \"./types\";\n\nconst VERSION = \"0.1.0\";\nconst BASE_URL = \"https://api.orth.sh\";\n\n/**\n * Coerce an error payload into a human-readable string.\n *\n * Upstream providers surface errors as structured objects (e.g. People Data Labs\n * returns `{type: [...], message: \"...\"}`). Passing those to `new Error()` coerces\n * to `\"[object Object]\"`, which is useless to SDK consumers. We prefer the most\n * specific string field when present, and fall back to JSON so callers can still\n * see the full payload.\n */\nfunction formatError(raw: unknown, status: number): string {\n if (raw == null) return `Request failed with status ${status}`;\n if (typeof raw === \"string\") {\n return raw.length > 0 ? raw : `Request failed with status ${status}`;\n }\n if (typeof raw === \"object\") {\n const obj = raw as Record<string, unknown>;\n // Only use .message / .error if they are non-empty strings; otherwise fall\n // through to JSON.stringify so callers still see the full payload.\n if (typeof obj.message === \"string\" && obj.message.length > 0) return obj.message;\n if (typeof obj.error === \"string\" && obj.error.length > 0) return obj.error;\n try {\n const json = JSON.stringify(raw);\n // \"{}\" / \"[]\" / \"null\" aren't useful; fall back to the status message.\n if (json && json !== \"{}\" && json !== \"[]\" && json !== \"null\") return json;\n return `Request failed with status ${status}`;\n } catch {\n return `Request failed with status ${status}`;\n }\n }\n return String(raw);\n}\n\n/**\n * Error thrown by {@link Orthogonal.run} on a non-2xx response.\n *\n * Extends `Error` (so existing `catch (e) { e.message }` keeps working) but also\n * carries the structured server payload. On a contract violation the API returns\n * an `_orthogonal` self-correction hint (expected schema, unexpected/missing\n * fields, numeric bounds) — exposed here as `orthogonal` so an agent can fix the\n * request and retry instead of only seeing the terse message.\n */\nexport class OrthogonalRunError extends Error {\n /** HTTP status of the failed response. */\n status: number;\n /** The API's `_orthogonal` self-correction hint, when present. */\n orthogonal?: unknown;\n /** The full parsed response body. */\n responseBody?: unknown;\n\n constructor(\n message: string,\n opts: { status: number; orthogonal?: unknown; responseBody?: unknown },\n ) {\n super(message);\n this.name = \"OrthogonalRunError\";\n this.status = opts.status;\n this.orthogonal = opts.orthogonal;\n this.responseBody = opts.responseBody;\n // Restore the prototype chain for instanceof across the compiled target.\n Object.setPrototypeOf(this, OrthogonalRunError.prototype);\n }\n}\n\n/**\n * Orthogonal SDK client\n *\n * @example\n * ```typescript\n * import Orthogonal from \"@orth/sdk\";\n *\n * const orthogonal = new Orthogonal({\n * apiKey: process.env.ORTHOGONAL_API_KEY\n * });\n *\n * const response = await orthogonal.run({\n * api: \"andi\",\n * path: \"/api/v1/search\",\n * query: { q: \"hello world\" }\n * });\n *\n * console.log(response.data);\n * ```\n */\nexport class Orthogonal {\n private apiKey: string;\n private customHeaders: Record<string, string>;\n\n constructor(config: OrthogonalConfig) {\n if (!config.apiKey) {\n throw new Error(\"Orthogonal API key is required\");\n }\n this.apiKey = config.apiKey;\n this.customHeaders = config.headers || {};\n }\n\n /**\n * Call any API on the Orthogonal platform\n */\n async run(options: RunOptions): Promise<RunResponse> {\n const { api, path, query, body } = options;\n\n const response = await fetch(`${BASE_URL}/v1/run`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n \"User-Agent\": `@orth/sdk/${VERSION}`,\n \"X-Orthogonal-Source\": \"sdk\",\n ...this.customHeaders,\n },\n body: JSON.stringify({ api, path, query, body }),\n });\n\n const data = await response.json();\n\n if (!response.ok) {\n const orthogonal = (data as any)?._orthogonal;\n // Provide helpful error messages for common cases\n if (response.status === 401) {\n throw new OrthogonalRunError(\n \"Invalid API key. Visit https://orthogonal.com to get one!\",\n { status: 401, orthogonal, responseBody: data },\n );\n }\n if (response.status === 402) {\n // 402 now covers several distinct cases: insufficient credits, a per-key\n // daily spend limit, and an account-wide daily spend limit. Surface the\n // server's specific message when it provided one so callers know which\n // applies. We test `rawError` directly (not formatError's output) so a\n // real message that happens to start with \"Request failed\" isn't mistaken\n // for the no-message fallback.\n const rawError = data.data?.error || data.error;\n const hasServerMessage =\n rawError !== undefined && rawError !== null && rawError !== \"\";\n throw new OrthogonalRunError(\n hasServerMessage\n ? formatError(rawError, response.status)\n : \"Insufficient credits. Top up your balance at https://www.orthogonal.com/dashboard/balance\",\n { status: 402, orthogonal, responseBody: data },\n );\n }\n // Check for nested error in data.error (e.g., from target API). Use `||`\n // (not `??`) so that falsy values like `\"\"` still fall through the chain\n // to the status-based fallback inside `formatError`.\n const rawError = data.data?.error || data.error;\n const errorMessage = formatError(rawError, response.status);\n throw new OrthogonalRunError(errorMessage, {\n status: response.status,\n orthogonal,\n responseBody: data,\n });\n }\n\n return data as RunResponse;\n }\n}\n\n// Export types\nexport * from \"./types\";\n\n// Default export\nexport default Orthogonal;\n"],"mappings":";AAEA,IAAM,UAAU;AAChB,IAAM,WAAW;AAWjB,SAAS,YAAY,KAAc,QAAwB;AACzD,MAAI,OAAO,KAAM,QAAO,8BAA8B,MAAM;AAC5D,MAAI,OAAO,QAAQ,UAAU;AAC3B,WAAO,IAAI,SAAS,IAAI,MAAM,8BAA8B,MAAM;AAAA,EACpE;AACA,MAAI,OAAO,QAAQ,UAAU;AAC3B,UAAM,MAAM;AAGZ,QAAI,OAAO,IAAI,YAAY,YAAY,IAAI,QAAQ,SAAS,EAAG,QAAO,IAAI;AAC1E,QAAI,OAAO,IAAI,UAAU,YAAY,IAAI,MAAM,SAAS,EAAG,QAAO,IAAI;AACtE,QAAI;AACF,YAAM,OAAO,KAAK,UAAU,GAAG;AAE/B,UAAI,QAAQ,SAAS,QAAQ,SAAS,QAAQ,SAAS,OAAQ,QAAO;AACtE,aAAO,8BAA8B,MAAM;AAAA,IAC7C,QAAQ;AACN,aAAO,8BAA8B,MAAM;AAAA,IAC7C;AAAA,EACF;AACA,SAAO,OAAO,GAAG;AACnB;AAWO,IAAM,qBAAN,MAAM,4BAA2B,MAAM;AAAA,EAQ5C,YACE,SACA,MACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,KAAK;AACnB,SAAK,aAAa,KAAK;AACvB,SAAK,eAAe,KAAK;AAEzB,WAAO,eAAe,MAAM,oBAAmB,SAAS;AAAA,EAC1D;AACF;AAsBO,IAAM,aAAN,MAAiB;AAAA,EAItB,YAAY,QAA0B;AACpC,QAAI,CAAC,OAAO,QAAQ;AAClB,YAAM,IAAI,MAAM,gCAAgC;AAAA,IAClD;AACA,SAAK,SAAS,OAAO;AACrB,SAAK,gBAAgB,OAAO,WAAW,CAAC;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,IAAI,SAA2C;AACnD,UAAM,EAAE,KAAK,MAAM,OAAO,KAAK,IAAI;AAEnC,UAAM,WAAW,MAAM,MAAM,GAAG,QAAQ,WAAW;AAAA,MACjD,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,eAAe,UAAU,KAAK,MAAM;AAAA,QACpC,gBAAgB;AAAA,QAChB,cAAc,aAAa,OAAO;AAAA,QAClC,uBAAuB;AAAA,QACvB,GAAG,KAAK;AAAA,MACV;AAAA,MACA,MAAM,KAAK,UAAU,EAAE,KAAK,MAAM,OAAO,KAAK,CAAC;AAAA,IACjD,CAAC;AAED,UAAM,OAAO,MAAM,SAAS,KAAK;AAEjC,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,aAAc,MAAc;AAElC,UAAI,SAAS,WAAW,KAAK;AAC3B,cAAM,IAAI;AAAA,UACR;AAAA,UACA,EAAE,QAAQ,KAAK,YAAY,cAAc,KAAK;AAAA,QAChD;AAAA,MACF;AACA,UAAI,SAAS,WAAW,KAAK;AAO3B,cAAMA,YAAW,KAAK,MAAM,SAAS,KAAK;AAC1C,cAAM,mBACJA,cAAa,UAAaA,cAAa,QAAQA,cAAa;AAC9D,cAAM,IAAI;AAAA,UACR,mBACI,YAAYA,WAAU,SAAS,MAAM,IACrC;AAAA,UACJ,EAAE,QAAQ,KAAK,YAAY,cAAc,KAAK;AAAA,QAChD;AAAA,MACF;AAIA,YAAM,WAAW,KAAK,MAAM,SAAS,KAAK;AAC1C,YAAM,eAAe,YAAY,UAAU,SAAS,MAAM;AAC1D,YAAM,IAAI,mBAAmB,cAAc;AAAA,QACzC,QAAQ,SAAS;AAAA,QACjB;AAAA,QACA,cAAc;AAAA,MAChB,CAAC;AAAA,IACH;AAEA,WAAO;AAAA,EACT;AACF;AAMA,IAAO,gBAAQ;","names":["rawError"]}