@datocms/cma-client 5.8.1 → 6.0.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.
@@ -1,38 +1,94 @@
1
+ import type * as ApiTypes from '../generated/ApiTypes.js';
1
2
  import BaseUpload from '../generated/resources/Upload.js';
3
+ import {
4
+ encodeDefaultFieldMetadata,
5
+ normalizeUpload,
6
+ } from '../utilities/defaultFieldMetadata.js';
2
7
 
3
8
  /**
4
- * Legacy locale-keyed shape of an upload's `default_field_metadata`, as
5
- * returned and accepted by environments where the `non_localized_focal_points`
6
- * opt-in is inactive.
9
+ * `default_field_metadata` travels in one of two shapes, and which one an
10
+ * environment speaks depends on the `non_localized_focal_points` opt-in — each
11
+ * rejects the other with `422 INVALID_FORMAT`. This resource hides that: you
12
+ * always read and write the field-keyed shape the types describe, and the
13
+ * legacy one is converted to and from as needed.
7
14
  *
8
- * The generated `Upload.default_field_metadata` type reflects the new
9
- * field-keyed shape (the path forward). This type is provided so consumers
10
- * targeting opted-out environments during the transition can cast the
11
- * response value to a structurally accurate shape.
15
+ * The raw methods are deliberately left alone: they are the escape hatch for
16
+ * anyone who needs to see what actually goes over the wire.
12
17
  */
13
- export type UploadLocaleKeyedDefaultFieldMetadata = {
14
- [localeCode: string]: {
15
- alt: string | null;
16
- title: string | null;
17
- custom_data: { [k: string]: unknown };
18
- focal_point: { x: number; y: number } | null;
19
- poster_time: number | null;
20
- };
21
- };
18
+ export default class UploadResource extends BaseUpload {
19
+ /**
20
+ * Create a new upload
21
+ *
22
+ * Read more: https://www.datocms.com/docs/content-management-api/resources/upload/create
23
+ *
24
+ * @throws {ApiError}
25
+ * @throws {TimeoutError}
26
+ */
27
+ async create(body: ApiTypes.UploadCreateSchema) {
28
+ return normalizeUpload(
29
+ await super.create(await encodeDefaultFieldMetadata(this.client, body)),
30
+ );
31
+ }
22
32
 
23
- /**
24
- * Legacy locale-keyed shape accepted on `create` / `update` request bodies
25
- * by environments where the `non_localized_focal_points` opt-in is inactive.
26
- * All fields are optional, matching the partial-write contract.
27
- */
28
- export type UploadLocaleKeyedDefaultFieldMetadataInRequest = {
29
- [localeCode: string]: {
30
- alt?: string | null;
31
- title?: string | null;
32
- custom_data?: { [k: string]: unknown };
33
- focal_point?: { x: number; y: number } | null;
34
- poster_time?: number | null;
35
- };
36
- };
33
+ /**
34
+ * Update an upload
35
+ *
36
+ * Read more: https://www.datocms.com/docs/content-management-api/resources/upload/update
37
+ *
38
+ * @throws {ApiError}
39
+ * @throws {TimeoutError}
40
+ */
41
+ async update(
42
+ uploadId: string | ApiTypes.UploadData,
43
+ body: ApiTypes.UploadUpdateSchema,
44
+ queryParams?: ApiTypes.UploadUpdateHrefSchema,
45
+ ) {
46
+ return normalizeUpload(
47
+ await super.update(
48
+ uploadId,
49
+ await encodeDefaultFieldMetadata(this.client, body),
50
+ queryParams,
51
+ ),
52
+ );
53
+ }
54
+
55
+ /**
56
+ * Retrieve an upload
57
+ *
58
+ * Read more: https://www.datocms.com/docs/content-management-api/resources/upload/self
59
+ *
60
+ * @throws {ApiError}
61
+ * @throws {TimeoutError}
62
+ */
63
+ async find(uploadId: string | ApiTypes.UploadData) {
64
+ return normalizeUpload(await super.find(uploadId));
65
+ }
66
+
67
+ /**
68
+ * List all uploads
69
+ *
70
+ * Read more: https://www.datocms.com/docs/content-management-api/resources/upload/instances
71
+ *
72
+ * @throws {ApiError}
73
+ * @throws {TimeoutError}
74
+ */
75
+ async list(queryParams?: ApiTypes.UploadInstancesHrefSchema) {
76
+ return (await super.list(queryParams)).map(normalizeUpload);
77
+ }
37
78
 
38
- export default class UploadResource extends BaseUpload {}
79
+ /**
80
+ * Async iterator to auto-paginate over elements returned by list()
81
+ *
82
+ * Read more: https://www.datocms.com/docs/content-management-api/resources/upload/instances
83
+ *
84
+ * @throws {ApiError}
85
+ * @throws {TimeoutError}
86
+ */
87
+ async *listPagedIterator(
88
+ ...args: Parameters<BaseUpload['listPagedIterator']>
89
+ ) {
90
+ for await (const upload of super.listPagedIterator(...args)) {
91
+ yield normalizeUpload(upload);
92
+ }
93
+ }
94
+ }
@@ -0,0 +1,193 @@
1
+ import type * as ApiTypes from '../generated/ApiTypes.js';
2
+ import type { Client } from '../generated/Client.js';
3
+ import {
4
+ fetchEnvironmentSettings,
5
+ isEnvironmentFlagActive,
6
+ } from './environmentSettings.js';
7
+
8
+ /**
9
+ * Legacy locale-keyed shape of an upload's `default_field_metadata`, as
10
+ * returned and accepted by environments where the `non_localized_focal_points`
11
+ * opt-in is inactive.
12
+ *
13
+ * The `uploads` resource converts to and from this shape on your behalf, so you
14
+ * only ever see the field-keyed one. The type is exported for those working at
15
+ * the raw layer, which performs no conversion.
16
+ */
17
+ export type UploadLocaleKeyedDefaultFieldMetadata = {
18
+ [localeCode: string]: {
19
+ alt: string | null;
20
+ title: string | null;
21
+ custom_data: { [k: string]: unknown };
22
+ focal_point: { x: number; y: number } | null;
23
+ poster_time: number | null;
24
+ };
25
+ };
26
+
27
+ /**
28
+ * Legacy locale-keyed shape accepted on `create` / `update` request bodies
29
+ * by environments where the `non_localized_focal_points` opt-in is inactive.
30
+ * All fields are optional, matching the partial-write contract.
31
+ */
32
+ export type UploadLocaleKeyedDefaultFieldMetadataInRequest = {
33
+ [localeCode: string]: {
34
+ alt?: string | null;
35
+ title?: string | null;
36
+ custom_data?: { [k: string]: unknown };
37
+ focal_point?: { x: number; y: number } | null;
38
+ poster_time?: number | null;
39
+ };
40
+ };
41
+
42
+ export type DefaultFieldMetadata = ApiTypes.Upload['default_field_metadata'];
43
+
44
+ export type DefaultFieldMetadataInRequest = NonNullable<
45
+ ApiTypes.UploadUpdateSchema['default_field_metadata']
46
+ >;
47
+
48
+ /**
49
+ * Tells the two wire shapes apart. A field-keyed payload always carries a
50
+ * top-level `focal_point`, and a locale-keyed one never can: its keys are
51
+ * locale codes, and no locale code is the literal string `focal_point`.
52
+ */
53
+ export function isFieldKeyed(
54
+ metadata: DefaultFieldMetadata | UploadLocaleKeyedDefaultFieldMetadata,
55
+ ): metadata is DefaultFieldMetadata {
56
+ return 'focal_point' in metadata;
57
+ }
58
+
59
+ /**
60
+ * Collapses a legacy response payload into the field-keyed shape. The API
61
+ * replicates the non-localized values into every locale entry on read, so every
62
+ * entry carries the same value and the first one is enough.
63
+ */
64
+ export function fromLocaleKeyed(
65
+ byLocale: UploadLocaleKeyedDefaultFieldMetadata,
66
+ ): DefaultFieldMetadata {
67
+ const alt: Record<string, string | null> = {};
68
+ const title: Record<string, string | null> = {};
69
+ const customData: Record<string, { [k: string]: unknown }> = {};
70
+
71
+ let focalPoint: { x: number; y: number } | null = null;
72
+ let posterTime: number | null = null;
73
+ let seenAnEntry = false;
74
+
75
+ for (const [locale, entry] of Object.entries(byLocale)) {
76
+ alt[locale] = entry.alt;
77
+ title[locale] = entry.title;
78
+ customData[locale] = entry.custom_data;
79
+
80
+ if (!seenAnEntry) {
81
+ seenAnEntry = true;
82
+ focalPoint = entry.focal_point;
83
+ posterTime = entry.poster_time;
84
+ }
85
+ }
86
+
87
+ return {
88
+ alt,
89
+ title,
90
+ custom_data: customData,
91
+ focal_point: focalPoint,
92
+ poster_time: posterTime,
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Rewrites a field-keyed patch into the legacy locale-keyed one: the localized
98
+ * keys are pivoted per locale, and the non-localized ones ride along on a
99
+ * single entry. The API takes `focal_point` / `poster_time` off the first entry
100
+ * that carries one and ignores the rest, so writing them once is enough — on
101
+ * any locale the patch already touches, or the environment's first one when it
102
+ * touches none.
103
+ */
104
+ export function toLocaleKeyed(
105
+ {
106
+ alt,
107
+ title,
108
+ custom_data,
109
+ focal_point,
110
+ poster_time,
111
+ }: DefaultFieldMetadataInRequest,
112
+ environmentLocales: string[],
113
+ ): UploadLocaleKeyedDefaultFieldMetadataInRequest {
114
+ const result: UploadLocaleKeyedDefaultFieldMetadataInRequest = {};
115
+
116
+ function entryFor(locale: string) {
117
+ const entry = result[locale] ?? {};
118
+ result[locale] = entry;
119
+ return entry;
120
+ }
121
+
122
+ for (const [locale, value] of Object.entries(alt ?? {})) {
123
+ entryFor(locale).alt = value;
124
+ }
125
+
126
+ for (const [locale, value] of Object.entries(title ?? {})) {
127
+ entryFor(locale).title = value;
128
+ }
129
+
130
+ for (const [locale, value] of Object.entries(custom_data ?? {})) {
131
+ entryFor(locale).custom_data = value;
132
+ }
133
+
134
+ if (focal_point !== undefined || poster_time !== undefined) {
135
+ const locale = Object.keys(result)[0] ?? environmentLocales[0];
136
+
137
+ if (locale) {
138
+ if (focal_point !== undefined) entryFor(locale).focal_point = focal_point;
139
+ if (poster_time !== undefined) entryFor(locale).poster_time = poster_time;
140
+ }
141
+ }
142
+
143
+ return result;
144
+ }
145
+
146
+ /**
147
+ * Normalizes an upload as served by the API into the field-keyed shape the
148
+ * `Upload` type describes. Returns the entity untouched — no copy — when it is
149
+ * already field-keyed, which is the case for every environment that has taken
150
+ * the opt-in.
151
+ */
152
+ export function normalizeUpload(upload: ApiTypes.Upload): ApiTypes.Upload {
153
+ const metadata = upload.default_field_metadata;
154
+
155
+ if (!metadata || isFieldKeyed(metadata)) {
156
+ return upload;
157
+ }
158
+
159
+ return { ...upload, default_field_metadata: fromLocaleKeyed(metadata) };
160
+ }
161
+
162
+ /**
163
+ * Encodes a `create` / `update` body into the shape the environment accepts.
164
+ *
165
+ * The environment is only consulted when there is metadata to encode, so a
166
+ * client that never writes asset metadata never asks — and when it does ask,
167
+ * the lookup is memoized and shared, so a batch of writes pays for one.
168
+ */
169
+ export async function encodeDefaultFieldMetadata<
170
+ T extends { default_field_metadata?: DefaultFieldMetadataInRequest },
171
+ >(client: Client, body: T): Promise<T> {
172
+ const metadata = body.default_field_metadata;
173
+
174
+ if (!metadata) {
175
+ return body;
176
+ }
177
+
178
+ if (await isEnvironmentFlagActive(client, 'non_localized_focal_points')) {
179
+ return body;
180
+ }
181
+
182
+ const { locales } = await fetchEnvironmentSettings(client);
183
+
184
+ return {
185
+ ...body,
186
+ // The declared type describes the field-keyed shape, which is what callers
187
+ // write. The legacy payload is this module's business.
188
+ default_field_metadata: toLocaleKeyed(
189
+ metadata,
190
+ locales,
191
+ ) as unknown as DefaultFieldMetadataInRequest,
192
+ };
193
+ }
@@ -0,0 +1,80 @@
1
+ import type * as ApiTypes from '../generated/ApiTypes.js';
2
+ import type { Client } from '../generated/Client.js';
3
+
4
+ /**
5
+ * Every boolean an environment reports about itself in `site.meta`: the
6
+ * product-update opt-ins (`improved_items_listing`, `milliseconds_in_datetime`,
7
+ * `non_localized_focal_points`, …) plus the plain state flags.
8
+ *
9
+ * Derived from the generated type rather than listed, so a flag added to the
10
+ * schema is usable here as soon as the types are regenerated, with nothing to
11
+ * keep in sync.
12
+ */
13
+ export type EnvironmentFlag = {
14
+ [K in keyof ApiTypes.SiteMeta]-?: boolean extends ApiTypes.SiteMeta[K]
15
+ ? K
16
+ : never;
17
+ }[keyof ApiTypes.SiteMeta];
18
+
19
+ /** How long a fetched `site` is reused before we ask again. */
20
+ const TTL_MS = 20 * 60 * 1000;
21
+
22
+ type Cache = { promise: Promise<ApiTypes.Site>; expiresAt: number };
23
+
24
+ /**
25
+ * Keyed by client, so the cache covers every resource that asks and dies with
26
+ * the client that owns it.
27
+ */
28
+ const caches = new WeakMap<Client, Cache>();
29
+
30
+ /**
31
+ * `site.find()`, memoized per client for {@link TTL_MS}.
32
+ *
33
+ * The promise is cached rather than its result, so concurrent callers share one
34
+ * request instead of firing one each — the difference between one lookup and
35
+ * ten thousand when a batch job starts. A failed lookup is not cached.
36
+ *
37
+ * Everything expires on the same clock, including flags that in practice never
38
+ * change back: re-reading `site` every twenty minutes costs nothing next to the
39
+ * work these clients are doing, and it means a client stays correct across an
40
+ * activation that happens while it runs.
41
+ */
42
+ export function fetchEnvironmentSettings(
43
+ client: Client,
44
+ ): Promise<ApiTypes.Site> {
45
+ const cached = caches.get(client);
46
+ const now = Date.now();
47
+
48
+ if (cached && cached.expiresAt > now) {
49
+ return cached.promise;
50
+ }
51
+
52
+ const promise = client.site.find();
53
+
54
+ // A failed lookup must not be cached, or every later caller inherits it
55
+ promise.catch(() => {
56
+ if (caches.get(client)?.promise === promise) {
57
+ caches.delete(client);
58
+ }
59
+ });
60
+
61
+ caches.set(client, { promise, expiresAt: now + TTL_MS });
62
+
63
+ return promise;
64
+ }
65
+
66
+ /**
67
+ * Whether a `site.meta` flag is on for the environment this client talks to.
68
+ *
69
+ * An API predating a flag omits it from the meta entirely, which the types
70
+ * don't admit but runtime does — so anything short of an explicit `true` reads
71
+ * as off.
72
+ */
73
+ export async function isEnvironmentFlagActive(
74
+ client: Client,
75
+ flag: EnvironmentFlag,
76
+ ): Promise<boolean> {
77
+ const site = await fetchEnvironmentSettings(client);
78
+
79
+ return (site.meta as Partial<ApiTypes.SiteMeta> | undefined)?.[flag] === true;
80
+ }