@syntaxcircus/cmsify-client 0.0.0-bootstrap.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/dist/index.js ADDED
@@ -0,0 +1,286 @@
1
+ // src/etag.ts
2
+ var ETagStore = class {
3
+ values = /* @__PURE__ */ new Map();
4
+ get(key) {
5
+ return this.values.get(key);
6
+ }
7
+ set(key, etag) {
8
+ if (etag) {
9
+ this.values.set(key, etag);
10
+ }
11
+ }
12
+ };
13
+
14
+ // src/errors.ts
15
+ var CmsifyApiError = class extends Error {
16
+ problem;
17
+ status;
18
+ traceId;
19
+ correlationId;
20
+ constructor(problem, correlationId) {
21
+ super(problem.detail ?? problem.title ?? `Cmsify API request failed with ${problem.status ?? "unknown status"}`);
22
+ this.name = "CmsifyApiError";
23
+ this.problem = problem;
24
+ this.status = problem.status ?? 0;
25
+ this.traceId = typeof problem.traceId === "string" ? problem.traceId : void 0;
26
+ this.correlationId = correlationId;
27
+ }
28
+ };
29
+ var CmsifyTimeoutError = class extends Error {
30
+ constructor(timeoutMs) {
31
+ super(`Cmsify API request exceeded its ${timeoutMs}ms timeout budget.`);
32
+ this.name = "CmsifyTimeoutError";
33
+ }
34
+ };
35
+ var isProblemDetails = (value) => typeof value === "object" && value !== null && ("status" in value || "title" in value || "type" in value);
36
+
37
+ // src/pagination.ts
38
+ async function* listAll(loader) {
39
+ for (let page = 1; ; page += 1) {
40
+ const result = await loader(page);
41
+ for (const item of result.items) {
42
+ yield item;
43
+ }
44
+ if (page >= result.totalPages || result.items.length === 0) {
45
+ return;
46
+ }
47
+ }
48
+ }
49
+
50
+ // src/client.ts
51
+ var CmsifyClient = class {
52
+ content = {
53
+ list: (options = {}) => this.request(this.workspacePath("/content", contentQuery(options, true))),
54
+ listAll: (options = {}) => listAll((page) => this.content.list({ ...options, page })),
55
+ get: (id, options = {}) => this.request(this.workspacePath(`/content/${encodeURIComponent(id)}`, detailQuery(options))),
56
+ bySlug: (slug, options = {}) => this.request(this.workspacePath(`/content/by-slug/${encodeURIComponent(slug)}`, detailQuery(options, false))),
57
+ translations: (id, options = {}) => this.request(this.workspacePath(`/content/${encodeURIComponent(id)}/translations`, pageQuery(options)))
58
+ };
59
+ templates = {
60
+ list: (options = {}) => this.request(this.workspacePath("/templates", pageQuery(options))),
61
+ get: (id) => this.request(this.workspacePath(`/templates/${encodeURIComponent(id)}`))
62
+ };
63
+ media = {
64
+ list: (options = {}) => this.request(this.workspacePath("/media", pageQuery(options))),
65
+ get: (id) => this.request(this.workspacePath(`/media/${encodeURIComponent(id)}`)),
66
+ download: (id) => this.request(this.workspacePath(`/media/${encodeURIComponent(id)}/file`), {}, {}, "blob")
67
+ };
68
+ baseUrl;
69
+ baseOrigin;
70
+ workspaceId;
71
+ token;
72
+ fetchImpl;
73
+ retryByDefault;
74
+ timeoutMs;
75
+ now;
76
+ delay;
77
+ etags = new ETagStore();
78
+ constructor(options) {
79
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
80
+ this.baseOrigin = new URL(this.baseUrl).origin;
81
+ this.workspaceId = options.workspaceId;
82
+ this.token = options.apiToken;
83
+ this.fetchImpl = options.fetch ?? fetch;
84
+ this.retryByDefault = options.retry !== false;
85
+ this.timeoutMs = options.timeoutMs;
86
+ this.now = options.now ?? Date.now;
87
+ this.delay = options.delay ?? delay;
88
+ }
89
+ async request(path, init = {}, options = {}, responseType = "json") {
90
+ const url = this.requestUrl(path);
91
+ const headers = new Headers(init.headers);
92
+ headers.set("Accept", responseType === "blob" ? "*/*" : "application/json");
93
+ headers.set("X-Correlation-Id", createCorrelationId());
94
+ if (this.token) headers.set("Authorization", `Bearer ${this.token}`);
95
+ if (init.body && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");
96
+ if (options.idempotencyKey) headers.set("Idempotency-Key", options.idempotencyKey);
97
+ const method = (init.method ?? "GET").toUpperCase();
98
+ const trackedEtag = options.ifMatch ?? this.etags.get(url);
99
+ if (trackedEtag && isMutation(method)) headers.set("If-Match", trackedEtag);
100
+ const retry = (options.retry ?? this.retryByDefault) && (isIdempotent(method) || Boolean(options.idempotencyKey)) && isReplayableBody(init.body);
101
+ const response = await this.fetchWithRetry(url, { ...init, headers }, retry, options.signal, options.timeoutMs ?? this.timeoutMs);
102
+ this.etags.set(url, response.headers.get("ETag"));
103
+ if (!response.ok) {
104
+ const correlationId = response.headers.get("X-Correlation-Id") ?? headers.get("X-Correlation-Id") ?? void 0;
105
+ const body = await this.safeReadJson(response);
106
+ const problem = isProblemDetails(body) ? { ...body, status: response.status } : { status: response.status, title: response.statusText };
107
+ throw new CmsifyApiError(problem, correlationId);
108
+ }
109
+ if (hasEmptySuccessBody(response)) return void 0;
110
+ if (responseType === "blob") return await response.blob();
111
+ return await this.safeReadJson(response);
112
+ }
113
+ workspacePath(path, query) {
114
+ if (!isGuid(this.workspaceId)) throw new Error("workspaceId must be a GUID.");
115
+ const search = new URLSearchParams();
116
+ for (const [key, value] of Object.entries(query ?? {})) if (value !== void 0) search.set(key, String(value));
117
+ const suffix = search.size > 0 ? `?${search}` : "";
118
+ return `/api/v1/workspaces/${encodeURIComponent(this.workspaceId)}${path}${suffix}`;
119
+ }
120
+ requestUrl(path) {
121
+ const url = new URL(path, `${this.baseUrl}/`);
122
+ if (url.origin !== this.baseOrigin) throw new Error("CmsifyClient requests must target the configured Cmsify origin.");
123
+ return url.toString();
124
+ }
125
+ async fetchWithRetry(url, init, retry, callerSignal, timeoutMs) {
126
+ const deadline = timeoutMs === void 0 ? void 0 : this.now() + Math.max(0, timeoutMs);
127
+ for (let attempt = 1; ; attempt += 1) {
128
+ const controller = new AbortController();
129
+ const timeout = timeoutMs === void 0 ? void 0 : Math.max(0, (deadline ?? this.now()) - this.now());
130
+ const cleanup = connectAbortSignals(controller, callerSignal, timeout, timeoutMs);
131
+ try {
132
+ const response = await this.fetchImpl(url, { ...init, signal: controller.signal });
133
+ if (!retry || attempt >= 3 || !isRetryableResponse(response)) return response;
134
+ await this.delay(retryDelay(response.headers.get("Retry-After"), attempt, this.now), controller.signal);
135
+ } catch (error) {
136
+ if (controller.signal.aborted) throw controller.signal.reason ?? error;
137
+ if (!retry || attempt >= 3 || !isTransportFault(error)) throw error;
138
+ await this.delay(100 * 2 ** (attempt - 1), controller.signal);
139
+ } finally {
140
+ cleanup();
141
+ }
142
+ }
143
+ }
144
+ async safeReadJson(response) {
145
+ const text = await response.text();
146
+ if (!text) return void 0;
147
+ try {
148
+ return JSON.parse(text);
149
+ } catch {
150
+ return { status: response.status, title: response.statusText };
151
+ }
152
+ }
153
+ };
154
+ var contentQuery = (options, resolve) => ({
155
+ Q: options.q,
156
+ TemplateVersionId: options.templateVersionId,
157
+ TemplateId: options.templateId,
158
+ Status: options.status,
159
+ LocaleCode: options.localeCode,
160
+ TranslationGroupId: options.translationGroupId,
161
+ Slug: options.slug,
162
+ Tags: options.tags,
163
+ CreatedAfter: asIso(options.createdAfter),
164
+ CreatedBefore: asIso(options.createdBefore),
165
+ PublishedAfter: asIso(options.publishedAfter),
166
+ PublishedBefore: asIso(options.publishedBefore),
167
+ Resolve: resolve,
168
+ AsOf: asIso(options.asOf),
169
+ SortBy: options.sortBy,
170
+ SortDesc: options.sortDesc,
171
+ page: options.page,
172
+ pageSize: options.pageSize
173
+ });
174
+ var detailQuery = (options, resolve = true) => options.asOf === void 0 ? {} : { ...resolve ? { resolve: true } : {}, asOf: asIso(options.asOf) };
175
+ var pageQuery = (options) => ({ page: options.page, pageSize: options.pageSize });
176
+ var asIso = (value) => value instanceof Date ? value.toISOString() : value;
177
+ var isGuid = (value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
178
+ var isIdempotent = (method) => ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"].includes(method);
179
+ var isMutation = (method) => !["GET", "HEAD", "OPTIONS"].includes(method);
180
+ var isRetryableResponse = (response) => response.status === 429 || response.status >= 500;
181
+ var isTransportFault = (error) => error instanceof TypeError || error instanceof Error && error.name === "NetworkError";
182
+ var isReplayableBody = (body) => !(typeof ReadableStream !== "undefined" && body instanceof ReadableStream);
183
+ var hasEmptySuccessBody = (response) => response.status === 204 || response.headers.get("Content-Length") === "0";
184
+ var retryDelay = (header, attempt, now) => retryAfterDelay(header, now) ?? 100 * 2 ** (attempt - 1);
185
+ var retryAfterDelay = (header, now) => {
186
+ if (header === null) return void 0;
187
+ const seconds = Number(header);
188
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
189
+ const date = Date.parse(header);
190
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - now());
191
+ };
192
+ var connectAbortSignals = (controller, callerSignal, timeout, timeoutBudget) => {
193
+ const abortForCaller = () => controller.abort(callerSignal?.reason);
194
+ if (callerSignal?.aborted) abortForCaller();
195
+ else callerSignal?.addEventListener("abort", abortForCaller, { once: true });
196
+ const timer = timeout === void 0 ? void 0 : setTimeout(() => controller.abort(new CmsifyTimeoutError(timeoutBudget ?? timeout)), timeout);
197
+ return () => {
198
+ callerSignal?.removeEventListener("abort", abortForCaller);
199
+ if (timer !== void 0) clearTimeout(timer);
200
+ };
201
+ };
202
+ var delay = (milliseconds, signal) => new Promise((resolve, reject) => {
203
+ if (signal.aborted) {
204
+ reject(signal.reason);
205
+ return;
206
+ }
207
+ const timer = setTimeout(resolve, milliseconds);
208
+ signal.addEventListener("abort", () => {
209
+ clearTimeout(timer);
210
+ reject(signal.reason);
211
+ }, { once: true });
212
+ });
213
+ var createCorrelationId = () => globalThis.crypto?.randomUUID?.() ?? `cmsify-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
214
+
215
+ // src/formatting.ts
216
+ var TEXT_FORMAT_HINTS = [
217
+ "plaintext",
218
+ "html",
219
+ "markdown",
220
+ "json",
221
+ "xml",
222
+ "yaml",
223
+ "csv",
224
+ "toml",
225
+ "sql",
226
+ "code",
227
+ "url",
228
+ "email",
229
+ "regex"
230
+ ];
231
+ var MIME_BY_HINT = {
232
+ plaintext: "text/plain",
233
+ html: "text/html",
234
+ markdown: "text/markdown",
235
+ json: "application/json",
236
+ xml: "application/xml",
237
+ yaml: "application/yaml",
238
+ csv: "text/csv",
239
+ toml: "application/toml",
240
+ sql: "application/sql",
241
+ code: "text/plain",
242
+ url: "text/uri-list",
243
+ email: "text/plain",
244
+ regex: "text/plain"
245
+ };
246
+ function toMimeType(hint) {
247
+ if (hint && hint in MIME_BY_HINT) {
248
+ return MIME_BY_HINT[hint];
249
+ }
250
+ return "text/plain";
251
+ }
252
+ function getFormatHint(fieldConfig) {
253
+ if (!fieldConfig || typeof fieldConfig !== "object") {
254
+ return "plaintext";
255
+ }
256
+ const raw = fieldConfig.formatHint;
257
+ if (typeof raw !== "string") {
258
+ return "plaintext";
259
+ }
260
+ const normalized = raw.toLowerCase();
261
+ return TEXT_FORMAT_HINTS.includes(normalized) ? normalized : "plaintext";
262
+ }
263
+ function isProseHint(hint) {
264
+ return hint === "plaintext" || hint === "markdown" || hint === "html";
265
+ }
266
+
267
+ // src/generated/schema.ts
268
+ var schema_exports = {};
269
+
270
+ // src/generated/client.ts
271
+ import createClient from "openapi-fetch";
272
+ var createCmsifyFetchClient = (baseUrl, fetchImpl) => fetchImpl ? createClient({ baseUrl, fetch: fetchImpl }) : createClient({ baseUrl });
273
+ export {
274
+ CmsifyApiError,
275
+ CmsifyClient,
276
+ CmsifyTimeoutError,
277
+ ETagStore,
278
+ TEXT_FORMAT_HINTS,
279
+ createCmsifyFetchClient,
280
+ schema_exports as generated,
281
+ getFormatHint,
282
+ isProseHint,
283
+ listAll,
284
+ toMimeType
285
+ };
286
+ //# sourceMappingURL=index.js.map