@datocms/cma-client 5.8.0 → 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.
@@ -0,0 +1,84 @@
1
+ import type * as ApiTypes from '../generated/ApiTypes.js';
2
+ import type { Client } from '../generated/Client.js';
3
+ /**
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.
7
+ *
8
+ * The `uploads` resource converts to and from this shape on your behalf, so you
9
+ * only ever see the field-keyed one. The type is exported for those working at
10
+ * the raw layer, which performs no conversion.
11
+ */
12
+ export type UploadLocaleKeyedDefaultFieldMetadata = {
13
+ [localeCode: string]: {
14
+ alt: string | null;
15
+ title: string | null;
16
+ custom_data: {
17
+ [k: string]: unknown;
18
+ };
19
+ focal_point: {
20
+ x: number;
21
+ y: number;
22
+ } | null;
23
+ poster_time: number | null;
24
+ };
25
+ };
26
+ /**
27
+ * Legacy locale-keyed shape accepted on `create` / `update` request bodies
28
+ * by environments where the `non_localized_focal_points` opt-in is inactive.
29
+ * All fields are optional, matching the partial-write contract.
30
+ */
31
+ export type UploadLocaleKeyedDefaultFieldMetadataInRequest = {
32
+ [localeCode: string]: {
33
+ alt?: string | null;
34
+ title?: string | null;
35
+ custom_data?: {
36
+ [k: string]: unknown;
37
+ };
38
+ focal_point?: {
39
+ x: number;
40
+ y: number;
41
+ } | null;
42
+ poster_time?: number | null;
43
+ };
44
+ };
45
+ export type DefaultFieldMetadata = ApiTypes.Upload['default_field_metadata'];
46
+ export type DefaultFieldMetadataInRequest = NonNullable<ApiTypes.UploadUpdateSchema['default_field_metadata']>;
47
+ /**
48
+ * Tells the two wire shapes apart. A field-keyed payload always carries a
49
+ * top-level `focal_point`, and a locale-keyed one never can: its keys are
50
+ * locale codes, and no locale code is the literal string `focal_point`.
51
+ */
52
+ export declare function isFieldKeyed(metadata: DefaultFieldMetadata | UploadLocaleKeyedDefaultFieldMetadata): metadata is DefaultFieldMetadata;
53
+ /**
54
+ * Collapses a legacy response payload into the field-keyed shape. The API
55
+ * replicates the non-localized values into every locale entry on read, so every
56
+ * entry carries the same value and the first one is enough.
57
+ */
58
+ export declare function fromLocaleKeyed(byLocale: UploadLocaleKeyedDefaultFieldMetadata): DefaultFieldMetadata;
59
+ /**
60
+ * Rewrites a field-keyed patch into the legacy locale-keyed one: the localized
61
+ * keys are pivoted per locale, and the non-localized ones ride along on a
62
+ * single entry. The API takes `focal_point` / `poster_time` off the first entry
63
+ * that carries one and ignores the rest, so writing them once is enough — on
64
+ * any locale the patch already touches, or the environment's first one when it
65
+ * touches none.
66
+ */
67
+ export declare function toLocaleKeyed({ alt, title, custom_data, focal_point, poster_time, }: DefaultFieldMetadataInRequest, environmentLocales: string[]): UploadLocaleKeyedDefaultFieldMetadataInRequest;
68
+ /**
69
+ * Normalizes an upload as served by the API into the field-keyed shape the
70
+ * `Upload` type describes. Returns the entity untouched — no copy — when it is
71
+ * already field-keyed, which is the case for every environment that has taken
72
+ * the opt-in.
73
+ */
74
+ export declare function normalizeUpload(upload: ApiTypes.Upload): ApiTypes.Upload;
75
+ /**
76
+ * Encodes a `create` / `update` body into the shape the environment accepts.
77
+ *
78
+ * The environment is only consulted when there is metadata to encode, so a
79
+ * client that never writes asset metadata never asks — and when it does ask,
80
+ * the lookup is memoized and shared, so a batch of writes pays for one.
81
+ */
82
+ export declare function encodeDefaultFieldMetadata<T extends {
83
+ default_field_metadata?: DefaultFieldMetadataInRequest;
84
+ }>(client: Client, body: T): Promise<T>;
@@ -0,0 +1,122 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { fetchEnvironmentSettings, isEnvironmentFlagActive, } from './environmentSettings.js';
11
+ /**
12
+ * Tells the two wire shapes apart. A field-keyed payload always carries a
13
+ * top-level `focal_point`, and a locale-keyed one never can: its keys are
14
+ * locale codes, and no locale code is the literal string `focal_point`.
15
+ */
16
+ export function isFieldKeyed(metadata) {
17
+ return 'focal_point' in metadata;
18
+ }
19
+ /**
20
+ * Collapses a legacy response payload into the field-keyed shape. The API
21
+ * replicates the non-localized values into every locale entry on read, so every
22
+ * entry carries the same value and the first one is enough.
23
+ */
24
+ export function fromLocaleKeyed(byLocale) {
25
+ const alt = {};
26
+ const title = {};
27
+ const customData = {};
28
+ let focalPoint = null;
29
+ let posterTime = null;
30
+ let seenAnEntry = false;
31
+ for (const [locale, entry] of Object.entries(byLocale)) {
32
+ alt[locale] = entry.alt;
33
+ title[locale] = entry.title;
34
+ customData[locale] = entry.custom_data;
35
+ if (!seenAnEntry) {
36
+ seenAnEntry = true;
37
+ focalPoint = entry.focal_point;
38
+ posterTime = entry.poster_time;
39
+ }
40
+ }
41
+ return {
42
+ alt,
43
+ title,
44
+ custom_data: customData,
45
+ focal_point: focalPoint,
46
+ poster_time: posterTime,
47
+ };
48
+ }
49
+ /**
50
+ * Rewrites a field-keyed patch into the legacy locale-keyed one: the localized
51
+ * keys are pivoted per locale, and the non-localized ones ride along on a
52
+ * single entry. The API takes `focal_point` / `poster_time` off the first entry
53
+ * that carries one and ignores the rest, so writing them once is enough — on
54
+ * any locale the patch already touches, or the environment's first one when it
55
+ * touches none.
56
+ */
57
+ export function toLocaleKeyed({ alt, title, custom_data, focal_point, poster_time, }, environmentLocales) {
58
+ var _a;
59
+ const result = {};
60
+ function entryFor(locale) {
61
+ var _a;
62
+ const entry = (_a = result[locale]) !== null && _a !== void 0 ? _a : {};
63
+ result[locale] = entry;
64
+ return entry;
65
+ }
66
+ for (const [locale, value] of Object.entries(alt !== null && alt !== void 0 ? alt : {})) {
67
+ entryFor(locale).alt = value;
68
+ }
69
+ for (const [locale, value] of Object.entries(title !== null && title !== void 0 ? title : {})) {
70
+ entryFor(locale).title = value;
71
+ }
72
+ for (const [locale, value] of Object.entries(custom_data !== null && custom_data !== void 0 ? custom_data : {})) {
73
+ entryFor(locale).custom_data = value;
74
+ }
75
+ if (focal_point !== undefined || poster_time !== undefined) {
76
+ const locale = (_a = Object.keys(result)[0]) !== null && _a !== void 0 ? _a : environmentLocales[0];
77
+ if (locale) {
78
+ if (focal_point !== undefined)
79
+ entryFor(locale).focal_point = focal_point;
80
+ if (poster_time !== undefined)
81
+ entryFor(locale).poster_time = poster_time;
82
+ }
83
+ }
84
+ return result;
85
+ }
86
+ /**
87
+ * Normalizes an upload as served by the API into the field-keyed shape the
88
+ * `Upload` type describes. Returns the entity untouched — no copy — when it is
89
+ * already field-keyed, which is the case for every environment that has taken
90
+ * the opt-in.
91
+ */
92
+ export function normalizeUpload(upload) {
93
+ const metadata = upload.default_field_metadata;
94
+ if (!metadata || isFieldKeyed(metadata)) {
95
+ return upload;
96
+ }
97
+ return Object.assign(Object.assign({}, upload), { default_field_metadata: fromLocaleKeyed(metadata) });
98
+ }
99
+ /**
100
+ * Encodes a `create` / `update` body into the shape the environment accepts.
101
+ *
102
+ * The environment is only consulted when there is metadata to encode, so a
103
+ * client that never writes asset metadata never asks — and when it does ask,
104
+ * the lookup is memoized and shared, so a batch of writes pays for one.
105
+ */
106
+ export function encodeDefaultFieldMetadata(client, body) {
107
+ return __awaiter(this, void 0, void 0, function* () {
108
+ const metadata = body.default_field_metadata;
109
+ if (!metadata) {
110
+ return body;
111
+ }
112
+ if (yield isEnvironmentFlagActive(client, 'non_localized_focal_points')) {
113
+ return body;
114
+ }
115
+ const { locales } = yield fetchEnvironmentSettings(client);
116
+ return Object.assign(Object.assign({}, body), {
117
+ // The declared type describes the field-keyed shape, which is what callers
118
+ // write. The legacy payload is this module's business.
119
+ default_field_metadata: toLocaleKeyed(metadata, locales) });
120
+ });
121
+ }
122
+ //# sourceMappingURL=defaultFieldMetadata.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defaultFieldMetadata.js","sourceRoot":"","sources":["../../../src/utilities/defaultFieldMetadata.ts"],"names":[],"mappings":";;;;;;;;;AAEA,OAAO,EACL,wBAAwB,EACxB,uBAAuB,GACxB,MAAM,0BAA0B,CAAC;AA0ClC;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAC1B,QAAsE;IAEtE,OAAO,aAAa,IAAI,QAAQ,CAAC;AACnC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAC7B,QAA+C;IAE/C,MAAM,GAAG,GAAkC,EAAE,CAAC;IAC9C,MAAM,KAAK,GAAkC,EAAE,CAAC;IAChD,MAAM,UAAU,GAA6C,EAAE,CAAC;IAEhE,IAAI,UAAU,GAAoC,IAAI,CAAC;IACvD,IAAI,UAAU,GAAkB,IAAI,CAAC;IACrC,IAAI,WAAW,GAAG,KAAK,CAAC;IAExB,KAAK,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;QACtD,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC;QACxB,KAAK,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC;QAC5B,UAAU,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,WAAW,CAAC;QAEvC,IAAI,CAAC,WAAW,EAAE;YAChB,WAAW,GAAG,IAAI,CAAC;YACnB,UAAU,GAAG,KAAK,CAAC,WAAW,CAAC;YAC/B,UAAU,GAAG,KAAK,CAAC,WAAW,CAAC;SAChC;KACF;IAED,OAAO;QACL,GAAG;QACH,KAAK;QACL,WAAW,EAAE,UAAU;QACvB,WAAW,EAAE,UAAU;QACvB,WAAW,EAAE,UAAU;KACxB,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAC3B,EACE,GAAG,EACH,KAAK,EACL,WAAW,EACX,WAAW,EACX,WAAW,GACmB,EAChC,kBAA4B;;IAE5B,MAAM,MAAM,GAAmD,EAAE,CAAC;IAElE,SAAS,QAAQ,CAAC,MAAc;;QAC9B,MAAM,KAAK,GAAG,MAAA,MAAM,CAAC,MAAM,CAAC,mCAAI,EAAE,CAAC;QACnC,MAAM,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC;QACvB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,KAAK,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,aAAH,GAAG,cAAH,GAAG,GAAI,EAAE,CAAC,EAAE;QACvD,QAAQ,CAAC,MAAM,CAAC,CAAC,GAAG,GAAG,KAAK,CAAC;KAC9B;IAED,KAAK,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,aAAL,KAAK,cAAL,KAAK,GAAI,EAAE,CAAC,EAAE;QACzD,QAAQ,CAAC,MAAM,CAAC,CAAC,KAAK,GAAG,KAAK,CAAC;KAChC;IAED,KAAK,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,WAAW,aAAX,WAAW,cAAX,WAAW,GAAI,EAAE,CAAC,EAAE;QAC/D,QAAQ,CAAC,MAAM,CAAC,CAAC,WAAW,GAAG,KAAK,CAAC;KACtC;IAED,IAAI,WAAW,KAAK,SAAS,IAAI,WAAW,KAAK,SAAS,EAAE;QAC1D,MAAM,MAAM,GAAG,MAAA,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,mCAAI,kBAAkB,CAAC,CAAC,CAAC,CAAC;QAE/D,IAAI,MAAM,EAAE;YACV,IAAI,WAAW,KAAK,SAAS;gBAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,WAAW,GAAG,WAAW,CAAC;YAC1E,IAAI,WAAW,KAAK,SAAS;gBAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,WAAW,GAAG,WAAW,CAAC;SAC3E;KACF;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,MAAuB;IACrD,MAAM,QAAQ,GAAG,MAAM,CAAC,sBAAsB,CAAC;IAE/C,IAAI,CAAC,QAAQ,IAAI,YAAY,CAAC,QAAQ,CAAC,EAAE;QACvC,OAAO,MAAM,CAAC;KACf;IAED,uCAAY,MAAM,KAAE,sBAAsB,EAAE,eAAe,CAAC,QAAQ,CAAC,IAAG;AAC1E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAgB,0BAA0B,CAE9C,MAAc,EAAE,IAAO;;QACvB,MAAM,QAAQ,GAAG,IAAI,CAAC,sBAAsB,CAAC;QAE7C,IAAI,CAAC,QAAQ,EAAE;YACb,OAAO,IAAI,CAAC;SACb;QAED,IAAI,MAAM,uBAAuB,CAAC,MAAM,EAAE,4BAA4B,CAAC,EAAE;YACvE,OAAO,IAAI,CAAC;SACb;QAED,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,wBAAwB,CAAC,MAAM,CAAC,CAAC;QAE3D,uCACK,IAAI;YACP,2EAA2E;YAC3E,uDAAuD;YACvD,sBAAsB,EAAE,aAAa,CACnC,QAAQ,EACR,OAAO,CACoC,IAC7C;IACJ,CAAC;CAAA"}
@@ -0,0 +1,35 @@
1
+ import type * as ApiTypes from '../generated/ApiTypes.js';
2
+ import type { Client } from '../generated/Client.js';
3
+ /**
4
+ * Every boolean an environment reports about itself in `site.meta`: the
5
+ * product-update opt-ins (`improved_items_listing`, `milliseconds_in_datetime`,
6
+ * `non_localized_focal_points`, …) plus the plain state flags.
7
+ *
8
+ * Derived from the generated type rather than listed, so a flag added to the
9
+ * schema is usable here as soon as the types are regenerated, with nothing to
10
+ * keep in sync.
11
+ */
12
+ export type EnvironmentFlag = {
13
+ [K in keyof ApiTypes.SiteMeta]-?: boolean extends ApiTypes.SiteMeta[K] ? K : never;
14
+ }[keyof ApiTypes.SiteMeta];
15
+ /**
16
+ * `site.find()`, memoized per client for {@link TTL_MS}.
17
+ *
18
+ * The promise is cached rather than its result, so concurrent callers share one
19
+ * request instead of firing one each — the difference between one lookup and
20
+ * ten thousand when a batch job starts. A failed lookup is not cached.
21
+ *
22
+ * Everything expires on the same clock, including flags that in practice never
23
+ * change back: re-reading `site` every twenty minutes costs nothing next to the
24
+ * work these clients are doing, and it means a client stays correct across an
25
+ * activation that happens while it runs.
26
+ */
27
+ export declare function fetchEnvironmentSettings(client: Client): Promise<ApiTypes.Site>;
28
+ /**
29
+ * Whether a `site.meta` flag is on for the environment this client talks to.
30
+ *
31
+ * An API predating a flag omits it from the meta entirely, which the types
32
+ * don't admit but runtime does — so anything short of an explicit `true` reads
33
+ * as off.
34
+ */
35
+ export declare function isEnvironmentFlagActive(client: Client, flag: EnvironmentFlag): Promise<boolean>;
@@ -0,0 +1,60 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ /** How long a fetched `site` is reused before we ask again. */
11
+ const TTL_MS = 20 * 60 * 1000;
12
+ /**
13
+ * Keyed by client, so the cache covers every resource that asks and dies with
14
+ * the client that owns it.
15
+ */
16
+ const caches = new WeakMap();
17
+ /**
18
+ * `site.find()`, memoized per client for {@link TTL_MS}.
19
+ *
20
+ * The promise is cached rather than its result, so concurrent callers share one
21
+ * request instead of firing one each — the difference between one lookup and
22
+ * ten thousand when a batch job starts. A failed lookup is not cached.
23
+ *
24
+ * Everything expires on the same clock, including flags that in practice never
25
+ * change back: re-reading `site` every twenty minutes costs nothing next to the
26
+ * work these clients are doing, and it means a client stays correct across an
27
+ * activation that happens while it runs.
28
+ */
29
+ export function fetchEnvironmentSettings(client) {
30
+ const cached = caches.get(client);
31
+ const now = Date.now();
32
+ if (cached && cached.expiresAt > now) {
33
+ return cached.promise;
34
+ }
35
+ const promise = client.site.find();
36
+ // A failed lookup must not be cached, or every later caller inherits it
37
+ promise.catch(() => {
38
+ var _a;
39
+ if (((_a = caches.get(client)) === null || _a === void 0 ? void 0 : _a.promise) === promise) {
40
+ caches.delete(client);
41
+ }
42
+ });
43
+ caches.set(client, { promise, expiresAt: now + TTL_MS });
44
+ return promise;
45
+ }
46
+ /**
47
+ * Whether a `site.meta` flag is on for the environment this client talks to.
48
+ *
49
+ * An API predating a flag omits it from the meta entirely, which the types
50
+ * don't admit but runtime does — so anything short of an explicit `true` reads
51
+ * as off.
52
+ */
53
+ export function isEnvironmentFlagActive(client, flag) {
54
+ var _a;
55
+ return __awaiter(this, void 0, void 0, function* () {
56
+ const site = yield fetchEnvironmentSettings(client);
57
+ return ((_a = site.meta) === null || _a === void 0 ? void 0 : _a[flag]) === true;
58
+ });
59
+ }
60
+ //# sourceMappingURL=environmentSettings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"environmentSettings.js","sourceRoot":"","sources":["../../../src/utilities/environmentSettings.ts"],"names":[],"mappings":";;;;;;;;;AAkBA,+DAA+D;AAC/D,MAAM,MAAM,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAI9B;;;GAGG;AACH,MAAM,MAAM,GAAG,IAAI,OAAO,EAAiB,CAAC;AAE5C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,wBAAwB,CACtC,MAAc;IAEd,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAClC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAEvB,IAAI,MAAM,IAAI,MAAM,CAAC,SAAS,GAAG,GAAG,EAAE;QACpC,OAAO,MAAM,CAAC,OAAO,CAAC;KACvB;IAED,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;IAEnC,wEAAwE;IACxE,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE;;QACjB,IAAI,CAAA,MAAA,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,0CAAE,OAAO,MAAK,OAAO,EAAE;YAC3C,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;SACvB;IACH,CAAC,CAAC,CAAC;IAEH,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,GAAG,MAAM,EAAE,CAAC,CAAC;IAEzD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAgB,uBAAuB,CAC3C,MAAc,EACd,IAAqB;;;QAErB,MAAM,IAAI,GAAG,MAAM,wBAAwB,CAAC,MAAM,CAAC,CAAC;QAEpD,OAAO,CAAA,MAAC,IAAI,CAAC,IAA+C,0CAAG,IAAI,CAAC,MAAK,IAAI,CAAC;;CAC/E"}
@@ -4,7 +4,7 @@ export * from './fieldTypes/index.js';
4
4
  export { Client } from './generated/Client.js';
5
5
  export type { ClientConfigOptions } from './generated/Client.js';
6
6
  export * as Resources from './generated/resources/index.js';
7
- export type { UploadLocaleKeyedDefaultFieldMetadata, UploadLocaleKeyedDefaultFieldMetadataInRequest, } from './resources/Upload.js';
7
+ export type { UploadLocaleKeyedDefaultFieldMetadata, UploadLocaleKeyedDefaultFieldMetadataInRequest, } from './utilities/defaultFieldMetadata.js';
8
8
  export * from './utilities/buildBlockRecord.js';
9
9
  export * from './utilities/duplicateBlockRecord.js';
10
10
  export * from './utilities/fieldsContainingReferences.js';
@@ -1,44 +1,59 @@
1
+ import type * as ApiTypes from '../generated/ApiTypes.js';
1
2
  import BaseUpload from '../generated/resources/Upload.js';
2
3
  /**
3
- * Legacy locale-keyed shape of an upload's `default_field_metadata`, as
4
- * returned and accepted by environments where the `non_localized_focal_points`
5
- * opt-in is inactive.
4
+ * `default_field_metadata` travels in one of two shapes, and which one an
5
+ * environment speaks depends on the `non_localized_focal_points` opt-in — each
6
+ * rejects the other with `422 INVALID_FORMAT`. This resource hides that: you
7
+ * always read and write the field-keyed shape the types describe, and the
8
+ * legacy one is converted to and from as needed.
6
9
  *
7
- * The generated `Upload.default_field_metadata` type reflects the new
8
- * field-keyed shape (the path forward). This type is provided so consumers
9
- * targeting opted-out environments during the transition can cast the
10
- * response value to a structurally accurate shape.
10
+ * The raw methods are deliberately left alone: they are the escape hatch for
11
+ * anyone who needs to see what actually goes over the wire.
11
12
  */
12
- export type UploadLocaleKeyedDefaultFieldMetadata = {
13
- [localeCode: string]: {
14
- alt: string | null;
15
- title: string | null;
16
- custom_data: {
17
- [k: string]: unknown;
18
- };
19
- focal_point: {
20
- x: number;
21
- y: number;
22
- } | null;
23
- };
24
- };
25
- /**
26
- * Legacy locale-keyed shape accepted on `create` / `update` request bodies
27
- * by environments where the `non_localized_focal_points` opt-in is inactive.
28
- * All fields are optional, matching the partial-write contract.
29
- */
30
- export type UploadLocaleKeyedDefaultFieldMetadataInRequest = {
31
- [localeCode: string]: {
32
- alt?: string | null;
33
- title?: string | null;
34
- custom_data?: {
35
- [k: string]: unknown;
36
- };
37
- focal_point?: {
38
- x: number;
39
- y: number;
40
- } | null;
41
- };
42
- };
43
13
  export default class UploadResource extends BaseUpload {
14
+ /**
15
+ * Create a new upload
16
+ *
17
+ * Read more: https://www.datocms.com/docs/content-management-api/resources/upload/create
18
+ *
19
+ * @throws {ApiError}
20
+ * @throws {TimeoutError}
21
+ */
22
+ create(body: ApiTypes.UploadCreateSchema): Promise<ApiTypes.Upload>;
23
+ /**
24
+ * Update an upload
25
+ *
26
+ * Read more: https://www.datocms.com/docs/content-management-api/resources/upload/update
27
+ *
28
+ * @throws {ApiError}
29
+ * @throws {TimeoutError}
30
+ */
31
+ update(uploadId: string | ApiTypes.UploadData, body: ApiTypes.UploadUpdateSchema, queryParams?: ApiTypes.UploadUpdateHrefSchema): Promise<ApiTypes.Upload>;
32
+ /**
33
+ * Retrieve an upload
34
+ *
35
+ * Read more: https://www.datocms.com/docs/content-management-api/resources/upload/self
36
+ *
37
+ * @throws {ApiError}
38
+ * @throws {TimeoutError}
39
+ */
40
+ find(uploadId: string | ApiTypes.UploadData): Promise<ApiTypes.Upload>;
41
+ /**
42
+ * List all uploads
43
+ *
44
+ * Read more: https://www.datocms.com/docs/content-management-api/resources/upload/instances
45
+ *
46
+ * @throws {ApiError}
47
+ * @throws {TimeoutError}
48
+ */
49
+ list(queryParams?: ApiTypes.UploadInstancesHrefSchema): Promise<ApiTypes.Upload[]>;
50
+ /**
51
+ * Async iterator to auto-paginate over elements returned by list()
52
+ *
53
+ * Read more: https://www.datocms.com/docs/content-management-api/resources/upload/instances
54
+ *
55
+ * @throws {ApiError}
56
+ * @throws {TimeoutError}
57
+ */
58
+ listPagedIterator(...args: Parameters<BaseUpload['listPagedIterator']>): AsyncGenerator<ApiTypes.Upload, void, unknown>;
44
59
  }
@@ -0,0 +1,84 @@
1
+ import type * as ApiTypes from '../generated/ApiTypes.js';
2
+ import type { Client } from '../generated/Client.js';
3
+ /**
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.
7
+ *
8
+ * The `uploads` resource converts to and from this shape on your behalf, so you
9
+ * only ever see the field-keyed one. The type is exported for those working at
10
+ * the raw layer, which performs no conversion.
11
+ */
12
+ export type UploadLocaleKeyedDefaultFieldMetadata = {
13
+ [localeCode: string]: {
14
+ alt: string | null;
15
+ title: string | null;
16
+ custom_data: {
17
+ [k: string]: unknown;
18
+ };
19
+ focal_point: {
20
+ x: number;
21
+ y: number;
22
+ } | null;
23
+ poster_time: number | null;
24
+ };
25
+ };
26
+ /**
27
+ * Legacy locale-keyed shape accepted on `create` / `update` request bodies
28
+ * by environments where the `non_localized_focal_points` opt-in is inactive.
29
+ * All fields are optional, matching the partial-write contract.
30
+ */
31
+ export type UploadLocaleKeyedDefaultFieldMetadataInRequest = {
32
+ [localeCode: string]: {
33
+ alt?: string | null;
34
+ title?: string | null;
35
+ custom_data?: {
36
+ [k: string]: unknown;
37
+ };
38
+ focal_point?: {
39
+ x: number;
40
+ y: number;
41
+ } | null;
42
+ poster_time?: number | null;
43
+ };
44
+ };
45
+ export type DefaultFieldMetadata = ApiTypes.Upload['default_field_metadata'];
46
+ export type DefaultFieldMetadataInRequest = NonNullable<ApiTypes.UploadUpdateSchema['default_field_metadata']>;
47
+ /**
48
+ * Tells the two wire shapes apart. A field-keyed payload always carries a
49
+ * top-level `focal_point`, and a locale-keyed one never can: its keys are
50
+ * locale codes, and no locale code is the literal string `focal_point`.
51
+ */
52
+ export declare function isFieldKeyed(metadata: DefaultFieldMetadata | UploadLocaleKeyedDefaultFieldMetadata): metadata is DefaultFieldMetadata;
53
+ /**
54
+ * Collapses a legacy response payload into the field-keyed shape. The API
55
+ * replicates the non-localized values into every locale entry on read, so every
56
+ * entry carries the same value and the first one is enough.
57
+ */
58
+ export declare function fromLocaleKeyed(byLocale: UploadLocaleKeyedDefaultFieldMetadata): DefaultFieldMetadata;
59
+ /**
60
+ * Rewrites a field-keyed patch into the legacy locale-keyed one: the localized
61
+ * keys are pivoted per locale, and the non-localized ones ride along on a
62
+ * single entry. The API takes `focal_point` / `poster_time` off the first entry
63
+ * that carries one and ignores the rest, so writing them once is enough — on
64
+ * any locale the patch already touches, or the environment's first one when it
65
+ * touches none.
66
+ */
67
+ export declare function toLocaleKeyed({ alt, title, custom_data, focal_point, poster_time, }: DefaultFieldMetadataInRequest, environmentLocales: string[]): UploadLocaleKeyedDefaultFieldMetadataInRequest;
68
+ /**
69
+ * Normalizes an upload as served by the API into the field-keyed shape the
70
+ * `Upload` type describes. Returns the entity untouched — no copy — when it is
71
+ * already field-keyed, which is the case for every environment that has taken
72
+ * the opt-in.
73
+ */
74
+ export declare function normalizeUpload(upload: ApiTypes.Upload): ApiTypes.Upload;
75
+ /**
76
+ * Encodes a `create` / `update` body into the shape the environment accepts.
77
+ *
78
+ * The environment is only consulted when there is metadata to encode, so a
79
+ * client that never writes asset metadata never asks — and when it does ask,
80
+ * the lookup is memoized and shared, so a batch of writes pays for one.
81
+ */
82
+ export declare function encodeDefaultFieldMetadata<T extends {
83
+ default_field_metadata?: DefaultFieldMetadataInRequest;
84
+ }>(client: Client, body: T): Promise<T>;
@@ -0,0 +1,35 @@
1
+ import type * as ApiTypes from '../generated/ApiTypes.js';
2
+ import type { Client } from '../generated/Client.js';
3
+ /**
4
+ * Every boolean an environment reports about itself in `site.meta`: the
5
+ * product-update opt-ins (`improved_items_listing`, `milliseconds_in_datetime`,
6
+ * `non_localized_focal_points`, …) plus the plain state flags.
7
+ *
8
+ * Derived from the generated type rather than listed, so a flag added to the
9
+ * schema is usable here as soon as the types are regenerated, with nothing to
10
+ * keep in sync.
11
+ */
12
+ export type EnvironmentFlag = {
13
+ [K in keyof ApiTypes.SiteMeta]-?: boolean extends ApiTypes.SiteMeta[K] ? K : never;
14
+ }[keyof ApiTypes.SiteMeta];
15
+ /**
16
+ * `site.find()`, memoized per client for {@link TTL_MS}.
17
+ *
18
+ * The promise is cached rather than its result, so concurrent callers share one
19
+ * request instead of firing one each — the difference between one lookup and
20
+ * ten thousand when a batch job starts. A failed lookup is not cached.
21
+ *
22
+ * Everything expires on the same clock, including flags that in practice never
23
+ * change back: re-reading `site` every twenty minutes costs nothing next to the
24
+ * work these clients are doing, and it means a client stays correct across an
25
+ * activation that happens while it runs.
26
+ */
27
+ export declare function fetchEnvironmentSettings(client: Client): Promise<ApiTypes.Site>;
28
+ /**
29
+ * Whether a `site.meta` flag is on for the environment this client talks to.
30
+ *
31
+ * An API predating a flag omits it from the meta entirely, which the types
32
+ * don't admit but runtime does — so anything short of an explicit `true` reads
33
+ * as off.
34
+ */
35
+ export declare function isEnvironmentFlagActive(client: Client, flag: EnvironmentFlag): Promise<boolean>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datocms/cma-client",
3
- "version": "5.8.0",
3
+ "version": "6.0.0",
4
4
  "description": "JS client for DatoCMS REST Content Management API",
5
5
  "keywords": [
6
6
  "datocms",
@@ -55,5 +55,5 @@
55
55
  "devDependencies": {
56
56
  "@datocms/dashboard-client": "^5.8.0"
57
57
  },
58
- "gitHead": "6280620a11120a1f612a8114c2cbf879dc245599"
58
+ "gitHead": "ac4164968026ba62a2841d31d2b60c31eadb2cc8"
59
59
  }
@@ -151,7 +151,7 @@ export class Client {
151
151
  ...this.config,
152
152
  ...options,
153
153
  logFn: this.config.logFn || console.log,
154
- userAgent: '@datocms/cma-client v5.8.0',
154
+ userAgent: '@datocms/cma-client v6.0.0',
155
155
  baseUrl: this.baseUrl,
156
156
  preCallStack: new Error().stack,
157
157
  extraHeaders: {
package/src/index.ts CHANGED
@@ -7,7 +7,7 @@ export * as Resources from './generated/resources/index.js';
7
7
  export type {
8
8
  UploadLocaleKeyedDefaultFieldMetadata,
9
9
  UploadLocaleKeyedDefaultFieldMetadataInRequest,
10
- } from './resources/Upload.js';
10
+ } from './utilities/defaultFieldMetadata.js';
11
11
  export * from './utilities/buildBlockRecord.js';
12
12
  export * from './utilities/duplicateBlockRecord.js';
13
13
  export * from './utilities/fieldsContainingReferences.js';