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.
- package/LICENSE +21 -0
- package/README.md +198 -2
- package/dist/cjs/client.d.ts +62 -0
- package/dist/cjs/client.js +206 -0
- package/dist/cjs/core.d.ts +45 -0
- package/dist/cjs/core.js +9 -0
- package/dist/cjs/errors.d.ts +68 -0
- package/dist/cjs/errors.js +153 -0
- package/dist/cjs/generated/resources.d.ts +854 -0
- package/dist/cjs/generated/resources.js +668 -0
- package/dist/cjs/generated/schema.d.ts +5674 -0
- package/dist/cjs/generated/schema.js +3 -0
- package/dist/cjs/generated/types.d.ts +199 -0
- package/dist/cjs/generated/types.js +3 -0
- package/dist/cjs/index.d.ts +11 -0
- package/dist/cjs/index.js +29 -0
- package/dist/cjs/media.d.ts +42 -0
- package/dist/cjs/media.js +114 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/pagination.d.ts +27 -0
- package/dist/cjs/pagination.js +58 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/esm/client.d.ts +62 -0
- package/dist/esm/client.js +199 -0
- package/dist/esm/core.d.ts +45 -0
- package/dist/esm/core.js +6 -0
- package/dist/esm/errors.d.ts +68 -0
- package/dist/esm/errors.js +135 -0
- package/dist/esm/generated/resources.d.ts +854 -0
- package/dist/esm/generated/resources.js +655 -0
- package/dist/esm/generated/schema.d.ts +5674 -0
- package/dist/esm/generated/schema.js +2 -0
- package/dist/esm/generated/types.d.ts +199 -0
- package/dist/esm/generated/types.js +2 -0
- package/dist/esm/index.d.ts +11 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/media.d.ts +42 -0
- package/dist/esm/media.js +109 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/pagination.d.ts +27 -0
- package/dist/esm/pagination.js +54 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/package.json +70 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Amlabs Artur Muszyński (Ampost)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,199 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Ampost Node.js SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The official TypeScript and JavaScript client for the [Ampost API](https://ampost.io/docs?ref=github):
|
|
4
|
+
publish, schedule and track posts on Instagram, Facebook, Threads, X, YouTube, Pinterest, Bluesky,
|
|
5
|
+
Telegram and Discord with one call.
|
|
6
|
+
|
|
7
|
+
- Typed requests and responses for every endpoint, generated from the [OpenAPI document](https://api.ampost.io/openapi.json)
|
|
8
|
+
- Retries on 429 and 5xx with `Retry-After`, automatic `Idempotency-Key`s, typed errors
|
|
9
|
+
- `for await` pagination and a one-call media upload
|
|
10
|
+
- No runtime dependencies. ESM and CommonJS, Node 18+
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm install ampost
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Quick start
|
|
19
|
+
|
|
20
|
+
Create an API key in [Settings, API keys](https://ampost.io/app/settings/api-keys?ref=github), connect
|
|
21
|
+
Bluesky and Threads in the [dashboard](https://ampost.io/app?ref=github), then:
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { Ampost } from "ampost";
|
|
25
|
+
|
|
26
|
+
const ampost = new Ampost({ apiKey: process.env.AMPOST_API_KEY });
|
|
27
|
+
|
|
28
|
+
const post = await ampost.posts.create({
|
|
29
|
+
text: "Hello from the Ampost API 👋",
|
|
30
|
+
targets: [{ platforms: ["bluesky", "threads"] }],
|
|
31
|
+
publishNow: true,
|
|
32
|
+
});
|
|
33
|
+
console.log(post.id, post.status, post.platformPosts.map((p) => `${p.platform}: ${p.status}`));
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Leave out `publishNow` for a draft, or set `scheduledFor: "2026-12-01T09:00:00Z"` to schedule it
|
|
37
|
+
(paid plans). CommonJS works the same: `const { Ampost } = require("ampost")`.
|
|
38
|
+
|
|
39
|
+
## Authentication
|
|
40
|
+
|
|
41
|
+
Every request sends the key as `Authorization: Bearer <key>`. Without `apiKey` the client reads
|
|
42
|
+
`AMPOST_API_KEY`, and `AMPOST_BASE_URL` overrides `https://api.ampost.io`.
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
const ampost = new Ampost({
|
|
46
|
+
apiKey: "amp_...",
|
|
47
|
+
maxRetries: 2, // after a 429, a 5xx or a network error
|
|
48
|
+
timeoutMs: 60_000, // per attempt
|
|
49
|
+
});
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
A key has scopes (`posts:write`, `analytics:read`, ...) and can be limited to some platform sets. A
|
|
53
|
+
call outside them fails with `PermissionDeniedError` and `code: "INSUFFICIENT_SCOPE"` or
|
|
54
|
+
`"PLATFORM_SET_NOT_ALLOWED"`. See [scopes](https://ampost.io/docs?ref=github#scopes).
|
|
55
|
+
|
|
56
|
+
## Errors
|
|
57
|
+
|
|
58
|
+
Every API error is `{ error: { code, message, details } }`, thrown as a subclass of `APIError`:
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { APIError, BadRequestError, RateLimitError } from "ampost";
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
await ampost.posts.create({ text: "x".repeat(500), targets: [{ platforms: ["bluesky"] }] });
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (error instanceof BadRequestError) console.log(error.code, error.details); // CONTENT_TOO_LONG, ...
|
|
67
|
+
else if (error instanceof RateLimitError) console.log(`retry in ${error.retryAfterSeconds} s`);
|
|
68
|
+
else if (error instanceof APIError) console.log(error.status, error.code, error.requestId);
|
|
69
|
+
else throw error;
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
| Status | Class | Typical `code` |
|
|
74
|
+
| ------ | ----- | -------------- |
|
|
75
|
+
| 400 | `BadRequestError` | `VALIDATION_FAILED`, `CONTENT_TOO_LONG`, `PLATFORM_NOT_CONNECTED` |
|
|
76
|
+
| 401 | `AuthenticationError` | `UNAUTHORIZED` |
|
|
77
|
+
| 403 | `PermissionDeniedError` | `INSUFFICIENT_SCOPE`, `UPGRADE_REQUIRED`, `PLATFORM_COMING_SOON` |
|
|
78
|
+
| 404 | `NotFoundError` | `POST_NOT_FOUND`, `ACCOUNT_NOT_FOUND` |
|
|
79
|
+
| 409 | `ConflictError` | `INVALID_STATUS_TRANSITION`, `IDEMPOTENCY_KEY_REUSED` |
|
|
80
|
+
| 413 | `PayloadTooLargeError` | `PAYLOAD_TOO_LARGE` |
|
|
81
|
+
| 422 | `UnprocessableEntityError` | `ANALYTICS_NOT_AVAILABLE_ON_PLATFORM` |
|
|
82
|
+
| 429 | `RateLimitError` | `RATE_LIMITED`, `QUOTA_EXCEEDED` |
|
|
83
|
+
| 5xx | `InternalServerError` | `INTERNAL_ERROR`, `PLATFORM_REQUEST_FAILED` |
|
|
84
|
+
|
|
85
|
+
No response at all is `APIConnectionError` (`APITimeoutError` after `timeoutMs`). All of them extend
|
|
86
|
+
`AmpostError`. Quote `error.requestId` when you contact support. Every code is listed in
|
|
87
|
+
[the docs](https://ampost.io/docs?ref=github#errors).
|
|
88
|
+
|
|
89
|
+
A post that was accepted can still fail on one platform: check `post.platformPosts[].status` and
|
|
90
|
+
`.error`, or subscribe to [webhooks](https://ampost.io/docs?ref=github#webhooks).
|
|
91
|
+
|
|
92
|
+
## Idempotency
|
|
93
|
+
|
|
94
|
+
`posts.create`, `posts.publish`, `posts.retry`, `posts.importCsv`, `accounts.connect`,
|
|
95
|
+
`platformSets.create`, `webhooks.create` and `feedback.submit` take an `Idempotency-Key`. The SDK
|
|
96
|
+
sends a new key with each call and keeps it across that call's retries, so a retried request never
|
|
97
|
+
posts twice. To stay safe across restarts too (a cron job, a queue worker), pass your own key:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
await ampost.posts.create(
|
|
101
|
+
{ text: "v1.4.0 is out", targets: [{ platforms: ["bluesky"] }], publishNow: true },
|
|
102
|
+
{ idempotencyKey: "release-v1.4.0" },
|
|
103
|
+
);
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
The same key with the same request returns the first result for 24 hours; with a different request
|
|
107
|
+
it is `ConflictError` `IDEMPOTENCY_KEY_REUSED`. See
|
|
108
|
+
[idempotency](https://ampost.io/docs?ref=github#idempotency).
|
|
109
|
+
|
|
110
|
+
## Retries
|
|
111
|
+
|
|
112
|
+
| What happened | Retried? |
|
|
113
|
+
| ------------- | -------- |
|
|
114
|
+
| 429 `RATE_LIMITED`, `QUOTA_EXCEEDED` | Yes, after `Retry-After`, if it is under `maxRetryDelayMs` (60 s) |
|
|
115
|
+
| 409 `IDEMPOTENCY_REQUEST_IN_PROGRESS` | Yes |
|
|
116
|
+
| 5xx, timeout, network error | Reads and calls with an `Idempotency-Key` only |
|
|
117
|
+
| Anything else | No |
|
|
118
|
+
|
|
119
|
+
Waits without `Retry-After` back off from 0.5 s to 8 s. Set `maxRetries` on the client or per call:
|
|
120
|
+
`ampost.posts.get(id, { maxRetries: 0 })`. Every method also takes `signal`, `timeoutMs` and `headers`.
|
|
121
|
+
|
|
122
|
+
## Pagination
|
|
123
|
+
|
|
124
|
+
List methods return a page you can await, or iterate to get every item:
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
const { data, pagination } = await ampost.posts.list({ status: "failed", limit: 50 });
|
|
128
|
+
|
|
129
|
+
for await (const post of ampost.posts.list({ status: "failed" })) {
|
|
130
|
+
await ampost.posts.retry(post.id);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const accounts = await ampost.accounts.list().toArray();
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Media upload
|
|
137
|
+
|
|
138
|
+
`media.upload()` takes a path, a `Blob`/`File` or bytes, sends the file straight to storage (your API
|
|
139
|
+
key is not sent there), waits until Ampost has checked it and returns a `media` item:
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
const video = await ampost.media.upload("./launch.mp4");
|
|
143
|
+
await ampost.posts.create({
|
|
144
|
+
text: "We launched 🚀",
|
|
145
|
+
media: [video],
|
|
146
|
+
targets: [{ platforms: ["youtube", "threads"] }],
|
|
147
|
+
options: { youtube: { title: "Launch day" } },
|
|
148
|
+
});
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Public URLs work without an upload: `media: [{ url: "https://example.com/a.jpg", type: "image" }]`.
|
|
152
|
+
For files on a user's device, show `uploadPageUrl` from `media.createUpload()` and call
|
|
153
|
+
`media.waitForUpload(id)`. See [media upload](https://ampost.io/docs?ref=github#media-upload).
|
|
154
|
+
|
|
155
|
+
## Everything else
|
|
156
|
+
|
|
157
|
+
Each tag of the API is a property: `posts`, `accounts`, `platformSets` (and posting queues),
|
|
158
|
+
`media`, `analytics`, `webhooks`, `platforms`, `docs`, `feedback`. Types for every request and response
|
|
159
|
+
are exported by name:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
import type { Post, PostsCreateBody, AnalyticsOverview } from "ampost";
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
`ampost.platforms.list()` returns each platform's limits and options, and `ampost.posts.validate(body)`
|
|
166
|
+
checks a post without creating it.
|
|
167
|
+
|
|
168
|
+
AI agents can use the same API through the hosted MCP server at `https://api.ampost.io/mcp`
|
|
169
|
+
([setup](https://ampost.io/docs/mcp?ref=github)).
|
|
170
|
+
|
|
171
|
+
## Development
|
|
172
|
+
|
|
173
|
+
The typed layer in `src/generated/` comes from `openapi.json`; never edit it by hand.
|
|
174
|
+
|
|
175
|
+
```sh
|
|
176
|
+
npm ci
|
|
177
|
+
npm run generate # from the committed openapi.json
|
|
178
|
+
npm run generate -- --spec https://api.ampost.io/openapi.json # refresh the snapshot, then generate
|
|
179
|
+
npm run typecheck && npm test && npm run build
|
|
180
|
+
AMPOST_API_KEY=amp_... npm run test:smoke # reads and validates only
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
`npm run check` regenerates and fails if anything changed, as CI does.
|
|
184
|
+
|
|
185
|
+
Why this generator: [openapi-typescript](https://openapi-ts.dev) turns the spec into types only, with
|
|
186
|
+
no runtime. A short script (`scripts/generate.mjs`) adds one method per operation on top, and the
|
|
187
|
+
hand-written client (`src/client.ts`) adds auth, retries, idempotency, errors and pagination. The
|
|
188
|
+
published package has no dependencies and its methods read like the API docs.
|
|
189
|
+
|
|
190
|
+
## Links
|
|
191
|
+
|
|
192
|
+
- [API docs](https://ampost.io/docs?ref=github) and [llms.txt](https://ampost.io/llms.txt?ref=github)
|
|
193
|
+
- [MCP server](https://ampost.io/docs/mcp?ref=github)
|
|
194
|
+
- [Pricing](https://ampost.io/pricing?ref=github)
|
|
195
|
+
- [Python SDK](https://github.com/ampost-io/ampost-python)
|
|
196
|
+
|
|
197
|
+
## License
|
|
198
|
+
|
|
199
|
+
MIT
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { IdempotentRequestOptions, ListResponse, RequestOptions, RequestSpec } from "./core.js";
|
|
2
|
+
import { AmpostResources } from "./generated/resources.js";
|
|
3
|
+
import { MediaResource } from "./media.js";
|
|
4
|
+
import { PagePromise } from "./pagination.js";
|
|
5
|
+
export declare const DEFAULT_BASE_URL = "https://api.ampost.io";
|
|
6
|
+
export interface ClientOptions {
|
|
7
|
+
/** An API key from https://ampost.io/app/settings/api-keys. Default: `process.env.AMPOST_API_KEY`. */
|
|
8
|
+
apiKey?: string;
|
|
9
|
+
/** Default: `process.env.AMPOST_BASE_URL`, else `https://api.ampost.io`. */
|
|
10
|
+
baseUrl?: string;
|
|
11
|
+
/** Retries after a 429, a 5xx or a network error (see README, "Retries"). Default 2. */
|
|
12
|
+
maxRetries?: number;
|
|
13
|
+
/** Per-attempt timeout in milliseconds. Default 60 000. */
|
|
14
|
+
timeoutMs?: number;
|
|
15
|
+
/** A `Retry-After` longer than this is not waited for: the error is thrown. Default 60 000. */
|
|
16
|
+
maxRetryDelayMs?: number;
|
|
17
|
+
/** Headers sent with every request. */
|
|
18
|
+
defaultHeaders?: Record<string, string>;
|
|
19
|
+
/** Custom fetch, for proxies or tests. Default: the global `fetch` (Node 18+). */
|
|
20
|
+
fetch?: typeof fetch;
|
|
21
|
+
}
|
|
22
|
+
/** A finished HTTP exchange with the body already read. */
|
|
23
|
+
export interface RawResponse {
|
|
24
|
+
status: number;
|
|
25
|
+
statusText: string;
|
|
26
|
+
ok: boolean;
|
|
27
|
+
headers: Headers;
|
|
28
|
+
text: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The Ampost API client.
|
|
32
|
+
*
|
|
33
|
+
* import { Ampost } from "ampost";
|
|
34
|
+
* const client = new Ampost(); // reads AMPOST_API_KEY
|
|
35
|
+
* const post = await client.posts.create({ text: "Hello", targets: [{ platforms: ["bluesky"] }], publishNow: true });
|
|
36
|
+
*/
|
|
37
|
+
export declare class Ampost extends AmpostResources {
|
|
38
|
+
#private;
|
|
39
|
+
/** Media uploads, with `upload()` on top of the generated methods. */
|
|
40
|
+
readonly media: MediaResource;
|
|
41
|
+
readonly baseUrl: string;
|
|
42
|
+
readonly maxRetries: number;
|
|
43
|
+
readonly timeoutMs: number;
|
|
44
|
+
readonly maxRetryDelayMs: number;
|
|
45
|
+
constructor(options?: ClientOptions);
|
|
46
|
+
/**
|
|
47
|
+
* Sends one API call with auth, the idempotency key and retries. The generated methods call this;
|
|
48
|
+
* use it directly only for an endpoint this SDK version does not know yet.
|
|
49
|
+
*/
|
|
50
|
+
request<T>(spec: RequestSpec, options?: IdempotentRequestOptions): Promise<T>;
|
|
51
|
+
/** Like `request`, for list operations: returns a page that also iterates every item. */
|
|
52
|
+
paginate<T extends ListResponse>(spec: RequestSpec, options?: RequestOptions): PagePromise<T>;
|
|
53
|
+
/** Milliseconds to wait before retrying, or undefined to give up. */
|
|
54
|
+
private retryDelay;
|
|
55
|
+
/** @internal One HTTP exchange with the timeout; reads the body. Throws APIConnectionError without a response. */
|
|
56
|
+
send(url: string, init: RequestInit, options?: RequestOptions): Promise<RawResponse>;
|
|
57
|
+
}
|
|
58
|
+
export declare function buildUrl(baseUrl: string, path: string, query?: object): string;
|
|
59
|
+
/** Exponential backoff with jitter: about 0.5 s, 1 s, 2 s, ... up to 8 s. */
|
|
60
|
+
export declare function backoff(attempt: number): number;
|
|
61
|
+
/** A UUID v4 for `Idempotency-Key`; Node 18 has no global `crypto` without a flag, hence the fallback. */
|
|
62
|
+
export declare function randomKey(): string;
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Ampost = exports.DEFAULT_BASE_URL = void 0;
|
|
4
|
+
exports.buildUrl = buildUrl;
|
|
5
|
+
exports.backoff = backoff;
|
|
6
|
+
exports.randomKey = randomKey;
|
|
7
|
+
const errors_js_1 = require("./errors.js");
|
|
8
|
+
const resources_js_1 = require("./generated/resources.js");
|
|
9
|
+
const media_js_1 = require("./media.js");
|
|
10
|
+
const pagination_js_1 = require("./pagination.js");
|
|
11
|
+
const version_js_1 = require("./version.js");
|
|
12
|
+
exports.DEFAULT_BASE_URL = "https://api.ampost.io";
|
|
13
|
+
const env = (name) => typeof process === "undefined" ? undefined : process.env?.[name] || undefined;
|
|
14
|
+
/**
|
|
15
|
+
* The Ampost API client.
|
|
16
|
+
*
|
|
17
|
+
* import { Ampost } from "ampost";
|
|
18
|
+
* const client = new Ampost(); // reads AMPOST_API_KEY
|
|
19
|
+
* const post = await client.posts.create({ text: "Hello", targets: [{ platforms: ["bluesky"] }], publishNow: true });
|
|
20
|
+
*/
|
|
21
|
+
class Ampost extends resources_js_1.AmpostResources {
|
|
22
|
+
/** Media uploads, with `upload()` on top of the generated methods. */
|
|
23
|
+
media;
|
|
24
|
+
baseUrl;
|
|
25
|
+
maxRetries;
|
|
26
|
+
timeoutMs;
|
|
27
|
+
maxRetryDelayMs;
|
|
28
|
+
#apiKey;
|
|
29
|
+
#defaultHeaders;
|
|
30
|
+
#fetch;
|
|
31
|
+
constructor(options = {}) {
|
|
32
|
+
super();
|
|
33
|
+
const apiKey = options.apiKey ?? env("AMPOST_API_KEY");
|
|
34
|
+
if (!apiKey) {
|
|
35
|
+
throw new errors_js_1.AmpostError("Missing API key: pass { apiKey } or set AMPOST_API_KEY. Create one at https://ampost.io/app/settings/api-keys?ref=github");
|
|
36
|
+
}
|
|
37
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
38
|
+
if (typeof fetchImpl !== "function")
|
|
39
|
+
throw new errors_js_1.AmpostError("No fetch available: use Node 18+ or pass { fetch }");
|
|
40
|
+
this.#apiKey = apiKey;
|
|
41
|
+
this.#fetch = fetchImpl;
|
|
42
|
+
this.#defaultHeaders = { ...options.defaultHeaders };
|
|
43
|
+
this.baseUrl = (options.baseUrl ?? env("AMPOST_BASE_URL") ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
44
|
+
this.maxRetries = options.maxRetries ?? 2;
|
|
45
|
+
this.timeoutMs = options.timeoutMs ?? 60_000;
|
|
46
|
+
this.maxRetryDelayMs = options.maxRetryDelayMs ?? 60_000;
|
|
47
|
+
this.media = new media_js_1.MediaResource(this, (url, init, requestOptions) => this.send(url, init, requestOptions));
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Sends one API call with auth, the idempotency key and retries. The generated methods call this;
|
|
51
|
+
* use it directly only for an endpoint this SDK version does not know yet.
|
|
52
|
+
*/
|
|
53
|
+
async request(spec, options = {}) {
|
|
54
|
+
const headers = {
|
|
55
|
+
Accept: "application/json",
|
|
56
|
+
"User-Agent": `ampost-node/${version_js_1.VERSION}`,
|
|
57
|
+
...this.#defaultHeaders,
|
|
58
|
+
...options.headers,
|
|
59
|
+
Authorization: `Bearer ${this.#apiKey}`,
|
|
60
|
+
};
|
|
61
|
+
let body;
|
|
62
|
+
if (spec.body !== undefined) {
|
|
63
|
+
headers["Content-Type"] = "application/json";
|
|
64
|
+
body = JSON.stringify(spec.body);
|
|
65
|
+
}
|
|
66
|
+
if (spec.idempotent)
|
|
67
|
+
headers["Idempotency-Key"] = options.idempotencyKey ?? randomKey();
|
|
68
|
+
// Without a key, a write that timed out may have been done: only reads and keyed writes repeat.
|
|
69
|
+
const repeatable = spec.method === "GET" || spec.idempotent === true;
|
|
70
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
71
|
+
const url = buildUrl(this.baseUrl, spec.path, spec.query);
|
|
72
|
+
for (let attempt = 0;; attempt++) {
|
|
73
|
+
let response;
|
|
74
|
+
try {
|
|
75
|
+
response = await this.send(url, { method: spec.method, headers, body }, options);
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (!(error instanceof errors_js_1.APIConnectionError) || !repeatable || attempt >= maxRetries)
|
|
79
|
+
throw error;
|
|
80
|
+
await sleep(backoff(attempt), options.signal);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (response.ok)
|
|
84
|
+
return parseJson(response);
|
|
85
|
+
const error = errors_js_1.APIError.from(response.status, parseMaybeJson(response.text), response.headers, response.statusText);
|
|
86
|
+
const delay = this.retryDelay(error, attempt, repeatable);
|
|
87
|
+
if (delay === undefined || attempt >= maxRetries)
|
|
88
|
+
throw error;
|
|
89
|
+
await sleep(delay, options.signal);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** Like `request`, for list operations: returns a page that also iterates every item. */
|
|
93
|
+
paginate(spec, options) {
|
|
94
|
+
return new pagination_js_1.PagePromise((offset) => this.request(offset === undefined ? spec : { ...spec, query: { ...spec.query, offset } }, options));
|
|
95
|
+
}
|
|
96
|
+
/** Milliseconds to wait before retrying, or undefined to give up. */
|
|
97
|
+
retryDelay(error, attempt, repeatable) {
|
|
98
|
+
const retryable = error.status === 429 || // refused before anything ran
|
|
99
|
+
error.code === "IDEMPOTENCY_REQUEST_IN_PROGRESS" || // the first request with this key still runs
|
|
100
|
+
((error.status >= 500 || error.status === 408) && repeatable);
|
|
101
|
+
if (!retryable)
|
|
102
|
+
return undefined;
|
|
103
|
+
const retryAfter = (0, errors_js_1.parseRetryAfter)(error.headers.get("retry-after"));
|
|
104
|
+
if (retryAfter === undefined)
|
|
105
|
+
return backoff(attempt);
|
|
106
|
+
// A quota reset days away is not worth blocking on.
|
|
107
|
+
return retryAfter <= this.maxRetryDelayMs ? retryAfter : undefined;
|
|
108
|
+
}
|
|
109
|
+
/** @internal One HTTP exchange with the timeout; reads the body. Throws APIConnectionError without a response. */
|
|
110
|
+
async send(url, init, options = {}) {
|
|
111
|
+
const { signal } = options;
|
|
112
|
+
if (signal?.aborted)
|
|
113
|
+
throw abortReason(signal);
|
|
114
|
+
const controller = new AbortController();
|
|
115
|
+
const timeoutMs = options.timeoutMs ?? this.timeoutMs;
|
|
116
|
+
let timedOut = false;
|
|
117
|
+
const timer = setTimeout(() => {
|
|
118
|
+
timedOut = true;
|
|
119
|
+
controller.abort();
|
|
120
|
+
}, timeoutMs);
|
|
121
|
+
const onAbort = () => controller.abort();
|
|
122
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
123
|
+
try {
|
|
124
|
+
const response = await this.#fetch(url, { ...init, signal: controller.signal });
|
|
125
|
+
const text = await response.text();
|
|
126
|
+
return { status: response.status, statusText: response.statusText, ok: response.ok, headers: response.headers, text };
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
if (signal?.aborted)
|
|
130
|
+
throw abortReason(signal);
|
|
131
|
+
if (timedOut)
|
|
132
|
+
throw new errors_js_1.APITimeoutError(`Request timed out after ${timeoutMs} ms`, { cause: error });
|
|
133
|
+
throw new errors_js_1.APIConnectionError(`Connection error: ${error instanceof Error ? error.message : String(error)}`, {
|
|
134
|
+
cause: error,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
signal?.removeEventListener("abort", onAbort);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
exports.Ampost = Ampost;
|
|
144
|
+
function buildUrl(baseUrl, path, query) {
|
|
145
|
+
const url = new URL(`${baseUrl}${path}`);
|
|
146
|
+
for (const [key, value] of Object.entries(query ?? {})) {
|
|
147
|
+
if (value === undefined || value === null)
|
|
148
|
+
continue;
|
|
149
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
150
|
+
url.searchParams.append(key, item instanceof Date ? item.toISOString() : String(item));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return url.toString();
|
|
154
|
+
}
|
|
155
|
+
function parseMaybeJson(text) {
|
|
156
|
+
try {
|
|
157
|
+
return JSON.parse(text);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return text;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function parseJson(response) {
|
|
164
|
+
if (!response.text)
|
|
165
|
+
return undefined;
|
|
166
|
+
try {
|
|
167
|
+
return JSON.parse(response.text);
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
throw new errors_js_1.AmpostError(`Expected JSON from the API, got: ${response.text.slice(0, 200)}`, { cause: error });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** Exponential backoff with jitter: about 0.5 s, 1 s, 2 s, ... up to 8 s. */
|
|
174
|
+
function backoff(attempt) {
|
|
175
|
+
const base = Math.min(500 * 2 ** attempt, 8_000);
|
|
176
|
+
return Math.round(base * (0.75 + Math.random() * 0.5));
|
|
177
|
+
}
|
|
178
|
+
function abortReason(signal) {
|
|
179
|
+
return signal.reason ?? new DOMException("The operation was aborted", "AbortError");
|
|
180
|
+
}
|
|
181
|
+
function sleep(ms, signal) {
|
|
182
|
+
return new Promise((resolve, reject) => {
|
|
183
|
+
if (signal?.aborted)
|
|
184
|
+
return reject(abortReason(signal));
|
|
185
|
+
const timer = setTimeout(() => {
|
|
186
|
+
signal?.removeEventListener("abort", onAbort);
|
|
187
|
+
resolve();
|
|
188
|
+
}, ms);
|
|
189
|
+
const onAbort = () => {
|
|
190
|
+
clearTimeout(timer);
|
|
191
|
+
reject(abortReason(signal));
|
|
192
|
+
};
|
|
193
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
/** A UUID v4 for `Idempotency-Key`; Node 18 has no global `crypto` without a flag, hence the fallback. */
|
|
197
|
+
function randomKey() {
|
|
198
|
+
const webCrypto = globalThis.crypto;
|
|
199
|
+
if (webCrypto?.randomUUID)
|
|
200
|
+
return webCrypto.randomUUID();
|
|
201
|
+
const hex = Array.from({ length: 32 }, () => Math.floor(Math.random() * 16).toString(16));
|
|
202
|
+
hex[12] = "4";
|
|
203
|
+
hex[16] = ((parseInt(hex[16], 16) & 0x3) | 0x8).toString(16);
|
|
204
|
+
const s = hex.join("");
|
|
205
|
+
return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`;
|
|
206
|
+
}
|
|
@@ -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;
|
package/dist/cjs/core.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.encodePathParam = encodePathParam;
|
|
4
|
+
function encodePathParam(value) {
|
|
5
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
6
|
+
throw new TypeError(`Expected a non-empty string path parameter, got ${JSON.stringify(value)}`);
|
|
7
|
+
}
|
|
8
|
+
return encodeURIComponent(value);
|
|
9
|
+
}
|
|
@@ -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;
|