bulkit 0.0.1 → 0.1.1
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 +266 -2
- package/dist/index.cjs +853 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +5741 -0
- package/dist/index.d.ts +5741 -0
- package/dist/index.js +828 -0
- package/dist/index.js.map +1 -0
- package/package.json +86 -6
package/dist/index.js
ADDED
|
@@ -0,0 +1,828 @@
|
|
|
1
|
+
//#region src/core/api-promise.ts
|
|
2
|
+
/**
|
|
3
|
+
* A `Promise` of the parsed response body that can also hand back the raw `Response`:
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* const post = await client.posts.retrieve('pst_123');
|
|
7
|
+
* const { data, requestId, rateLimit } = await client.posts.retrieve('pst_123').withResponse();
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
var APIPromise = class extends Promise {
|
|
11
|
+
#responsePromise;
|
|
12
|
+
constructor(responsePromise) {
|
|
13
|
+
super((resolve) => resolve(null));
|
|
14
|
+
this.#responsePromise = responsePromise;
|
|
15
|
+
}
|
|
16
|
+
/** Resolves to the body together with the raw response and its metadata. */
|
|
17
|
+
withResponse() {
|
|
18
|
+
return this.#responsePromise;
|
|
19
|
+
}
|
|
20
|
+
#parsed;
|
|
21
|
+
#parse() {
|
|
22
|
+
this.#parsed ??= this.#responsePromise.then((r) => r.data);
|
|
23
|
+
return this.#parsed;
|
|
24
|
+
}
|
|
25
|
+
then(onfulfilled, onrejected) {
|
|
26
|
+
return this.#parse().then(onfulfilled, onrejected);
|
|
27
|
+
}
|
|
28
|
+
catch(onrejected) {
|
|
29
|
+
return this.#parse().catch(onrejected);
|
|
30
|
+
}
|
|
31
|
+
finally(onfinally) {
|
|
32
|
+
return this.#parse().finally(onfinally);
|
|
33
|
+
}
|
|
34
|
+
static get [Symbol.species]() {
|
|
35
|
+
return Promise;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
function rateLimitFrom(headers) {
|
|
39
|
+
const num = (name) => {
|
|
40
|
+
const raw = headers.get(name);
|
|
41
|
+
const value = raw === null ? NaN : Number(raw);
|
|
42
|
+
return Number.isFinite(value) ? value : null;
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
limit: num("x-ratelimit-limit"),
|
|
46
|
+
remaining: num("x-ratelimit-remaining"),
|
|
47
|
+
reset: num("x-ratelimit-reset")
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/core/errors.ts
|
|
52
|
+
/** Base class for every error this SDK throws. `instanceof BulkitError` catches them all. */
|
|
53
|
+
var BulkitError = class extends Error {
|
|
54
|
+
name = "BulkitError";
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* The API answered with a non-2xx status.
|
|
58
|
+
*
|
|
59
|
+
* Branch on `code` (stable within v1) rather than `message` (prose, may change).
|
|
60
|
+
* New codes can appear at any time, so always keep a fallback branch.
|
|
61
|
+
*/
|
|
62
|
+
var APIError = class extends BulkitError {
|
|
63
|
+
name = "APIError";
|
|
64
|
+
/** HTTP status code. */
|
|
65
|
+
status;
|
|
66
|
+
/** Machine-readable error code, e.g. `content_too_long`. */
|
|
67
|
+
code;
|
|
68
|
+
/** Path into the request body (or the header name) that caused the failure. */
|
|
69
|
+
field;
|
|
70
|
+
/** Every field-level failure when schema validation rejected more than one. */
|
|
71
|
+
details;
|
|
72
|
+
/** Quote this when contacting support: it is what Bulkit searches on. */
|
|
73
|
+
requestId;
|
|
74
|
+
headers;
|
|
75
|
+
/** The parsed `error` object exactly as the API sent it. */
|
|
76
|
+
error;
|
|
77
|
+
constructor(status, error, message, headers) {
|
|
78
|
+
super(message);
|
|
79
|
+
this.status = status;
|
|
80
|
+
this.error = error;
|
|
81
|
+
this.code = error?.code;
|
|
82
|
+
this.field = error?.field ?? void 0;
|
|
83
|
+
this.details = error?.details ?? void 0;
|
|
84
|
+
this.requestId = error?.requestId ?? headers.get("x-request-id") ?? void 0;
|
|
85
|
+
this.headers = headers;
|
|
86
|
+
}
|
|
87
|
+
/** @internal */
|
|
88
|
+
static from(status, body, headers) {
|
|
89
|
+
const error = extractError(body);
|
|
90
|
+
const message = error?.message ?? `Request failed with status ${status}`;
|
|
91
|
+
return new (errorClassFor(status))(status, error, message, headers);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
/** 400 — the request was malformed or failed schema validation. */
|
|
95
|
+
var BadRequestError = class extends APIError {
|
|
96
|
+
name = "BadRequestError";
|
|
97
|
+
};
|
|
98
|
+
/** 401 — the API key is missing, malformed, revoked or unknown. */
|
|
99
|
+
var AuthenticationError = class extends APIError {
|
|
100
|
+
name = "AuthenticationError";
|
|
101
|
+
};
|
|
102
|
+
/**
|
|
103
|
+
* 402 — the plan's allowance for this period is spent.
|
|
104
|
+
*
|
|
105
|
+
* This is NOT a rate limit: retrying will never succeed until the period resets.
|
|
106
|
+
* `client.usage.retrieve()` has the numbers and `periodEnd`. The SDK never retries it.
|
|
107
|
+
*/
|
|
108
|
+
var QuotaExceededError = class extends APIError {
|
|
109
|
+
name = "QuotaExceededError";
|
|
110
|
+
};
|
|
111
|
+
/** 403 — the key lacks the scope for this call (e.g. a read-only key attempting a write). */
|
|
112
|
+
var PermissionDeniedError = class extends APIError {
|
|
113
|
+
name = "PermissionDeniedError";
|
|
114
|
+
};
|
|
115
|
+
/** 404 — the resource does not exist in this workspace. */
|
|
116
|
+
var NotFoundError = class extends APIError {
|
|
117
|
+
name = "NotFoundError";
|
|
118
|
+
};
|
|
119
|
+
/** 409 — the resource is in a state that does not allow this, or a request with the same idempotency key is still running. */
|
|
120
|
+
var ConflictError = class extends APIError {
|
|
121
|
+
name = "ConflictError";
|
|
122
|
+
};
|
|
123
|
+
/** 413 — the request body or uploaded file is too large. */
|
|
124
|
+
var PayloadTooLargeError = class extends APIError {
|
|
125
|
+
name = "PayloadTooLargeError";
|
|
126
|
+
};
|
|
127
|
+
/** 415 — the uploaded file's type is not accepted. */
|
|
128
|
+
var UnsupportedMediaTypeError = class extends APIError {
|
|
129
|
+
name = "UnsupportedMediaTypeError";
|
|
130
|
+
};
|
|
131
|
+
/** 422 — well-formed but refused, e.g. a platform rule or an idempotency key reused with a different body. */
|
|
132
|
+
var UnprocessableEntityError = class extends APIError {
|
|
133
|
+
name = "UnprocessableEntityError";
|
|
134
|
+
};
|
|
135
|
+
/** 429 — too many requests. Retried automatically, honouring `Retry-After`. */
|
|
136
|
+
var RateLimitError = class extends APIError {
|
|
137
|
+
name = "RateLimitError";
|
|
138
|
+
/** Seconds the API asked us to wait before retrying, if it said. */
|
|
139
|
+
get retryAfter() {
|
|
140
|
+
const value = Number(this.headers.get("retry-after"));
|
|
141
|
+
return Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
/** 5xx — a fault on Bulkit's side or an unreachable dependency. */
|
|
145
|
+
var InternalServerError = class extends APIError {
|
|
146
|
+
name = "InternalServerError";
|
|
147
|
+
};
|
|
148
|
+
/** The request never got an HTTP response (DNS, TLS, connection reset, …). */
|
|
149
|
+
var APIConnectionError = class extends BulkitError {
|
|
150
|
+
name = "APIConnectionError";
|
|
151
|
+
constructor(message = "Connection error.", options) {
|
|
152
|
+
super(message, options);
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
/** The request exceeded the configured `timeout`. */
|
|
156
|
+
var APIConnectionTimeoutError = class extends APIConnectionError {
|
|
157
|
+
name = "APIConnectionTimeoutError";
|
|
158
|
+
constructor(message = "Request timed out.") {
|
|
159
|
+
super(message);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
/** The caller aborted the request through its `AbortSignal`. */
|
|
163
|
+
var APIUserAbortError = class extends BulkitError {
|
|
164
|
+
name = "APIUserAbortError";
|
|
165
|
+
constructor(message = "Request was aborted.") {
|
|
166
|
+
super(message);
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
/** A webhook delivery failed signature or timestamp verification. Respond 400 and drop it. */
|
|
170
|
+
var WebhookVerificationError = class extends BulkitError {
|
|
171
|
+
name = "WebhookVerificationError";
|
|
172
|
+
};
|
|
173
|
+
function errorClassFor(status) {
|
|
174
|
+
switch (status) {
|
|
175
|
+
case 400: return BadRequestError;
|
|
176
|
+
case 401: return AuthenticationError;
|
|
177
|
+
case 402: return QuotaExceededError;
|
|
178
|
+
case 403: return PermissionDeniedError;
|
|
179
|
+
case 404: return NotFoundError;
|
|
180
|
+
case 409: return ConflictError;
|
|
181
|
+
case 413: return PayloadTooLargeError;
|
|
182
|
+
case 415: return UnsupportedMediaTypeError;
|
|
183
|
+
case 422: return UnprocessableEntityError;
|
|
184
|
+
case 429: return RateLimitError;
|
|
185
|
+
default: return status >= 500 ? InternalServerError : APIError;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function extractError(body) {
|
|
189
|
+
if (body && typeof body === "object" && "error" in body) {
|
|
190
|
+
const error = body.error;
|
|
191
|
+
if (error && typeof error === "object" && "code" in error) return error;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
//#endregion
|
|
195
|
+
//#region src/core/pagination.ts
|
|
196
|
+
/**
|
|
197
|
+
* One page of a cursor-paginated list.
|
|
198
|
+
*
|
|
199
|
+
* Iterate it with `for await` to walk every item across every page, or page
|
|
200
|
+
* manually with `hasNextPage()` / `getNextPage()`.
|
|
201
|
+
*/
|
|
202
|
+
var CursorPage = class CursorPage {
|
|
203
|
+
data;
|
|
204
|
+
/** Opaque. Pass it back as `cursor`; never parse or construct one. */
|
|
205
|
+
nextCursor;
|
|
206
|
+
response;
|
|
207
|
+
#fetchPage;
|
|
208
|
+
constructor(body, response, fetchPage) {
|
|
209
|
+
this.data = body.data;
|
|
210
|
+
this.nextCursor = body.nextCursor;
|
|
211
|
+
this.response = response;
|
|
212
|
+
this.#fetchPage = fetchPage;
|
|
213
|
+
}
|
|
214
|
+
/** A null `nextCursor` — not an empty `data` — is the end of the list. */
|
|
215
|
+
hasNextPage() {
|
|
216
|
+
return this.nextCursor !== null;
|
|
217
|
+
}
|
|
218
|
+
async getNextPage() {
|
|
219
|
+
if (this.nextCursor === null) throw new Error("No next page; check `hasNextPage()` before calling `getNextPage()`.");
|
|
220
|
+
const { data, response } = await this.#fetchPage(this.nextCursor);
|
|
221
|
+
return new CursorPage(data, response, this.#fetchPage);
|
|
222
|
+
}
|
|
223
|
+
/** Yields this page and every page after it. */
|
|
224
|
+
async *iterPages() {
|
|
225
|
+
let page = this;
|
|
226
|
+
yield page;
|
|
227
|
+
while (page.hasNextPage()) {
|
|
228
|
+
page = await page.getNextPage();
|
|
229
|
+
yield page;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
async *[Symbol.asyncIterator]() {
|
|
233
|
+
for await (const page of this.iterPages()) yield* page.data;
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
/**
|
|
237
|
+
* Resolves to the first `CursorPage`, and is also directly async-iterable over every item:
|
|
238
|
+
*
|
|
239
|
+
* ```ts
|
|
240
|
+
* for await (const post of client.posts.list({ status: 'scheduled' })) { ... }
|
|
241
|
+
* ```
|
|
242
|
+
*/
|
|
243
|
+
var PagePromise = class extends APIPromise {
|
|
244
|
+
constructor(fetchPage, firstCursor) {
|
|
245
|
+
super(fetchPage(firstCursor).then((res) => ({
|
|
246
|
+
...res,
|
|
247
|
+
data: new CursorPage(res.data, res.response, fetchPage)
|
|
248
|
+
})));
|
|
249
|
+
}
|
|
250
|
+
async *[Symbol.asyncIterator]() {
|
|
251
|
+
yield* await this;
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
//#endregion
|
|
255
|
+
//#region src/core/utils.ts
|
|
256
|
+
/** Reads an environment variable on runtimes that have `process`, and nothing on those that do not. */
|
|
257
|
+
function readEnv(name) {
|
|
258
|
+
const value = (globalThis.process?.env)?.[name]?.trim();
|
|
259
|
+
return value ? value : void 0;
|
|
260
|
+
}
|
|
261
|
+
/** Tagged template that URI-encodes every interpolated path segment. */
|
|
262
|
+
function path(strings, ...params) {
|
|
263
|
+
return strings.reduce((acc, part, i) => {
|
|
264
|
+
const param = params[i];
|
|
265
|
+
if (param === void 0) return acc + part;
|
|
266
|
+
if (param === "") throw new TypeError("Path parameters must not be empty.");
|
|
267
|
+
return acc + part + encodeURIComponent(param);
|
|
268
|
+
}, "");
|
|
269
|
+
}
|
|
270
|
+
function buildQuery(query) {
|
|
271
|
+
if (!query) return "";
|
|
272
|
+
const params = new URLSearchParams();
|
|
273
|
+
for (const [key, value] of Object.entries(query)) for (const item of Array.isArray(value) ? value : [value]) if (item !== void 0 && item !== null) params.append(key, String(item));
|
|
274
|
+
const qs = params.toString();
|
|
275
|
+
return qs ? `?${qs}` : "";
|
|
276
|
+
}
|
|
277
|
+
function sleep(ms) {
|
|
278
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
279
|
+
}
|
|
280
|
+
function uuid() {
|
|
281
|
+
return globalThis.crypto.randomUUID();
|
|
282
|
+
}
|
|
283
|
+
function isBrowser() {
|
|
284
|
+
return typeof globalThis.window !== "undefined" && typeof globalThis.document !== "undefined";
|
|
285
|
+
}
|
|
286
|
+
//#endregion
|
|
287
|
+
//#region src/core/resource.ts
|
|
288
|
+
var APIResource = class {
|
|
289
|
+
_client;
|
|
290
|
+
constructor(client) {
|
|
291
|
+
this._client = client;
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
//#endregion
|
|
295
|
+
//#region src/resources/channels.ts
|
|
296
|
+
var Channels = class extends APIResource {
|
|
297
|
+
/** Every channel this workspace can post to. Call this before composing a post. */
|
|
298
|
+
list(options) {
|
|
299
|
+
return this._client.get("/channels", void 0, options);
|
|
300
|
+
}
|
|
301
|
+
/** Account-level rules for one channel (privacy levels, required flair, …), read live from the platform. */
|
|
302
|
+
capabilities(channelId, options) {
|
|
303
|
+
return this._client.get(path`/channels/${channelId}/capabilities`, void 0, options);
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Search the values of a `search`-type option, such as Instagram's `location_id`.
|
|
307
|
+
* Pass `q` to turn a name into values, or `value` to turn a stored value back into its label.
|
|
308
|
+
*/
|
|
309
|
+
optionChoices(channelId, key, params, options) {
|
|
310
|
+
return this._client.get(path`/channels/${channelId}/options/${key}/choices`, params, options);
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
//#endregion
|
|
314
|
+
//#region src/resources/media.ts
|
|
315
|
+
var Media = class extends APIResource {
|
|
316
|
+
uploads = new MediaUploads(this._client);
|
|
317
|
+
/** The workspace's media library. */
|
|
318
|
+
list(options) {
|
|
319
|
+
return this._client.get("/media", void 0, options);
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Upload a file in one request: images up to 10 MB, video and PDFs up to 100 MB,
|
|
323
|
+
* subtitles up to 5 MB. For larger video, use `uploadMultipart()`.
|
|
324
|
+
*/
|
|
325
|
+
upload(file, params = {}, options) {
|
|
326
|
+
const blob = toBlob(file, params.mimeType);
|
|
327
|
+
const fileName = params.fileName ?? (file instanceof File ? file.name : void 0);
|
|
328
|
+
if (!fileName) throw new TypeError("`fileName` is required unless `file` is a File.");
|
|
329
|
+
const form = new FormData();
|
|
330
|
+
form.append("file", blob, fileName);
|
|
331
|
+
return this._client.post("/media", form, options);
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Upload a large video through an upload session: start it, PUT every part to its
|
|
335
|
+
* signed URL, then complete it. The session is aborted if any step fails.
|
|
336
|
+
*
|
|
337
|
+
* An `idempotencyKey` passed here is split per step (`<key>:start`, `<key>:complete`),
|
|
338
|
+
* since the API holds a key to one route. Keep it under 246 characters so both fit.
|
|
339
|
+
*/
|
|
340
|
+
async uploadMultipart(file, params = {}, options) {
|
|
341
|
+
const blob = toBlob(file, params.mimeType);
|
|
342
|
+
const fileName = params.fileName ?? (file instanceof File ? file.name : void 0);
|
|
343
|
+
const mimeType = params.mimeType ?? blob.type;
|
|
344
|
+
if (!fileName) throw new TypeError("`fileName` is required unless `file` is a File.");
|
|
345
|
+
if (!mimeType) throw new TypeError("`mimeType` is required when the Blob has no type.");
|
|
346
|
+
const session = await this.uploads.start({
|
|
347
|
+
fileName,
|
|
348
|
+
mimeType,
|
|
349
|
+
size: blob.size
|
|
350
|
+
}, stepOptions(options, "start"));
|
|
351
|
+
const concurrency = Math.max(1, Math.min(params.concurrency ?? 4, 100));
|
|
352
|
+
try {
|
|
353
|
+
const partNumbers = Array.from({ length: session.partCount }, (_, i) => i + 1);
|
|
354
|
+
for (let i = 0; i < partNumbers.length; i += concurrency) {
|
|
355
|
+
const batch = partNumbers.slice(i, i + concurrency);
|
|
356
|
+
const parts = await this.uploads.signParts(session.id, { partNumbers: batch }, {
|
|
357
|
+
...options,
|
|
358
|
+
idempotencyKey: void 0
|
|
359
|
+
});
|
|
360
|
+
await Promise.all(parts.map((part) => this.#putPart(blob, session, part, options?.signal)));
|
|
361
|
+
}
|
|
362
|
+
return await this.uploads.complete(session.id, stepOptions(options, "complete"));
|
|
363
|
+
} catch (error) {
|
|
364
|
+
await this.uploads.abort(session.id).catch(() => void 0);
|
|
365
|
+
throw error;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
/** Delete a file from the media library. */
|
|
369
|
+
delete(mediaId, options) {
|
|
370
|
+
return this._client.delete(path`/media/${mediaId}`, options);
|
|
371
|
+
}
|
|
372
|
+
async #putPart(blob, session, part, signal) {
|
|
373
|
+
const start = (part.partNumber - 1) * session.partSize;
|
|
374
|
+
const body = blob.slice(start, start + session.partSize);
|
|
375
|
+
const response = await this._client.fetchExternal(part.url, {
|
|
376
|
+
method: "PUT",
|
|
377
|
+
body,
|
|
378
|
+
signal
|
|
379
|
+
});
|
|
380
|
+
if (!response.ok) throw new APIConnectionError(`Uploading part ${part.partNumber} failed with status ${response.status}.`);
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
/** Low-level upload-session calls. `media.uploadMultipart()` drives them for you. */
|
|
384
|
+
var MediaUploads = class extends APIResource {
|
|
385
|
+
start(params, options) {
|
|
386
|
+
return this._client.post("/media/uploads", params, options);
|
|
387
|
+
}
|
|
388
|
+
/** Signed PUT URLs for up to 100 parts. Valid for an hour, so ask as you go. */
|
|
389
|
+
signParts(uploadId, params, options) {
|
|
390
|
+
return this._client.post(path`/media/uploads/${uploadId}/parts`, params, options);
|
|
391
|
+
}
|
|
392
|
+
/** Finish the session. Returns the new media item, whose `id` goes in `mediaIds`. */
|
|
393
|
+
complete(uploadId, options) {
|
|
394
|
+
return this._client.post(path`/media/uploads/${uploadId}/complete`, void 0, options);
|
|
395
|
+
}
|
|
396
|
+
abort(uploadId, options) {
|
|
397
|
+
return this._client.delete(path`/media/uploads/${uploadId}`, options);
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
function toBlob(file, type) {
|
|
401
|
+
if (file instanceof Blob) return type && type !== file.type ? new Blob([file], { type }) : file;
|
|
402
|
+
const bytes = file instanceof ArrayBuffer ? new Uint8Array(file) : new Uint8Array(file.buffer, file.byteOffset, file.byteLength).slice();
|
|
403
|
+
return new Blob([bytes], type ? { type } : {});
|
|
404
|
+
}
|
|
405
|
+
/** The caller's key for one step of a multi-request call, or the options untouched. */
|
|
406
|
+
function stepOptions(options, step) {
|
|
407
|
+
if (!options?.idempotencyKey) return options;
|
|
408
|
+
return {
|
|
409
|
+
...options,
|
|
410
|
+
idempotencyKey: `${options.idempotencyKey}:${step}`
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
//#endregion
|
|
414
|
+
//#region src/resources/platforms.ts
|
|
415
|
+
var Platforms = class extends APIResource {
|
|
416
|
+
/**
|
|
417
|
+
* Live per-platform rules: character counts, attachments, thread length, accepted
|
|
418
|
+
* media types. Read these instead of hard-coding them — they change.
|
|
419
|
+
*/
|
|
420
|
+
list(options) {
|
|
421
|
+
return this._client.get("/platforms", void 0, options);
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
//#endregion
|
|
425
|
+
//#region src/resources/posts.ts
|
|
426
|
+
var Posts = class extends APIResource {
|
|
427
|
+
comments = new Comments(this._client);
|
|
428
|
+
/**
|
|
429
|
+
* Create one submission targeting one or more channels.
|
|
430
|
+
*
|
|
431
|
+
* Call this ONCE with several `channels`, not once per channel. With `intent: 'now'`
|
|
432
|
+
* it returns as soon as the work is queued (`status: 'publishing'`); the outcome
|
|
433
|
+
* arrives later via webhooks or `retrieve()`.
|
|
434
|
+
*/
|
|
435
|
+
create(params, options) {
|
|
436
|
+
return this._client.post("/posts", params, options);
|
|
437
|
+
}
|
|
438
|
+
retrieve(postId, options) {
|
|
439
|
+
return this._client.get(path`/posts/${postId}`, void 0, options);
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Submissions, newest first. Await it for one page, or iterate it for every post:
|
|
443
|
+
*
|
|
444
|
+
* ```ts
|
|
445
|
+
* for await (const post of bulkit.posts.list({ status: 'failed' })) { ... }
|
|
446
|
+
* ```
|
|
447
|
+
*/
|
|
448
|
+
list(params, options) {
|
|
449
|
+
return this._client.getPage("/posts", params, options);
|
|
450
|
+
}
|
|
451
|
+
/** Replace an unpublished submission. Once it has published, use `revise()`. */
|
|
452
|
+
update(postId, params, options) {
|
|
453
|
+
return this._client.put(path`/posts/${postId}`, params, options);
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Remove Bulkit's record of a submission. Published copies stay LIVE on the
|
|
457
|
+
* platforms — use `retract()` to take them down.
|
|
458
|
+
*/
|
|
459
|
+
delete(postId, options) {
|
|
460
|
+
return this._client.delete(path`/posts/${postId}`, options);
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Publish now, or retry a failed / partially published submission. Channels that
|
|
464
|
+
* already published are skipped. Asynchronous, like `intent: 'now'`.
|
|
465
|
+
*/
|
|
466
|
+
publish(postId, options) {
|
|
467
|
+
return this._client.post(path`/posts/${postId}/publish`, void 0, options);
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* PERMANENTLY delete the published copies from their platforms, with their likes and
|
|
471
|
+
* replies. Not every channel can be retracted: always read `remaining`.
|
|
472
|
+
*/
|
|
473
|
+
retract(postId, options) {
|
|
474
|
+
return this._client.post(path`/posts/${postId}/retract`, void 0, options);
|
|
475
|
+
}
|
|
476
|
+
/** Rewrite live copy in place, where the platform allows it (`limits.remoteEdit`). */
|
|
477
|
+
revise(postId, params, options) {
|
|
478
|
+
return this._client.post(path`/posts/${postId}/revise`, params, options);
|
|
479
|
+
}
|
|
480
|
+
metrics(postId, options) {
|
|
481
|
+
return this._client.get(path`/posts/${postId}/metrics`, void 0, options);
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
var Comments = class extends APIResource {
|
|
485
|
+
/** Comments on one channel's copy of a post, read live from the platform. */
|
|
486
|
+
list(postId, params, options) {
|
|
487
|
+
return this._client.getPage(path`/posts/${postId}/comments`, params, options);
|
|
488
|
+
}
|
|
489
|
+
/** Reply publicly to a comment. The reply is visible the moment this returns. */
|
|
490
|
+
reply(postId, commentId, params, options) {
|
|
491
|
+
return this._client.post(path`/posts/${postId}/comments/${commentId}/replies`, params, options);
|
|
492
|
+
}
|
|
493
|
+
};
|
|
494
|
+
//#endregion
|
|
495
|
+
//#region src/resources/stats.ts
|
|
496
|
+
var Stats = class extends APIResource {
|
|
497
|
+
/** Analytics counted from the posts themselves. Can go down when posts are deleted. */
|
|
498
|
+
retrieve(params, options) {
|
|
499
|
+
return this._client.get("/stats", params, options);
|
|
500
|
+
}
|
|
501
|
+
/** When, where and in what format the workspace's posts perform best. */
|
|
502
|
+
insights(params, options) {
|
|
503
|
+
return this._client.get("/stats/insights", params, options);
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
//#endregion
|
|
507
|
+
//#region src/resources/tags.ts
|
|
508
|
+
var Tags = class extends APIResource {
|
|
509
|
+
/** The workspace's own labels for submissions. Never published, unlike hashtags. */
|
|
510
|
+
list(options) {
|
|
511
|
+
return this._client.get("/tags", void 0, options);
|
|
512
|
+
}
|
|
513
|
+
};
|
|
514
|
+
//#endregion
|
|
515
|
+
//#region src/resources/usage.ts
|
|
516
|
+
var Usage = class extends APIResource {
|
|
517
|
+
/**
|
|
518
|
+
* The billing meter for the current period. The only endpoint that predicts a
|
|
519
|
+
* `QuotaExceededError` — do not use `stats` for that.
|
|
520
|
+
*/
|
|
521
|
+
retrieve(options) {
|
|
522
|
+
return this._client.get("/usage", void 0, options);
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
//#endregion
|
|
526
|
+
//#region src/webhooks.ts
|
|
527
|
+
const SIGNATURE_HEADER = "x-bulkit-signature";
|
|
528
|
+
const DEFAULT_TOLERANCE_SECONDS = 300;
|
|
529
|
+
/**
|
|
530
|
+
* Verify a webhook delivery and return the parsed event.
|
|
531
|
+
*
|
|
532
|
+
* `payload` MUST be the raw request body exactly as received — not `JSON.stringify(req.body)`,
|
|
533
|
+
* whose key order and whitespace differ and so produce a different signature.
|
|
534
|
+
*
|
|
535
|
+
* ```ts
|
|
536
|
+
* app.post('/webhooks/bulkit', express.raw({ type: 'application/json' }), async (req, res) => {
|
|
537
|
+
* const event = await verifyWebhook(req.body, req.headers, { secret });
|
|
538
|
+
* res.sendStatus(200);
|
|
539
|
+
* });
|
|
540
|
+
* ```
|
|
541
|
+
*
|
|
542
|
+
* @throws {WebhookVerificationError} if the signature or timestamp does not check out.
|
|
543
|
+
*/
|
|
544
|
+
async function verifyWebhook(payload, headers, options) {
|
|
545
|
+
const body = typeof payload === "string" ? payload : new TextDecoder().decode(payload);
|
|
546
|
+
const header = getHeader(headers, SIGNATURE_HEADER);
|
|
547
|
+
if (!header) throw new WebhookVerificationError(`Missing ${SIGNATURE_HEADER} header.`);
|
|
548
|
+
const { timestamp, signatures } = parseSignatureHeader(header);
|
|
549
|
+
const now = Math.floor((options.now?.() ?? Date.now()) / 1e3);
|
|
550
|
+
const tolerance = options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
|
|
551
|
+
if (Math.abs(now - timestamp) > tolerance) throw new WebhookVerificationError("Webhook timestamp is outside the tolerance window.");
|
|
552
|
+
const expected = await sign(options.secret, `${timestamp}.${body}`);
|
|
553
|
+
if (!signatures.some((candidate) => timingSafeEqual(expected, candidate))) throw new WebhookVerificationError("Webhook signature does not match.");
|
|
554
|
+
try {
|
|
555
|
+
return JSON.parse(body);
|
|
556
|
+
} catch {
|
|
557
|
+
throw new WebhookVerificationError("Webhook body is not valid JSON.");
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
/** Compute the `x-bulkit-signature` header value for a payload. Useful for testing your receiver. */
|
|
561
|
+
async function signWebhookPayload(payload, secret, timestamp = Math.floor(Date.now() / 1e3)) {
|
|
562
|
+
return `t=${timestamp},v1=${await sign(secret, `${timestamp}.${payload}`)}`;
|
|
563
|
+
}
|
|
564
|
+
async function sign(secret, message) {
|
|
565
|
+
const encoder = new TextEncoder();
|
|
566
|
+
const key = await globalThis.crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
567
|
+
name: "HMAC",
|
|
568
|
+
hash: "SHA-256"
|
|
569
|
+
}, false, ["sign"]);
|
|
570
|
+
const digest = await globalThis.crypto.subtle.sign("HMAC", key, encoder.encode(message));
|
|
571
|
+
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
572
|
+
}
|
|
573
|
+
function parseSignatureHeader(header) {
|
|
574
|
+
let timestamp = NaN;
|
|
575
|
+
const signatures = [];
|
|
576
|
+
for (const part of header.split(",")) {
|
|
577
|
+
const [key, value] = part.trim().split("=", 2);
|
|
578
|
+
if (key === "t") timestamp = Number(value);
|
|
579
|
+
else if (key === "v1" && value) signatures.push(value);
|
|
580
|
+
}
|
|
581
|
+
if (!Number.isInteger(timestamp) || signatures.length === 0) throw new WebhookVerificationError(`Malformed ${SIGNATURE_HEADER} header.`);
|
|
582
|
+
return {
|
|
583
|
+
timestamp,
|
|
584
|
+
signatures
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
/** Constant-time string comparison, so timing does not leak how much of a guess was right. */
|
|
588
|
+
function timingSafeEqual(a, b) {
|
|
589
|
+
if (a.length !== b.length) return false;
|
|
590
|
+
let diff = 0;
|
|
591
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
592
|
+
return diff === 0;
|
|
593
|
+
}
|
|
594
|
+
function getHeader(headers, name) {
|
|
595
|
+
if (headers instanceof Headers) return headers.get(name) ?? void 0;
|
|
596
|
+
const key = Object.keys(headers).find((k) => k.toLowerCase() === name);
|
|
597
|
+
const value = key === void 0 ? void 0 : headers[key];
|
|
598
|
+
return Array.isArray(value) ? value[0] : value;
|
|
599
|
+
}
|
|
600
|
+
//#endregion
|
|
601
|
+
//#region src/resources/webhooks.ts
|
|
602
|
+
var Webhooks = class extends APIResource {
|
|
603
|
+
/**
|
|
604
|
+
* Register an endpoint. The response carries the signing `secret` — store it now;
|
|
605
|
+
* no other call returns it.
|
|
606
|
+
*/
|
|
607
|
+
create(params, options) {
|
|
608
|
+
return this._client.post("/webhooks", params, options);
|
|
609
|
+
}
|
|
610
|
+
retrieve(webhookId, options) {
|
|
611
|
+
return this._client.get(path`/webhooks/${webhookId}`, void 0, options);
|
|
612
|
+
}
|
|
613
|
+
list(options) {
|
|
614
|
+
return this._client.get("/webhooks", void 0, options);
|
|
615
|
+
}
|
|
616
|
+
/** Update an endpoint. Setting `enabled: true` also clears its failure streak. */
|
|
617
|
+
update(webhookId, params, options) {
|
|
618
|
+
return this._client.put(path`/webhooks/${webhookId}`, params, options);
|
|
619
|
+
}
|
|
620
|
+
delete(webhookId, options) {
|
|
621
|
+
return this._client.delete(path`/webhooks/${webhookId}`, options);
|
|
622
|
+
}
|
|
623
|
+
/** Every delivery attempt to this endpoint, newest first. */
|
|
624
|
+
deliveries(webhookId, params, options) {
|
|
625
|
+
return this._client.getPage(path`/webhooks/${webhookId}/deliveries`, params, options);
|
|
626
|
+
}
|
|
627
|
+
/** Issue a new signing secret. The old one stops working immediately. */
|
|
628
|
+
rollSecret(webhookId, options) {
|
|
629
|
+
return this._client.post(path`/webhooks/${webhookId}/roll-secret`, void 0, options);
|
|
630
|
+
}
|
|
631
|
+
/** Send a signed `webhook.test` event now. Works with test keys, which emit no real events. */
|
|
632
|
+
test(webhookId, options) {
|
|
633
|
+
return this._client.post(path`/webhooks/${webhookId}/test`, void 0, options);
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Verify a delivery's signature and parse it. Same as the standalone `verifyWebhook()`,
|
|
637
|
+
* which needs no API key — prefer that in a receiver that makes no API calls.
|
|
638
|
+
*/
|
|
639
|
+
unwrap(payload, headers, options) {
|
|
640
|
+
return verifyWebhook(payload, headers, options);
|
|
641
|
+
}
|
|
642
|
+
};
|
|
643
|
+
//#endregion
|
|
644
|
+
//#region src/version.ts
|
|
645
|
+
const VERSION = "0.1.1";
|
|
646
|
+
//#endregion
|
|
647
|
+
//#region src/client.ts
|
|
648
|
+
const DEFAULT_BASE_URL = "https://api.bulkit.io";
|
|
649
|
+
const API_PREFIX = "/public/v1";
|
|
650
|
+
const DEFAULT_TIMEOUT_MS = 6e4;
|
|
651
|
+
const DEFAULT_MAX_RETRIES = 2;
|
|
652
|
+
const INITIAL_RETRY_DELAY_MS = 500;
|
|
653
|
+
const MAX_RETRY_DELAY_MS = 8e3;
|
|
654
|
+
/**
|
|
655
|
+
* The Bulkit API client.
|
|
656
|
+
*
|
|
657
|
+
* ```ts
|
|
658
|
+
* import { Bulkit } from 'bulkit';
|
|
659
|
+
*
|
|
660
|
+
* const bulkit = new Bulkit(); // reads BULKIT_API_KEY
|
|
661
|
+
* const channels = await bulkit.channels.list();
|
|
662
|
+
* ```
|
|
663
|
+
*/
|
|
664
|
+
var Bulkit = class {
|
|
665
|
+
channels = new Channels(this);
|
|
666
|
+
platforms = new Platforms(this);
|
|
667
|
+
posts = new Posts(this);
|
|
668
|
+
media = new Media(this);
|
|
669
|
+
tags = new Tags(this);
|
|
670
|
+
stats = new Stats(this);
|
|
671
|
+
usage = new Usage(this);
|
|
672
|
+
webhooks = new Webhooks(this);
|
|
673
|
+
baseURL;
|
|
674
|
+
timeout;
|
|
675
|
+
maxRetries;
|
|
676
|
+
#apiKey;
|
|
677
|
+
#fetch;
|
|
678
|
+
#defaultHeaders;
|
|
679
|
+
constructor(options = {}) {
|
|
680
|
+
const apiKey = options.apiKey ?? readEnv("BULKIT_API_KEY");
|
|
681
|
+
if (!apiKey) throw new BulkitError("Missing API key. Pass `apiKey` to `new Bulkit()` or set the BULKIT_API_KEY environment variable.");
|
|
682
|
+
if (isBrowser() && !options.dangerouslyAllowBrowser) throw new BulkitError("Running in a browser would expose your secret API key to every visitor. Call Bulkit from your server instead, or pass `dangerouslyAllowBrowser: true` if you understand the risk.");
|
|
683
|
+
const baseURL = options.baseURL ?? readEnv("BULKIT_BASE_URL") ?? DEFAULT_BASE_URL;
|
|
684
|
+
this.baseURL = baseURL.replace(/\/+$/, "");
|
|
685
|
+
this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
|
|
686
|
+
this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
687
|
+
this.#apiKey = apiKey;
|
|
688
|
+
this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
689
|
+
this.#defaultHeaders = options.defaultHeaders ?? {};
|
|
690
|
+
}
|
|
691
|
+
/** `true` for a `bk_test_…` key: validates like live, but publishes nothing and bills nothing. */
|
|
692
|
+
get isTestMode() {
|
|
693
|
+
return this.#apiKey.startsWith("bk_test_");
|
|
694
|
+
}
|
|
695
|
+
get(path, query, options) {
|
|
696
|
+
return this.request({
|
|
697
|
+
method: "GET",
|
|
698
|
+
path,
|
|
699
|
+
query,
|
|
700
|
+
...options
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
post(path, body, options) {
|
|
704
|
+
return this.request({
|
|
705
|
+
method: "POST",
|
|
706
|
+
path,
|
|
707
|
+
body,
|
|
708
|
+
...options
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
put(path, body, options) {
|
|
712
|
+
return this.request({
|
|
713
|
+
method: "PUT",
|
|
714
|
+
path,
|
|
715
|
+
body,
|
|
716
|
+
...options
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
delete(path, options) {
|
|
720
|
+
return this.request({
|
|
721
|
+
method: "DELETE",
|
|
722
|
+
path,
|
|
723
|
+
...options
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
/** @internal */
|
|
727
|
+
getPage(path, query, options) {
|
|
728
|
+
return new PagePromise((cursor) => this.request({
|
|
729
|
+
method: "GET",
|
|
730
|
+
path,
|
|
731
|
+
query: cursor ? {
|
|
732
|
+
...query,
|
|
733
|
+
cursor
|
|
734
|
+
} : query,
|
|
735
|
+
...options
|
|
736
|
+
}).withResponse());
|
|
737
|
+
}
|
|
738
|
+
/** @internal Fetch a non-API URL (e.g. a presigned upload URL) without credentials. */
|
|
739
|
+
fetchExternal(url, init) {
|
|
740
|
+
return this.#fetch(url, init);
|
|
741
|
+
}
|
|
742
|
+
/** Sends a request, retrying what is safe to retry. Prefer the resource methods. */
|
|
743
|
+
request(req) {
|
|
744
|
+
return new APIPromise(this.#send(req));
|
|
745
|
+
}
|
|
746
|
+
async #send(req) {
|
|
747
|
+
const maxRetries = req.maxRetries ?? this.maxRetries;
|
|
748
|
+
const idempotencyKey = req.method === "POST" || req.method === "PUT" ? req.idempotencyKey ?? uuid() : void 0;
|
|
749
|
+
const url = this.baseURL + API_PREFIX + req.path + buildQuery(req.query);
|
|
750
|
+
for (let attempt = 0;; attempt++) {
|
|
751
|
+
const retriesLeft = maxRetries - attempt;
|
|
752
|
+
let response;
|
|
753
|
+
try {
|
|
754
|
+
response = await this.#fetchWithTimeout(url, req, idempotencyKey);
|
|
755
|
+
} catch (error) {
|
|
756
|
+
if (error instanceof APIUserAbortError || retriesLeft <= 0) throw error;
|
|
757
|
+
await sleep(retryDelay(attempt));
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
if (response.ok) return {
|
|
761
|
+
data: await parseBody(response),
|
|
762
|
+
response,
|
|
763
|
+
requestId: response.headers.get("x-request-id"),
|
|
764
|
+
rateLimit: rateLimitFrom(response.headers)
|
|
765
|
+
};
|
|
766
|
+
const body = await parseBody(response).catch(() => void 0);
|
|
767
|
+
const error = APIError.from(response.status, body, response.headers);
|
|
768
|
+
if (retriesLeft <= 0 || !shouldRetry(error, req.method)) throw error;
|
|
769
|
+
await sleep(retryDelay(attempt, error));
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
async #fetchWithTimeout(url, req, idempotencyKey) {
|
|
773
|
+
const timeout = req.timeout ?? this.timeout;
|
|
774
|
+
const timeoutSignal = AbortSignal.timeout(timeout);
|
|
775
|
+
const signal = req.signal ? AbortSignal.any([req.signal, timeoutSignal]) : timeoutSignal;
|
|
776
|
+
const isForm = req.body instanceof FormData;
|
|
777
|
+
const headers = {
|
|
778
|
+
Accept: "application/json",
|
|
779
|
+
"User-Agent": `bulkit-node/${VERSION}`,
|
|
780
|
+
...this.#defaultHeaders,
|
|
781
|
+
...req.headers,
|
|
782
|
+
Authorization: `Bearer ${this.#apiKey}`
|
|
783
|
+
};
|
|
784
|
+
if (req.body !== void 0 && !isForm) headers["Content-Type"] = "application/json";
|
|
785
|
+
if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
|
|
786
|
+
try {
|
|
787
|
+
return await this.#fetch(url, {
|
|
788
|
+
method: req.method,
|
|
789
|
+
headers,
|
|
790
|
+
body: req.body === void 0 ? void 0 : isForm ? req.body : JSON.stringify(req.body),
|
|
791
|
+
signal
|
|
792
|
+
});
|
|
793
|
+
} catch (error) {
|
|
794
|
+
if (req.signal?.aborted) throw new APIUserAbortError();
|
|
795
|
+
if (timeoutSignal.aborted) throw new APIConnectionTimeoutError();
|
|
796
|
+
throw new APIConnectionError(void 0, { cause: error });
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
/**
|
|
801
|
+
* What is worth retrying, per the API's contract:
|
|
802
|
+
* - 429 and 409 `request_in_progress`: transient by definition.
|
|
803
|
+
* - 408, 502, 503, 504: the request was not (fully) attempted.
|
|
804
|
+
* - 500: only on reads. A write's idempotency key is kept on a 500, so retrying it
|
|
805
|
+
* would only replay the same failure; the caller must inspect state first.
|
|
806
|
+
* - 402 `quota_exceeded` and every other 4xx: retrying can never succeed.
|
|
807
|
+
*/
|
|
808
|
+
function shouldRetry(error, method) {
|
|
809
|
+
const { status } = error;
|
|
810
|
+
if (status === 429 || status === 408 || status === 502 || status === 503 || status === 504) return true;
|
|
811
|
+
if (status === 409) return error.code === "request_in_progress";
|
|
812
|
+
if (status === 500) return method === "GET" || method === "DELETE";
|
|
813
|
+
return false;
|
|
814
|
+
}
|
|
815
|
+
function retryDelay(attempt, error) {
|
|
816
|
+
if (error instanceof RateLimitError && error.retryAfter !== void 0) return Math.min(error.retryAfter * 1e3, 6e4);
|
|
817
|
+
return Math.min(INITIAL_RETRY_DELAY_MS * 2 ** attempt, MAX_RETRY_DELAY_MS) * (.75 + Math.random() * .25);
|
|
818
|
+
}
|
|
819
|
+
async function parseBody(response) {
|
|
820
|
+
if (response.status === 204) return void 0;
|
|
821
|
+
const text = await response.text();
|
|
822
|
+
if (!text) return void 0;
|
|
823
|
+
return (response.headers.get("content-type") ?? "").includes("json") ? JSON.parse(text) : text;
|
|
824
|
+
}
|
|
825
|
+
//#endregion
|
|
826
|
+
export { APIConnectionError, APIConnectionTimeoutError, APIError, APIPromise, APIUserAbortError, AuthenticationError, BadRequestError, Bulkit, BulkitError, ConflictError, CursorPage, InternalServerError, NotFoundError, PagePromise, PayloadTooLargeError, PermissionDeniedError, QuotaExceededError, RateLimitError, SIGNATURE_HEADER, UnprocessableEntityError, UnsupportedMediaTypeError, VERSION, WebhookVerificationError, signWebhookPayload, verifyWebhook };
|
|
827
|
+
|
|
828
|
+
//# sourceMappingURL=index.js.map
|