@makeswift/runtime 0.24.7-canary.1 → 0.24.7-canary.2

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 (73) hide show
  1. package/client/package.json +5 -0
  2. package/dist/cjs/client/index.js +686 -0
  3. package/dist/cjs/client/index.js.map +1 -0
  4. package/dist/cjs/next/api-handler/handlers/manifest.js +1 -1
  5. package/dist/cjs/next/client.js +8 -654
  6. package/dist/cjs/next/client.js.map +1 -1
  7. package/dist/cjs/next/components/MakeswiftComponent.js +1 -1
  8. package/dist/cjs/next/components/MakeswiftComponent.js.map +1 -1
  9. package/dist/cjs/next/components/Slot.js.map +1 -1
  10. package/dist/cjs/next/components/page.js +1 -1
  11. package/dist/cjs/next/components/page.js.map +1 -1
  12. package/dist/cjs/next/index.js.map +1 -1
  13. package/dist/cjs/runtimes/react/testing/element-data.js.map +1 -1
  14. package/dist/cjs/utils/async-iterable.js.map +1 -0
  15. package/dist/cjs/utils/pagination.js.map +1 -0
  16. package/dist/esm/client/index.js +671 -0
  17. package/dist/esm/client/index.js.map +1 -0
  18. package/dist/esm/next/api-handler/handlers/manifest.js +1 -1
  19. package/dist/esm/next/client.js +7 -662
  20. package/dist/esm/next/client.js.map +1 -1
  21. package/dist/esm/next/components/MakeswiftComponent.js +1 -1
  22. package/dist/esm/next/components/MakeswiftComponent.js.map +1 -1
  23. package/dist/esm/next/components/Slot.js.map +1 -1
  24. package/dist/esm/next/components/page.js +1 -1
  25. package/dist/esm/next/components/page.js.map +1 -1
  26. package/dist/esm/next/index.js.map +1 -1
  27. package/dist/esm/runtimes/react/testing/element-data.js.map +1 -1
  28. package/dist/esm/utils/async-iterable.js.map +1 -0
  29. package/dist/esm/utils/pagination.js.map +1 -0
  30. package/dist/types/client/index.d.ts +697 -0
  31. package/dist/types/client/index.d.ts.map +1 -0
  32. package/dist/types/client/tests/client.error-handling.test.d.ts.map +1 -0
  33. package/dist/types/client/tests/client.get-component-snapshot.test.d.ts.map +1 -0
  34. package/dist/types/client/tests/client.get-page-snapshot.test.d.ts.map +1 -0
  35. package/dist/types/client/tests/client.get-pages.test.d.ts.map +1 -0
  36. package/dist/types/client/tests/client.get-resources.test.d.ts.map +1 -0
  37. package/dist/types/next/client.d.ts +3 -690
  38. package/dist/types/next/client.d.ts.map +1 -1
  39. package/dist/types/next/components/MakeswiftComponent.d.ts +1 -1
  40. package/dist/types/next/components/MakeswiftComponent.d.ts.map +1 -1
  41. package/dist/types/next/components/Slot.d.ts +1 -1
  42. package/dist/types/next/components/Slot.d.ts.map +1 -1
  43. package/dist/types/next/components/page.d.ts +1 -1
  44. package/dist/types/next/components/page.d.ts.map +1 -1
  45. package/dist/types/next/index.d.ts +1 -1
  46. package/dist/types/next/index.d.ts.map +1 -1
  47. package/dist/types/runtimes/react/testing/element-data.d.ts +1 -1
  48. package/dist/types/runtimes/react/testing/element-data.d.ts.map +1 -1
  49. package/dist/types/utils/async-iterable.d.ts.map +1 -0
  50. package/dist/types/utils/pagination.d.ts.map +1 -0
  51. package/package.json +7 -1
  52. package/dist/cjs/next/utils/async-iterable.js.map +0 -1
  53. package/dist/cjs/next/utils/pagination.js.map +0 -1
  54. package/dist/esm/next/utils/async-iterable.js.map +0 -1
  55. package/dist/esm/next/utils/pagination.js.map +0 -1
  56. package/dist/types/next/tests/client.error-handling.test.d.ts.map +0 -1
  57. package/dist/types/next/tests/client.get-component-snapshot.test.d.ts.map +0 -1
  58. package/dist/types/next/tests/client.get-page-snapshot.test.d.ts.map +0 -1
  59. package/dist/types/next/tests/client.get-pages.test.d.ts.map +0 -1
  60. package/dist/types/next/tests/client.get-resources.test.d.ts.map +0 -1
  61. package/dist/types/next/utils/async-iterable.d.ts.map +0 -1
  62. package/dist/types/next/utils/pagination.d.ts.map +0 -1
  63. /package/dist/cjs/{next/utils → utils}/async-iterable.js +0 -0
  64. /package/dist/cjs/{next/utils → utils}/pagination.js +0 -0
  65. /package/dist/esm/{next/utils → utils}/async-iterable.js +0 -0
  66. /package/dist/esm/{next/utils → utils}/pagination.js +0 -0
  67. /package/dist/types/{next → client}/tests/client.error-handling.test.d.ts +0 -0
  68. /package/dist/types/{next → client}/tests/client.get-component-snapshot.test.d.ts +0 -0
  69. /package/dist/types/{next → client}/tests/client.get-page-snapshot.test.d.ts +0 -0
  70. /package/dist/types/{next → client}/tests/client.get-pages.test.d.ts +0 -0
  71. /package/dist/types/{next → client}/tests/client.get-resources.test.d.ts +0 -0
  72. /package/dist/types/{next/utils → utils}/async-iterable.d.ts +0 -0
  73. /package/dist/types/{next/utils → utils}/pagination.d.ts +0 -0
@@ -0,0 +1,671 @@
1
+ import { z } from "zod";
2
+ import {
3
+ APIResourceType
4
+ } from "../api";
5
+ import { GraphQLClient } from "../api/graphql/client";
6
+ import { FileQuery, IntrospectedResourcesQuery, TableQuery } from "../api/graphql/documents";
7
+ import { CacheData } from "../api/react";
8
+ import {
9
+ getElementChildren,
10
+ getSwatchIds,
11
+ getFileIds,
12
+ getPageIds,
13
+ getTableIds,
14
+ getTypographyIds
15
+ } from "../prop-controllers/introspection";
16
+ import {
17
+ getPropControllerDescriptors,
18
+ isElementReference
19
+ } from "../state/react-page";
20
+ import { MakeswiftSiteVersion } from "../api/site-version";
21
+ import { toIterablePaginationResult } from "../utils/pagination";
22
+ import { deterministicUUID } from "../utils/deterministic-uuid";
23
+ import { Schema } from "@makeswift/controls";
24
+ import { EMBEDDED_DOCUMENT_TYPE } from "../state/modules/read-only-documents";
25
+ const makeswiftPageResultSchema = z.object({
26
+ id: z.string(),
27
+ path: z.string(),
28
+ title: z.string().nullable(),
29
+ description: z.string().nullable(),
30
+ canonicalUrl: z.string().nullable(),
31
+ socialImageUrl: z.string().nullable(),
32
+ sitemapPriority: z.number().nullable(),
33
+ sitemapFrequency: z.enum(["always", "hourly", "daily", "weekly", "monthly", "yearly", "never"]).nullable(),
34
+ createdAt: z.string(),
35
+ updatedAt: z.string(),
36
+ publishedAt: z.string().nullable(),
37
+ isOnline: z.boolean().nullable(),
38
+ excludedFromSearch: z.boolean().nullable(),
39
+ locale: z.string(),
40
+ localizedVariants: z.array(
41
+ z.object({
42
+ locale: z.string(),
43
+ path: z.string()
44
+ })
45
+ )
46
+ });
47
+ const makeswiftGetPagesResultAPISchema = z.object({
48
+ data: z.array(makeswiftPageResultSchema),
49
+ hasMore: z.boolean()
50
+ });
51
+ const makeswiftGetPagesParamsSchema = z.object({
52
+ limit: z.number().optional(),
53
+ after: z.string().optional(),
54
+ sortBy: z.enum(["title", "path", "description", "createdAt", "updatedAt"]).optional(),
55
+ sortDirection: z.enum(["asc", "desc"]).optional(),
56
+ includeOffline: z.boolean().optional(),
57
+ pathPrefix: z.string().optional(),
58
+ locale: z.string().optional()
59
+ });
60
+ function getPagesQueryParams({
61
+ limit = 20,
62
+ after,
63
+ sortBy,
64
+ sortDirection,
65
+ includeOffline,
66
+ pathPrefix,
67
+ locale
68
+ }) {
69
+ const params = new URLSearchParams();
70
+ if (limit != null)
71
+ params.set("limit", limit.toString());
72
+ if (after != null)
73
+ params.set("after", after);
74
+ if (sortBy != null)
75
+ params.set("sortBy", sortBy);
76
+ if (sortDirection != null)
77
+ params.set("sortDirection", sortDirection);
78
+ if (includeOffline != null)
79
+ params.set("includeOffline", includeOffline.toString());
80
+ if (pathPrefix != null)
81
+ params.set("pathPrefix", pathPrefix);
82
+ if (locale != null)
83
+ params.set("locale", locale);
84
+ return params;
85
+ }
86
+ function pageToRootDocument(pageDocument) {
87
+ const { locale, localizedPages, id, data } = pageDocument;
88
+ const localizedPage = localizedPages.find(({ parentId }) => parentId == null);
89
+ return localizedPage ? { key: localizedPage.elementTreeId, rootElement: localizedPage.data, locale } : { key: id, rootElement: data, locale };
90
+ }
91
+ const makeswiftComponentDocumentSchema = z.object({
92
+ id: z.string(),
93
+ name: z.string().nullable(),
94
+ locale: z.string().nullable(),
95
+ data: Schema.element,
96
+ siteId: z.string(),
97
+ inheritsFromParent: z.boolean()
98
+ });
99
+ const makeswiftComponentDocumentFallbackSchema = z.object({
100
+ id: z.string(),
101
+ locale: z.string().nullable(),
102
+ data: z.null()
103
+ });
104
+ function componentDocumentToRootEmbeddedDocument({
105
+ document,
106
+ documentKey,
107
+ name,
108
+ type,
109
+ meta
110
+ }) {
111
+ const { data: rootElement, locale, id } = document;
112
+ if (rootElement != null && rootElement.type !== type) {
113
+ throw new Error(
114
+ `Type "${rootElement.type}" does not match the expected type "${type}" from the snapshot`
115
+ );
116
+ }
117
+ const rootDocument = {
118
+ key: documentKey,
119
+ rootElement: rootElement ?? {
120
+ // Fallback rootElement
121
+ // Create a stable uuid so two different clients will have the same empty element data.
122
+ // This is needed to make presence feature work for an element that is not yet created.
123
+ key: deterministicUUID({ id, locale, seed: documentKey }),
124
+ type,
125
+ props: {}
126
+ },
127
+ locale,
128
+ id,
129
+ type,
130
+ name,
131
+ meta,
132
+ __type: EMBEDDED_DOCUMENT_TYPE
133
+ };
134
+ return rootDocument;
135
+ }
136
+ async function failedResponseBody(response) {
137
+ try {
138
+ const text = await response.text();
139
+ try {
140
+ return JSON.parse(text);
141
+ } catch {
142
+ return text;
143
+ }
144
+ } catch (e) {
145
+ return `Failed to extract response body: ${e}`;
146
+ }
147
+ }
148
+ function responseError(response) {
149
+ return `${response.status} ${response.statusText}`;
150
+ }
151
+ const pagePathnameSlicesAPISchema = z.array(
152
+ z.object({
153
+ id: z.string(),
154
+ basePageId: z.string(),
155
+ pathname: z.string(),
156
+ localizedPathname: z.string().optional(),
157
+ __typename: z.literal("PagePathnameSlice")
158
+ }).nullable()
159
+ );
160
+ const getPageAPISchema = z.object({
161
+ pathname: z.string(),
162
+ locale: z.string(),
163
+ alternate: z.array(
164
+ z.object({
165
+ pathname: z.string(),
166
+ locale: z.string()
167
+ })
168
+ )
169
+ });
170
+ class MakeswiftClient {
171
+ graphqlClient;
172
+ runtime;
173
+ apiKey;
174
+ apiOrigin;
175
+ constructor(apiKey, { apiOrigin = "https://api.makeswift.com", runtime }) {
176
+ if (typeof apiKey !== "string") {
177
+ throw new Error(
178
+ `The Makeswift client must be passed a valid Makeswift site API key: \`new Makeswift('<makeswift_site_api_key>')\`
179
+ Received "${apiKey}" instead.`
180
+ );
181
+ }
182
+ this.apiKey = apiKey;
183
+ try {
184
+ this.apiOrigin = new URL(apiOrigin);
185
+ } catch {
186
+ throw new Error(
187
+ `The Makeswift client received an invalid \`apiOrigin\` parameter: "${apiOrigin}".`
188
+ );
189
+ }
190
+ this.graphqlClient = new GraphQLClient(new URL("graphql", apiOrigin).href);
191
+ this.runtime = runtime;
192
+ }
193
+ async fetch(path, siteVersion) {
194
+ const response = await fetch(new URL(path, this.apiOrigin).toString(), {
195
+ headers: {
196
+ ["X-API-Key"]: this.apiKey,
197
+ "Makeswift-Site-API-Key": this.apiKey,
198
+ "Makeswift-Site-Version": siteVersion
199
+ },
200
+ ...siteVersion === MakeswiftSiteVersion.Working ? { cache: "no-store" } : {},
201
+ ...this.fetchOptions(siteVersion)
202
+ });
203
+ return response;
204
+ }
205
+ /**
206
+ * Override this method to provide additional fetch options, e.g. revalidation, cache tags, etc.
207
+ */
208
+ fetchOptions(_siteVersion) {
209
+ return {};
210
+ }
211
+ getPagesInternal = async ({
212
+ siteVersion = MakeswiftSiteVersion.Live,
213
+ ...params
214
+ } = {}) => {
215
+ const queryParams = getPagesQueryParams(params);
216
+ const response = await this.fetch(`v4/pages?${queryParams.toString()}`, siteVersion);
217
+ if (!response.ok) {
218
+ console.error("Failed to get pages", {
219
+ response: await failedResponseBody(response),
220
+ siteVersion,
221
+ params
222
+ });
223
+ throw new Error(`Failed to get pages: ${responseError(response)}`);
224
+ }
225
+ const result = await response.json();
226
+ const parsedResponse = makeswiftGetPagesResultAPISchema.safeParse(result);
227
+ if (!parsedResponse.success) {
228
+ throw new Error(
229
+ `Failed to parse 'getPages' response: ${parsedResponse.error.errors.map((e) => e.message).join("; ")}`
230
+ );
231
+ }
232
+ return parsedResponse.data;
233
+ };
234
+ getPages = toIterablePaginationResult(this.getPagesInternal);
235
+ async getPage(pathname, {
236
+ siteVersion = MakeswiftSiteVersion.Live,
237
+ locale
238
+ } = {}) {
239
+ const url = new URL(`v2/pages/${encodeURIComponent(pathname)}`, this.apiOrigin);
240
+ if (locale)
241
+ url.searchParams.set("locale", locale);
242
+ const response = await this.fetch(url.pathname + url.search, siteVersion);
243
+ if (!response.ok) {
244
+ if (response.status === 404)
245
+ return null;
246
+ console.error(`Failed to get page snapshot for '${pathname}'`, {
247
+ response: await failedResponseBody(response),
248
+ siteVersion,
249
+ locale
250
+ });
251
+ throw new Error(`Failed to get page snapshot for '${pathname}': ${responseError(response)}`);
252
+ }
253
+ const json = await response.json();
254
+ return getPageAPISchema.parse(json);
255
+ }
256
+ async getTypographies(typographyIds, siteVersion) {
257
+ if (typographyIds.length === 0)
258
+ return [];
259
+ const url = new URL(`v2/typographies/bulk`, this.apiOrigin);
260
+ typographyIds.forEach((id) => {
261
+ url.searchParams.append("ids", id);
262
+ });
263
+ const response = await this.fetch(url.pathname + url.search, siteVersion);
264
+ if (!response.ok) {
265
+ console.error(`Failed to get typographies for [${typographyIds.join(", ")}]`, {
266
+ response: await failedResponseBody(response),
267
+ siteVersion
268
+ });
269
+ return [];
270
+ }
271
+ const body = await response.json();
272
+ return body;
273
+ }
274
+ async getSwatches(ids, siteVersion) {
275
+ if (ids.length === 0)
276
+ return [];
277
+ const url = new URL(`v2/swatches/bulk`, this.apiOrigin);
278
+ ids.forEach((id) => {
279
+ url.searchParams.append("ids", id);
280
+ });
281
+ const response = await this.fetch(url.pathname + url.search, siteVersion);
282
+ if (!response.ok) {
283
+ console.error(`Failed to get swatches for ${ids.join(", ")}`, {
284
+ response: await failedResponseBody(response),
285
+ siteVersion
286
+ });
287
+ return [];
288
+ }
289
+ return await response.json();
290
+ }
291
+ async getIntrospectedResources({
292
+ swatchIds,
293
+ ...introspectedResourceIds
294
+ }, siteVersion) {
295
+ const result = await this.graphqlClient.request(IntrospectedResourcesQuery, introspectedResourceIds);
296
+ const swatches = await this.getSwatches(swatchIds, siteVersion);
297
+ return { ...result, swatches };
298
+ }
299
+ async introspect(element, siteVersion, locale) {
300
+ const runtime = this.runtime;
301
+ const descriptors = getPropControllerDescriptors(runtime.store.getState());
302
+ const swatchIds = /* @__PURE__ */ new Set();
303
+ const fileIds = /* @__PURE__ */ new Set();
304
+ const typographyIds = /* @__PURE__ */ new Set();
305
+ const tableIds = /* @__PURE__ */ new Set();
306
+ const pageIds = /* @__PURE__ */ new Set();
307
+ const globalElements = /* @__PURE__ */ new Map();
308
+ const localizedGlobalElements = /* @__PURE__ */ new Map();
309
+ const localizedResourcesMap = /* @__PURE__ */ new Map();
310
+ const remaining = [element];
311
+ const seen = /* @__PURE__ */ new Set();
312
+ let current;
313
+ while (current = remaining.pop()) {
314
+ let getResourcesFromElementDescriptors2 = function(elementDescriptors2, props) {
315
+ Object.entries(elementDescriptors2).forEach(([propName, descriptor]) => {
316
+ getSwatchIds(descriptor, props[propName]).forEach((swatchId) => {
317
+ swatchIds.add(swatchId);
318
+ });
319
+ getFileIds(descriptor, props[propName]).forEach((fileId) => fileIds.add(fileId));
320
+ getTypographyIds(descriptor, props[propName]).forEach(
321
+ (typographyId) => typographyIds.add(typographyId)
322
+ );
323
+ getTableIds(descriptor, props[propName]).forEach((tableId) => tableIds.add(tableId));
324
+ getPageIds(descriptor, props[propName]).forEach((pageId) => pageIds.add(pageId));
325
+ getElementChildren(descriptor, props[propName]).forEach((child) => {
326
+ if (!seen.has(child.key)) {
327
+ seen.add(child.key);
328
+ remaining.push(child);
329
+ }
330
+ });
331
+ });
332
+ };
333
+ var getResourcesFromElementDescriptors = getResourcesFromElementDescriptors2;
334
+ let element2;
335
+ if (isElementReference(current)) {
336
+ const globalElementId = current.value;
337
+ const globalElement = await this.getGlobalElement(globalElementId, siteVersion);
338
+ let elementData = globalElement?.data;
339
+ if (locale) {
340
+ const localizedGlobalElement = await this.getLocalizedGlobalElement(
341
+ globalElementId,
342
+ locale,
343
+ siteVersion
344
+ );
345
+ if (localizedGlobalElement) {
346
+ elementData = localizedGlobalElement.data;
347
+ localizedResourcesMap.set(globalElementId, localizedGlobalElement.id);
348
+ localizedGlobalElements.set(localizedGlobalElement.id, localizedGlobalElement);
349
+ }
350
+ }
351
+ globalElements.set(globalElementId, globalElement);
352
+ if (elementData == null)
353
+ continue;
354
+ element2 = elementData;
355
+ } else {
356
+ element2 = current;
357
+ }
358
+ const elementDescriptors = descriptors.get(element2.type);
359
+ if (elementDescriptors == null)
360
+ continue;
361
+ getResourcesFromElementDescriptors2(elementDescriptors, element2.props);
362
+ }
363
+ const typographies = await this.getTypographies([...typographyIds], siteVersion);
364
+ typographies.forEach((typography) => {
365
+ typography?.style.forEach((style) => {
366
+ const swatchId = style.value.color?.swatchId;
367
+ if (swatchId != null)
368
+ swatchIds.add(swatchId);
369
+ });
370
+ });
371
+ const pagePathnames = await this.getPagePathnameSlices([...pageIds], siteVersion, { locale });
372
+ const { swatches, files, tables } = await this.getIntrospectedResources(
373
+ {
374
+ swatchIds: [...swatchIds],
375
+ fileIds: [...fileIds],
376
+ tableIds: [...tableIds]
377
+ },
378
+ siteVersion
379
+ );
380
+ const apiResources = {
381
+ [APIResourceType.Swatch]: [...swatchIds].map((id) => ({
382
+ id,
383
+ value: swatches.find((swatch) => swatch?.id === id) ?? null
384
+ })),
385
+ [APIResourceType.File]: [...fileIds].map((id) => ({
386
+ id,
387
+ value: files.find((file) => file?.id === id) ?? null
388
+ })),
389
+ [APIResourceType.Typography]: [...typographyIds].map((id) => ({
390
+ id,
391
+ value: typographies.find((typography) => typography?.id === id) ?? null
392
+ })),
393
+ [APIResourceType.Table]: [...tableIds].map((id) => ({
394
+ id,
395
+ value: tables.find((table) => table?.id === id) ?? null
396
+ })),
397
+ [APIResourceType.PagePathnameSlice]: [...pageIds].map((id) => ({
398
+ id,
399
+ value: pagePathnames.find((pagePathnameSlice) => pagePathnameSlice?.id === id) ?? null,
400
+ locale
401
+ })),
402
+ [APIResourceType.GlobalElement]: [...globalElements.entries()].map(([id, value]) => ({
403
+ id,
404
+ value
405
+ })),
406
+ [APIResourceType.LocalizedGlobalElement]: [...localizedGlobalElements.entries()].map(
407
+ ([id, value]) => ({
408
+ id,
409
+ value,
410
+ locale
411
+ })
412
+ )
413
+ };
414
+ return {
415
+ apiResources,
416
+ localizedResourcesMap: locale != null ? { [locale]: Object.fromEntries(localizedResourcesMap.entries()) } : {}
417
+ };
418
+ }
419
+ async getPageSnapshot(pathname, {
420
+ siteVersion: siteVersionPromise,
421
+ locale,
422
+ allowLocaleFallback = true
423
+ }) {
424
+ const queryParams = () => {
425
+ const params = new URLSearchParams();
426
+ if (locale)
427
+ params.set("locale", locale);
428
+ if (allowLocaleFallback != null)
429
+ params.set("allowLocaleFallback", `${allowLocaleFallback}`);
430
+ return params.toString();
431
+ };
432
+ const siteVersion = await siteVersionPromise;
433
+ const response = await this.fetch(
434
+ `v3/pages/${encodeURIComponent(pathname)}/document?${queryParams()}`,
435
+ siteVersion
436
+ );
437
+ if (!response.ok) {
438
+ if (response.status === 404)
439
+ return null;
440
+ console.error(`Failed to get page snapshot for '${pathname}'`, {
441
+ response: await failedResponseBody(response),
442
+ siteVersion,
443
+ locale
444
+ });
445
+ throw new Error(`Failed to get page snapshot for '${pathname}': ${responseError(response)}`);
446
+ }
447
+ const document = await response.json();
448
+ const baseLocalizedPage = document.localizedPages.find(({ parentId }) => parentId == null);
449
+ const cacheData = await this.introspect(
450
+ baseLocalizedPage?.data ?? document.data,
451
+ siteVersion,
452
+ // The /v3/pages endpoint returns null for document.locale when the requested locale is the default.
453
+ // This legacy behavior is set to change with the upcoming /v4/pages endpoint.
454
+ // We rely on document.locale when reading from the API cache, so ensure the cache is built during
455
+ // introspection using the same value.
456
+ document.locale
457
+ );
458
+ return {
459
+ document,
460
+ cacheData
461
+ };
462
+ }
463
+ async getComponentSnapshot(id, {
464
+ siteVersion: siteVersionPromise,
465
+ locale,
466
+ allowLocaleFallback = true
467
+ }) {
468
+ const searchParams = new URLSearchParams();
469
+ if (locale)
470
+ searchParams.set("locale", locale);
471
+ const siteVersion = await siteVersionPromise;
472
+ const key = deterministicUUID({ id, locale, seed: this.apiKey.split("-").at(0) });
473
+ const baseLocaleWasRequested = locale == null;
474
+ const canAttemptLocaleFallback = !baseLocaleWasRequested && allowLocaleFallback;
475
+ let response;
476
+ const responseForRequestedLocale = await this.fetch(
477
+ `v1/element-trees/${encodeURIComponent(id)}?${searchParams.toString()}`,
478
+ siteVersion
479
+ );
480
+ if (responseForRequestedLocale.status === 404 && canAttemptLocaleFallback) {
481
+ response = await this.fetch(`v1/element-trees/${encodeURIComponent(id)}`, siteVersion);
482
+ } else {
483
+ response = responseForRequestedLocale;
484
+ }
485
+ if (!response.ok) {
486
+ if (response.status === 404) {
487
+ return {
488
+ document: {
489
+ id,
490
+ locale: locale ?? null,
491
+ data: null
492
+ },
493
+ key,
494
+ cacheData: CacheData.empty(),
495
+ meta: {
496
+ allowLocaleFallback,
497
+ requestedLocale: locale ?? null
498
+ }
499
+ };
500
+ }
501
+ console.error(`Failed to get component snapshot for '${id}':`, {
502
+ response: await failedResponseBody(response),
503
+ siteVersion,
504
+ locale
505
+ });
506
+ throw new Error(`Failed to get component snapshot for '${id}': ${responseError(response)}`);
507
+ }
508
+ const document = makeswiftComponentDocumentSchema.parse(await response.json());
509
+ const cacheData = await this.introspect(document.data, siteVersion, locale ?? null);
510
+ return {
511
+ document,
512
+ cacheData,
513
+ key,
514
+ meta: {
515
+ allowLocaleFallback,
516
+ requestedLocale: locale ?? null
517
+ }
518
+ };
519
+ }
520
+ async getSwatch(swatchId, siteVersion) {
521
+ const response = await this.fetch(`v2/swatches/${swatchId}`, siteVersion);
522
+ if (!response.ok) {
523
+ if (response.status !== 404) {
524
+ console.error(`Failed to get swatch '${swatchId}'`, {
525
+ response: await failedResponseBody(response),
526
+ siteVersion
527
+ });
528
+ }
529
+ return null;
530
+ }
531
+ const swatch = await response.json();
532
+ return swatch;
533
+ }
534
+ async getFile(fileId) {
535
+ const result = await this.graphqlClient.request(
536
+ FileQuery,
537
+ { fileId }
538
+ );
539
+ return result.file;
540
+ }
541
+ async getTypography(typographyId, siteVersion) {
542
+ const response = await this.fetch(`v2/typographies/${typographyId}`, siteVersion);
543
+ if (!response.ok) {
544
+ if (response.status !== 404) {
545
+ console.error(`Failed to get typography '${typographyId}'`, {
546
+ response: await failedResponseBody(response),
547
+ siteVersion
548
+ });
549
+ }
550
+ return null;
551
+ }
552
+ const typography = await response.json();
553
+ return typography;
554
+ }
555
+ async getGlobalElement(globalElementId, siteVersion) {
556
+ const response = await this.fetch(`v2/global-elements/${globalElementId}`, siteVersion);
557
+ if (!response.ok) {
558
+ if (response.status !== 404) {
559
+ console.error(`Failed to get global element '${globalElementId}'`, {
560
+ response: await failedResponseBody(response),
561
+ siteVersion
562
+ });
563
+ }
564
+ return null;
565
+ }
566
+ const globalElement = await response.json();
567
+ return globalElement;
568
+ }
569
+ async getLocalizedGlobalElement(globalElementId, locale, siteVersion) {
570
+ const response = await this.fetch(
571
+ `v2/localized-global-elements/${globalElementId}?locale=${locale}`,
572
+ siteVersion
573
+ );
574
+ if (!response.ok) {
575
+ if (response.status !== 404) {
576
+ console.error(`Failed to get localized global element '${globalElementId}'`, {
577
+ response: await failedResponseBody(response),
578
+ siteVersion,
579
+ locale
580
+ });
581
+ }
582
+ return null;
583
+ }
584
+ const localizedGlobalElement = await response.json();
585
+ return localizedGlobalElement;
586
+ }
587
+ async getPagePathnameSlices(pageIds, siteVersion, { locale }) {
588
+ if (pageIds.length === 0)
589
+ return [];
590
+ const url = new URL(`v2/page-pathname-slices/bulk`, this.apiOrigin);
591
+ pageIds.forEach((id) => url.searchParams.append("ids", id));
592
+ if (locale != null)
593
+ url.searchParams.set("locale", locale);
594
+ const response = await this.fetch(url.pathname + url.search, siteVersion);
595
+ if (!response.ok) {
596
+ console.error(`Failed to get page pathname slice(s) for ${pageIds.join(", ")}`, {
597
+ response: await failedResponseBody(response),
598
+ siteVersion,
599
+ locale
600
+ });
601
+ return [];
602
+ }
603
+ const json = await response.json();
604
+ const pagePathnameSlices = pagePathnameSlicesAPISchema.parse(json);
605
+ return pagePathnameSlices.map((pagePathnameSlice) => {
606
+ if (pagePathnameSlice == null)
607
+ return null;
608
+ return {
609
+ ...pagePathnameSlice,
610
+ id: pagePathnameSlice.basePageId,
611
+ localizedPathname: pagePathnameSlice.localizedPathname ?? null
612
+ };
613
+ });
614
+ }
615
+ async getPagePathnameSlice(pageId, siteVersion, { locale } = {}) {
616
+ const pagePathnameSlices = await this.getPagePathnameSlices([pageId], siteVersion, { locale });
617
+ return pagePathnameSlices.at(0) ?? null;
618
+ }
619
+ async getTable(tableId) {
620
+ const result = await this.graphqlClient.request(
621
+ TableQuery,
622
+ { tableId }
623
+ );
624
+ return result.table;
625
+ }
626
+ /**
627
+ * @deprecated `getSitemap` is deprecated. We recommend constructing a sitemap
628
+ * using data from `getPages` instead.
629
+ */
630
+ async getSitemap({
631
+ limit = 50,
632
+ after,
633
+ pathnamePrefix,
634
+ locale
635
+ } = {}) {
636
+ const url = new URL("v1/sitemap", this.apiOrigin);
637
+ url.searchParams.set("limit", limit.toString());
638
+ if (after != null)
639
+ url.searchParams.set("after", after);
640
+ if (pathnamePrefix != null)
641
+ url.searchParams.set("pathnamePrefix", pathnamePrefix);
642
+ if (locale != null)
643
+ url.searchParams.set("locale", locale);
644
+ const response = await this.fetch(url.pathname + url.search, MakeswiftSiteVersion.Live);
645
+ if (!response.ok) {
646
+ console.error("Failed to get sitemap ", {
647
+ response: await failedResponseBody(response),
648
+ limit,
649
+ after,
650
+ pathnamePrefix,
651
+ locale
652
+ });
653
+ throw new Error(`Failed to get sitemap with error: ${responseError(response)}`);
654
+ }
655
+ const sitemap = await response.json();
656
+ return sitemap;
657
+ }
658
+ getTranslatableData(elementTree) {
659
+ return this.runtime.getTranslatableData(elementTree);
660
+ }
661
+ mergeTranslatedData(elementTree, translatedData) {
662
+ return this.runtime.mergeTranslatedData(elementTree, translatedData);
663
+ }
664
+ }
665
+ export {
666
+ MakeswiftClient,
667
+ componentDocumentToRootEmbeddedDocument,
668
+ failedResponseBody,
669
+ pageToRootDocument
670
+ };
671
+ //# sourceMappingURL=index.js.map