ampost 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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +198 -2
  3. package/dist/cjs/client.d.ts +62 -0
  4. package/dist/cjs/client.js +206 -0
  5. package/dist/cjs/core.d.ts +45 -0
  6. package/dist/cjs/core.js +9 -0
  7. package/dist/cjs/errors.d.ts +68 -0
  8. package/dist/cjs/errors.js +153 -0
  9. package/dist/cjs/generated/resources.d.ts +854 -0
  10. package/dist/cjs/generated/resources.js +668 -0
  11. package/dist/cjs/generated/schema.d.ts +5674 -0
  12. package/dist/cjs/generated/schema.js +3 -0
  13. package/dist/cjs/generated/types.d.ts +199 -0
  14. package/dist/cjs/generated/types.js +3 -0
  15. package/dist/cjs/index.d.ts +11 -0
  16. package/dist/cjs/index.js +29 -0
  17. package/dist/cjs/media.d.ts +42 -0
  18. package/dist/cjs/media.js +114 -0
  19. package/dist/cjs/package.json +3 -0
  20. package/dist/cjs/pagination.d.ts +27 -0
  21. package/dist/cjs/pagination.js +58 -0
  22. package/dist/cjs/version.d.ts +2 -0
  23. package/dist/cjs/version.js +5 -0
  24. package/dist/esm/client.d.ts +62 -0
  25. package/dist/esm/client.js +199 -0
  26. package/dist/esm/core.d.ts +45 -0
  27. package/dist/esm/core.js +6 -0
  28. package/dist/esm/errors.d.ts +68 -0
  29. package/dist/esm/errors.js +135 -0
  30. package/dist/esm/generated/resources.d.ts +854 -0
  31. package/dist/esm/generated/resources.js +655 -0
  32. package/dist/esm/generated/schema.d.ts +5674 -0
  33. package/dist/esm/generated/schema.js +2 -0
  34. package/dist/esm/generated/types.d.ts +199 -0
  35. package/dist/esm/generated/types.js +2 -0
  36. package/dist/esm/index.d.ts +11 -0
  37. package/dist/esm/index.js +6 -0
  38. package/dist/esm/media.d.ts +42 -0
  39. package/dist/esm/media.js +109 -0
  40. package/dist/esm/package.json +3 -0
  41. package/dist/esm/pagination.d.ts +27 -0
  42. package/dist/esm/pagination.js +54 -0
  43. package/dist/esm/version.d.ts +2 -0
  44. package/dist/esm/version.js +2 -0
  45. package/package.json +70 -4
@@ -0,0 +1,199 @@
1
+ import { AmpostError, APIConnectionError, APIError, APITimeoutError, parseRetryAfter } from "./errors.js";
2
+ import { AmpostResources } from "./generated/resources.js";
3
+ import { MediaResource } from "./media.js";
4
+ import { PagePromise } from "./pagination.js";
5
+ import { VERSION } from "./version.js";
6
+ export const DEFAULT_BASE_URL = "https://api.ampost.io";
7
+ const env = (name) => typeof process === "undefined" ? undefined : process.env?.[name] || undefined;
8
+ /**
9
+ * The Ampost API client.
10
+ *
11
+ * import { Ampost } from "ampost";
12
+ * const client = new Ampost(); // reads AMPOST_API_KEY
13
+ * const post = await client.posts.create({ text: "Hello", targets: [{ platforms: ["bluesky"] }], publishNow: true });
14
+ */
15
+ export class Ampost extends AmpostResources {
16
+ /** Media uploads, with `upload()` on top of the generated methods. */
17
+ media;
18
+ baseUrl;
19
+ maxRetries;
20
+ timeoutMs;
21
+ maxRetryDelayMs;
22
+ #apiKey;
23
+ #defaultHeaders;
24
+ #fetch;
25
+ constructor(options = {}) {
26
+ super();
27
+ const apiKey = options.apiKey ?? env("AMPOST_API_KEY");
28
+ if (!apiKey) {
29
+ throw new AmpostError("Missing API key: pass { apiKey } or set AMPOST_API_KEY. Create one at https://ampost.io/app/settings/api-keys?ref=github");
30
+ }
31
+ const fetchImpl = options.fetch ?? globalThis.fetch;
32
+ if (typeof fetchImpl !== "function")
33
+ throw new AmpostError("No fetch available: use Node 18+ or pass { fetch }");
34
+ this.#apiKey = apiKey;
35
+ this.#fetch = fetchImpl;
36
+ this.#defaultHeaders = { ...options.defaultHeaders };
37
+ this.baseUrl = (options.baseUrl ?? env("AMPOST_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
38
+ this.maxRetries = options.maxRetries ?? 2;
39
+ this.timeoutMs = options.timeoutMs ?? 60_000;
40
+ this.maxRetryDelayMs = options.maxRetryDelayMs ?? 60_000;
41
+ this.media = new MediaResource(this, (url, init, requestOptions) => this.send(url, init, requestOptions));
42
+ }
43
+ /**
44
+ * Sends one API call with auth, the idempotency key and retries. The generated methods call this;
45
+ * use it directly only for an endpoint this SDK version does not know yet.
46
+ */
47
+ async request(spec, options = {}) {
48
+ const headers = {
49
+ Accept: "application/json",
50
+ "User-Agent": `ampost-node/${VERSION}`,
51
+ ...this.#defaultHeaders,
52
+ ...options.headers,
53
+ Authorization: `Bearer ${this.#apiKey}`,
54
+ };
55
+ let body;
56
+ if (spec.body !== undefined) {
57
+ headers["Content-Type"] = "application/json";
58
+ body = JSON.stringify(spec.body);
59
+ }
60
+ if (spec.idempotent)
61
+ headers["Idempotency-Key"] = options.idempotencyKey ?? randomKey();
62
+ // Without a key, a write that timed out may have been done: only reads and keyed writes repeat.
63
+ const repeatable = spec.method === "GET" || spec.idempotent === true;
64
+ const maxRetries = options.maxRetries ?? this.maxRetries;
65
+ const url = buildUrl(this.baseUrl, spec.path, spec.query);
66
+ for (let attempt = 0;; attempt++) {
67
+ let response;
68
+ try {
69
+ response = await this.send(url, { method: spec.method, headers, body }, options);
70
+ }
71
+ catch (error) {
72
+ if (!(error instanceof APIConnectionError) || !repeatable || attempt >= maxRetries)
73
+ throw error;
74
+ await sleep(backoff(attempt), options.signal);
75
+ continue;
76
+ }
77
+ if (response.ok)
78
+ return parseJson(response);
79
+ const error = APIError.from(response.status, parseMaybeJson(response.text), response.headers, response.statusText);
80
+ const delay = this.retryDelay(error, attempt, repeatable);
81
+ if (delay === undefined || attempt >= maxRetries)
82
+ throw error;
83
+ await sleep(delay, options.signal);
84
+ }
85
+ }
86
+ /** Like `request`, for list operations: returns a page that also iterates every item. */
87
+ paginate(spec, options) {
88
+ return new PagePromise((offset) => this.request(offset === undefined ? spec : { ...spec, query: { ...spec.query, offset } }, options));
89
+ }
90
+ /** Milliseconds to wait before retrying, or undefined to give up. */
91
+ retryDelay(error, attempt, repeatable) {
92
+ const retryable = error.status === 429 || // refused before anything ran
93
+ error.code === "IDEMPOTENCY_REQUEST_IN_PROGRESS" || // the first request with this key still runs
94
+ ((error.status >= 500 || error.status === 408) && repeatable);
95
+ if (!retryable)
96
+ return undefined;
97
+ const retryAfter = parseRetryAfter(error.headers.get("retry-after"));
98
+ if (retryAfter === undefined)
99
+ return backoff(attempt);
100
+ // A quota reset days away is not worth blocking on.
101
+ return retryAfter <= this.maxRetryDelayMs ? retryAfter : undefined;
102
+ }
103
+ /** @internal One HTTP exchange with the timeout; reads the body. Throws APIConnectionError without a response. */
104
+ async send(url, init, options = {}) {
105
+ const { signal } = options;
106
+ if (signal?.aborted)
107
+ throw abortReason(signal);
108
+ const controller = new AbortController();
109
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
110
+ let timedOut = false;
111
+ const timer = setTimeout(() => {
112
+ timedOut = true;
113
+ controller.abort();
114
+ }, timeoutMs);
115
+ const onAbort = () => controller.abort();
116
+ signal?.addEventListener("abort", onAbort, { once: true });
117
+ try {
118
+ const response = await this.#fetch(url, { ...init, signal: controller.signal });
119
+ const text = await response.text();
120
+ return { status: response.status, statusText: response.statusText, ok: response.ok, headers: response.headers, text };
121
+ }
122
+ catch (error) {
123
+ if (signal?.aborted)
124
+ throw abortReason(signal);
125
+ if (timedOut)
126
+ throw new APITimeoutError(`Request timed out after ${timeoutMs} ms`, { cause: error });
127
+ throw new APIConnectionError(`Connection error: ${error instanceof Error ? error.message : String(error)}`, {
128
+ cause: error,
129
+ });
130
+ }
131
+ finally {
132
+ clearTimeout(timer);
133
+ signal?.removeEventListener("abort", onAbort);
134
+ }
135
+ }
136
+ }
137
+ export function buildUrl(baseUrl, path, query) {
138
+ const url = new URL(`${baseUrl}${path}`);
139
+ for (const [key, value] of Object.entries(query ?? {})) {
140
+ if (value === undefined || value === null)
141
+ continue;
142
+ for (const item of Array.isArray(value) ? value : [value]) {
143
+ url.searchParams.append(key, item instanceof Date ? item.toISOString() : String(item));
144
+ }
145
+ }
146
+ return url.toString();
147
+ }
148
+ function parseMaybeJson(text) {
149
+ try {
150
+ return JSON.parse(text);
151
+ }
152
+ catch {
153
+ return text;
154
+ }
155
+ }
156
+ function parseJson(response) {
157
+ if (!response.text)
158
+ return undefined;
159
+ try {
160
+ return JSON.parse(response.text);
161
+ }
162
+ catch (error) {
163
+ throw new AmpostError(`Expected JSON from the API, got: ${response.text.slice(0, 200)}`, { cause: error });
164
+ }
165
+ }
166
+ /** Exponential backoff with jitter: about 0.5 s, 1 s, 2 s, ... up to 8 s. */
167
+ export function backoff(attempt) {
168
+ const base = Math.min(500 * 2 ** attempt, 8_000);
169
+ return Math.round(base * (0.75 + Math.random() * 0.5));
170
+ }
171
+ function abortReason(signal) {
172
+ return signal.reason ?? new DOMException("The operation was aborted", "AbortError");
173
+ }
174
+ function sleep(ms, signal) {
175
+ return new Promise((resolve, reject) => {
176
+ if (signal?.aborted)
177
+ return reject(abortReason(signal));
178
+ const timer = setTimeout(() => {
179
+ signal?.removeEventListener("abort", onAbort);
180
+ resolve();
181
+ }, ms);
182
+ const onAbort = () => {
183
+ clearTimeout(timer);
184
+ reject(abortReason(signal));
185
+ };
186
+ signal?.addEventListener("abort", onAbort, { once: true });
187
+ });
188
+ }
189
+ /** A UUID v4 for `Idempotency-Key`; Node 18 has no global `crypto` without a flag, hence the fallback. */
190
+ export function randomKey() {
191
+ const webCrypto = globalThis.crypto;
192
+ if (webCrypto?.randomUUID)
193
+ return webCrypto.randomUUID();
194
+ const hex = Array.from({ length: 32 }, () => Math.floor(Math.random() * 16).toString(16));
195
+ hex[12] = "4";
196
+ hex[16] = ((parseInt(hex[16], 16) & 0x3) | 0x8).toString(16);
197
+ const s = hex.join("");
198
+ return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`;
199
+ }
@@ -0,0 +1,45 @@
1
+ import type { PagePromise } from "./pagination.js";
2
+ export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
3
+ /** One API call, as the generated resource methods describe it. */
4
+ export interface RequestSpec {
5
+ method: HttpMethod;
6
+ /** Path with its parameters already filled in and encoded, e.g. `/api/posts/123`. */
7
+ path: string;
8
+ query?: object;
9
+ body?: unknown;
10
+ /** The operation takes an `Idempotency-Key` header. */
11
+ idempotent?: boolean;
12
+ }
13
+ export interface RequestOptions {
14
+ /** Cancels the request, including retries and waits between them. */
15
+ signal?: AbortSignal;
16
+ /** Per-attempt timeout. Default: the client's `timeoutMs`. */
17
+ timeoutMs?: number;
18
+ /** Default: the client's `maxRetries`. */
19
+ maxRetries?: number;
20
+ /** Extra headers for this request. */
21
+ headers?: Record<string, string>;
22
+ }
23
+ export interface IdempotentRequestOptions extends RequestOptions {
24
+ /**
25
+ * Sent as `Idempotency-Key`. The same key with the same request returns the first result instead of
26
+ * acting twice (kept 24 hours). Without one, the SDK generates a key per call and reuses it on retries.
27
+ * Pass your own to stay safe across process restarts, for example a hash of the content you post.
28
+ */
29
+ idempotencyKey?: string;
30
+ }
31
+ /** A list response: one page of `data` plus offset pagination. */
32
+ export interface ListResponse {
33
+ data: unknown[];
34
+ pagination: {
35
+ limit: number;
36
+ offset: number;
37
+ total: number;
38
+ hasMore: boolean;
39
+ };
40
+ }
41
+ export interface Transport {
42
+ request<T>(spec: RequestSpec, options?: IdempotentRequestOptions): Promise<T>;
43
+ paginate<T extends ListResponse>(spec: RequestSpec, options?: RequestOptions): PagePromise<T>;
44
+ }
45
+ export declare function encodePathParam(value: string): string;
@@ -0,0 +1,6 @@
1
+ export function encodePathParam(value) {
2
+ if (typeof value !== "string" || value.length === 0) {
3
+ throw new TypeError(`Expected a non-empty string path parameter, got ${JSON.stringify(value)}`);
4
+ }
5
+ return encodeURIComponent(value);
6
+ }
@@ -0,0 +1,68 @@
1
+ /** Base class of every error the SDK throws. */
2
+ export declare class AmpostError extends Error {
3
+ constructor(message: string, options?: {
4
+ cause?: unknown;
5
+ });
6
+ }
7
+ /**
8
+ * The API answered with an error status. The body is `{ error: { code, message, details } }`:
9
+ * `code` is stable (for example `VALIDATION_FAILED`, `POST_NOT_FOUND`); the full list is at
10
+ * https://ampost.io/docs?ref=github#errors.
11
+ */
12
+ export declare class APIError extends AmpostError {
13
+ readonly status: number;
14
+ readonly code: string;
15
+ readonly details: Record<string, unknown> | undefined;
16
+ /** `X-Request-Id`: quote it when you contact support. */
17
+ readonly requestId: string | undefined;
18
+ readonly headers: Headers;
19
+ constructor(status: number, code: string, message: string, details: Record<string, unknown> | undefined, headers: Headers);
20
+ /** Builds the subclass that matches the status. */
21
+ static from(status: number, body: unknown, headers: Headers, statusText?: string): APIError;
22
+ }
23
+ /** 400: the request is invalid (`VALIDATION_FAILED`, `CONTENT_TOO_LONG`, ...). `details.issues` lists the problems. */
24
+ export declare class BadRequestError extends APIError {
25
+ }
26
+ /** 401: the API key is missing, wrong or revoked. */
27
+ export declare class AuthenticationError extends APIError {
28
+ }
29
+ /** 403: the key lacks a scope, the plan lacks a feature, or the account is suspended. */
30
+ export declare class PermissionDeniedError extends APIError {
31
+ }
32
+ /** 404: no such resource belongs to you. */
33
+ export declare class NotFoundError extends APIError {
34
+ }
35
+ /** 409: the resource's state does not allow it, or an idempotency key was reused. */
36
+ export declare class ConflictError extends APIError {
37
+ }
38
+ /** 413: the request body is too large; upload files with `client.media.upload()`. */
39
+ export declare class PayloadTooLargeError extends APIError {
40
+ }
41
+ /** 422: the request is well formed but cannot be done (for example analytics on Discord). */
42
+ export declare class UnprocessableEntityError extends APIError {
43
+ }
44
+ /** 429: `RATE_LIMITED` or `QUOTA_EXCEEDED`. Retried automatically when `Retry-After` is short. */
45
+ export declare class RateLimitError extends APIError {
46
+ /** Seconds the API asked to wait (`Retry-After`). */
47
+ get retryAfterSeconds(): number | undefined;
48
+ }
49
+ /** 5xx: something failed on Ampost's side or at a platform. */
50
+ export declare class InternalServerError extends APIError {
51
+ }
52
+ /** No response: DNS, TCP, TLS or a reset connection. */
53
+ export declare class APIConnectionError extends AmpostError {
54
+ }
55
+ /** No response within `timeoutMs`. */
56
+ export declare class APITimeoutError extends APIConnectionError {
57
+ }
58
+ /** `client.media.upload()` did not end with a usable file. */
59
+ export declare class MediaUploadError extends AmpostError {
60
+ /** `upload_rejected`: the file PUT failed; `failed`/`expired`: the upload's status; `timeout`: still pending. */
61
+ readonly reason: "failed" | "expired" | "timeout" | "upload_rejected";
62
+ readonly uploadId: string;
63
+ constructor(message: string,
64
+ /** `upload_rejected`: the file PUT failed; `failed`/`expired`: the upload's status; `timeout`: still pending. */
65
+ reason: "failed" | "expired" | "timeout" | "upload_rejected", uploadId: string);
66
+ }
67
+ /** `Retry-After` in milliseconds: delta-seconds or an HTTP date. */
68
+ export declare function parseRetryAfter(value: string | null, now?: number): number | undefined;
@@ -0,0 +1,135 @@
1
+ /** Base class of every error the SDK throws. */
2
+ export class AmpostError extends Error {
3
+ constructor(message, options) {
4
+ super(message);
5
+ this.name = new.target.name;
6
+ if (options && "cause" in options)
7
+ this.cause = options.cause;
8
+ }
9
+ }
10
+ /**
11
+ * The API answered with an error status. The body is `{ error: { code, message, details } }`:
12
+ * `code` is stable (for example `VALIDATION_FAILED`, `POST_NOT_FOUND`); the full list is at
13
+ * https://ampost.io/docs?ref=github#errors.
14
+ */
15
+ export class APIError extends AmpostError {
16
+ status;
17
+ code;
18
+ details;
19
+ /** `X-Request-Id`: quote it when you contact support. */
20
+ requestId;
21
+ headers;
22
+ constructor(status, code, message, details, headers) {
23
+ super(`${status} ${code}: ${message}`);
24
+ this.status = status;
25
+ this.code = code;
26
+ this.details = details;
27
+ this.headers = headers;
28
+ this.requestId = headers.get("x-request-id") ?? undefined;
29
+ }
30
+ /** Builds the subclass that matches the status. */
31
+ static from(status, body, headers, statusText = "") {
32
+ const { code, message, details } = parseErrorBody(status, body, statusText);
33
+ const Class = errorClassFor(status);
34
+ return new Class(status, code, message, details, headers);
35
+ }
36
+ }
37
+ /** 400: the request is invalid (`VALIDATION_FAILED`, `CONTENT_TOO_LONG`, ...). `details.issues` lists the problems. */
38
+ export class BadRequestError extends APIError {
39
+ }
40
+ /** 401: the API key is missing, wrong or revoked. */
41
+ export class AuthenticationError extends APIError {
42
+ }
43
+ /** 403: the key lacks a scope, the plan lacks a feature, or the account is suspended. */
44
+ export class PermissionDeniedError extends APIError {
45
+ }
46
+ /** 404: no such resource belongs to you. */
47
+ export class NotFoundError extends APIError {
48
+ }
49
+ /** 409: the resource's state does not allow it, or an idempotency key was reused. */
50
+ export class ConflictError extends APIError {
51
+ }
52
+ /** 413: the request body is too large; upload files with `client.media.upload()`. */
53
+ export class PayloadTooLargeError extends APIError {
54
+ }
55
+ /** 422: the request is well formed but cannot be done (for example analytics on Discord). */
56
+ export class UnprocessableEntityError extends APIError {
57
+ }
58
+ /** 429: `RATE_LIMITED` or `QUOTA_EXCEEDED`. Retried automatically when `Retry-After` is short. */
59
+ export class RateLimitError extends APIError {
60
+ /** Seconds the API asked to wait (`Retry-After`). */
61
+ get retryAfterSeconds() {
62
+ const seconds = parseRetryAfter(this.headers.get("retry-after"));
63
+ return seconds === undefined ? undefined : Math.ceil(seconds / 1000);
64
+ }
65
+ }
66
+ /** 5xx: something failed on Ampost's side or at a platform. */
67
+ export class InternalServerError extends APIError {
68
+ }
69
+ /** No response: DNS, TCP, TLS or a reset connection. */
70
+ export class APIConnectionError extends AmpostError {
71
+ }
72
+ /** No response within `timeoutMs`. */
73
+ export class APITimeoutError extends APIConnectionError {
74
+ }
75
+ /** `client.media.upload()` did not end with a usable file. */
76
+ export class MediaUploadError extends AmpostError {
77
+ reason;
78
+ uploadId;
79
+ constructor(message,
80
+ /** `upload_rejected`: the file PUT failed; `failed`/`expired`: the upload's status; `timeout`: still pending. */
81
+ reason, uploadId) {
82
+ super(message);
83
+ this.reason = reason;
84
+ this.uploadId = uploadId;
85
+ }
86
+ }
87
+ function errorClassFor(status) {
88
+ if (status === 400)
89
+ return BadRequestError;
90
+ if (status === 401)
91
+ return AuthenticationError;
92
+ if (status === 403)
93
+ return PermissionDeniedError;
94
+ if (status === 404)
95
+ return NotFoundError;
96
+ if (status === 409)
97
+ return ConflictError;
98
+ if (status === 413)
99
+ return PayloadTooLargeError;
100
+ if (status === 422)
101
+ return UnprocessableEntityError;
102
+ if (status === 429)
103
+ return RateLimitError;
104
+ if (status >= 500)
105
+ return InternalServerError;
106
+ return APIError;
107
+ }
108
+ function parseErrorBody(status, body, statusText) {
109
+ const fallback = { code: `HTTP_${status}`, message: statusText || "Request failed", details: undefined };
110
+ if (!body || typeof body !== "object" || !("error" in body)) {
111
+ return typeof body === "string" && body.trim() ? { ...fallback, message: body.trim().slice(0, 500) } : fallback;
112
+ }
113
+ const error = body.error;
114
+ // A few edge routes answer `{ error: "message" }`.
115
+ if (typeof error === "string")
116
+ return { ...fallback, message: error };
117
+ if (!error || typeof error !== "object")
118
+ return fallback;
119
+ const { code, message, details } = error;
120
+ return {
121
+ code: typeof code === "string" ? code : fallback.code,
122
+ message: typeof message === "string" ? message : fallback.message,
123
+ details: details && typeof details === "object" ? details : undefined,
124
+ };
125
+ }
126
+ /** `Retry-After` in milliseconds: delta-seconds or an HTTP date. */
127
+ export function parseRetryAfter(value, now = Date.now()) {
128
+ if (!value)
129
+ return undefined;
130
+ const trimmed = value.trim();
131
+ if (/^\d+(\.\d+)?$/.test(trimmed))
132
+ return Number(trimmed) * 1000;
133
+ const date = Date.parse(trimmed);
134
+ return Number.isNaN(date) ? undefined : Math.max(0, date - now);
135
+ }