@sortdo/sdk 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,18 @@
1
- # Temporary Holding Version
1
+ # @sortdo/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The TypeScript client of the [Sort API](https://docs.trysort.com/api/): every operation, typed, and a check for webhook signatures.
4
+
5
+ ```sh
6
+ npm install @sortdo/sdk
7
+ ```
8
+
9
+ ```ts
10
+ import { createSort } from '@sortdo/sdk'
11
+
12
+ const sort = createSort({ token: process.env.SORT_API_KEY! })
13
+ const { items } = await sort.teams.list({})
14
+ ```
15
+
16
+ Sign in with an agent member's API key or an OAuth access token. Errors are `SortError` with a `code` and a `message`; an action that waits for a person's approval throws `ApprovalRequired` with the approval's `url`. `verifyWebhook(body, signatureHeader, secret)` checks a webhook request.
17
+
18
+ Docs: https://docs.trysort.com/api/
@@ -0,0 +1,55 @@
1
+ import type { Operations } from './operations.js';
2
+ export { AREAS, type Operations } from './operations.js';
3
+ export { verifyWebhook, type SortEvent } from './webhooks.js';
4
+ export type OperationName = keyof Operations;
5
+ export type Input<N extends OperationName> = Operations[N]['input'];
6
+ export type Output<N extends OperationName> = Operations[N]['output'];
7
+ /** A refused or failed call. `code` is from a closed list, such as missing_scope or not_found; `message` says what to do. */
8
+ export declare class SortError extends Error {
9
+ readonly code: string;
10
+ readonly status: number;
11
+ readonly details: Record<string, unknown>;
12
+ constructor(code: string, message: string, status: number, details?: Record<string, unknown>);
13
+ }
14
+ /** Nothing changed yet: a person must approve the call. Give them `approval.url`; read the outcome with notifications.get_approval. */
15
+ export declare class ApprovalRequired extends Error {
16
+ readonly approval: {
17
+ id: string;
18
+ summary: string;
19
+ url: string;
20
+ expiresAt: string;
21
+ };
22
+ constructor(approval: {
23
+ id: string;
24
+ summary: string;
25
+ url: string;
26
+ expiresAt: string;
27
+ });
28
+ }
29
+ export type SortOptions = {
30
+ /** An agent member's API key (sort_key_…) or an OAuth access token. */
31
+ token: string;
32
+ /** Default https://api.trysort.com/v1. */
33
+ baseUrl?: string;
34
+ fetch?: typeof fetch;
35
+ };
36
+ export type CallOptions = {
37
+ /** Writes with the same key run once; a repeat returns the first result, for 24 hours. */
38
+ idempotencyKey?: string;
39
+ signal?: AbortSignal;
40
+ };
41
+ type AreaOf<N> = N extends `${infer Area}.${string}` ? Area : never;
42
+ /** The operations grouped by area: `sort.teams.list({})` calls teams.list. */
43
+ export type Namespaces = {
44
+ [Area in AreaOf<OperationName>]: {
45
+ [Name in OperationName as Name extends `${Area}.${infer Action}` ? Action : never]: (input: Input<Name>, options?: CallOptions) => Promise<Output<Name>>;
46
+ };
47
+ };
48
+ export declare class SortClient {
49
+ #private;
50
+ constructor(options: SortOptions);
51
+ /** Calls one operation by name. */
52
+ call<N extends OperationName>(name: N, input: Input<N>, options?: CallOptions): Promise<Output<N>>;
53
+ }
54
+ /** A client with the operations grouped by area: `const sort = createSort({ token }); await sort.teams.list({})`. */
55
+ export declare function createSort(options: SortOptions): SortClient & Namespaces;
package/dist/index.js ADDED
@@ -0,0 +1,80 @@
1
+ export { AREAS } from './operations.js';
2
+ export { verifyWebhook } from './webhooks.js';
3
+ /** A refused or failed call. `code` is from a closed list, such as missing_scope or not_found; `message` says what to do. */
4
+ export class SortError extends Error {
5
+ code;
6
+ status;
7
+ details;
8
+ constructor(code, message, status, details = {}) {
9
+ super(message);
10
+ this.code = code;
11
+ this.status = status;
12
+ this.details = details;
13
+ this.name = 'SortError';
14
+ }
15
+ }
16
+ /** Nothing changed yet: a person must approve the call. Give them `approval.url`; read the outcome with notifications.get_approval. */
17
+ export class ApprovalRequired extends Error {
18
+ approval;
19
+ constructor(approval) {
20
+ super(approval.summary);
21
+ this.approval = approval;
22
+ this.name = 'ApprovalRequired';
23
+ }
24
+ }
25
+ export class SortClient {
26
+ #token;
27
+ #baseUrl;
28
+ #fetch;
29
+ constructor(options) {
30
+ if (!options.token)
31
+ throw new Error('Pass an API key or an access token as token.');
32
+ this.#token = options.token;
33
+ this.#baseUrl = (options.baseUrl || 'https://api.trysort.com/v1').replace(/\/$/, '');
34
+ this.#fetch = options.fetch || globalThis.fetch.bind(globalThis);
35
+ }
36
+ /** Calls one operation by name. */
37
+ async call(name, input, options = {}) {
38
+ const headers = { Authorization: `Bearer ${this.#token}`, 'Content-Type': 'application/json', Accept: 'application/json' };
39
+ if (options.idempotencyKey)
40
+ headers['Idempotency-Key'] = options.idempotencyKey;
41
+ let response;
42
+ try {
43
+ response = await this.#fetch(`${this.#baseUrl}/${name}`, { method: 'POST', headers, body: JSON.stringify(input ?? {}), signal: options.signal });
44
+ }
45
+ catch (error) {
46
+ if (options.signal?.aborted)
47
+ throw error;
48
+ throw new SortError('network', 'Could not reach Sort. Check the connection and try again.', 0);
49
+ }
50
+ const body = await response.json().catch(() => null);
51
+ if (response.status === 200)
52
+ return body;
53
+ if (response.status === 202 && body?.approval)
54
+ throw new ApprovalRequired(body.approval);
55
+ const error = body?.error;
56
+ if (error?.code) {
57
+ const { code, message, ...details } = error;
58
+ throw new SortError(code, message, response.status, details);
59
+ }
60
+ throw new SortError('internal', 'Something went wrong. Try again.', response.status);
61
+ }
62
+ }
63
+ /** A client with the operations grouped by area: `const sort = createSort({ token }); await sort.teams.list({})`. */
64
+ export function createSort(options) {
65
+ const client = new SortClient(options);
66
+ return new Proxy(client, {
67
+ get(target, property) {
68
+ if (typeof property !== 'string' || property in target) {
69
+ const value = Reflect.get(target, property, target);
70
+ // Methods run on the client itself, which holds the token in private fields.
71
+ return typeof value === 'function' ? value.bind(target) : value;
72
+ }
73
+ return new Proxy({}, {
74
+ get: (_, action) => typeof action === 'string'
75
+ ? (input, callOptions) => target.call(`${property}.${action}`, input, callOptions)
76
+ : undefined,
77
+ });
78
+ },
79
+ });
80
+ }