@cms0/cms0 0.2.20 → 0.2.22

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.
Files changed (33) hide show
  1. package/README.md +11 -0
  2. package/dist/cjs/custom-types/registry.cjs +6 -0
  3. package/dist/cjs/index.cjs +400 -65
  4. package/dist/cjs/libs/cli/config-loader.cjs +45 -4
  5. package/dist/cjs/libs/cli/publisher.cjs +24 -11
  6. package/dist/esm/custom-types/registry.js +6 -0
  7. package/dist/esm/index.js +401 -66
  8. package/dist/esm/libs/cli/config-loader.js +45 -4
  9. package/dist/esm/libs/cli/publisher.js +24 -11
  10. package/dist/types/custom-types/index.d.ts +2 -1
  11. package/dist/types/custom-types/index.d.ts.map +1 -1
  12. package/dist/types/custom-types/registry.d.ts.map +1 -1
  13. package/dist/types/index.d.ts +131 -7
  14. package/dist/types/index.d.ts.map +1 -1
  15. package/dist/types/libs/cli/config-loader.d.ts.map +1 -1
  16. package/dist/types/libs/cli/publisher.d.ts.map +1 -1
  17. package/package.json +13 -9
  18. package/dist/cjs/index-old-1.cjs +0 -866
  19. package/dist/cjs/index-old.cjs +0 -1016
  20. package/dist/cjs/libs/cli/descriptor-builder.cjs +0 -273
  21. package/dist/cjs/utils/index.cjs +0 -2
  22. package/dist/esm/index-old-1.js +0 -862
  23. package/dist/esm/index-old.js +0 -1012
  24. package/dist/esm/libs/cli/descriptor-builder.js +0 -268
  25. package/dist/esm/utils/index.js +0 -1
  26. package/dist/types/index-old-1.d.ts +0 -175
  27. package/dist/types/index-old-1.d.ts.map +0 -1
  28. package/dist/types/index-old.d.ts +0 -151
  29. package/dist/types/index-old.d.ts.map +0 -1
  30. package/dist/types/libs/cli/descriptor-builder.d.ts +0 -5
  31. package/dist/types/libs/cli/descriptor-builder.d.ts.map +0 -1
  32. package/dist/types/utils/index.d.ts +0 -2
  33. package/dist/types/utils/index.d.ts.map +0 -1
@@ -1,1012 +0,0 @@
1
- import { schemaDescriptor } from "@cms0/cms0/schema-descriptors";
2
- import { buildZodSchemasFromDescriptor, } from "@cms0/shared";
3
- const DEFAULT_REQUEST_CONCURRENCY = 6;
4
- const DEFAULT_REQUEST_RETRIES = 3;
5
- const DEFAULT_REQUEST_RETRY_BASE_MS = 250;
6
- const DEFAULT_REQUEST_RETRY_MAX_MS = 4000;
7
- const DEFAULT_MODEL_NORMALIZATION_CONCURRENCY = 8;
8
- const COLLECTION_SHAPE_ERROR = "Invalid collection response. Expected array or { items, total }.";
9
- function normalizeUploadsPath(uploadsPath) {
10
- const raw = uploadsPath?.trim() || "/uploads";
11
- const withLeadingSlash = raw.startsWith("/") ? raw : `/${raw}`;
12
- const normalized = withLeadingSlash.replace(/\/+$/, "");
13
- return normalized || "/uploads";
14
- }
15
- function normalizeAssetBaseUrl(baseUrl) {
16
- const trimmed = baseUrl?.trim() ?? "";
17
- return trimmed.replace(/\/+$/, "");
18
- }
19
- function encodeFilenameForUrl(filename) {
20
- const normalized = filename.replace(/\\/g, "/").replace(/^\/+/, "").trim();
21
- if (!normalized)
22
- return "";
23
- return normalized
24
- .split("/")
25
- .filter(Boolean)
26
- .map((segment) => encodeURIComponent(segment))
27
- .join("/");
28
- }
29
- function buildAssetUrlBuilder(apiBaseUrl, assetOptions) {
30
- const uploadsPath = normalizeUploadsPath(assetOptions?.uploadsPath);
31
- const explicitBaseUrl = normalizeAssetBaseUrl(assetOptions?.baseUrl);
32
- if (explicitBaseUrl) {
33
- return (filename) => `${explicitBaseUrl}${uploadsPath}/${encodeFilenameForUrl(filename)}`;
34
- }
35
- let inferredBaseUrl = "";
36
- try {
37
- inferredBaseUrl = new URL(apiBaseUrl).origin;
38
- }
39
- catch {
40
- inferredBaseUrl = "";
41
- }
42
- return (filename) => `${inferredBaseUrl}${uploadsPath}/${encodeFilenameForUrl(filename)}`;
43
- }
44
- function maybeAttachAssetUrl(value, assetUrlBuilder) {
45
- if (!value || typeof value !== "object" || Array.isArray(value))
46
- return value;
47
- const source = value;
48
- const filename = typeof source.filename === "string" ? source.filename.trim() : "";
49
- if (!filename)
50
- return value;
51
- const isAssetShape = typeof source.mimeType === "string" ||
52
- typeof source.extension === "string" ||
53
- typeof source.size === "number" ||
54
- typeof source.width === "number" ||
55
- typeof source.height === "number" ||
56
- typeof source.length === "number";
57
- if (!isAssetShape)
58
- return value;
59
- const existingUrl = typeof source.url === "string" && source.url.trim().length > 0
60
- ? source.url
61
- : null;
62
- return {
63
- ...source,
64
- url: existingUrl ?? assetUrlBuilder(filename),
65
- };
66
- }
67
- function toPlainText(value) {
68
- if (typeof value === "string")
69
- return value;
70
- if (typeof value === "number" || typeof value === "boolean")
71
- return String(value);
72
- if (!value || typeof value !== "object")
73
- return "";
74
- const node = value;
75
- if (typeof node.text === "string")
76
- return node.text;
77
- if ("value" in node)
78
- return toPlainText(node.value);
79
- if (Array.isArray(node.content)) {
80
- return node.content
81
- .map((child) => toPlainText(child))
82
- .filter(Boolean)
83
- .join(" ")
84
- .trim();
85
- }
86
- return "";
87
- }
88
- function coerceRichTextValue(value) {
89
- const source = value && typeof value === "object" ? value : {};
90
- const nested = source.value && typeof source.value === "object"
91
- ? source.value
92
- : null;
93
- const normalizedValue = source.value !== undefined ? source.value : value ?? {};
94
- const html = typeof source.html === "string"
95
- ? source.html
96
- : typeof nested?.html === "string"
97
- ? nested.html
98
- : "";
99
- return {
100
- value: normalizedValue ?? {},
101
- html,
102
- };
103
- }
104
- function normalizeLocaleTag(value) {
105
- return typeof value === "string" ? value.trim() : "";
106
- }
107
- function normalizeLocalizedMap(source, normalizeValue) {
108
- const record = source && typeof source === "object" ? source : {};
109
- const localesSource = record.locales && typeof record.locales === "object" && !Array.isArray(record.locales)
110
- ? record.locales
111
- : {};
112
- const locales = {};
113
- for (const [locale, raw] of Object.entries(localesSource)) {
114
- const localeKey = normalizeLocaleTag(locale);
115
- if (!localeKey)
116
- continue;
117
- locales[localeKey] = normalizeValue(raw);
118
- }
119
- const explicitDefault = normalizeLocaleTag(record.defaultLocale);
120
- const firstLocale = Object.keys(locales)[0] ?? "";
121
- const defaultLocale = explicitDefault || firstLocale;
122
- return { defaultLocale, locales };
123
- }
124
- function projectLocalizedByLocale(localized, locale) {
125
- if (!locale || locale === "all")
126
- return localized;
127
- const requested = normalizeLocaleTag(locale);
128
- if (!requested)
129
- return localized;
130
- const requestedValue = localized.locales[requested];
131
- if (requestedValue === undefined) {
132
- return {
133
- defaultLocale: requested,
134
- locales: {},
135
- };
136
- }
137
- return {
138
- defaultLocale: requested,
139
- locales: {
140
- [requested]: requestedValue,
141
- },
142
- };
143
- }
144
- function coerceLocalizedStringValue(value, locale, defaultLocale) {
145
- const normalized = normalizeLocalizedMap(value, (entry) => toPlainText(entry));
146
- if (!normalized.defaultLocale && defaultLocale) {
147
- normalized.defaultLocale = defaultLocale;
148
- }
149
- return projectLocalizedByLocale(normalized, locale);
150
- }
151
- function coerceLocalizedRichTextValue(value, locale, defaultLocale) {
152
- const normalized = normalizeLocalizedMap(value, (entry) => coerceRichTextValue(entry));
153
- if (!normalized.defaultLocale && defaultLocale) {
154
- normalized.defaultLocale = defaultLocale;
155
- }
156
- return projectLocalizedByLocale(normalized, locale);
157
- }
158
- function coerceCustomTypeValue(descriptor, value, options) {
159
- const customType = descriptor.customType;
160
- if (!customType)
161
- return value;
162
- if (customType === "RichText")
163
- return coerceRichTextValue(value);
164
- if (customType === "File" || customType === "Image" || customType === "Video") {
165
- return maybeAttachAssetUrl(value, options?.assetUrlBuilder ?? ((filename) => filename));
166
- }
167
- if (customType === "LocalizedString") {
168
- return coerceLocalizedStringValue(value, options?.locale, options?.defaultLocale);
169
- }
170
- if (customType === "LocalizedRichText") {
171
- return coerceLocalizedRichTextValue(value, options?.locale, options?.defaultLocale);
172
- }
173
- return value;
174
- }
175
- function isPrimitiveDescriptor(desc) {
176
- return desc.kind === "primitive";
177
- }
178
- function isModelRefDescriptor(desc) {
179
- return desc.kind === "modelRef";
180
- }
181
- function isObjectDescriptor(desc) {
182
- return desc.type === "object" && !!desc.properties;
183
- }
184
- function isArrayDescriptor(desc) {
185
- return desc.type === "array" && !!desc.items;
186
- }
187
- function asModelObjectDescriptor(modelName, descriptor) {
188
- const model = descriptor.models?.[modelName];
189
- if (!model) {
190
- throw new Error(`Unknown model '${modelName}' in schema descriptor.`);
191
- }
192
- return {
193
- type: "object",
194
- properties: model.properties,
195
- optional: false,
196
- nullable: false,
197
- };
198
- }
199
- function normalizeBaseUrl(baseUrl) {
200
- const cleaned = baseUrl?.trim().replace(/\/$/, "") ?? "";
201
- if (!cleaned) {
202
- throw new Error("cms0: apiConfig.baseUrl is required to consume API resources.");
203
- }
204
- return cleaned;
205
- }
206
- function resolveIncludeIdMode(includeId) {
207
- if (includeId === true)
208
- return "all";
209
- if (includeId === false)
210
- return "none";
211
- return "collections";
212
- }
213
- function shouldIncludeObjectId(mode, isCollectionItem) {
214
- if (mode === "all")
215
- return true;
216
- if (mode === "collections")
217
- return isCollectionItem;
218
- return false;
219
- }
220
- function buildSearchParams(query) {
221
- const params = new URLSearchParams();
222
- if (!query)
223
- return params;
224
- for (const [key, rawValue] of Object.entries(query)) {
225
- if (rawValue === undefined || rawValue === null)
226
- continue;
227
- if (Array.isArray(rawValue)) {
228
- rawValue.forEach((value) => {
229
- if (value === undefined || value === null)
230
- return;
231
- params.append(key, String(value));
232
- });
233
- continue;
234
- }
235
- params.set(key, String(rawValue));
236
- }
237
- return params;
238
- }
239
- function ensureCollectionEnvelope(data, path) {
240
- if (Array.isArray(data)) {
241
- return { items: data, total: data.length };
242
- }
243
- if (data && typeof data === "object" && Array.isArray(data.items)) {
244
- return {
245
- items: data.items,
246
- total: Number(data.total ?? data.items.length ?? 0),
247
- };
248
- }
249
- throw new Error(`${COLLECTION_SHAPE_ERROR} Path: '${path}'.`);
250
- }
251
- function clampInteger(value, fallback, minimum) {
252
- if (!Number.isFinite(value))
253
- return fallback;
254
- const normalized = Math.floor(value);
255
- return normalized >= minimum ? normalized : fallback;
256
- }
257
- function normalizeRequestOptions(options) {
258
- const concurrency = clampInteger(options?.concurrency, DEFAULT_REQUEST_CONCURRENCY, 1);
259
- const retries = clampInteger(options?.retries, DEFAULT_REQUEST_RETRIES, 0);
260
- const baseDelayMs = clampInteger(options?.retryBaseMs, DEFAULT_REQUEST_RETRY_BASE_MS, 1);
261
- const maxDelayCandidate = clampInteger(options?.retryMaxMs, DEFAULT_REQUEST_RETRY_MAX_MS, 1);
262
- const maxDelayMs = Math.max(maxDelayCandidate, baseDelayMs);
263
- const modelNormalizationConcurrency = Math.max(concurrency, DEFAULT_MODEL_NORMALIZATION_CONCURRENCY);
264
- return {
265
- concurrency,
266
- retry: {
267
- retries,
268
- baseDelayMs,
269
- maxDelayMs,
270
- },
271
- modelNormalizationConcurrency,
272
- };
273
- }
274
- function createAbortError() {
275
- const error = new Error("The operation was aborted.");
276
- error.name = "AbortError";
277
- return error;
278
- }
279
- function isAbortError(error) {
280
- return !!error && typeof error === "object" && error.name === "AbortError";
281
- }
282
- function waitForDelay(ms, signal) {
283
- if (!Number.isFinite(ms) || ms <= 0) {
284
- if (signal?.aborted)
285
- return Promise.reject(createAbortError());
286
- return Promise.resolve();
287
- }
288
- return new Promise((resolve, reject) => {
289
- if (signal?.aborted) {
290
- reject(createAbortError());
291
- return;
292
- }
293
- const timer = setTimeout(() => {
294
- signal?.removeEventListener("abort", onAbort);
295
- resolve();
296
- }, ms);
297
- function onAbort() {
298
- clearTimeout(timer);
299
- signal?.removeEventListener("abort", onAbort);
300
- reject(createAbortError());
301
- }
302
- signal?.addEventListener("abort", onAbort, { once: true });
303
- });
304
- }
305
- function parseRetryAfterMs(retryAfterValue) {
306
- if (!retryAfterValue)
307
- return null;
308
- const value = retryAfterValue.trim();
309
- if (!value)
310
- return null;
311
- const seconds = Number(value);
312
- if (Number.isFinite(seconds)) {
313
- return Math.max(0, Math.round(seconds * 1000));
314
- }
315
- const at = Date.parse(value);
316
- if (Number.isNaN(at))
317
- return null;
318
- return Math.max(0, at - Date.now());
319
- }
320
- function shouldRetryStatus(status) {
321
- return status === 429 || (status >= 500 && status <= 599);
322
- }
323
- function createRequestScheduler(maxConcurrency) {
324
- let active = 0;
325
- const queue = [];
326
- const pump = () => {
327
- while (active < maxConcurrency && queue.length > 0) {
328
- const next = queue.shift();
329
- if (!next)
330
- continue;
331
- next();
332
- }
333
- };
334
- return (task, signal) => new Promise((resolve, reject) => {
335
- if (signal?.aborted) {
336
- reject(createAbortError());
337
- return;
338
- }
339
- let queued = true;
340
- let settled = false;
341
- const run = () => {
342
- if (settled)
343
- return;
344
- queued = false;
345
- active += 1;
346
- Promise.resolve()
347
- .then(task)
348
- .then(resolve, reject)
349
- .finally(() => {
350
- settled = true;
351
- active = Math.max(0, active - 1);
352
- signal?.removeEventListener("abort", onAbort);
353
- pump();
354
- });
355
- };
356
- const onAbort = () => {
357
- if (!queued || settled)
358
- return;
359
- settled = true;
360
- const index = queue.indexOf(run);
361
- if (index >= 0) {
362
- queue.splice(index, 1);
363
- }
364
- reject(createAbortError());
365
- };
366
- signal?.addEventListener("abort", onAbort, { once: true });
367
- queue.push(run);
368
- pump();
369
- });
370
- }
371
- async function mapWithConcurrency(items, concurrency, mapper) {
372
- if (items.length === 0)
373
- return [];
374
- const limit = Math.max(1, Math.floor(concurrency));
375
- if (limit >= items.length) {
376
- return Promise.all(items.map((item, index) => mapper(item, index)));
377
- }
378
- const results = new Array(items.length);
379
- let nextIndex = 0;
380
- const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
381
- while (true) {
382
- const current = nextIndex++;
383
- if (current >= items.length)
384
- break;
385
- results[current] = await mapper(items[current], current);
386
- }
387
- });
388
- await Promise.all(workers);
389
- return results;
390
- }
391
- function extractId(value) {
392
- if (typeof value === "string" && value.length > 0)
393
- return value;
394
- if (value && typeof value === "object" && typeof value.id === "string") {
395
- return value.id;
396
- }
397
- return null;
398
- }
399
- function capitalize(input) {
400
- return input ? input[0].toUpperCase() + input.slice(1) : input;
401
- }
402
- function lowerFirst(input) {
403
- return input ? input[0].toLowerCase() + input.slice(1) : input;
404
- }
405
- function camelCaseModelIdKey(modelName) {
406
- return `${lowerFirst(modelName)}Id`;
407
- }
408
- function snakeCaseModelIdKey(modelName) {
409
- const snake = modelName
410
- .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
411
- .replace(/\s+/g, "_")
412
- .toLowerCase();
413
- return `${snake}_id`;
414
- }
415
- function extractModelRefId(raw, modelName, options) {
416
- if (typeof raw === "string")
417
- return raw;
418
- if (!raw || typeof raw !== "object")
419
- return null;
420
- const object = raw;
421
- const prop = options?.propertyName ?? "";
422
- const propertyCandidates = [
423
- prop ? `${prop}Id` : "",
424
- prop
425
- ? `${prop.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase()}_id`
426
- : "",
427
- ].filter(Boolean);
428
- const modelCandidates = [
429
- camelCaseModelIdKey(modelName),
430
- snakeCaseModelIdKey(modelName),
431
- ];
432
- // Prefer property-specific FKs (e.g., logoId) over model-level defaults
433
- // (e.g., imageId) when multiple refs share the same model in one object row.
434
- const candidates = Array.from(new Set([...propertyCandidates, ...modelCandidates, "value"]));
435
- for (const key of candidates) {
436
- const found = extractId(object[key]);
437
- if (found)
438
- return found;
439
- }
440
- const allowObjectIdFallback = options?.allowObjectIdFallback ?? true;
441
- if (allowObjectIdFallback) {
442
- const keys = Object.keys(object);
443
- const hasOnlyId = keys.length === 1 && keys[0] === "id";
444
- if (hasOnlyId) {
445
- const byId = extractId(object);
446
- if (byId)
447
- return byId;
448
- }
449
- }
450
- return null;
451
- }
452
- function buildModelRefCacheKey(modelName, id, context, isCollectionItem) {
453
- const locale = context.options.locale ?? "";
454
- const defaultLocale = context.options.defaultLocale ?? "";
455
- const includeIdMode = context.options.includeIdMode;
456
- const refsMode = context.options.resolveModelRefs ? "resolve" : "ids";
457
- const collectionFlag = isCollectionItem ? "collection" : "single";
458
- return [
459
- modelName,
460
- id,
461
- locale,
462
- defaultLocale,
463
- includeIdMode,
464
- refsMode,
465
- collectionFlag,
466
- ].join("|");
467
- }
468
- function extractInlineModelObject(raw, modelDescriptor) {
469
- if (!raw || typeof raw !== "object" || Array.isArray(raw))
470
- return null;
471
- if (!isObjectDescriptor(modelDescriptor))
472
- return null;
473
- const source = raw;
474
- const propertyKeys = Object.keys(modelDescriptor.properties ?? {});
475
- const hasModelField = propertyKeys.some((key) => key in source);
476
- if (!hasModelField)
477
- return null;
478
- return source;
479
- }
480
- function formatValidationError(name, error) {
481
- const payload = error && typeof error === "object" && "format" in error
482
- ? error.format()
483
- : error;
484
- return `Invalid data received for '${name}': ${JSON.stringify(payload)}`;
485
- }
486
- function levenshtein(a, b) {
487
- if (a === b)
488
- return 0;
489
- if (!a.length)
490
- return b.length;
491
- if (!b.length)
492
- return a.length;
493
- const rows = a.length + 1;
494
- const cols = b.length + 1;
495
- const matrix = Array.from({ length: rows }, () => new Array(cols).fill(0));
496
- for (let i = 0; i < rows; i++)
497
- matrix[i][0] = i;
498
- for (let j = 0; j < cols; j++)
499
- matrix[0][j] = j;
500
- for (let i = 1; i < rows; i++) {
501
- for (let j = 1; j < cols; j++) {
502
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
503
- matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost);
504
- }
505
- }
506
- return matrix[rows - 1][cols - 1];
507
- }
508
- function unknownKeyError(key, roots, models) {
509
- const candidates = [...roots, ...models];
510
- const normalized = key.toLowerCase();
511
- const suggestions = candidates
512
- .map((candidate) => ({
513
- candidate,
514
- distance: levenshtein(normalized, candidate.toLowerCase()),
515
- }))
516
- .sort((a, b) => a.distance - b.distance)
517
- .slice(0, 3)
518
- .map((entry) => entry.candidate);
519
- const suggestionText = suggestions.length
520
- ? ` Did you mean: ${suggestions.join(", ")}?`
521
- : "";
522
- const rootsText = `Available roots: [${roots.join(", ")}]`;
523
- const modelsText = models.length
524
- ? `, models (under data.models.*): [${models.join(", ")}]`
525
- : "";
526
- throw new Error(`Unknown schema key '${key}'. ${rootsText}${modelsText}.${suggestionText}`);
527
- }
528
- async function normalizeModelRef(modelName, id, context, trail, isCollectionItem, inlineValue) {
529
- if (!id)
530
- return null;
531
- if (!context.options.resolveModelRefs)
532
- return id;
533
- const nodeKey = buildModelRefCacheKey(modelName, id, context, isCollectionItem);
534
- if (trail.has(nodeKey)) {
535
- return shouldIncludeObjectId(context.options.includeIdMode, isCollectionItem)
536
- ? { id }
537
- : id;
538
- }
539
- const modelDescriptor = context.modelDescriptors.get(modelName);
540
- if (!modelDescriptor) {
541
- return id;
542
- }
543
- const inlineModel = extractInlineModelObject(inlineValue, modelDescriptor);
544
- const cached = context.modelCache.get(nodeKey);
545
- if (cached) {
546
- return cached;
547
- }
548
- const sharedInflight = context.sharedModelInflightCache.get(nodeKey);
549
- if (sharedInflight) {
550
- context.modelCache.set(nodeKey, sharedInflight);
551
- return sharedInflight;
552
- }
553
- const nextTrail = new Set(trail);
554
- nextTrail.add(nodeKey);
555
- const promise = (async () => {
556
- const rawModel = inlineModel ??
557
- (await context.requestJson(`models/${modelName}/${id}`, {
558
- query: {
559
- raw: 1,
560
- ...(context.options.locale ? { locale: context.options.locale } : {}),
561
- },
562
- }));
563
- return normalizeField(modelDescriptor, `models/${modelName}/${encodeURIComponent(id)}`, rawModel, context, nextTrail, isCollectionItem);
564
- })();
565
- context.modelCache.set(nodeKey, promise);
566
- context.sharedModelInflightCache.set(nodeKey, promise);
567
- promise
568
- .then(() => undefined, () => {
569
- context.modelCache.delete(nodeKey);
570
- })
571
- .finally(() => {
572
- context.sharedModelInflightCache.delete(nodeKey);
573
- });
574
- return promise;
575
- }
576
- function missingModelRefValue(descriptor) {
577
- if (descriptor.nullable)
578
- return null;
579
- if (descriptor.optional)
580
- return undefined;
581
- return null;
582
- }
583
- async function normalizeObjectField(descriptor, path, raw, context, trail, isCollectionItem) {
584
- const source = raw && typeof raw === "object" ? raw : {};
585
- const output = {};
586
- for (const [propertyName, propertyDescriptor] of Object.entries(descriptor.properties)) {
587
- if (isPrimitiveDescriptor(propertyDescriptor)) {
588
- output[propertyName] = coerceCustomTypeValue(propertyDescriptor, source[propertyName], {
589
- locale: context.options.locale,
590
- defaultLocale: context.options.defaultLocale,
591
- assetUrlBuilder: context.options.assetUrlBuilder,
592
- });
593
- continue;
594
- }
595
- if (isModelRefDescriptor(propertyDescriptor)) {
596
- const inlineValue = source[propertyName];
597
- const inlineModelDescriptor = context.modelDescriptors.get(propertyDescriptor.model);
598
- const inlineModel = inlineModelDescriptor
599
- ? extractInlineModelObject(inlineValue, inlineModelDescriptor)
600
- : null;
601
- const refId = extractModelRefId(inlineValue, propertyDescriptor.model, {
602
- allowObjectIdFallback: true,
603
- }) ??
604
- (inlineModel ? extractId(inlineModel) : null) ??
605
- extractModelRefId(source, propertyDescriptor.model, {
606
- propertyName,
607
- allowObjectIdFallback: false,
608
- });
609
- if (!refId) {
610
- const missing = missingModelRefValue(propertyDescriptor);
611
- if (missing !== undefined) {
612
- output[propertyName] = missing;
613
- }
614
- continue;
615
- }
616
- output[propertyName] = await normalizeModelRef(propertyDescriptor.model, refId, context, trail, false, inlineValue);
617
- continue;
618
- }
619
- if (isArrayDescriptor(propertyDescriptor)) {
620
- const childPath = `${path}/${propertyName}`;
621
- const childRaw = await context.requestJson(childPath, {
622
- query: {
623
- raw: 1,
624
- ...(context.options.locale ? { locale: context.options.locale } : {}),
625
- },
626
- });
627
- const normalizedChild = await normalizeArrayField(propertyDescriptor, childPath, childRaw, context, trail);
628
- output[propertyName] = coerceCustomTypeValue(propertyDescriptor, normalizedChild, {
629
- locale: context.options.locale,
630
- defaultLocale: context.options.defaultLocale,
631
- assetUrlBuilder: context.options.assetUrlBuilder,
632
- });
633
- continue;
634
- }
635
- if (isObjectDescriptor(propertyDescriptor)) {
636
- const childPath = `${path}/${propertyName}`;
637
- const childRaw = await context.requestJson(childPath, {
638
- query: {
639
- raw: 1,
640
- ...(context.options.locale ? { locale: context.options.locale } : {}),
641
- },
642
- });
643
- const normalizedChild = await normalizeObjectField(propertyDescriptor, childPath, childRaw, context, trail, false);
644
- output[propertyName] = coerceCustomTypeValue(propertyDescriptor, normalizedChild, {
645
- locale: context.options.locale,
646
- defaultLocale: context.options.defaultLocale,
647
- assetUrlBuilder: context.options.assetUrlBuilder,
648
- });
649
- }
650
- }
651
- if (shouldIncludeObjectId(context.options.includeIdMode, isCollectionItem)) {
652
- const rowId = extractId(source);
653
- if (rowId)
654
- output.id = rowId;
655
- }
656
- if (typeof source.url === "string" &&
657
- source.url.trim().length > 0 &&
658
- typeof output.filename === "string") {
659
- output.url = source.url;
660
- }
661
- return maybeAttachAssetUrl(output, context.options.assetUrlBuilder);
662
- }
663
- async function normalizeArrayField(descriptor, path, raw, context, trail) {
664
- const envelope = ensureCollectionEnvelope(raw, path);
665
- const itemDescriptor = descriptor.items;
666
- if (isPrimitiveDescriptor(itemDescriptor)) {
667
- return envelope.items.map((row) => {
668
- const value = row && typeof row === "object" && "value" in row
669
- ? row.value
670
- : row;
671
- if (context.options.includeIdMode !== "all") {
672
- return value;
673
- }
674
- const id = extractId(row);
675
- return id ? { id, value } : value;
676
- });
677
- }
678
- if (isModelRefDescriptor(itemDescriptor)) {
679
- const inlineModelDescriptor = context.modelDescriptors.get(itemDescriptor.model);
680
- return mapWithConcurrency(envelope.items, context.options.modelNormalizationConcurrency, async (row) => {
681
- const inlineModel = inlineModelDescriptor
682
- ? extractInlineModelObject(row, inlineModelDescriptor)
683
- : null;
684
- const refId = extractModelRefId(row, itemDescriptor.model, {
685
- allowObjectIdFallback: false,
686
- }) ?? (inlineModel ? extractId(inlineModel) : null);
687
- return normalizeModelRef(itemDescriptor.model, refId, context, trail, true, row);
688
- });
689
- }
690
- if (isObjectDescriptor(itemDescriptor)) {
691
- return mapWithConcurrency(envelope.items, context.options.modelNormalizationConcurrency, async (row) => {
692
- const rowId = extractId(row);
693
- const rowPath = rowId
694
- ? `${path}/${encodeURIComponent(rowId)}`
695
- : path;
696
- return normalizeObjectField(itemDescriptor, rowPath, row, context, trail, true);
697
- });
698
- }
699
- return envelope.items;
700
- }
701
- async function normalizeField(descriptor, path, raw, context, trail, isCollectionItem) {
702
- if (isPrimitiveDescriptor(descriptor)) {
703
- const value = raw && typeof raw === "object" && "value" in raw
704
- ? raw.value
705
- : raw;
706
- return coerceCustomTypeValue(descriptor, value, {
707
- locale: context.options.locale,
708
- defaultLocale: context.options.defaultLocale,
709
- assetUrlBuilder: context.options.assetUrlBuilder,
710
- });
711
- }
712
- if (isModelRefDescriptor(descriptor)) {
713
- const inlineModelDescriptor = context.modelDescriptors.get(descriptor.model);
714
- const inlineModel = inlineModelDescriptor
715
- ? extractInlineModelObject(raw, inlineModelDescriptor)
716
- : null;
717
- const refId = extractModelRefId(raw, descriptor.model, {
718
- allowObjectIdFallback: true,
719
- }) ?? (inlineModel ? extractId(inlineModel) : null);
720
- if (!refId) {
721
- return missingModelRefValue(descriptor);
722
- }
723
- return normalizeModelRef(descriptor.model, refId, context, trail, isCollectionItem, raw);
724
- }
725
- if (isArrayDescriptor(descriptor)) {
726
- const normalized = await normalizeArrayField(descriptor, path, raw, context, trail);
727
- return coerceCustomTypeValue(descriptor, normalized, {
728
- locale: context.options.locale,
729
- defaultLocale: context.options.defaultLocale,
730
- assetUrlBuilder: context.options.assetUrlBuilder,
731
- });
732
- }
733
- if (isObjectDescriptor(descriptor)) {
734
- const normalized = await normalizeObjectField(descriptor, path, raw, context, trail, isCollectionItem);
735
- return coerceCustomTypeValue(descriptor, normalized, {
736
- locale: context.options.locale,
737
- defaultLocale: context.options.defaultLocale,
738
- assetUrlBuilder: context.options.assetUrlBuilder,
739
- });
740
- }
741
- return raw;
742
- }
743
- function createResourceRegistry(descriptor) {
744
- const roots = new Map();
745
- const rootsCaseInsensitive = new Map();
746
- for (const [key, rootDescriptor] of Object.entries(descriptor.roots ?? {})) {
747
- const entry = {
748
- kind: "root",
749
- key,
750
- path: key,
751
- descriptor: rootDescriptor,
752
- isCollection: isArrayDescriptor(rootDescriptor),
753
- };
754
- roots.set(key, entry);
755
- rootsCaseInsensitive.set(key.toLowerCase(), entry);
756
- }
757
- const models = new Map();
758
- const modelsCaseInsensitive = new Map();
759
- for (const modelName of Object.keys(descriptor.models ?? {})) {
760
- const entry = {
761
- kind: "model",
762
- key: modelName,
763
- path: `models/${modelName}`,
764
- descriptor: asModelObjectDescriptor(modelName, descriptor),
765
- isCollection: true,
766
- modelName,
767
- };
768
- models.set(modelName, entry);
769
- modelsCaseInsensitive.set(modelName.toLowerCase(), entry);
770
- }
771
- return {
772
- roots,
773
- rootsCaseInsensitive,
774
- models,
775
- modelsCaseInsensitive,
776
- };
777
- }
778
- async function requestJson(baseUrl, apiKey, path, options, runtime) {
779
- const params = buildSearchParams(options?.query);
780
- const url = `${baseUrl}/${path}${params.toString() ? `?${params.toString()}` : ""}`;
781
- const execute = async () => {
782
- const retry = runtime?.retry ?? {
783
- retries: DEFAULT_REQUEST_RETRIES,
784
- baseDelayMs: DEFAULT_REQUEST_RETRY_BASE_MS,
785
- maxDelayMs: DEFAULT_REQUEST_RETRY_MAX_MS,
786
- };
787
- let attempt = 0;
788
- while (true) {
789
- let response;
790
- try {
791
- response = runtime?.scheduler
792
- ? await runtime.scheduler(() => fetch(url, {
793
- method: "GET",
794
- signal: options?.signal,
795
- headers: {
796
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
797
- },
798
- }), options?.signal)
799
- : await fetch(url, {
800
- method: "GET",
801
- signal: options?.signal,
802
- headers: {
803
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
804
- },
805
- });
806
- }
807
- catch (error) {
808
- if (isAbortError(error))
809
- throw error;
810
- if (attempt >= retry.retries)
811
- throw error;
812
- const delayMs = Math.min(retry.baseDelayMs * 2 ** attempt, retry.maxDelayMs);
813
- attempt += 1;
814
- await waitForDelay(delayMs, options?.signal);
815
- continue;
816
- }
817
- if (response.ok) {
818
- return response.json();
819
- }
820
- const canRetry = shouldRetryStatus(response.status) && attempt < retry.retries;
821
- if (!canRetry) {
822
- throw new Error(`Request failed for '${path}' with status ${response.status}: ${response.statusText}`);
823
- }
824
- const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
825
- const fallbackDelay = Math.min(retry.baseDelayMs * 2 ** attempt, retry.maxDelayMs);
826
- const delayMs = retryAfterMs ?? fallbackDelay;
827
- attempt += 1;
828
- await waitForDelay(delayMs, options?.signal);
829
- }
830
- };
831
- const useInflightDedup = !options?.signal && !!runtime;
832
- if (!useInflightDedup || !runtime) {
833
- return execute();
834
- }
835
- const cached = runtime.inflightRequestCache.get(url);
836
- if (cached)
837
- return cached;
838
- const promise = execute().finally(() => {
839
- runtime.inflightRequestCache.delete(url);
840
- });
841
- runtime.inflightRequestCache.set(url, promise);
842
- return promise;
843
- }
844
- function validateResult(resource, result, descriptor, includeIdMode, zodSchemas, modelZodSchemas) {
845
- if (includeIdMode === "all")
846
- return;
847
- if (resource.kind === "root") {
848
- const schema = zodSchemas[resource.key];
849
- if (!schema)
850
- return;
851
- const parsed = schema.safeParse(result);
852
- if (!parsed.success) {
853
- throw new Error(formatValidationError(resource.key, parsed.error));
854
- }
855
- return;
856
- }
857
- const modelName = resource.modelName;
858
- if (!modelName)
859
- return;
860
- const modelSchema = modelZodSchemas[modelName];
861
- if (!modelSchema)
862
- return;
863
- if (Array.isArray(result)) {
864
- const parsed = modelSchema.array().safeParse(result);
865
- if (!parsed.success) {
866
- throw new Error(formatValidationError(modelName, parsed.error));
867
- }
868
- return;
869
- }
870
- if (result === null || result === undefined)
871
- return;
872
- const parsed = modelSchema.safeParse(result);
873
- if (!parsed.success) {
874
- throw new Error(formatValidationError(modelName, parsed.error));
875
- }
876
- }
877
- async function runResource(resource, descriptor, baseUrl, apiKey, defaultLocale, assetUrlBuilder, requestRuntime, sharedModelInflightCache, modelNormalizationConcurrency, zodSchemas, modelZodSchemas, options, byId) {
878
- const responseMode = options?.response ?? "normalized";
879
- const includeIdMode = resolveIncludeIdMode(options?.includeId);
880
- const resolveModelRefs = options?.resolveModelRefs !== false;
881
- const requestedLocale = options?.locale ??
882
- (typeof options?.query?.locale === "string"
883
- ? options.query.locale
884
- : undefined);
885
- const locale = requestedLocale ??
886
- (responseMode === "normalized" ? "all" : undefined);
887
- const query = {
888
- ...(options?.query ?? {}),
889
- };
890
- const shouldNormalize = responseMode !== "raw";
891
- if (shouldNormalize && query.raw === undefined) {
892
- query.raw = 1;
893
- }
894
- if (locale && query.locale === undefined) {
895
- query.locale = locale;
896
- }
897
- const resourcePath = byId
898
- ? `${resource.path}/${encodeURIComponent(byId)}`
899
- : resource.path;
900
- const rawData = await requestJson(baseUrl, apiKey, resourcePath, {
901
- query,
902
- signal: options?.signal,
903
- }, requestRuntime);
904
- if (!shouldNormalize) {
905
- return rawData;
906
- }
907
- const modelDescriptors = new Map();
908
- for (const modelName of Object.keys(descriptor.models ?? {})) {
909
- modelDescriptors.set(modelName, asModelObjectDescriptor(modelName, descriptor));
910
- }
911
- const context = {
912
- requestJson: (path, requestOptions) => requestJson(baseUrl, apiKey, path, {
913
- ...requestOptions,
914
- signal: options?.signal,
915
- }, requestRuntime),
916
- modelDescriptors,
917
- modelCache: new Map(),
918
- sharedModelInflightCache,
919
- options: {
920
- includeIdMode,
921
- resolveModelRefs,
922
- locale,
923
- defaultLocale,
924
- assetUrlBuilder,
925
- modelNormalizationConcurrency,
926
- },
927
- };
928
- if (resource.isCollection && !byId) {
929
- const envelope = ensureCollectionEnvelope(rawData, resource.path);
930
- const descriptorForCollection = resource.kind === "root" && isArrayDescriptor(resource.descriptor)
931
- ? resource.descriptor
932
- : {
933
- type: "array",
934
- items: resource.descriptor,
935
- optional: false,
936
- nullable: false,
937
- };
938
- const normalizedItems = await normalizeArrayField(descriptorForCollection, resource.path, envelope, context, new Set());
939
- if (responseMode === "envelope") {
940
- validateResult(resource, normalizedItems, descriptor, includeIdMode, zodSchemas, modelZodSchemas);
941
- return {
942
- items: normalizedItems,
943
- total: envelope.total,
944
- };
945
- }
946
- validateResult(resource, normalizedItems, descriptor, includeIdMode, zodSchemas, modelZodSchemas);
947
- return normalizedItems;
948
- }
949
- const normalized = await normalizeField(resource.descriptor, resourcePath, rawData, context, new Set(), false);
950
- validateResult(resource, normalized, descriptor, includeIdMode, zodSchemas, modelZodSchemas);
951
- return normalized;
952
- }
953
- export function createCmsClient(descriptor, config) {
954
- const baseUrl = normalizeBaseUrl(config.apiConfig?.baseUrl);
955
- const apiKey = config.apiConfig?.key;
956
- const assetUrlBuilder = buildAssetUrlBuilder(baseUrl, config.assets);
957
- const registry = createResourceRegistry(descriptor);
958
- const rootKeys = Array.from(registry.roots.keys());
959
- const modelKeys = Array.from(registry.models.keys());
960
- const { zodSchemas, modelZodSchemas } = buildZodSchemasFromDescriptor(descriptor);
961
- const requestOptions = normalizeRequestOptions(config.requests);
962
- const requestRuntime = {
963
- scheduler: createRequestScheduler(requestOptions.concurrency),
964
- inflightRequestCache: new Map(),
965
- retry: requestOptions.retry,
966
- };
967
- const sharedModelInflightCache = new Map();
968
- const buildModelAccessor = (entry) => {
969
- const accessor = (async (options) => runResource(entry, descriptor, baseUrl, apiKey, config.defaultLocale, assetUrlBuilder, requestRuntime, sharedModelInflightCache, requestOptions.modelNormalizationConcurrency, zodSchemas, modelZodSchemas, options));
970
- accessor.byId = async (id, options) => runResource(entry, descriptor, baseUrl, apiKey, config.defaultLocale, assetUrlBuilder, requestRuntime, sharedModelInflightCache, requestOptions.modelNormalizationConcurrency, zodSchemas, modelZodSchemas, options, id);
971
- return accessor;
972
- };
973
- const modelsProxy = new Proxy({}, {
974
- get(_target, property) {
975
- if (typeof property !== "string")
976
- return undefined;
977
- if (property === "then")
978
- return undefined;
979
- const modelEntry = registry.models.get(property) ??
980
- registry.modelsCaseInsensitive.get(property.toLowerCase());
981
- if (!modelEntry) {
982
- unknownKeyError(property, [], modelKeys);
983
- }
984
- return buildModelAccessor(modelEntry);
985
- },
986
- });
987
- const rootProxy = new Proxy({}, {
988
- get(_target, property) {
989
- if (typeof property !== "string")
990
- return undefined;
991
- if (property === "then")
992
- return undefined;
993
- if (property === "models")
994
- return modelsProxy;
995
- const entry = registry.roots.get(property) ??
996
- registry.rootsCaseInsensitive.get(property.toLowerCase());
997
- if (!entry) {
998
- unknownKeyError(property, rootKeys, []);
999
- }
1000
- return async (options) => runResource(entry, descriptor, baseUrl, apiKey, config.defaultLocale, assetUrlBuilder, requestRuntime, sharedModelInflightCache, requestOptions.modelNormalizationConcurrency, zodSchemas, modelZodSchemas, options);
1001
- },
1002
- });
1003
- return rootProxy;
1004
- }
1005
- /**
1006
- * Initializes the CMS SDK for a given schema.
1007
- * @param config configuration including API base URL and API key.
1008
- * @returns typed accessors for root resources and model resources.
1009
- */
1010
- export function cms0(config) {
1011
- return createCmsClient(schemaDescriptor, config);
1012
- }