frutebox 0.0.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +69 -0
- package/README.md +174 -23
- package/account.d.ts +125 -0
- package/account.mjs +413 -0
- package/bin/frutebox.mjs +608 -0
- package/errors.mjs +100 -0
- package/index.d.ts +211 -30
- package/index.mjs +461 -63
- package/package.json +28 -2
- package/spec.mjs +42 -0
package/account.mjs
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The FIRST-PARTY, SESSION-AUTHENTICATED surface — a different client, on purpose.
|
|
3
|
+
*
|
|
4
|
+
* WHY THIS IS NOT ON `Frutebox`. The public developer API is 16 operations under `/api/v1`, every
|
|
5
|
+
* one authenticated by an `sk_live_…` key and published in `GET /api/v1/openapi.json`. These
|
|
6
|
+
* endpoints are none of that: they live outside `/api/v1`, they authenticate the ACCOUNT
|
|
7
|
+
* (`getCurrentUser()` — the session cookie, or the same session JWT as `Authorization: Bearer` for
|
|
8
|
+
* a native client), and they have no spec entry and no `REQUIRED_SCOPE` entry.
|
|
9
|
+
*
|
|
10
|
+
* An API key is not a session. Putting `rename()` on `Frutebox` would ship a method that 401s for
|
|
11
|
+
* every developer who called it with the key the docs told them to get, and it would fail this
|
|
12
|
+
* SDK's own drift check as an operation the spec does not publish. Two auth models, two clients.
|
|
13
|
+
*
|
|
14
|
+
* import { FruteboxAccount } from "frutebox/account";
|
|
15
|
+
*
|
|
16
|
+
* const me = new FruteboxAccount(); // reads FRUTEBOX_SESSION_TOKEN
|
|
17
|
+
* await me.conversations.rename("conv_123", "Q3 planning");
|
|
18
|
+
* await me.featureRequests.create({ title: "Export to CSV" });
|
|
19
|
+
*
|
|
20
|
+
* WHERE THE SHAPES COME FROM. These two routes were written on `lane2/backend` and are NOT on main
|
|
21
|
+
* at the time of writing — 46a7a38d (conversation rename) and a403cb55 (feature requests) — so the
|
|
22
|
+
* request and response shapes are taken from those routes' own zod schemas and `NextResponse.json`
|
|
23
|
+
* calls, which is the actual contract in code and the best ground truth available with no published
|
|
24
|
+
* spec entry to record fixtures from. Until MAIN merges them these methods 404 against production.
|
|
25
|
+
*
|
|
26
|
+
* ORG / GROUPS / RULES AND USER IMPORT ARE DELIBERATELY ABSENT: BACKEND is making them accept an
|
|
27
|
+
* API key with an org-admin scope, at which point they belong on `Frutebox` with a scope entry and
|
|
28
|
+
* a spec entry. Adding them here now would mean moving them later.
|
|
29
|
+
*/
|
|
30
|
+
import { FruteboxError, errorFromBody } from "./errors.mjs";
|
|
31
|
+
|
|
32
|
+
export const DEFAULT_BASE_URL = "https://frutebox.com";
|
|
33
|
+
export const DEFAULT_TIMEOUT_MS = 60_000;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The server the published spec gives these paths. The developer API is `/api/v1`; the
|
|
37
|
+
* first-party endpoints carry their own `servers` override of `/api`, and the paths below are
|
|
38
|
+
* written RELATIVE to it so they compare directly against the spec.
|
|
39
|
+
*/
|
|
40
|
+
export const ACCOUNT_PREFIX = "/api";
|
|
41
|
+
|
|
42
|
+
/** `MAX_USER_TITLE` in the rename route — 120, not the auto-title's 48. */
|
|
43
|
+
export const MAX_CONVERSATION_TITLE = 120;
|
|
44
|
+
/** `MAX_FR_TITLE` and `MAX_FR_BODY` in the feature-requests route. */
|
|
45
|
+
export const MAX_FEATURE_REQUEST_TITLE = 160;
|
|
46
|
+
export const MAX_FEATURE_REQUEST_DESCRIPTION = 4000;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The session-authed operations, mapped to the method that calls them.
|
|
50
|
+
* DELIBERATELY SEPARATE from `OPERATIONS` in `spec.mjs`, which is checked against the published
|
|
51
|
+
* OpenAPI document in both directions; these paths are not in it and must not be.
|
|
52
|
+
*/
|
|
53
|
+
export const SESSION_OPERATIONS = Object.freeze({
|
|
54
|
+
"PATCH /conversations/{id}": "conversations.rename",
|
|
55
|
+
"POST /feature-requests": "featureRequests.create",
|
|
56
|
+
"GET /feature-requests": "featureRequests.list",
|
|
57
|
+
"PATCH /org/{id}/groups/{groupId}": "org.groups.setRules",
|
|
58
|
+
"GET /me/policy": "me.policy",
|
|
59
|
+
// Standby Agents (plan 31), published 2026-10-15.
|
|
60
|
+
"POST /standby/runs": "standby.create",
|
|
61
|
+
"GET /standby/runs": "standby.list",
|
|
62
|
+
"GET /standby/runs/{id}": "standby.retrieve",
|
|
63
|
+
"GET /standby/runs/{id}/logs": "standby.logs",
|
|
64
|
+
"GET /standby/runs/{id}/results": "standby.results",
|
|
65
|
+
"POST /standby/runs/{id}/pause": "standby.pause",
|
|
66
|
+
"POST /standby/runs/{id}/resume": "standby.resume",
|
|
67
|
+
"POST /standby/runs/{id}/stop": "standby.stop",
|
|
68
|
+
"POST /standby/runs/{id}/steps/{stepId}": "standby.answerStep",
|
|
69
|
+
// Push registration.
|
|
70
|
+
"GET /me/push-tokens": "me.pushTokens.list",
|
|
71
|
+
"POST /me/push-tokens": "me.pushTokens.register",
|
|
72
|
+
"DELETE /me/push-tokens": "me.pushTokens.forget",
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
/** Step kinds the published schema accepts. `effect` — send, publish, spend — always asks. */
|
|
76
|
+
export const STEP_KINDS = Object.freeze(["read", "edit", "command", "test", "effect"]);
|
|
77
|
+
export const STEP_DECISIONS = Object.freeze(["approve", "deny"]);
|
|
78
|
+
export const MAX_GOAL = 2000;
|
|
79
|
+
export const MAX_STEP_DETAIL = 4000;
|
|
80
|
+
export const MAX_TEST_COMMAND = 500;
|
|
81
|
+
export const MAX_STEPS = 50;
|
|
82
|
+
|
|
83
|
+
export class FruteboxAccount {
|
|
84
|
+
#token;
|
|
85
|
+
#timeoutMs;
|
|
86
|
+
#fetch;
|
|
87
|
+
|
|
88
|
+
constructor({ sessionToken, baseUrl = DEFAULT_BASE_URL, timeoutMs = DEFAULT_TIMEOUT_MS, fetch: fetchImpl } = {}) {
|
|
89
|
+
const token = sessionToken
|
|
90
|
+
|| (typeof process !== "undefined" && process.env ? process.env.FRUTEBOX_SESSION_TOKEN : undefined);
|
|
91
|
+
if (!token) {
|
|
92
|
+
throw new FruteboxError(
|
|
93
|
+
"A Frutebox SESSION token is required. Pass { sessionToken } or set "
|
|
94
|
+
+ "FRUTEBOX_SESSION_TOKEN. NOTE: an sk_live_ API key will NOT work here — these endpoints "
|
|
95
|
+
+ "authenticate the account, not a key.",
|
|
96
|
+
{ code: "missing_session_token" },
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
if (token.startsWith("sk_live_") || token.startsWith("sk_test_")) {
|
|
100
|
+
// Refused rather than sent: the 401 that comes back says "Unauthorized" and gives no hint
|
|
101
|
+
// that the wrong KIND of credential was used.
|
|
102
|
+
throw new FruteboxError(
|
|
103
|
+
"That looks like an API key, not a session token. The account endpoints authenticate a "
|
|
104
|
+
+ "session; use `new Frutebox({ apiKey })` for the public API.",
|
|
105
|
+
{ code: "api_key_is_not_a_session" },
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const base = String(baseUrl).replace(/\/+$/, "");
|
|
110
|
+
const isLocal = base.startsWith("http://localhost") || base.startsWith("http://127.0.0.1");
|
|
111
|
+
if (!base.startsWith("https://") && !isLocal) {
|
|
112
|
+
throw new FruteboxError(
|
|
113
|
+
"baseUrl must use https:// (refusing to send your session token in plaintext).",
|
|
114
|
+
{ code: "insecure_base_url" },
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
this.baseUrl = base;
|
|
119
|
+
this.#token = token;
|
|
120
|
+
this.#timeoutMs = timeoutMs;
|
|
121
|
+
this.#fetch = fetchImpl ?? ((...a) => fetch(...a));
|
|
122
|
+
|
|
123
|
+
this.conversations = {
|
|
124
|
+
/**
|
|
125
|
+
* Give a conversation your own name. `PATCH /api/conversations/{id}`.
|
|
126
|
+
*
|
|
127
|
+
* The name OVERRIDES the auto-title derived from the first message. The server stores it
|
|
128
|
+
* encrypted and reads it back decrypted, so the returned value is what is STORED rather than
|
|
129
|
+
* the string you sent. Trimmed, 1..120 characters after trimming.
|
|
130
|
+
*/
|
|
131
|
+
rename: async (conversationId, title) => {
|
|
132
|
+
if (typeof title !== "string") {
|
|
133
|
+
throw new FruteboxError("`title` must be a string.", { code: "invalid_request" });
|
|
134
|
+
}
|
|
135
|
+
const trimmed = title.trim();
|
|
136
|
+
if (!trimmed) {
|
|
137
|
+
throw new FruteboxError(
|
|
138
|
+
"`title` must not be blank. Clearing a title is not a rename — the route rejects it, "
|
|
139
|
+
+ "because clearing would drop the auto-title too and leave 'New chat'.",
|
|
140
|
+
{ code: "invalid_request" },
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
if (trimmed.length > MAX_CONVERSATION_TITLE) {
|
|
144
|
+
throw new FruteboxError(
|
|
145
|
+
`\`title\` is ${trimmed.length} characters; the maximum is ${MAX_CONVERSATION_TITLE}.`,
|
|
146
|
+
{ code: "invalid_request" },
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
return this.#request("PATCH", `/conversations/${encodeURIComponent(conversationId)}`, { title: trimmed });
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
this.featureRequests = {
|
|
154
|
+
/** File a feature request. `POST /api/feature-requests` → 201 `{id, status, createdAt}`. */
|
|
155
|
+
create: async ({ title, description } = {}) => {
|
|
156
|
+
if (typeof title !== "string" || !title.trim()) {
|
|
157
|
+
throw new FruteboxError("`title` must be a non-empty string.", { code: "invalid_request" });
|
|
158
|
+
}
|
|
159
|
+
const trimmed = title.trim();
|
|
160
|
+
if (trimmed.length > MAX_FEATURE_REQUEST_TITLE) {
|
|
161
|
+
throw new FruteboxError(
|
|
162
|
+
`\`title\` is ${trimmed.length} characters; the maximum is ${MAX_FEATURE_REQUEST_TITLE}.`,
|
|
163
|
+
{ code: "invalid_request" },
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
const body = { title: trimmed };
|
|
167
|
+
if (description !== undefined && description !== null) {
|
|
168
|
+
if (String(description).length > MAX_FEATURE_REQUEST_DESCRIPTION) {
|
|
169
|
+
throw new FruteboxError(
|
|
170
|
+
`\`description\` is ${String(description).length} characters; the maximum is `
|
|
171
|
+
+ `${MAX_FEATURE_REQUEST_DESCRIPTION}.`,
|
|
172
|
+
{ code: "invalid_request" },
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
// "" is sent, not dropped: the route stores it, and its comment says a one-line request
|
|
176
|
+
// is a real request.
|
|
177
|
+
body.description = String(description);
|
|
178
|
+
}
|
|
179
|
+
return this.#request("POST", "/feature-requests", body);
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Your company's queue, newest first. `GET /api/feature-requests`.
|
|
184
|
+
*
|
|
185
|
+
* **ADMINS ONLY** — a non-admin gets 403 "Admins only.", thrown as `PolicyError`. Submitters
|
|
186
|
+
* are named by id only. `limit` is clamped by the server to 1..200 and defaults to 50.
|
|
187
|
+
*/
|
|
188
|
+
list: async ({ limit } = {}) => {
|
|
189
|
+
let query = "";
|
|
190
|
+
if (limit !== undefined && limit !== null) {
|
|
191
|
+
if (!Number.isInteger(limit) || limit <= 0) {
|
|
192
|
+
throw new FruteboxError("`limit` must be a positive integer.", { code: "invalid_request" });
|
|
193
|
+
}
|
|
194
|
+
query = `?limit=${limit}`;
|
|
195
|
+
}
|
|
196
|
+
return this.#request("GET", `/feature-requests${query}`);
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
this.org = {
|
|
201
|
+
groups: {
|
|
202
|
+
/**
|
|
203
|
+
* Set a group's rules. `PATCH /org/{id}/groups/{groupId}` (Feature 1).
|
|
204
|
+
*
|
|
205
|
+
* A group can only ever RESTRICT — the layers union at resolve time, so anything set here
|
|
206
|
+
* is added to the org's rules rather than replacing them.
|
|
207
|
+
*
|
|
208
|
+
* ONLY THE FIELDS YOU PASS ARE WRITTEN. Every field is optional in the published schema,
|
|
209
|
+
* so an omitted one is left alone; `[]` is meaningful and IS sent, because it differs
|
|
210
|
+
* from omitted. Admin-only at the server — a non-admin gets 403 (`PolicyError`).
|
|
211
|
+
*/
|
|
212
|
+
setRules: async (orgId, groupId, fields = {}) => {
|
|
213
|
+
const allowed = ["name", "requiredRegion", "teeOnly", "allowedTalents",
|
|
214
|
+
"requiredTemplates", "branding", "addMembers", "removeMembers"];
|
|
215
|
+
const body = {};
|
|
216
|
+
for (const k of allowed) if (fields[k] !== undefined && fields[k] !== null) body[k] = fields[k];
|
|
217
|
+
const unknown = Object.keys(fields).filter((k) => !allowed.includes(k));
|
|
218
|
+
if (unknown.length) {
|
|
219
|
+
// Refused rather than dropped: a field the route will not read is the silent kind of
|
|
220
|
+
// wrong this SDK already fixed once on the media endpoints.
|
|
221
|
+
throw new FruteboxError(
|
|
222
|
+
`setRules() was given field(s) the published schema does not declare: ${unknown.join(", ")}.`,
|
|
223
|
+
{ code: "invalid_request" },
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
if (Object.keys(body).length === 0) {
|
|
227
|
+
throw new FruteboxError(
|
|
228
|
+
"setRules() was given nothing to change. Pass at least one field — an empty PATCH "
|
|
229
|
+
+ "would be a round trip that says nothing.",
|
|
230
|
+
{ code: "invalid_request" },
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
return this.#request(
|
|
234
|
+
"PATCH",
|
|
235
|
+
`/org/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(groupId)}`,
|
|
236
|
+
body,
|
|
237
|
+
);
|
|
238
|
+
},
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
const enc = encodeURIComponent;
|
|
243
|
+
|
|
244
|
+
this.standby = {
|
|
245
|
+
/**
|
|
246
|
+
* Queue work that continues on the node network while your device is off.
|
|
247
|
+
* `POST /standby/runs` -> 201 `{id, started, held}`.
|
|
248
|
+
*
|
|
249
|
+
* `replicas` is the mirror count you are choosing to pay for — the winner is paid the serve
|
|
250
|
+
* rate and each losing mirror a standby rate. Side-effecting steps are never mirrored
|
|
251
|
+
* regardless: mirroring a step that sends an email sends N emails.
|
|
252
|
+
*/
|
|
253
|
+
create: async ({ goal, steps, workspace, replicas, stepBudget } = {}) => {
|
|
254
|
+
if (typeof goal !== "string" || !goal.trim()) {
|
|
255
|
+
throw new FruteboxError("`goal` must be a non-empty string.", { code: "invalid_request" });
|
|
256
|
+
}
|
|
257
|
+
if (goal.length > MAX_GOAL) {
|
|
258
|
+
throw new FruteboxError(`\`goal\` is ${goal.length} characters; the maximum is ${MAX_GOAL}.`,
|
|
259
|
+
{ code: "invalid_request" });
|
|
260
|
+
}
|
|
261
|
+
const list = Array.isArray(steps) ? steps : [];
|
|
262
|
+
if (list.length < 1 || list.length > MAX_STEPS) {
|
|
263
|
+
throw new FruteboxError(
|
|
264
|
+
`\`steps\` must hold between 1 and ${MAX_STEPS} entries; got ${list.length}.`,
|
|
265
|
+
{ code: "invalid_request" });
|
|
266
|
+
}
|
|
267
|
+
list.forEach((step, i) => {
|
|
268
|
+
if (!step || typeof step !== "object") {
|
|
269
|
+
throw new FruteboxError(`steps[${i}] must be an object.`, { code: "invalid_request" });
|
|
270
|
+
}
|
|
271
|
+
if (!STEP_KINDS.includes(step.kind)) {
|
|
272
|
+
throw new FruteboxError(
|
|
273
|
+
`steps[${i}].kind is ${JSON.stringify(step.kind)}; the published schema accepts `
|
|
274
|
+
+ `${STEP_KINDS.join(", ")}.`, { code: "invalid_request" });
|
|
275
|
+
}
|
|
276
|
+
if (typeof step.detail !== "string" || !step.detail) {
|
|
277
|
+
throw new FruteboxError(`steps[${i}].detail is required.`, { code: "invalid_request" });
|
|
278
|
+
}
|
|
279
|
+
if (step.detail.length > MAX_STEP_DETAIL) {
|
|
280
|
+
throw new FruteboxError(
|
|
281
|
+
`steps[${i}].detail is ${step.detail.length} characters; the maximum is ${MAX_STEP_DETAIL}.`,
|
|
282
|
+
{ code: "invalid_request" });
|
|
283
|
+
}
|
|
284
|
+
if (step.testCommand !== undefined && String(step.testCommand).length > MAX_TEST_COMMAND) {
|
|
285
|
+
throw new FruteboxError(
|
|
286
|
+
`steps[${i}].testCommand exceeds ${MAX_TEST_COMMAND} characters.`,
|
|
287
|
+
{ code: "invalid_request" });
|
|
288
|
+
}
|
|
289
|
+
const unknown = Object.keys(step).filter((k) => !["kind", "detail", "testCommand"].includes(k));
|
|
290
|
+
if (unknown.length) {
|
|
291
|
+
// Refused, not dropped: a field the route will not read is the silent kind of wrong.
|
|
292
|
+
throw new FruteboxError(
|
|
293
|
+
`steps[${i}] has field(s) the published schema does not declare: ${unknown.join(", ")}.`,
|
|
294
|
+
{ code: "invalid_request" });
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
const body = { goal, steps: list };
|
|
298
|
+
if (workspace !== undefined && workspace !== null) body.workspace = workspace;
|
|
299
|
+
if (replicas !== undefined && replicas !== null) body.replicas = replicas;
|
|
300
|
+
if (stepBudget !== undefined && stepBudget !== null) body.stepBudget = stepBudget;
|
|
301
|
+
return this.#request("POST", "/standby/runs", body);
|
|
302
|
+
},
|
|
303
|
+
|
|
304
|
+
/** `GET /standby/runs` — this caller's runs, newest first. */
|
|
305
|
+
list: async ({ limit } = {}) => {
|
|
306
|
+
if (limit !== undefined && limit !== null && (!Number.isInteger(limit) || limit <= 0)) {
|
|
307
|
+
throw new FruteboxError("`limit` must be a positive integer.", { code: "invalid_request" });
|
|
308
|
+
}
|
|
309
|
+
const q = limit === undefined || limit === null ? "" : `?limit=${limit}`;
|
|
310
|
+
return this.#request("GET", `/standby/runs${q}`);
|
|
311
|
+
},
|
|
312
|
+
|
|
313
|
+
retrieve: async (runId) => this.#request("GET", `/standby/runs/${enc(runId)}`),
|
|
314
|
+
/** The trail records tool name, argument preview and output LENGTH — never the output. */
|
|
315
|
+
logs: async (runId) => this.#request("GET", `/standby/runs/${enc(runId)}/logs`),
|
|
316
|
+
results: async (runId) => this.#request("GET", `/standby/runs/${enc(runId)}/results`),
|
|
317
|
+
/** Stops posting NEW steps. Mirrors already in flight are NOT cancelled. */
|
|
318
|
+
pause: async (runId) => this.#request("POST", `/standby/runs/${enc(runId)}/pause`),
|
|
319
|
+
resume: async (runId) => this.#request("POST", `/standby/runs/${enc(runId)}/resume`),
|
|
320
|
+
/** Cancels the run AND the mirrors in flight — unlike `pause`. */
|
|
321
|
+
stop: async (runId) => this.#request("POST", `/standby/runs/${enc(runId)}/stop`),
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Answer a held step. **Approving an `effect` step requires `totp`** — the step-up re-auth.
|
|
325
|
+
* This client does not guess which steps are effects; it sends what you pass and lets the
|
|
326
|
+
* server rule.
|
|
327
|
+
*/
|
|
328
|
+
answerStep: async (runId, stepId, { decision, totp } = {}) => {
|
|
329
|
+
if (!STEP_DECISIONS.includes(decision)) {
|
|
330
|
+
throw new FruteboxError(
|
|
331
|
+
`\`decision\` must be one of ${STEP_DECISIONS.join(", ")}; got ${JSON.stringify(decision)}.`,
|
|
332
|
+
{ code: "invalid_request" });
|
|
333
|
+
}
|
|
334
|
+
const body = { decision };
|
|
335
|
+
if (totp !== undefined && totp !== null) body.totp = totp;
|
|
336
|
+
return this.#request("POST", `/standby/runs/${enc(runId)}/steps/${enc(stepId)}`, body);
|
|
337
|
+
},
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
this.me = {
|
|
341
|
+
pushTokens: {
|
|
342
|
+
/** Tokens come back REDACTED — the list is for recognising a device, not reading it back. */
|
|
343
|
+
list: async () => this.#request("GET", "/me/push-tokens"),
|
|
344
|
+
register: async ({ token, platform, deviceName } = {}) => {
|
|
345
|
+
if (typeof token !== "string" || !token.trim()) {
|
|
346
|
+
throw new FruteboxError("`token` must be a non-empty string.", { code: "invalid_request" });
|
|
347
|
+
}
|
|
348
|
+
const body = { token };
|
|
349
|
+
if (platform !== undefined && platform !== null) body.platform = platform;
|
|
350
|
+
if (deviceName !== undefined && deviceName !== null) body.deviceName = deviceName;
|
|
351
|
+
return this.#request("POST", "/me/push-tokens", body);
|
|
352
|
+
},
|
|
353
|
+
forget: async (token) => {
|
|
354
|
+
if (typeof token !== "string" || !token.trim()) {
|
|
355
|
+
throw new FruteboxError("`token` must be a non-empty string.", { code: "invalid_request" });
|
|
356
|
+
}
|
|
357
|
+
return this.#request("DELETE", `/me/push-tokens?token=${enc(token)}`);
|
|
358
|
+
},
|
|
359
|
+
},
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Your own effective policy. `GET /me/policy` — *the one poll every client uses*.
|
|
363
|
+
*
|
|
364
|
+
* Pass `since` and an unchanged policy answers `{version, unchanged: true}` without the
|
|
365
|
+
* body, so a 15-minute poll costs almost nothing.
|
|
366
|
+
*
|
|
367
|
+
* THE GATEWAY REMAINS AUTHORITATIVE. This is a mirror to pre-filter with; a stale or absent
|
|
368
|
+
* mirror must narrow what a client offers, never widen it.
|
|
369
|
+
*/
|
|
370
|
+
policy: async ({ since } = {}) =>
|
|
371
|
+
this.#request("GET", `/me/policy${since === undefined || since === null ? "" : `?since=${encodeURIComponent(since)}`}`),
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** Never the token. */
|
|
376
|
+
toJSON() { return { baseUrl: this.baseUrl }; }
|
|
377
|
+
[Symbol.for("nodejs.util.inspect.custom")]() { return `FruteboxAccount { baseUrl: '${this.baseUrl}' }`; }
|
|
378
|
+
|
|
379
|
+
async #request(method, path, body) {
|
|
380
|
+
const headers = { authorization: `Bearer ${this.#token}`, accept: "application/json" };
|
|
381
|
+
let payload;
|
|
382
|
+
if (body !== undefined) {
|
|
383
|
+
headers["content-type"] = "application/json";
|
|
384
|
+
payload = JSON.stringify(body);
|
|
385
|
+
}
|
|
386
|
+
const controller = new AbortController();
|
|
387
|
+
const timer = setTimeout(() => controller.abort(), this.#timeoutMs);
|
|
388
|
+
let res;
|
|
389
|
+
try {
|
|
390
|
+
res = await this.#fetch(`${this.baseUrl}${ACCOUNT_PREFIX}${path}`, { method, headers, body: payload, signal: controller.signal });
|
|
391
|
+
} catch (err) {
|
|
392
|
+
if (err && err.name === "AbortError") {
|
|
393
|
+
throw new FruteboxError(`Frutebox request timed out after ${this.#timeoutMs}ms.`, { code: "timeout" });
|
|
394
|
+
}
|
|
395
|
+
// Only the NAME: a fetch failure can carry the request, and the request carries the token.
|
|
396
|
+
throw new FruteboxError(
|
|
397
|
+
`Frutebox request failed: ${err && err.name ? err.name : "network error"}.`,
|
|
398
|
+
{ code: "network" },
|
|
399
|
+
);
|
|
400
|
+
} finally {
|
|
401
|
+
clearTimeout(timer);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
if (!res.ok) {
|
|
405
|
+
let parsed;
|
|
406
|
+
try { parsed = await res.json(); } catch { parsed = undefined; }
|
|
407
|
+
throw errorFromBody(res.status, parsed, res.headers?.get?.("retry-after"));
|
|
408
|
+
}
|
|
409
|
+
try { return await res.json(); } catch { return null; }
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
export default FruteboxAccount;
|