@capacms/sdk 1.0.0-next.10 → 1.0.0-next.12
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 +170 -0
- package/README.md +368 -5
- package/bin/capa-check-bundle.js +80 -0
- package/bin/capa.js +3 -3
- package/bin/graphql-project.js +1 -1
- package/dist/client.d.ts +84 -4
- package/dist/client.js +23 -5
- package/dist/esm/image/index.d.ts +69 -2
- package/dist/esm/image/index.js +108 -5
- package/dist/esm/image/shared-params.generated.d.ts +126 -2
- package/dist/esm/image/shared-params.generated.js +224 -5
- package/dist/esm/overlay/index.d.ts +4 -1
- package/dist/esm/overlay/index.js +382 -30
- package/dist/esm/overlay/live-fields.d.ts +133 -0
- package/dist/esm/overlay/live-fields.js +478 -0
- package/dist/esm/overlay/markdown.d.ts +38 -0
- package/dist/esm/overlay/markdown.js +536 -0
- package/dist/esm/overlay/protocol.d.ts +51 -5
- package/dist/esm/overlay/protocol.js +79 -9
- package/dist/image/index.d.ts +69 -2
- package/dist/image/index.js +109 -4
- package/dist/image/shared-params.generated.d.ts +126 -2
- package/dist/image/shared-params.generated.js +235 -6
- package/dist/index.d.ts +1 -1
- package/dist/next/attrs.d.ts +42 -1
- package/dist/next/attrs.js +42 -3
- package/dist/next/client.d.ts +48 -1
- package/dist/next/client.js +33 -2
- package/dist/next/entry-fields.d.ts +43 -2
- package/dist/next/graphql/request.d.ts +4 -0
- package/dist/next/graphql/request.js +4 -0
- package/dist/next/graphql/tree.js +9 -0
- package/dist/next/index.d.ts +4 -4
- package/dist/next/index.js +3 -1
- package/dist/nextjs/index.d.ts +91 -7
- package/dist/nextjs/index.js +230 -17
- package/dist/nextjs/write-key-guard.d.ts +117 -0
- package/dist/nextjs/write-key-guard.js +285 -0
- package/dist/overlay/index.d.ts +4 -1
- package/dist/overlay/index.js +399 -29
- package/dist/overlay/live-fields.d.ts +133 -0
- package/dist/overlay/live-fields.js +493 -0
- package/dist/overlay/markdown.d.ts +38 -0
- package/dist/overlay/markdown.js +539 -0
- package/dist/overlay/protocol.d.ts +51 -5
- package/dist/overlay/protocol.js +82 -9
- package/dist/server/browser.d.ts +1 -0
- package/dist/server/browser.js +20 -0
- package/dist/server/client.d.ts +268 -0
- package/dist/server/client.js +335 -0
- package/dist/server/errors.d.ts +60 -0
- package/dist/server/errors.js +120 -0
- package/dist/server/index.d.ts +14 -0
- package/dist/server/index.js +32 -0
- package/dist/server/key-format.d.ts +41 -0
- package/dist/server/key-format.js +91 -0
- package/dist/server/transport.d.ts +47 -0
- package/dist/server/transport.js +114 -0
- package/dist/webhooks.d.ts +8 -0
- package/package.json +18 -4
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WRITE_CLIENT_USER_AGENT = exports.DEFAULT_WRITE_TIMEOUT_MS = exports.MAX_RETRY_AFTER_SECONDS = exports.WRITE_API_VERSIONS = exports.DEFAULT_WRITE_BASE_URL = void 0;
|
|
4
|
+
exports.inBrowser = inBrowser;
|
|
5
|
+
exports.createWriteClient = createWriteClient;
|
|
6
|
+
/**
|
|
7
|
+
* client.ts — `createWriteClient`, the client for Capa's server write API
|
|
8
|
+
* (`https://write.capacms.com`).
|
|
9
|
+
*
|
|
10
|
+
* A write key (`capw_`) writes into its own project's content and works from
|
|
11
|
+
* a server only. So the client refuses to exist in a browser, checks the key's
|
|
12
|
+
* checksum before it sends anything, sends the key as `Authorization: Bearer`,
|
|
13
|
+
* and pins the API version on every request (`Capa-Version`).
|
|
14
|
+
*
|
|
15
|
+
* Every route of the write host is a method here, except the GitHub secret
|
|
16
|
+
* scanning endpoint, which GitHub calls. A refusal throws `CapaWriteError`
|
|
17
|
+
* with the host's `status`, `code` and `hint`. A `429` is retried once after
|
|
18
|
+
* its `Retry-After` when that is at most `maxRetryAfterSeconds` (10 by
|
|
19
|
+
* default); a longer wait, or a second `429`, throws. Every request names itself
|
|
20
|
+
* (`User-Agent: capacms-sdk/server`) and gives up after `timeoutMs`.
|
|
21
|
+
*/
|
|
22
|
+
const key_format_1 = require("./key-format");
|
|
23
|
+
const errors_1 = require("./errors");
|
|
24
|
+
const transport_1 = require("./transport");
|
|
25
|
+
exports.DEFAULT_WRITE_BASE_URL = "https://write.capacms.com";
|
|
26
|
+
exports.WRITE_API_VERSIONS = ["2026-10-01"];
|
|
27
|
+
/**
|
|
28
|
+
* The default `maxRetryAfterSeconds`: the longest `Retry-After` the client
|
|
29
|
+
* waits out before its one retry. 10 seconds, so a serverless function with a
|
|
30
|
+
* short limit is not killed mid-wait. A longer wait throws at once.
|
|
31
|
+
*/
|
|
32
|
+
exports.MAX_RETRY_AFTER_SECONDS = 10;
|
|
33
|
+
/** The default `timeoutMs`: 30 seconds. */
|
|
34
|
+
exports.DEFAULT_WRITE_TIMEOUT_MS = 30_000;
|
|
35
|
+
/** What every request names itself as, so the key's activity shows which client wrote. */
|
|
36
|
+
exports.WRITE_CLIENT_USER_AGENT = "capacms-sdk/server";
|
|
37
|
+
/** Whether this code runs where a browser would: `window` or `document` exists. */
|
|
38
|
+
function inBrowser() {
|
|
39
|
+
return typeof globalThis.window !== "undefined" || typeof globalThis.document !== "undefined";
|
|
40
|
+
}
|
|
41
|
+
function randomUuid() {
|
|
42
|
+
// The global Web Crypto, else Node's own (Node 18 has no global `crypto`).
|
|
43
|
+
const crypto = globalThis.crypto ?? (0, transport_1.builtinLoader)()?.("node:crypto");
|
|
44
|
+
if (typeof crypto?.randomUUID === "function")
|
|
45
|
+
return crypto.randomUUID();
|
|
46
|
+
throw new Error("@capacms/sdk/server: crypto.randomUUID is not available. Pass idempotencyKey to entries.create.");
|
|
47
|
+
}
|
|
48
|
+
function checkKey(key) {
|
|
49
|
+
if (typeof key !== "string" || key === "") {
|
|
50
|
+
throw new errors_1.CapaWriteKeyFormatError("@capacms/sdk/server: key is missing. Pass the capw_ key from a server-only environment variable.");
|
|
51
|
+
}
|
|
52
|
+
if (key.startsWith("cap_") || key.startsWith("pk_") || key.startsWith("sk_")) {
|
|
53
|
+
throw new errors_1.CapaWriteKeyFormatError("@capacms/sdk/server: the write API takes a capw_ server write key, and this is a read key. Mint one in the Capa admin under Developers > Keys, New server write key.");
|
|
54
|
+
}
|
|
55
|
+
if (!(0, key_format_1.isWriteKeyShaped)(key)) {
|
|
56
|
+
throw new errors_1.CapaWriteKeyFormatError("@capacms/sdk/server: key is not a capw_ key. A write key is capw_ and 49 letters and digits, 54 characters in all.");
|
|
57
|
+
}
|
|
58
|
+
if (!(0, key_format_1.writeKeyChecksumOk)(key)) {
|
|
59
|
+
throw new errors_1.CapaWriteKeyFormatError("@capacms/sdk/server: key's checksum is wrong, so it was mistyped or cut short. Copy it again from where you stored it, or rotate it in the Capa admin.");
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** Whether a URL's hostname is this machine: `localhost`, `127.x.x.x` or `[::1]`. */
|
|
63
|
+
function isLoopback(hostname) {
|
|
64
|
+
const host = hostname.toLowerCase();
|
|
65
|
+
return host === "localhost" || host === "[::1]" || /^127(\.\d{1,3}){3}$/.test(host);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The write host's address, without a trailing slash. `https` always; plain
|
|
69
|
+
* `http` only to this machine (a local write host in development), because
|
|
70
|
+
* the key is a header on every request and would cross the network in clear
|
|
71
|
+
* text. Even a host that redirects http to https has already received it.
|
|
72
|
+
*/
|
|
73
|
+
function checkBaseUrl(raw) {
|
|
74
|
+
const baseUrl = String(raw).replace(/\/+$/, "");
|
|
75
|
+
let url;
|
|
76
|
+
try {
|
|
77
|
+
url = new URL(baseUrl);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
throw new TypeError("@capacms/sdk/server: baseUrl must be an https URL, such as https://write.capacms.com.");
|
|
81
|
+
}
|
|
82
|
+
if (url.protocol === "https:")
|
|
83
|
+
return baseUrl;
|
|
84
|
+
if (url.protocol === "http:" && isLoopback(url.hostname))
|
|
85
|
+
return baseUrl;
|
|
86
|
+
if (url.protocol === "http:") {
|
|
87
|
+
throw new TypeError("@capacms/sdk/server: baseUrl must be https. Plain http is allowed only for localhost, 127.0.0.1 and [::1], because the key would cross the network in clear text.");
|
|
88
|
+
}
|
|
89
|
+
throw new TypeError("@capacms/sdk/server: baseUrl must be an https URL, such as https://write.capacms.com.");
|
|
90
|
+
}
|
|
91
|
+
function nonEmpty(value, name) {
|
|
92
|
+
if (typeof value !== "string" || value === "")
|
|
93
|
+
throw new TypeError(`@capacms/sdk/server: ${name} must be a non-empty string.`);
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
96
|
+
function segment(value, name) {
|
|
97
|
+
if (typeof value !== "string" || value === "")
|
|
98
|
+
throw new TypeError(`@capacms/sdk/server: ${name} must be a non-empty string.`);
|
|
99
|
+
return encodeURIComponent(value);
|
|
100
|
+
}
|
|
101
|
+
function ifMatchHeader(value) {
|
|
102
|
+
if (value === undefined)
|
|
103
|
+
return undefined;
|
|
104
|
+
if (!Number.isInteger(value) || value < 1)
|
|
105
|
+
throw new TypeError("@capacms/sdk/server: ifMatch must be the entry's version number, a positive integer.");
|
|
106
|
+
return `"${value}"`;
|
|
107
|
+
}
|
|
108
|
+
function sleep(ms, signal) {
|
|
109
|
+
return new Promise((resolve, reject) => {
|
|
110
|
+
if (signal?.aborted)
|
|
111
|
+
return reject(signal.reason);
|
|
112
|
+
const timer = setTimeout(resolve, ms);
|
|
113
|
+
signal?.addEventListener?.("abort", () => {
|
|
114
|
+
clearTimeout(timer);
|
|
115
|
+
reject(signal.reason);
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
function createWriteClient(config) {
|
|
120
|
+
if (inBrowser())
|
|
121
|
+
throw new errors_1.CapaWriteKeyInBrowserError();
|
|
122
|
+
const value = (config ?? {});
|
|
123
|
+
checkKey(value.key);
|
|
124
|
+
if (typeof value.version !== "string" || value.version === "") {
|
|
125
|
+
throw new TypeError(`@capacms/sdk/server: version is required. Pin it in code: version: "${exports.WRITE_API_VERSIONS[0]}".`);
|
|
126
|
+
}
|
|
127
|
+
const baseUrl = checkBaseUrl(value.baseUrl ?? exports.DEFAULT_WRITE_BASE_URL);
|
|
128
|
+
const transport = (0, transport_1.defaultTransport)(value.fetch);
|
|
129
|
+
if (!transport)
|
|
130
|
+
throw new Error("@capacms/sdk/server: no way to send a request here. Pass a fetch in config.fetch.");
|
|
131
|
+
const key = value.key;
|
|
132
|
+
const version = value.version;
|
|
133
|
+
const timeoutMs = value.timeoutMs ?? exports.DEFAULT_WRITE_TIMEOUT_MS;
|
|
134
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs < 0)
|
|
135
|
+
throw new TypeError("@capacms/sdk/server: timeoutMs must be 0 or more milliseconds.");
|
|
136
|
+
const maxRetryAfter = value.maxRetryAfterSeconds ?? exports.MAX_RETRY_AFTER_SECONDS;
|
|
137
|
+
if (!Number.isFinite(maxRetryAfter) || maxRetryAfter < 0) {
|
|
138
|
+
throw new TypeError("@capacms/sdk/server: maxRetryAfterSeconds must be 0 or more seconds.");
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* One request, its body read, within `timeoutMs`. A timeout throws
|
|
142
|
+
* `CapaWriteTimeoutError`; the caller's own abort throws what it always
|
|
143
|
+
* does.
|
|
144
|
+
*/
|
|
145
|
+
async function send(call) {
|
|
146
|
+
const url = new URL(baseUrl + call.path);
|
|
147
|
+
call.query?.forEach((v, k) => url.searchParams.append(k, v));
|
|
148
|
+
const headers = {
|
|
149
|
+
Accept: "application/json",
|
|
150
|
+
Authorization: `Bearer ${key}`,
|
|
151
|
+
"Capa-Version": version,
|
|
152
|
+
"User-Agent": exports.WRITE_CLIENT_USER_AGENT,
|
|
153
|
+
};
|
|
154
|
+
let body;
|
|
155
|
+
if (call.body !== undefined) {
|
|
156
|
+
headers["Content-Type"] = "application/json";
|
|
157
|
+
body = JSON.stringify(call.body);
|
|
158
|
+
}
|
|
159
|
+
if (call.idempotencyKey !== undefined)
|
|
160
|
+
headers["Idempotency-Key"] = call.idempotencyKey;
|
|
161
|
+
if (call.ifMatch !== undefined)
|
|
162
|
+
headers["If-Match"] = call.ifMatch;
|
|
163
|
+
const init = { method: call.method, headers, body };
|
|
164
|
+
if (!timeoutMs) {
|
|
165
|
+
const response = await transport(url.toString(), { ...init, signal: call.signal });
|
|
166
|
+
return { response, body: await parsed(response) };
|
|
167
|
+
}
|
|
168
|
+
const controller = new AbortController();
|
|
169
|
+
let timedOut = false;
|
|
170
|
+
const timer = setTimeout(() => {
|
|
171
|
+
timedOut = true;
|
|
172
|
+
controller.abort();
|
|
173
|
+
}, timeoutMs);
|
|
174
|
+
const forward = () => controller.abort(call.signal?.reason);
|
|
175
|
+
if (call.signal?.aborted)
|
|
176
|
+
forward();
|
|
177
|
+
else
|
|
178
|
+
call.signal?.addEventListener?.("abort", forward, { once: true });
|
|
179
|
+
try {
|
|
180
|
+
const response = await transport(url.toString(), { ...init, signal: controller.signal });
|
|
181
|
+
return { response, body: await parsed(response) };
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
if (timedOut)
|
|
185
|
+
throw new errors_1.CapaWriteTimeoutError(timeoutMs, call.method, call.path);
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
clearTimeout(timer);
|
|
190
|
+
call.signal?.removeEventListener?.("abort", forward);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
async function request(call) {
|
|
194
|
+
// Checked per call too: a client built on the server can be handed to code that runs in a browser.
|
|
195
|
+
if (inBrowser())
|
|
196
|
+
throw new errors_1.CapaWriteKeyInBrowserError();
|
|
197
|
+
let { response, body } = await send(call);
|
|
198
|
+
if (response.status === 429) {
|
|
199
|
+
// Once, and only for a wait a server route can afford. The retry is the
|
|
200
|
+
// same request, `Idempotency-Key` included, so a create is never made twice.
|
|
201
|
+
const wait = (0, errors_1.writeErrorFrom)(429, body, response.headers).retryAfter;
|
|
202
|
+
if (wait !== undefined && maxRetryAfter > 0 && wait <= maxRetryAfter) {
|
|
203
|
+
await sleep(wait * 1000, call.signal);
|
|
204
|
+
({ response, body } = await send(call));
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (response.status >= 300 && response.status < 400)
|
|
208
|
+
throw (0, errors_1.redirectRefused)(response.status, response.headers);
|
|
209
|
+
if (!response.ok)
|
|
210
|
+
throw (0, errors_1.writeErrorFrom)(response.status, body, response.headers);
|
|
211
|
+
if (response.status === 204)
|
|
212
|
+
return undefined;
|
|
213
|
+
if (!body || typeof body !== "object") {
|
|
214
|
+
throw (0, errors_1.writeErrorFrom)(response.status, null, response.headers);
|
|
215
|
+
}
|
|
216
|
+
return body;
|
|
217
|
+
}
|
|
218
|
+
async function parsed(response) {
|
|
219
|
+
const text = await response.text();
|
|
220
|
+
if (text === "")
|
|
221
|
+
return null;
|
|
222
|
+
try {
|
|
223
|
+
return JSON.parse(text);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const entries = {
|
|
230
|
+
list(model, options = {}) {
|
|
231
|
+
const query = new URLSearchParams();
|
|
232
|
+
if (options.limit !== undefined)
|
|
233
|
+
query.set("limit", String(options.limit));
|
|
234
|
+
if (options.after !== undefined)
|
|
235
|
+
query.set("after", options.after);
|
|
236
|
+
for (const [field, eq] of Object.entries(options.filter ?? {}))
|
|
237
|
+
query.set(`filter[${field}][eq]`, String(eq));
|
|
238
|
+
return request({ method: "GET", path: `/entries/${segment(model, "model")}`, query, signal: options.signal });
|
|
239
|
+
},
|
|
240
|
+
get(model, id, options = {}) {
|
|
241
|
+
return request({ method: "GET", path: `/entries/${segment(model, "model")}/${segment(id, "id")}`, signal: options.signal });
|
|
242
|
+
},
|
|
243
|
+
create(model, body, options = {}) {
|
|
244
|
+
return request({
|
|
245
|
+
method: "POST",
|
|
246
|
+
path: `/entries/${segment(model, "model")}`,
|
|
247
|
+
body,
|
|
248
|
+
idempotencyKey: options.idempotencyKey ?? randomUuid(),
|
|
249
|
+
signal: options.signal,
|
|
250
|
+
});
|
|
251
|
+
},
|
|
252
|
+
update(model, id, body, options = {}) {
|
|
253
|
+
return request({
|
|
254
|
+
method: "PATCH",
|
|
255
|
+
path: `/entries/${segment(model, "model")}/${segment(id, "id")}`,
|
|
256
|
+
body,
|
|
257
|
+
idempotencyKey: options.idempotencyKey,
|
|
258
|
+
ifMatch: ifMatchHeader(options.ifMatch),
|
|
259
|
+
signal: options.signal,
|
|
260
|
+
});
|
|
261
|
+
},
|
|
262
|
+
replace(model, id, body, options = {}) {
|
|
263
|
+
return request({
|
|
264
|
+
method: "PUT",
|
|
265
|
+
path: `/entries/${segment(model, "model")}/${segment(id, "id")}`,
|
|
266
|
+
body,
|
|
267
|
+
idempotencyKey: options.idempotencyKey,
|
|
268
|
+
ifMatch: ifMatchHeader(options.ifMatch),
|
|
269
|
+
signal: options.signal,
|
|
270
|
+
});
|
|
271
|
+
},
|
|
272
|
+
publish(model, id, body = {}, options = {}) {
|
|
273
|
+
return request({
|
|
274
|
+
method: "POST",
|
|
275
|
+
path: `/entries/${segment(model, "model")}/${segment(id, "id")}/publish`,
|
|
276
|
+
body,
|
|
277
|
+
idempotencyKey: options.idempotencyKey,
|
|
278
|
+
signal: options.signal,
|
|
279
|
+
});
|
|
280
|
+
},
|
|
281
|
+
unpublish(model, id, options = {}) {
|
|
282
|
+
return request({
|
|
283
|
+
method: "POST",
|
|
284
|
+
path: `/entries/${segment(model, "model")}/${segment(id, "id")}/unpublish`,
|
|
285
|
+
body: options.versionId === undefined ? {} : { versionId: nonEmpty(options.versionId, "versionId") },
|
|
286
|
+
idempotencyKey: options.idempotencyKey,
|
|
287
|
+
signal: options.signal,
|
|
288
|
+
});
|
|
289
|
+
},
|
|
290
|
+
delete(model, id, options = {}) {
|
|
291
|
+
return request({
|
|
292
|
+
method: "DELETE",
|
|
293
|
+
path: `/entries/${segment(model, "model")}/${segment(id, "id")}`,
|
|
294
|
+
idempotencyKey: options.idempotencyKey,
|
|
295
|
+
ifMatch: ifMatchHeader(options.ifMatch),
|
|
296
|
+
signal: options.signal,
|
|
297
|
+
});
|
|
298
|
+
},
|
|
299
|
+
};
|
|
300
|
+
const scheduledActions = {
|
|
301
|
+
get(id, options = {}) {
|
|
302
|
+
return request({ method: "GET", path: `/scheduled-actions/${segment(id, "id")}`, signal: options.signal });
|
|
303
|
+
},
|
|
304
|
+
list(options = {}) {
|
|
305
|
+
const query = new URLSearchParams();
|
|
306
|
+
if (options.targetId !== undefined)
|
|
307
|
+
query.set("targetId", options.targetId);
|
|
308
|
+
if (options.status !== undefined)
|
|
309
|
+
query.set("status", typeof options.status === "string" ? options.status : options.status.join(","));
|
|
310
|
+
if (options.limit !== undefined)
|
|
311
|
+
query.set("limit", String(options.limit));
|
|
312
|
+
if (options.after !== undefined)
|
|
313
|
+
query.set("after", options.after);
|
|
314
|
+
return request({ method: "GET", path: "/scheduled-actions", query, signal: options.signal });
|
|
315
|
+
},
|
|
316
|
+
cancel(id, options = {}) {
|
|
317
|
+
return request({
|
|
318
|
+
method: "POST",
|
|
319
|
+
path: `/scheduled-actions/${segment(id, "id")}/cancel`,
|
|
320
|
+
body: {},
|
|
321
|
+
idempotencyKey: options.idempotencyKey,
|
|
322
|
+
signal: options.signal,
|
|
323
|
+
});
|
|
324
|
+
},
|
|
325
|
+
};
|
|
326
|
+
return {
|
|
327
|
+
baseUrl,
|
|
328
|
+
version: version,
|
|
329
|
+
me(options = {}) {
|
|
330
|
+
return request({ method: "GET", path: "/me", signal: options.signal });
|
|
331
|
+
},
|
|
332
|
+
entries,
|
|
333
|
+
scheduledActions,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* errors.ts — what `@capacms/sdk/server` throws.
|
|
3
|
+
*
|
|
4
|
+
* `CapaWriteError` is a refusal from the write host, in the `/api/` envelope
|
|
5
|
+
* (`{ error: { type, code, message, param, hint, docs }, meta }`). It extends
|
|
6
|
+
* `CapaError`, so `isCapaError` from `@capacms/sdk/next` is true for it too,
|
|
7
|
+
* and it always carries `status`, `code` and, when the host sent one, `hint`.
|
|
8
|
+
*
|
|
9
|
+
* The other two are thrown before anything is sent: a key in a browser, and a
|
|
10
|
+
* value that is not a write key.
|
|
11
|
+
*/
|
|
12
|
+
import { CapaError } from "../next/errors";
|
|
13
|
+
/** The codes the write host answers, as the API reference lists them. Any other string can arrive too. */
|
|
14
|
+
export type WriteErrorCode = "version_required" | "version_unsupported" | "invalid_request" | "invalid_json" | "browser_refused" | "invalid_key" | "ip_not_allowed" | "scope_missing" | "key_maker_limited" | "relation_hidden" | "rate_limited" | "not_found" | "field_invalid" | "required_field" | "unknown_field" | "idempotency_key_required" | "idempotency_key_invalid" | "idempotency_mismatch" | "idempotency_in_progress" | "idempotency_replay_unavailable" | "version_conflict" | "stale_model_version" | "conflict" | "already_running" | "not_pending" | "subscription_required" | "internal" | "unparseable_response" | "redirect_refused" | (string & {});
|
|
15
|
+
export declare class CapaWriteError extends CapaError {
|
|
16
|
+
readonly code: WriteErrorCode;
|
|
17
|
+
constructor(input: ConstructorParameters<typeof CapaError>[0]);
|
|
18
|
+
}
|
|
19
|
+
export declare function isCapaWriteError(error: unknown): error is CapaWriteError;
|
|
20
|
+
/**
|
|
21
|
+
* Thrown by `createWriteClient` and by every call when `window` or `document`
|
|
22
|
+
* exists. A write key works from a server only: the write host refuses a
|
|
23
|
+
* browser and turns the key off.
|
|
24
|
+
*/
|
|
25
|
+
export declare class CapaWriteKeyInBrowserError extends Error {
|
|
26
|
+
readonly code = "write_key_in_browser";
|
|
27
|
+
constructor();
|
|
28
|
+
}
|
|
29
|
+
/** Thrown by `createWriteClient` for a key that is not a `capw_` key, or whose checksum is wrong. Nothing is sent. */
|
|
30
|
+
export declare class CapaWriteKeyFormatError extends TypeError {
|
|
31
|
+
readonly code = "invalid_key";
|
|
32
|
+
constructor(message: string);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Thrown when a request takes longer than the client's `timeoutMs`. The
|
|
36
|
+
* write may still have been applied on the host: retry with the same
|
|
37
|
+
* `idempotencyKey`, or read the entry first.
|
|
38
|
+
*/
|
|
39
|
+
export declare class CapaWriteTimeoutError extends Error {
|
|
40
|
+
readonly code = "timeout";
|
|
41
|
+
readonly timeoutMs: number;
|
|
42
|
+
constructor(timeoutMs: number, method: string, path: string);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The client never follows a redirect, so the key is never sent to another
|
|
46
|
+
* address. A 3xx is this error, code `redirect_refused`, naming where it
|
|
47
|
+
* pointed so the caller can fix `baseUrl`.
|
|
48
|
+
*/
|
|
49
|
+
export declare function redirectRefused(status: number, headers: {
|
|
50
|
+
get(name: string): string | null;
|
|
51
|
+
} | undefined): CapaWriteError;
|
|
52
|
+
/**
|
|
53
|
+
* A `CapaWriteError` from a failed response. The `/api/` envelope is read
|
|
54
|
+
* first. A body that is not one (a proxy's page, an empty body) still becomes
|
|
55
|
+
* an error with the status, code `unparseable_response`, so a caller always
|
|
56
|
+
* gets `status` and `code` to branch on.
|
|
57
|
+
*/
|
|
58
|
+
export declare function writeErrorFrom(status: number, body: unknown, headers: {
|
|
59
|
+
get(name: string): string | null;
|
|
60
|
+
} | undefined): CapaWriteError;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CapaWriteTimeoutError = exports.CapaWriteKeyFormatError = exports.CapaWriteKeyInBrowserError = exports.CapaWriteError = void 0;
|
|
4
|
+
exports.isCapaWriteError = isCapaWriteError;
|
|
5
|
+
exports.redirectRefused = redirectRefused;
|
|
6
|
+
exports.writeErrorFrom = writeErrorFrom;
|
|
7
|
+
/**
|
|
8
|
+
* errors.ts — what `@capacms/sdk/server` throws.
|
|
9
|
+
*
|
|
10
|
+
* `CapaWriteError` is a refusal from the write host, in the `/api/` envelope
|
|
11
|
+
* (`{ error: { type, code, message, param, hint, docs }, meta }`). It extends
|
|
12
|
+
* `CapaError`, so `isCapaError` from `@capacms/sdk/next` is true for it too,
|
|
13
|
+
* and it always carries `status`, `code` and, when the host sent one, `hint`.
|
|
14
|
+
*
|
|
15
|
+
* The other two are thrown before anything is sent: a key in a browser, and a
|
|
16
|
+
* value that is not a write key.
|
|
17
|
+
*/
|
|
18
|
+
const errors_1 = require("../next/errors");
|
|
19
|
+
class CapaWriteError extends errors_1.CapaError {
|
|
20
|
+
constructor(input) {
|
|
21
|
+
super(input);
|
|
22
|
+
this.name = "CapaWriteError";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
exports.CapaWriteError = CapaWriteError;
|
|
26
|
+
function isCapaWriteError(error) {
|
|
27
|
+
return error instanceof CapaWriteError;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Thrown by `createWriteClient` and by every call when `window` or `document`
|
|
31
|
+
* exists. A write key works from a server only: the write host refuses a
|
|
32
|
+
* browser and turns the key off.
|
|
33
|
+
*/
|
|
34
|
+
class CapaWriteKeyInBrowserError extends Error {
|
|
35
|
+
code = "write_key_in_browser";
|
|
36
|
+
constructor() {
|
|
37
|
+
super("@capacms/sdk/server: createWriteClient runs on a server only, and this code is running in a browser. " +
|
|
38
|
+
"A write key sent from a browser is refused and the key is turned off. Call the write API from a server route, a server action or a script.");
|
|
39
|
+
this.name = "CapaWriteKeyInBrowserError";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
exports.CapaWriteKeyInBrowserError = CapaWriteKeyInBrowserError;
|
|
43
|
+
/** Thrown by `createWriteClient` for a key that is not a `capw_` key, or whose checksum is wrong. Nothing is sent. */
|
|
44
|
+
class CapaWriteKeyFormatError extends TypeError {
|
|
45
|
+
code = "invalid_key";
|
|
46
|
+
constructor(message) {
|
|
47
|
+
super(message);
|
|
48
|
+
this.name = "CapaWriteKeyFormatError";
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
exports.CapaWriteKeyFormatError = CapaWriteKeyFormatError;
|
|
52
|
+
/**
|
|
53
|
+
* Thrown when a request takes longer than the client's `timeoutMs`. The
|
|
54
|
+
* write may still have been applied on the host: retry with the same
|
|
55
|
+
* `idempotencyKey`, or read the entry first.
|
|
56
|
+
*/
|
|
57
|
+
class CapaWriteTimeoutError extends Error {
|
|
58
|
+
code = "timeout";
|
|
59
|
+
timeoutMs;
|
|
60
|
+
constructor(timeoutMs, method, path) {
|
|
61
|
+
super(`@capacms/sdk/server: ${method} ${path} got no answer from the write API within ${timeoutMs} ms. ` +
|
|
62
|
+
"A write may still have been applied: retry it with the same idempotencyKey, or read the entry first.");
|
|
63
|
+
this.name = "CapaWriteTimeoutError";
|
|
64
|
+
this.timeoutMs = timeoutMs;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
exports.CapaWriteTimeoutError = CapaWriteTimeoutError;
|
|
68
|
+
/**
|
|
69
|
+
* The client never follows a redirect, so the key is never sent to another
|
|
70
|
+
* address. A 3xx is this error, code `redirect_refused`, naming where it
|
|
71
|
+
* pointed so the caller can fix `baseUrl`.
|
|
72
|
+
*/
|
|
73
|
+
function redirectRefused(status, headers) {
|
|
74
|
+
const location = headers?.get?.("Location") ?? null;
|
|
75
|
+
return new CapaWriteError({
|
|
76
|
+
status,
|
|
77
|
+
type: "api_error",
|
|
78
|
+
code: "redirect_refused",
|
|
79
|
+
message: `The Capa write API answered ${status}, a redirect${location ? ` to ${location.slice(0, 200)}` : ""}. ` +
|
|
80
|
+
"The client never follows one, so the key is not sent to another address. Set baseUrl to the write host itself.",
|
|
81
|
+
requestId: headers?.get?.("X-Request-Id") ?? "",
|
|
82
|
+
docs: "",
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* A `CapaWriteError` from a failed response. The `/api/` envelope is read
|
|
87
|
+
* first. A body that is not one (a proxy's page, an empty body) still becomes
|
|
88
|
+
* an error with the status, code `unparseable_response`, so a caller always
|
|
89
|
+
* gets `status` and `code` to branch on.
|
|
90
|
+
*/
|
|
91
|
+
function writeErrorFrom(status, body, headers) {
|
|
92
|
+
const requestId = headers?.get?.("X-Request-Id") ?? "";
|
|
93
|
+
const retryAfter = (0, errors_1.retryAfterOf)(headers?.get?.("Retry-After"));
|
|
94
|
+
const object = (body && typeof body === "object" ? body : {});
|
|
95
|
+
const detail = object.error && typeof object.error === "object" ? object.error : null;
|
|
96
|
+
const code = (0, errors_1.optionalString)(detail?.code) ?? (0, errors_1.optionalString)(object.code);
|
|
97
|
+
if (!code) {
|
|
98
|
+
return new CapaWriteError({
|
|
99
|
+
status,
|
|
100
|
+
type: "api_error",
|
|
101
|
+
code: "unparseable_response",
|
|
102
|
+
message: `The Capa write API answered ${status} with a body that is not an error envelope.`,
|
|
103
|
+
requestId,
|
|
104
|
+
docs: "",
|
|
105
|
+
retryAfter,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
const message = (0, errors_1.optionalString)(detail?.message) ?? (typeof object.error === "string" ? object.error : undefined) ?? (0, errors_1.optionalString)(object.message) ?? code;
|
|
109
|
+
return new CapaWriteError({
|
|
110
|
+
status,
|
|
111
|
+
type: (0, errors_1.optionalString)(detail?.type) ?? "api_error",
|
|
112
|
+
code,
|
|
113
|
+
message,
|
|
114
|
+
param: (0, errors_1.optionalString)(detail?.param),
|
|
115
|
+
hint: (0, errors_1.optionalString)(detail?.hint) ?? (0, errors_1.optionalString)(object.hint),
|
|
116
|
+
requestId: (0, errors_1.optionalString)(object.meta?.requestId) ?? requestId,
|
|
117
|
+
docs: (0, errors_1.optionalString)(detail?.docs) ?? "",
|
|
118
|
+
retryAfter,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @capacms/sdk/server — the client for Capa's server write API.
|
|
3
|
+
*
|
|
4
|
+
* SERVER ONLY. A `capw_` key writes your project's content. Never import this
|
|
5
|
+
* from code a browser loads: a browser build resolves it to a module that
|
|
6
|
+
* throws on import (browser.ts), `createWriteClient` throws
|
|
7
|
+
* `CapaWriteKeyInBrowserError` where `window` or `document` exists, and the
|
|
8
|
+
* write host refuses a browser and turns the key off.
|
|
9
|
+
*/
|
|
10
|
+
export { createWriteClient, DEFAULT_WRITE_BASE_URL, DEFAULT_WRITE_TIMEOUT_MS, inBrowser, MAX_RETRY_AFTER_SECONDS, WRITE_API_VERSIONS, WRITE_CLIENT_USER_AGENT, } from "./client";
|
|
11
|
+
export type { CallOptions, CapaWriteClient, ConditionalWriteOptions, EntryStatus, EntryWriteBody, ListEntriesOptions, ListScheduledActionsOptions, PublishBody, PublishNowBody, SchedulePublishBody, UnpublishOptions, ScheduledActionStatus, ScheduledPublish, WriteKeyAction, ScheduledAction, WriteApiVersion, WriteCallOptions, WriteClientConfig, WriteEntriesResource, WriteEntry, WriteFields, WriteFieldValue, WriteKeyInfo, WriteMeta, WritePage, WritePageInfo, WriteScheduledActionsResource, WriteSingle, } from "./client";
|
|
12
|
+
export { CapaWriteError, CapaWriteKeyFormatError, CapaWriteKeyInBrowserError, CapaWriteTimeoutError, isCapaWriteError, } from "./errors";
|
|
13
|
+
export type { WriteErrorCode } from "./errors";
|
|
14
|
+
export { isWriteKeyShaped, WRITE_KEY_IN_TEXT, WRITE_KEY_SHAPE, writeKeyChecksum, writeKeyChecksumOk, } from "./key-format";
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.writeKeyChecksumOk = exports.writeKeyChecksum = exports.WRITE_KEY_SHAPE = exports.WRITE_KEY_IN_TEXT = exports.isWriteKeyShaped = exports.isCapaWriteError = exports.CapaWriteTimeoutError = exports.CapaWriteKeyInBrowserError = exports.CapaWriteKeyFormatError = exports.CapaWriteError = exports.WRITE_CLIENT_USER_AGENT = exports.WRITE_API_VERSIONS = exports.MAX_RETRY_AFTER_SECONDS = exports.inBrowser = exports.DEFAULT_WRITE_TIMEOUT_MS = exports.DEFAULT_WRITE_BASE_URL = exports.createWriteClient = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* @capacms/sdk/server — the client for Capa's server write API.
|
|
6
|
+
*
|
|
7
|
+
* SERVER ONLY. A `capw_` key writes your project's content. Never import this
|
|
8
|
+
* from code a browser loads: a browser build resolves it to a module that
|
|
9
|
+
* throws on import (browser.ts), `createWriteClient` throws
|
|
10
|
+
* `CapaWriteKeyInBrowserError` where `window` or `document` exists, and the
|
|
11
|
+
* write host refuses a browser and turns the key off.
|
|
12
|
+
*/
|
|
13
|
+
var client_1 = require("./client");
|
|
14
|
+
Object.defineProperty(exports, "createWriteClient", { enumerable: true, get: function () { return client_1.createWriteClient; } });
|
|
15
|
+
Object.defineProperty(exports, "DEFAULT_WRITE_BASE_URL", { enumerable: true, get: function () { return client_1.DEFAULT_WRITE_BASE_URL; } });
|
|
16
|
+
Object.defineProperty(exports, "DEFAULT_WRITE_TIMEOUT_MS", { enumerable: true, get: function () { return client_1.DEFAULT_WRITE_TIMEOUT_MS; } });
|
|
17
|
+
Object.defineProperty(exports, "inBrowser", { enumerable: true, get: function () { return client_1.inBrowser; } });
|
|
18
|
+
Object.defineProperty(exports, "MAX_RETRY_AFTER_SECONDS", { enumerable: true, get: function () { return client_1.MAX_RETRY_AFTER_SECONDS; } });
|
|
19
|
+
Object.defineProperty(exports, "WRITE_API_VERSIONS", { enumerable: true, get: function () { return client_1.WRITE_API_VERSIONS; } });
|
|
20
|
+
Object.defineProperty(exports, "WRITE_CLIENT_USER_AGENT", { enumerable: true, get: function () { return client_1.WRITE_CLIENT_USER_AGENT; } });
|
|
21
|
+
var errors_1 = require("./errors");
|
|
22
|
+
Object.defineProperty(exports, "CapaWriteError", { enumerable: true, get: function () { return errors_1.CapaWriteError; } });
|
|
23
|
+
Object.defineProperty(exports, "CapaWriteKeyFormatError", { enumerable: true, get: function () { return errors_1.CapaWriteKeyFormatError; } });
|
|
24
|
+
Object.defineProperty(exports, "CapaWriteKeyInBrowserError", { enumerable: true, get: function () { return errors_1.CapaWriteKeyInBrowserError; } });
|
|
25
|
+
Object.defineProperty(exports, "CapaWriteTimeoutError", { enumerable: true, get: function () { return errors_1.CapaWriteTimeoutError; } });
|
|
26
|
+
Object.defineProperty(exports, "isCapaWriteError", { enumerable: true, get: function () { return errors_1.isCapaWriteError; } });
|
|
27
|
+
var key_format_1 = require("./key-format");
|
|
28
|
+
Object.defineProperty(exports, "isWriteKeyShaped", { enumerable: true, get: function () { return key_format_1.isWriteKeyShaped; } });
|
|
29
|
+
Object.defineProperty(exports, "WRITE_KEY_IN_TEXT", { enumerable: true, get: function () { return key_format_1.WRITE_KEY_IN_TEXT; } });
|
|
30
|
+
Object.defineProperty(exports, "WRITE_KEY_SHAPE", { enumerable: true, get: function () { return key_format_1.WRITE_KEY_SHAPE; } });
|
|
31
|
+
Object.defineProperty(exports, "writeKeyChecksum", { enumerable: true, get: function () { return key_format_1.writeKeyChecksum; } });
|
|
32
|
+
Object.defineProperty(exports, "writeKeyChecksumOk", { enumerable: true, get: function () { return key_format_1.writeKeyChecksumOk; } });
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* key-format.ts — the shape and checksum of a `capw_` server write key.
|
|
3
|
+
*
|
|
4
|
+
* capw_<43 base62 secret><6 base62 checksum>
|
|
5
|
+
*
|
|
6
|
+
* The checksum is CRC32 (IEEE) of the string `capw_<secret>`, written in
|
|
7
|
+
* base62 with the digits 0-9, A-Z, a-z in that order and left-padded with `0`
|
|
8
|
+
* to 6 characters. It lets a client (and a secret scanner) reject a mistyped
|
|
9
|
+
* or truncated key without asking the write host. It is not a secret and
|
|
10
|
+
* proves nothing about the key being real: only the write host can say that.
|
|
11
|
+
*
|
|
12
|
+
* The API holds the same rule (`apps/api/src/write-api/auth/key-format.ts`).
|
|
13
|
+
* Both are tested against vectors computed independently with `zlib.crc32`.
|
|
14
|
+
*/
|
|
15
|
+
/** `capw_` plus 49 base62 characters, the whole value. */
|
|
16
|
+
export declare const WRITE_KEY_SHAPE: RegExp;
|
|
17
|
+
/**
|
|
18
|
+
* The same shape inside other text, the regex a bundle scan uses (write API
|
|
19
|
+
* spec 6.2). No word boundaries, unlike GitHub's pattern: a key in a bundle
|
|
20
|
+
* can sit right after an escape (`"\ncapw_…"`), an underscore or other
|
|
21
|
+
* letters, and `\b` would miss it there. A run longer than 49 is matched on
|
|
22
|
+
* its first 49, whose checksum then decides whether it is a key.
|
|
23
|
+
*/
|
|
24
|
+
export declare const WRITE_KEY_IN_TEXT: RegExp;
|
|
25
|
+
export declare const WRITE_KEY_PREFIX = "capw_";
|
|
26
|
+
export declare const WRITE_KEY_LENGTH = 54;
|
|
27
|
+
/** CRC32 (IEEE 802.3, the zlib one) of an ASCII string. A key holds ASCII only. */
|
|
28
|
+
export declare function crc32(text: string): number;
|
|
29
|
+
/** A non-negative integer in base62, left-padded with `0` to `width`. */
|
|
30
|
+
export declare function base62(value: number, width: number): string;
|
|
31
|
+
/** The 6-character checksum of a 43-character secret. */
|
|
32
|
+
export declare function writeKeyChecksum(secret: string): string;
|
|
33
|
+
/** Whether `value` is shaped like a write key: `capw_` and 49 base62 characters. */
|
|
34
|
+
export declare function isWriteKeyShaped(value: unknown): value is string;
|
|
35
|
+
/** Whether `value` is shaped like a write key and its last 6 characters are the checksum of the rest. */
|
|
36
|
+
export declare function writeKeyChecksumOk(value: unknown): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* How a message names a key without printing it: the first 12 characters,
|
|
39
|
+
* which is the `keyPrefix` the admin lists. Never the secret.
|
|
40
|
+
*/
|
|
41
|
+
export declare function writeKeyLabel(value: string): string;
|