@makeswift/runtime 0.29.2 → 0.29.3-canary.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/api/api-resources-client.js +4 -2
- package/dist/cjs/api/api-resources-client.js.map +1 -1
- package/dist/cjs/api/graphql-api-client.js +1 -1
- package/dist/cjs/api/rest-api-client.js +40 -6
- package/dist/cjs/api/rest-api-client.js.map +1 -1
- package/dist/cjs/api/types.js.map +1 -1
- package/dist/cjs/api-handler/handlers/manifest.js +1 -1
- package/dist/cjs/client/component-snapshot.js +2 -1
- package/dist/cjs/client/component-snapshot.js.map +1 -1
- package/dist/cjs/client/index.js +22 -19
- package/dist/cjs/client/index.js.map +1 -1
- package/dist/cjs/components/builtin/Form/Form.js +1 -1
- package/dist/cjs/components/builtin/Form/Form.js.map +1 -1
- package/dist/cjs/components/builtin/Form/components/Field/index.js +2 -2
- package/dist/cjs/components/builtin/Form/components/Field/index.js.map +1 -1
- package/dist/cjs/components/builtin/Form/types.js.map +1 -1
- package/dist/cjs/runtimes/react/components/MakeswiftComponent.js +20 -17
- package/dist/cjs/runtimes/react/components/MakeswiftComponent.js.map +1 -1
- package/dist/cjs/runtimes/react/server/components/snapshot-renderer.js +2 -0
- package/dist/cjs/runtimes/react/server/components/snapshot-renderer.js.map +1 -1
- package/dist/cjs/state/modules/read-only-documents.js.map +1 -1
- package/dist/cjs/state/shared-api/actions.js.map +1 -1
- package/dist/esm/api/api-resources-client.js +2 -1
- package/dist/esm/api/api-resources-client.js.map +1 -1
- package/dist/esm/api/graphql-api-client.js +1 -1
- package/dist/esm/api/rest-api-client.js +40 -6
- package/dist/esm/api/rest-api-client.js.map +1 -1
- package/dist/esm/api/types.js.map +1 -1
- package/dist/esm/api-handler/handlers/manifest.js +1 -1
- package/dist/esm/client/component-snapshot.js +5 -2
- package/dist/esm/client/component-snapshot.js.map +1 -1
- package/dist/esm/client/index.js +13 -10
- package/dist/esm/client/index.js.map +1 -1
- package/dist/esm/components/builtin/Form/Form.js +1 -1
- package/dist/esm/components/builtin/Form/Form.js.map +1 -1
- package/dist/esm/components/builtin/Form/components/Field/index.js +2 -2
- package/dist/esm/components/builtin/Form/components/Field/index.js.map +1 -1
- package/dist/esm/runtimes/react/components/MakeswiftComponent.js +20 -17
- package/dist/esm/runtimes/react/components/MakeswiftComponent.js.map +1 -1
- package/dist/esm/runtimes/react/server/components/snapshot-renderer.js +2 -0
- package/dist/esm/runtimes/react/server/components/snapshot-renderer.js.map +1 -1
- package/dist/esm/state/modules/read-only-documents.js.map +1 -1
- package/dist/esm/state/shared-api/actions.js.map +1 -1
- package/dist/types/api/api-resources-client.d.ts +3 -0
- package/dist/types/api/api-resources-client.d.ts.map +1 -1
- package/dist/types/api/rest-api-client.d.ts +3 -0
- package/dist/types/api/rest-api-client.d.ts.map +1 -1
- package/dist/types/api/types.d.ts +9 -1
- package/dist/types/api/types.d.ts.map +1 -1
- package/dist/types/client/component-snapshot.d.ts +4 -2
- package/dist/types/client/component-snapshot.d.ts.map +1 -1
- package/dist/types/client/index.d.ts +0 -1
- package/dist/types/client/index.d.ts.map +1 -1
- package/dist/types/components/builtin/Form/types.d.ts +9 -9
- package/dist/types/components/builtin/Form/types.d.ts.map +1 -1
- package/dist/types/runtimes/react/components/MakeswiftComponent.d.ts +4 -1
- package/dist/types/runtimes/react/components/MakeswiftComponent.d.ts.map +1 -1
- package/dist/types/runtimes/react/server/components/snapshot-renderer.d.ts +1 -1
- package/dist/types/runtimes/react/server/components/snapshot-renderer.d.ts.map +1 -1
- package/dist/types/state/modules/read-only-documents.d.ts +8 -6
- package/dist/types/state/modules/read-only-documents.d.ts.map +1 -1
- package/dist/types/state/shared-api/actions.d.ts +2 -6
- package/dist/types/state/shared-api/actions.d.ts.map +1 -1
- package/package.json +2 -2
|
@@ -29,7 +29,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
29
29
|
var api_resources_client_exports = {};
|
|
30
30
|
__export(api_resources_client_exports, {
|
|
31
31
|
ApiResourcesClient: () => ApiResourcesClient,
|
|
32
|
-
CacheData: () => CacheData
|
|
32
|
+
CacheData: () => CacheData,
|
|
33
|
+
withTypename: () => withTypename
|
|
33
34
|
});
|
|
34
35
|
module.exports = __toCommonJS(api_resources_client_exports);
|
|
35
36
|
var ApiClientState = __toESM(require("../state/api-client/state"));
|
|
@@ -208,6 +209,7 @@ function withTypename(typename, resource) {
|
|
|
208
209
|
// Annotate the CommonJS export names for ESM import in node:
|
|
209
210
|
0 && (module.exports = {
|
|
210
211
|
ApiResourcesClient,
|
|
211
|
-
CacheData
|
|
212
|
+
CacheData,
|
|
213
|
+
withTypename
|
|
212
214
|
});
|
|
213
215
|
//# sourceMappingURL=api-resources-client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/api/api-resources-client.ts"],"sourcesContent":["import { type FetchableValue } from '@makeswift/controls'\n\nimport { type Store as ApiClientStore } from '../state/api-client/store'\nimport * as ApiClientState from '../state/api-client/state'\nimport { fetchAPIResource } from '../state/api-client/fetch-api-resource'\n\nimport {\n type File,\n type GlobalElement,\n type LocalizedGlobalElement,\n type Page,\n type PagePathnameSlice,\n type Site,\n type Snippet,\n type Swatch,\n type Table,\n type Typography,\n APIResourceType,\n} from './types'\n\nimport { type SiteVersion } from './site-version'\n\nexport type CacheData = ApiClientState.SerializedState\n\nexport const CacheData = {\n empty(): CacheData {\n return {\n apiResources: {},\n localizedResourcesMap: {},\n }\n },\n}\n\nexport abstract class ApiResourcesClient {\n readonly store: ApiClientStore\n readonly subscribe: ApiClientStore['subscribe']\n\n constructor({ store }: { store: ApiClientStore }) {\n this.store = store\n this.subscribe = this.store.subscribe\n }\n\n get cacheData(): CacheData {\n return ApiClientState.getSerializedState(this.store.getState())\n }\n\n async fetchSwatch(swatchId: string): Promise<Swatch | null> {\n const fetch = (id: string, version: SiteVersion | null) => this.fetchSwatchImpl(id, version)\n\n return await this.store.dispatch(fetchAPIResource(APIResourceType.Swatch, swatchId, fetch))\n }\n\n readSwatch(swatchId: string): Swatch | null {\n return ApiClientState.getAPIResource(this.store.getState(), APIResourceType.Swatch, swatchId)\n }\n\n resolveSwatch(swatchId: string | undefined): FetchableValue<Swatch | null> {\n return this.resolveResource(APIResourceType.Swatch, {\n id: swatchId,\n read: id => this.readSwatch(id),\n fetch: id => this.fetchSwatch(id),\n })\n }\n\n async fetchFile(fileId: string): Promise<File | null> {\n // The REST `files` endpoint doesn't return `__typename`, which the API resources store requires.\n const fetch = async (id: string, version: SiteVersion | null) =>\n withTypename(APIResourceType.File, await this.fetchFileImpl(id, version))\n\n return await this.store.dispatch(fetchAPIResource(APIResourceType.File, fileId, fetch))\n }\n\n readFile(fileId: string): File | null {\n return ApiClientState.getAPIResource(this.store.getState(), APIResourceType.File, fileId)\n }\n\n resolveFile(fileId: string | undefined): FetchableValue<File | null> {\n return this.resolveResource(APIResourceType.File, {\n id: fileId,\n read: id => this.readFile(id),\n fetch: id => this.fetchFile(id),\n })\n }\n\n async fetchTypography(typographyId: string): Promise<Typography | null> {\n const fetch = (id: string, version: SiteVersion | null) => this.fetchTypographyImpl(id, version)\n\n return await this.store.dispatch(\n fetchAPIResource(APIResourceType.Typography, typographyId, fetch),\n )\n }\n\n readTypography(typographyId: string): Typography | null {\n return ApiClientState.getAPIResource(\n this.store.getState(),\n APIResourceType.Typography,\n typographyId,\n )\n }\n\n resolveTypography(typographyId: string | undefined): FetchableValue<Typography | null> {\n return this.resolveResource(APIResourceType.Typography, {\n id: typographyId,\n read: id => this.readTypography(id),\n fetch: id => this.fetchTypography(id),\n })\n }\n\n async fetchGlobalElement(globalElementId: string): Promise<GlobalElement | null> {\n const fetch = (id: string, version: SiteVersion | null) =>\n this.fetchGlobalElementImpl(id, version)\n\n return await this.store.dispatch(\n fetchAPIResource(APIResourceType.GlobalElement, globalElementId, fetch),\n )\n }\n\n readGlobalElement(globalElementId: string): GlobalElement | null {\n return ApiClientState.getAPIResource(\n this.store.getState(),\n APIResourceType.GlobalElement,\n globalElementId,\n )\n }\n\n async fetchLocalizedGlobalElement({\n globalElementId,\n locale,\n }: {\n globalElementId: string\n locale: string\n }): Promise<LocalizedGlobalElement | null> {\n const fetch = (id: string, version: SiteVersion | null, locale: string | null | undefined) => {\n if (locale == null) throw new Error('Locale is required to fetch LocalizedGlobalElement')\n return this.fetchLocalizedGlobalElementImpl(id, version, locale)\n }\n\n return await this.store.dispatch(\n fetchAPIResource(APIResourceType.LocalizedGlobalElement, globalElementId, fetch, locale),\n )\n }\n\n readLocalizedGlobalElement({\n globalElementId,\n locale,\n }: {\n globalElementId: string\n locale: string\n }): LocalizedGlobalElement | null {\n return ApiClientState.getAPIResource(\n this.store.getState(),\n APIResourceType.LocalizedGlobalElement,\n globalElementId,\n locale,\n )\n }\n\n async fetchPagePathnameSlice({\n pageId,\n locale,\n }: {\n pageId: string\n locale: string | null\n }): Promise<PagePathnameSlice | null> {\n const fetch = (id: string, version: SiteVersion | null, locale: string | null | undefined) =>\n this.fetchPagePathnameSliceImpl(id, version, locale)\n\n return await this.store.dispatch(\n fetchAPIResource(APIResourceType.PagePathnameSlice, pageId, fetch, locale),\n )\n }\n\n readPagePathnameSlice({\n pageId,\n locale,\n }: {\n pageId: string\n locale: string | null\n }): PagePathnameSlice | null {\n return ApiClientState.getAPIResource(\n this.store.getState(),\n APIResourceType.PagePathnameSlice,\n pageId,\n locale,\n )\n }\n\n resolvePagePathnameSlice({\n pageId,\n locale,\n }: {\n pageId: string | undefined\n locale: string | null\n }): FetchableValue<PagePathnameSlice | null> {\n return this.resolveResource(APIResourceType.PagePathnameSlice, {\n id: pageId,\n read: id => this.readPagePathnameSlice({ pageId: id, locale }),\n fetch: id => this.fetchPagePathnameSlice({ pageId: id, locale }),\n })\n }\n\n resolveResource<R>(\n type: APIResourceType,\n {\n id,\n read,\n fetch,\n }: {\n id: string | undefined\n read: (id: string) => R | null\n fetch: (id: string) => Promise<R | null>\n },\n ): FetchableValue<R | null> {\n const _read = () => (id != null ? read(id) : null)\n let lastValue: R | null = null\n return {\n name: `${type}:${id}`,\n readStable: () => (lastValue = _read()),\n subscribe: (onUpdate: () => void) =>\n this.subscribe(() => {\n if (_read() !== lastValue) onUpdate()\n }),\n fetch: async () => (id != null ? fetch(id) : null),\n }\n }\n\n async fetchTable(tableId: string): Promise<Table | null> {\n // The REST `tables` endpoint doesn't return `__typename`, which the API resources store requires.\n const fetch = async (id: string, version: SiteVersion | null) =>\n withTypename(APIResourceType.Table, await this.fetchTableImpl(id, version))\n\n return await this.store.dispatch(fetchAPIResource(APIResourceType.Table, tableId, fetch))\n }\n\n readTable(tableId: string): Table | null {\n return ApiClientState.getAPIResource(this.store.getState(), APIResourceType.Table, tableId)\n }\n\n readSite(siteId: string): Site | null {\n return ApiClientState.getAPIResource(this.store.getState(), APIResourceType.Site, siteId)\n }\n\n readPage(pageId: string): Page | null {\n return ApiClientState.getAPIResource(this.store.getState(), APIResourceType.Page, pageId)\n }\n\n readSnippet(snippetId: string): Snippet | null {\n return ApiClientState.getAPIResource(this.store.getState(), APIResourceType.Snippet, snippetId)\n }\n\n protected abstract fetchSwatchImpl(\n id: string,\n version: SiteVersion | null,\n ): Promise<Swatch | null>\n\n protected abstract fetchFileImpl(id: string, version: SiteVersion | null): Promise<File | null>\n protected abstract fetchTypographyImpl(\n id: string,\n version: SiteVersion | null,\n ): Promise<Typography | null>\n\n protected abstract fetchGlobalElementImpl(\n id: string,\n version: SiteVersion | null,\n ): Promise<GlobalElement | null>\n\n protected abstract fetchLocalizedGlobalElementImpl(\n id: string,\n version: SiteVersion | null,\n locale: string,\n ): Promise<LocalizedGlobalElement | null>\n\n protected abstract fetchPagePathnameSliceImpl(\n id: string,\n version: SiteVersion | null,\n locale: string | null | undefined,\n ): Promise<PagePathnameSlice | null>\n\n protected abstract fetchTableImpl(id: string, version: SiteVersion | null): Promise<Table | null>\n}\n\nfunction withTypename<T extends APIResourceType, R extends object>(\n typename: T,\n resource: R |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AAAA,IACA;AAAA,IACA;AAAA,EACF,GAK0B;AAC1B,UAAM,QAAQ,MAAO,MAAM,OAAO,KAAK,EAAE,IAAI;AAC7C,QAAI,YAAsB;AAC1B,WAAO;AAAA,MACL,MAAM,GAAG,IAAI,IAAI,EAAE;AAAA,MACnB,YAAY,MAAO,YAAY,MAAM;AAAA,MACrC,WAAW,CAAC,aACV,KAAK,UAAU,MAAM;AACnB,YAAI,MAAM,MAAM;AAAW,mBAAS;AAAA,MACtC,CAAC;AAAA,MACH,OAAO,YAAa,MAAM,OAAO,MAAM,EAAE,IAAI;AAAA,IAC/C;AAAA,EACF;AAAA,EAEA,MAAM,WAAW,SAAwC;AAEvD,UAAM,QAAQ,OAAO,IAAY,YAC/B,aAAa,6BAAgB,OAAO,MAAM,KAAK,eAAe,IAAI,OAAO,CAAC;AAE5E,WAAO,MAAM,KAAK,MAAM,aAAS,4CAAiB,6BAAgB,OAAO,SAAS,KAAK,CAAC;AAAA,EAC1F;AAAA,EAEA,UAAU,SAA+B;AACvC,WAAO,eAAe,eAAe,KAAK,MAAM,SAAS,GAAG,6BAAgB,OAAO,OAAO;AAAA,EAC5F;AAAA,EAEA,SAAS,QAA6B;AACpC,WAAO,eAAe,eAAe,KAAK,MAAM,SAAS,GAAG,6BAAgB,MAAM,MAAM;AAAA,EAC1F;AAAA,EAEA,SAAS,QAA6B;AACpC,WAAO,eAAe,eAAe,KAAK,MAAM,SAAS,GAAG,6BAAgB,MAAM,MAAM;AAAA,EAC1F;AAAA,EAEA,YAAY,WAAmC;AAC7C,WAAO,eAAe,eAAe,KAAK,MAAM,SAAS,GAAG,6BAAgB,SAAS,SAAS;AAAA,EAChG;AA+BF;AAEA,SAAS,aACP,UACA,UACgC;AAChC,SAAO,YAAY,OAAO,OAAO,EAAE,GAAG,UAAU,YAAY,SAAS;AACvE;","names":["locale"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/api/api-resources-client.ts"],"sourcesContent":["import { type FetchableValue } from '@makeswift/controls'\n\nimport { type Store as ApiClientStore } from '../state/api-client/store'\nimport * as ApiClientState from '../state/api-client/state'\nimport { fetchAPIResource } from '../state/api-client/fetch-api-resource'\n\nimport {\n type File,\n type GlobalElement,\n type LocalizedGlobalElement,\n type Page,\n type PagePathnameSlice,\n type Site,\n type Snippet,\n type Swatch,\n type Table,\n type Typography,\n APIResourceType,\n} from './types'\n\nimport { type SiteVersion } from './site-version'\n\nexport type CacheData = ApiClientState.SerializedState\n\nexport const CacheData = {\n empty(): CacheData {\n return {\n apiResources: {},\n localizedResourcesMap: {},\n }\n },\n}\n\nexport abstract class ApiResourcesClient {\n readonly store: ApiClientStore\n readonly subscribe: ApiClientStore['subscribe']\n\n constructor({ store }: { store: ApiClientStore }) {\n this.store = store\n this.subscribe = this.store.subscribe\n }\n\n get cacheData(): CacheData {\n return ApiClientState.getSerializedState(this.store.getState())\n }\n\n async fetchSwatch(swatchId: string): Promise<Swatch | null> {\n const fetch = (id: string, version: SiteVersion | null) => this.fetchSwatchImpl(id, version)\n\n return await this.store.dispatch(fetchAPIResource(APIResourceType.Swatch, swatchId, fetch))\n }\n\n readSwatch(swatchId: string): Swatch | null {\n return ApiClientState.getAPIResource(this.store.getState(), APIResourceType.Swatch, swatchId)\n }\n\n resolveSwatch(swatchId: string | undefined): FetchableValue<Swatch | null> {\n return this.resolveResource(APIResourceType.Swatch, {\n id: swatchId,\n read: id => this.readSwatch(id),\n fetch: id => this.fetchSwatch(id),\n })\n }\n\n async fetchFile(fileId: string): Promise<File | null> {\n // The REST `files` endpoint doesn't return `__typename`, which the API resources store requires.\n const fetch = async (id: string, version: SiteVersion | null) =>\n withTypename(APIResourceType.File, await this.fetchFileImpl(id, version))\n\n return await this.store.dispatch(fetchAPIResource(APIResourceType.File, fileId, fetch))\n }\n\n readFile(fileId: string): File | null {\n return ApiClientState.getAPIResource(this.store.getState(), APIResourceType.File, fileId)\n }\n\n resolveFile(fileId: string | undefined): FetchableValue<File | null> {\n return this.resolveResource(APIResourceType.File, {\n id: fileId,\n read: id => this.readFile(id),\n fetch: id => this.fetchFile(id),\n })\n }\n\n async fetchTypography(typographyId: string): Promise<Typography | null> {\n const fetch = (id: string, version: SiteVersion | null) => this.fetchTypographyImpl(id, version)\n\n return await this.store.dispatch(\n fetchAPIResource(APIResourceType.Typography, typographyId, fetch),\n )\n }\n\n readTypography(typographyId: string): Typography | null {\n return ApiClientState.getAPIResource(\n this.store.getState(),\n APIResourceType.Typography,\n typographyId,\n )\n }\n\n resolveTypography(typographyId: string | undefined): FetchableValue<Typography | null> {\n return this.resolveResource(APIResourceType.Typography, {\n id: typographyId,\n read: id => this.readTypography(id),\n fetch: id => this.fetchTypography(id),\n })\n }\n\n async fetchGlobalElement(globalElementId: string): Promise<GlobalElement | null> {\n const fetch = (id: string, version: SiteVersion | null) =>\n this.fetchGlobalElementImpl(id, version)\n\n return await this.store.dispatch(\n fetchAPIResource(APIResourceType.GlobalElement, globalElementId, fetch),\n )\n }\n\n readGlobalElement(globalElementId: string): GlobalElement | null {\n return ApiClientState.getAPIResource(\n this.store.getState(),\n APIResourceType.GlobalElement,\n globalElementId,\n )\n }\n\n async fetchLocalizedGlobalElement({\n globalElementId,\n locale,\n }: {\n globalElementId: string\n locale: string\n }): Promise<LocalizedGlobalElement | null> {\n const fetch = (id: string, version: SiteVersion | null, locale: string | null | undefined) => {\n if (locale == null) throw new Error('Locale is required to fetch LocalizedGlobalElement')\n return this.fetchLocalizedGlobalElementImpl(id, version, locale)\n }\n\n return await this.store.dispatch(\n fetchAPIResource(APIResourceType.LocalizedGlobalElement, globalElementId, fetch, locale),\n )\n }\n\n readLocalizedGlobalElement({\n globalElementId,\n locale,\n }: {\n globalElementId: string\n locale: string\n }): LocalizedGlobalElement | null {\n return ApiClientState.getAPIResource(\n this.store.getState(),\n APIResourceType.LocalizedGlobalElement,\n globalElementId,\n locale,\n )\n }\n\n async fetchPagePathnameSlice({\n pageId,\n locale,\n }: {\n pageId: string\n locale: string | null\n }): Promise<PagePathnameSlice | null> {\n const fetch = (id: string, version: SiteVersion | null, locale: string | null | undefined) =>\n this.fetchPagePathnameSliceImpl(id, version, locale)\n\n return await this.store.dispatch(\n fetchAPIResource(APIResourceType.PagePathnameSlice, pageId, fetch, locale),\n )\n }\n\n readPagePathnameSlice({\n pageId,\n locale,\n }: {\n pageId: string\n locale: string | null\n }): PagePathnameSlice | null {\n return ApiClientState.getAPIResource(\n this.store.getState(),\n APIResourceType.PagePathnameSlice,\n pageId,\n locale,\n )\n }\n\n resolvePagePathnameSlice({\n pageId,\n locale,\n }: {\n pageId: string | undefined\n locale: string | null\n }): FetchableValue<PagePathnameSlice | null> {\n return this.resolveResource(APIResourceType.PagePathnameSlice, {\n id: pageId,\n read: id => this.readPagePathnameSlice({ pageId: id, locale }),\n fetch: id => this.fetchPagePathnameSlice({ pageId: id, locale }),\n })\n }\n\n resolveResource<R>(\n type: APIResourceType,\n {\n id,\n read,\n fetch,\n }: {\n id: string | undefined\n read: (id: string) => R | null\n fetch: (id: string) => Promise<R | null>\n },\n ): FetchableValue<R | null> {\n const _read = () => (id != null ? read(id) : null)\n let lastValue: R | null = null\n return {\n name: `${type}:${id}`,\n readStable: () => (lastValue = _read()),\n subscribe: (onUpdate: () => void) =>\n this.subscribe(() => {\n if (_read() !== lastValue) onUpdate()\n }),\n fetch: async () => (id != null ? fetch(id) : null),\n }\n }\n\n async fetchTable(tableId: string): Promise<Table | null> {\n // The REST `tables` endpoint doesn't return `__typename`, which the API resources store requires.\n const fetch = async (id: string, version: SiteVersion | null) =>\n withTypename(APIResourceType.Table, await this.fetchTableImpl(id, version))\n\n return await this.store.dispatch(fetchAPIResource(APIResourceType.Table, tableId, fetch))\n }\n\n readTable(tableId: string): Table | null {\n return ApiClientState.getAPIResource(this.store.getState(), APIResourceType.Table, tableId)\n }\n\n readSite(siteId: string): Site | null {\n return ApiClientState.getAPIResource(this.store.getState(), APIResourceType.Site, siteId)\n }\n\n readPage(pageId: string): Page | null {\n return ApiClientState.getAPIResource(this.store.getState(), APIResourceType.Page, pageId)\n }\n\n readSnippet(snippetId: string): Snippet | null {\n return ApiClientState.getAPIResource(this.store.getState(), APIResourceType.Snippet, snippetId)\n }\n\n protected abstract fetchSwatchImpl(\n id: string,\n version: SiteVersion | null,\n ): Promise<Swatch | null>\n\n protected abstract fetchFileImpl(id: string, version: SiteVersion | null): Promise<File | null>\n protected abstract fetchTypographyImpl(\n id: string,\n version: SiteVersion | null,\n ): Promise<Typography | null>\n\n protected abstract fetchGlobalElementImpl(\n id: string,\n version: SiteVersion | null,\n ): Promise<GlobalElement | null>\n\n protected abstract fetchLocalizedGlobalElementImpl(\n id: string,\n version: SiteVersion | null,\n locale: string,\n ): Promise<LocalizedGlobalElement | null>\n\n protected abstract fetchPagePathnameSliceImpl(\n id: string,\n version: SiteVersion | null,\n locale: string | null | undefined,\n ): Promise<PagePathnameSlice | null>\n\n protected abstract fetchTableImpl(id: string, version: SiteVersion | null): Promise<Table | null>\n}\n\nexport function withTypename<T extends APIResourceType, R extends object>(\n typename: T,\n resource: R | null,\n): (R & { __typename: T }) | null {\n return resource == null ? null : { ...resource, __typename: typename }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,qBAAgC;AAChC,gCAAiC;AAEjC,mBAYO;AAMA,MAAM,YAAY;AAAA,EACvB,QAAmB;AACjB,WAAO;AAAA,MACL,cAAc,CAAC;AAAA,MACf,uBAAuB,CAAC;AAAA,IAC1B;AAAA,EACF;AACF;AAEO,MAAe,mBAAmB;AAAA,EAC9B;AAAA,EACA;AAAA,EAET,YAAY,EAAE,MAAM,GAA8B;AAChD,SAAK,QAAQ;AACb,SAAK,YAAY,KAAK,MAAM;AAAA,EAC9B;AAAA,EAEA,IAAI,YAAuB;AACzB,WAAO,eAAe,mBAAmB,KAAK,MAAM,SAAS,CAAC;AAAA,EAChE;AAAA,EAEA,MAAM,YAAY,UAA0C;AAC1D,UAAM,QAAQ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CAAC;AAAA,EAC1F;AAAA,EAEA,UAAU,SAA+B;AACvC,WAAO,eAAe,eAAe,KAAK,MAAM,SAAS,GAAG,6BAAgB,OAAO,OAAO;AAAA,EAC5F;AAAA,EAEA,SAAS,QAA6B;AACpC,WAAO,eAAe,eAAe,KAAK,MAAM,SAAS,GAAG,6BAAgB,MAAM,MAAM;AAAA,EAC1F;AAAA,EAEA,SAAS,QAA6B;AACpC,WAAO,eAAe,eAAe,KAAK,MAAM,SAAS,GAAG,6BAAgB,MAAM,MAAM;AAAA,EAC1F;AAAA,EAEA,YAAY,WAAmC;AAC7C,WAAO,eAAe,eAAe,KAAK,MAAM,SAAS,GAAG,6BAAgB,SAAS,SAAS;AAAA,EAChG;AA+BF;AAEO,SAAS,aACd,UACA,UACgC;AAChC,SAAO,YAAY,OAAO,OAAO,EAAE,GAAG,UAAU,YAAY,SAAS;AACvE;","names":["locale"]}
|
|
@@ -27,7 +27,7 @@ class MakeswiftGraphQLApiClient {
|
|
|
27
27
|
graphqlClient;
|
|
28
28
|
constructor({ endpoint }) {
|
|
29
29
|
this.graphqlClient = new import_client.GraphQLClient(endpoint, {
|
|
30
|
-
"makeswift-runtime-version": "0.29.
|
|
30
|
+
"makeswift-runtime-version": "0.29.3-canary.1"
|
|
31
31
|
});
|
|
32
32
|
}
|
|
33
33
|
async getUnversionedResources({
|
|
@@ -35,7 +35,14 @@ __export(rest_api_client_exports, {
|
|
|
35
35
|
module.exports = __toCommonJS(rest_api_client_exports);
|
|
36
36
|
var import_ky = __toESM(require("./ky"));
|
|
37
37
|
var Schema = __toESM(require("./schema"));
|
|
38
|
-
const
|
|
38
|
+
const MAX_BULK_IDS_PER_REQUEST = 100;
|
|
39
|
+
function chunkRequestIds(ids) {
|
|
40
|
+
const batches = [];
|
|
41
|
+
for (let i = 0; i < ids.length; i += MAX_BULK_IDS_PER_REQUEST) {
|
|
42
|
+
batches.push(ids.slice(i, i + MAX_BULK_IDS_PER_REQUEST));
|
|
43
|
+
}
|
|
44
|
+
return batches;
|
|
45
|
+
}
|
|
39
46
|
const RetryBackoffConfig = {
|
|
40
47
|
MaxAttempts: 3,
|
|
41
48
|
MaxDelayMs: 5e3
|
|
@@ -146,10 +153,7 @@ class MakeswiftRestAPIClient {
|
|
|
146
153
|
}
|
|
147
154
|
return await response.json();
|
|
148
155
|
};
|
|
149
|
-
const batches =
|
|
150
|
-
for (let i = 0; i < globalElementIds.length; i += MAX_GLOBAL_ELEMENTS_PER_REQUEST) {
|
|
151
|
-
batches.push(globalElementIds.slice(i, i + MAX_GLOBAL_ELEMENTS_PER_REQUEST));
|
|
152
|
-
}
|
|
156
|
+
const batches = chunkRequestIds(globalElementIds);
|
|
153
157
|
const results = await Promise.all(batches.map(getGlobalElementsBatch));
|
|
154
158
|
return results.flat();
|
|
155
159
|
}
|
|
@@ -184,6 +188,36 @@ class MakeswiftRestAPIClient {
|
|
|
184
188
|
const table = await response.json();
|
|
185
189
|
return table;
|
|
186
190
|
}
|
|
191
|
+
async getFiles(fileIds) {
|
|
192
|
+
if (fileIds.length === 0)
|
|
193
|
+
return [];
|
|
194
|
+
const batches = chunkRequestIds(fileIds);
|
|
195
|
+
const results = await Promise.all(
|
|
196
|
+
batches.map((ids) => this.getUnversionedResourcesBatch("files", ids))
|
|
197
|
+
);
|
|
198
|
+
return results.flat();
|
|
199
|
+
}
|
|
200
|
+
async getTables(tableIds) {
|
|
201
|
+
if (tableIds.length === 0)
|
|
202
|
+
return [];
|
|
203
|
+
const batches = chunkRequestIds(tableIds);
|
|
204
|
+
const results = await Promise.all(
|
|
205
|
+
batches.map((ids) => this.getUnversionedResourcesBatch("tables", ids))
|
|
206
|
+
);
|
|
207
|
+
return results.flat();
|
|
208
|
+
}
|
|
209
|
+
async getUnversionedResourcesBatch(resource, ids) {
|
|
210
|
+
const url = new URL(`v1/${resource}/bulk`, this.apiOrigin);
|
|
211
|
+
ids.forEach((id) => url.searchParams.append("ids", id));
|
|
212
|
+
const response = await this.fetch(url.pathname + url.search, null);
|
|
213
|
+
if (!response.ok) {
|
|
214
|
+
const failedBody = await failedResponseBody(response);
|
|
215
|
+
throw new RestApiClientError(`Failed to get ${resource} for [${ids.join(", ")}]`, response, {
|
|
216
|
+
body: failedBody
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
return await response.json();
|
|
220
|
+
}
|
|
187
221
|
async getPagePathnameSlices(pageIds, siteVersion, { locale }) {
|
|
188
222
|
if (pageIds.length === 0)
|
|
189
223
|
return [];
|
|
@@ -223,7 +257,7 @@ class MakeswiftRestAPIClient {
|
|
|
223
257
|
const requestHeaders = new Headers({
|
|
224
258
|
"x-api-key": this.apiKey,
|
|
225
259
|
"makeswift-site-api-key": this.apiKey,
|
|
226
|
-
"makeswift-runtime-version": "0.29.
|
|
260
|
+
"makeswift-runtime-version": "0.29.3-canary.1"
|
|
227
261
|
});
|
|
228
262
|
if (siteVersion?.token) {
|
|
229
263
|
requestUrl.searchParams.set("version", siteVersion.version);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/api/rest-api-client.ts"],"sourcesContent":["import ky, { HTTPError, isHTTPError, type KyInstance } from './ky'\n\nimport {\n type File,\n type GlobalElement,\n type LocalizedGlobalElement,\n type PagePathnameSlice,\n type Swatch,\n type Table,\n type Typography,\n type HttpFetch,\n} from './types'\n\nimport { type SiteVersion } from './site-version'\nimport * as Schema from './schema'\n\nexport type GlobalElementWithLocalized = {\n base: GlobalElement | null\n localized: LocalizedGlobalElement | null\n}\n\nconst MAX_GLOBAL_ELEMENTS_PER_REQUEST = 100\n\nconst RetryBackoffConfig = {\n MaxAttempts: 3,\n MaxDelayMs: 5_000,\n}\n\nexport class MakeswiftRestAPIClient {\n private _fetch: KyInstance\n\n readonly apiKey: string\n readonly apiOrigin: string\n\n constructor({\n fetch,\n apiKey,\n apiOrigin,\n }: {\n fetch: HttpFetch\n apiKey: string\n apiOrigin: string\n }) {\n this._fetch = ky.create({\n fetch,\n timeout: false,\n retry: {\n statusCodes: [408, 429, 500, 502, 503, 504],\n limit: RetryBackoffConfig.MaxAttempts,\n backoffLimit: RetryBackoffConfig.MaxDelayMs,\n delay: attemptCount => 2 ** (attemptCount - 1) * 1000,\n jitter: true,\n },\n hooks: {\n beforeRetry: [\n async ({ request, error, retryCount }) => {\n console.warn(\n `Request to ${request.url} failed with ${error}. Retrying (${retryCount}/${RetryBackoffConfig.MaxAttempts})`,\n )\n // Drain the response body before retrying so we don't leak unconsumed\n // response bodies (see the comment on `failedResponseBody` below).\n if (isHTTPError(error)) await failedResponseBody(error.response)\n },\n ],\n },\n })\n\n this.apiKey = apiKey\n this.apiOrigin = apiOrigin\n }\n\n async getSwatch(swatchId: string, siteVersion: SiteVersion | null): Promise<Swatch | null> {\n const response = await this.fetch(`v3/swatches/${swatchId}`, siteVersion)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return null\n\n throw new RestApiClientError(`Failed to get swatch '${swatchId}'`, response, {\n body: failedBody,\n siteVersion,\n })\n }\n\n const swatch = await response.json()\n\n return swatch\n }\n\n async getFile(fileId: string): Promise<File | null> {\n const response = await this.fetch(`v1/files/${fileId}`, null)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return null\n\n throw new RestApiClientError(`Failed to get file '${fileId}'`, response, {\n body: failedBody,\n })\n }\n\n const file = await response.json()\n\n return file\n }\n\n async getTypography(\n typographyId: string,\n siteVersion: SiteVersion | null,\n ): Promise<Typography | null> {\n const response = await this.fetch(`v3/typographies/${typographyId}`, siteVersion)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return null\n\n throw new RestApiClientError(`Failed to get typography '${typographyId}'`, response, {\n body: failedBody,\n siteVersion,\n })\n }\n\n const typography = await response.json()\n\n return typography\n }\n\n async getGlobalElement(\n globalElementId: string,\n siteVersion: SiteVersion | null,\n ): Promise<GlobalElement | null> {\n const response = await this.fetch(`v3/global-elements/${globalElementId}`, siteVersion)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return null\n\n throw new RestApiClientError(`Failed to get global element '${globalElementId}'`, response, {\n body: failedBody,\n siteVersion,\n })\n }\n\n const globalElement = await response.json()\n\n return globalElement\n }\n\n async getGlobalElements(\n globalElementIds: string[],\n siteVersion: SiteVersion | null,\n { locale }: { locale?: string | null } = {},\n ): Promise<GlobalElementWithLocalized[]> {\n const getGlobalElementsBatch = async (ids: string[]): Promise<GlobalElementWithLocalized[]> => {\n const url = new URL(`content/v1/global-elements/bulk`, this.apiOrigin)\n\n ids.forEach(id => url.searchParams.append('ids', id))\n if (locale != null) url.searchParams.set('locale', locale)\n\n const response = await this.fetch(url.pathname + url.search, siteVersion)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n\n throw new RestApiClientError(\n `Failed to get global elements for [${ids.join(', ')}]`,\n response,\n { body: failedBody, siteVersion, locale },\n )\n }\n\n return await response.json()\n }\n\n const batches: string[][] = []\n\n for (let i = 0; i < globalElementIds.length; i += MAX_GLOBAL_ELEMENTS_PER_REQUEST) {\n batches.push(globalElementIds.slice(i, i + MAX_GLOBAL_ELEMENTS_PER_REQUEST))\n }\n\n const results = await Promise.all(batches.map(getGlobalElementsBatch))\n\n return results.flat()\n }\n\n async getLocalizedGlobalElement(\n globalElementId: string,\n locale: string,\n siteVersion: SiteVersion | null,\n ): Promise<LocalizedGlobalElement | null> {\n const response = await this.fetch(\n `v3/localized-global-elements/${globalElementId}?locale=${locale}`,\n siteVersion,\n )\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return null\n\n throw new RestApiClientError(\n `Failed to get localized global element '${globalElementId}'`,\n response,\n { body: failedBody, siteVersion, locale },\n )\n }\n\n const localizedGlobalElement = await response.json()\n\n return localizedGlobalElement\n }\n\n async getTable(tableId: string): Promise<Table | null> {\n const response = await this.fetch(`v1/tables/${tableId}`, null)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return null\n\n throw new RestApiClientError(`Failed to get table '${tableId}'`, response, {\n body: failedBody,\n })\n }\n\n const table = await response.json()\n\n return table\n }\n\n async getPagePathnameSlices(\n pageIds: string[],\n siteVersion: SiteVersion | null,\n { locale }: { locale?: string | null },\n ): Promise<(PagePathnameSlice | null)[]> {\n if (pageIds.length === 0) return []\n\n const url = new URL(`v3/page-pathname-slices/bulk`, this.apiOrigin)\n\n pageIds.forEach(id => url.searchParams.append('ids', id))\n if (locale != null) url.searchParams.set('locale', locale)\n\n const response = await this.fetch(url.pathname + url.search, siteVersion)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return []\n\n throw new RestApiClientError(\n `Failed to get page pathname slice(s) for ${pageIds.join(', ')}`,\n response,\n { body: failedBody, siteVersion, locale },\n )\n }\n\n const json = await response.json()\n\n const pagePathnameSlices = Schema.pagePathnameSlices.parse(json)\n\n // We're mapping the basePageId to be the id, because we're still using the GraphQL\n // fragment as our APIResource. The id on the APIResource needs to match the pageId\n // so that we can find the corresponding page pathname slice when we call getPagePathnameSlice(pageId).\n // TODO: Update this once we move away from the GraphQL fragments.\n return pagePathnameSlices.map(pagePathnameSlice => {\n if (pagePathnameSlice == null) return null\n\n return {\n ...pagePathnameSlice,\n id: pagePathnameSlice.basePageId,\n localizedPathname: pagePathnameSlice.localizedPathname ?? null,\n }\n })\n }\n\n async getPagePathnameSlice(\n pageId: string,\n siteVersion: SiteVersion | null,\n { locale }: { locale?: string | null } = {},\n ): Promise<PagePathnameSlice | null> {\n const pagePathnameSlices = await this.getPagePathnameSlices([pageId], siteVersion, { locale })\n\n return pagePathnameSlices.at(0) ?? null\n }\n\n protected async fetch(\n path: string,\n siteVersion: SiteVersion | null,\n init?: RequestInit,\n ): Promise<Response> {\n const requestUrl = new URL(path, this.apiOrigin)\n\n const requestHeaders = new Headers({\n 'x-api-key': this.apiKey,\n 'makeswift-site-api-key': this.apiKey,\n 'makeswift-runtime-version': PACKAGE_VERSION,\n })\n\n if (siteVersion?.token) {\n requestUrl.searchParams.set('version', siteVersion.version)\n requestHeaders.set('makeswift-preview-token', siteVersion.token)\n }\n\n if (init?.headers) {\n new Headers(init.headers).forEach((value, key) => {\n requestHeaders.set(key, value)\n })\n }\n\n try {\n return await this._fetch(requestUrl.toString(), {\n ...init,\n headers: requestHeaders,\n ...(siteVersion != null ? { cache: 'no-store' } : {}),\n })\n } catch (error) {\n if (error instanceof HTTPError) return error.response\n throw error\n }\n }\n}\n\n// This function attempts to consume the response body of a failed response, and\n// returns either the parsed JSON or raw text. This is useful for logging more\n// detailed error information when an API request fails.\n//\n// Cloudflare Worker Note: The Cloudflare Worker runtime has automatic deadlock\n// prevention (in the form of auto-cancelling responses) that triggers when too\n// many response bodies are unconsumed. This applies for error responses as\n// well. As such, in this client we use this function to consume the response\n// body whenever the request fails, even if we don't end up logging the body\n// itself, to avoid hitting the deadlock prevention.\nexport async function failedResponseBody(response: Response): Promise<unknown> {\n try {\n const text = await response.text()\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n } catch (e) {\n return `Failed to extract response body: ${e}`\n }\n}\n\nfunction responseError(response: Response): string {\n return `${response.status} ${response.statusText}`\n}\n\nexport class RestApiClientError extends Error {\n readonly status: number\n\n constructor(message: string, response: Response, cause: Record<string, unknown>) {\n super(`${message}: ${responseError(response)}`, { cause })\n\n this.name = 'RestApiClientError'\n this.status = response.status\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAA4D;AAc5D,aAAwB;AAOxB,MAAM,kCAAkC;AAExC,MAAM,qBAAqB;AAAA,EACzB,aAAa;AAAA,EACb,YAAY;AACd;AAEO,MAAM,uBAAuB;AAAA,EAC1B;AAAA,EAEC;AAAA,EACA;AAAA,EAET,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAIG;AACD,SAAK,SAAS,UAAAA,QAAG,OAAO;AAAA,MAC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,MAClB,0BAA0B,KAAK;AAAA,MAC/B,6BAA6B;AAAA,IAC/B,CAAC;AAED,QAAI,aAAa,OAAO;AACtB,iBAAW,aAAa,IAAI,WAAW,YAAY,OAAO;AAC1D,qBAAe,IAAI,2BAA2B,YAAY,KAAK;AAAA,IACjE;AAEA,QAAI,MAAM,SAAS;AACjB,UAAI,QAAQ,KAAK,OAAO,EAAE,QAAQ,CAAC,OAAO,QAAQ;AAChD,uBAAe,IAAI,KAAK,KAAK;AAAA,MAC/B,CAAC;AAAA,IACH;AAEA,QAAI;AACF,aAAO,MAAM,KAAK,OAAO,WAAW,SAAS,GAAG;AAAA,QAC9C,GAAG;AAAA,QACH,SAAS;AAAA,QACT,GAAI,eAAe,OAAO,EAAE,OAAO,WAAW,IAAI,CAAC;AAAA,MACrD,CAAC;AAAA,IACH,SAAS,OAAO;AACd,UAAI,iBAAiB;AAAW,eAAO,MAAM;AAC7C,YAAM;AAAA,IACR;AAAA,EACF;AACF;AAYA,eAAsB,mBAAmB,UAAsC;AAC7E,MAAI;AACF,UAAM,OAAO,MAAM,SAAS,KAAK;AACjC,QAAI;AACF,aAAO,KAAK,MAAM,IAAI;AAAA,IACxB,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF,SAAS,GAAG;AACV,WAAO,oCAAoC,CAAC;AAAA,EAC9C;AACF;AAEA,SAAS,cAAc,UAA4B;AACjD,SAAO,GAAG,SAAS,MAAM,IAAI,SAAS,UAAU;AAClD;AAEO,MAAM,2BAA2B,MAAM;AAAA,EACnC;AAAA,EAET,YAAY,SAAiB,UAAoB,OAAgC;AAC/E,UAAM,GAAG,OAAO,KAAK,cAAc,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;AAEzD,SAAK,OAAO;AACZ,SAAK,SAAS,SAAS;AAAA,EACzB;AACF;","names":["ky"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/api/rest-api-client.ts"],"sourcesContent":["import ky, { HTTPError, isHTTPError, type KyInstance } from './ky'\n\nimport {\n type File,\n type GlobalElement,\n type LocalizedGlobalElement,\n type PagePathnameSlice,\n type Swatch,\n type Table,\n type Typography,\n type HttpFetch,\n} from './types'\n\nimport { type SiteVersion } from './site-version'\nimport * as Schema from './schema'\n\nexport type GlobalElementWithLocalized = {\n base: GlobalElement | null\n localized: LocalizedGlobalElement | null\n}\n\nconst MAX_BULK_IDS_PER_REQUEST = 100\n\nfunction chunkRequestIds(ids: string[]): string[][] {\n const batches: string[][] = []\n\n for (let i = 0; i < ids.length; i += MAX_BULK_IDS_PER_REQUEST) {\n batches.push(ids.slice(i, i + MAX_BULK_IDS_PER_REQUEST))\n }\n\n return batches\n}\n\nconst RetryBackoffConfig = {\n MaxAttempts: 3,\n MaxDelayMs: 5_000,\n}\n\nexport class MakeswiftRestAPIClient {\n private _fetch: KyInstance\n\n readonly apiKey: string\n readonly apiOrigin: string\n\n constructor({\n fetch,\n apiKey,\n apiOrigin,\n }: {\n fetch: HttpFetch\n apiKey: string\n apiOrigin: string\n }) {\n this._fetch = ky.create({\n fetch,\n timeout: false,\n retry: {\n statusCodes: [408, 429, 500, 502, 503, 504],\n limit: RetryBackoffConfig.MaxAttempts,\n backoffLimit: RetryBackoffConfig.MaxDelayMs,\n delay: attemptCount => 2 ** (attemptCount - 1) * 1000,\n jitter: true,\n },\n hooks: {\n beforeRetry: [\n async ({ request, error, retryCount }) => {\n console.warn(\n `Request to ${request.url} failed with ${error}. Retrying (${retryCount}/${RetryBackoffConfig.MaxAttempts})`,\n )\n // Drain the response body before retrying so we don't leak unconsumed\n // response bodies (see the comment on `failedResponseBody` below).\n if (isHTTPError(error)) await failedResponseBody(error.response)\n },\n ],\n },\n })\n\n this.apiKey = apiKey\n this.apiOrigin = apiOrigin\n }\n\n async getSwatch(swatchId: string, siteVersion: SiteVersion | null): Promise<Swatch | null> {\n const response = await this.fetch(`v3/swatches/${swatchId}`, siteVersion)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return null\n\n throw new RestApiClientError(`Failed to get swatch '${swatchId}'`, response, {\n body: failedBody,\n siteVersion,\n })\n }\n\n const swatch = await response.json()\n\n return swatch\n }\n\n async getFile(fileId: string): Promise<File | null> {\n const response = await this.fetch(`v1/files/${fileId}`, null)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return null\n\n throw new RestApiClientError(`Failed to get file '${fileId}'`, response, {\n body: failedBody,\n })\n }\n\n const file = await response.json()\n\n return file\n }\n\n async getTypography(\n typographyId: string,\n siteVersion: SiteVersion | null,\n ): Promise<Typography | null> {\n const response = await this.fetch(`v3/typographies/${typographyId}`, siteVersion)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return null\n\n throw new RestApiClientError(`Failed to get typography '${typographyId}'`, response, {\n body: failedBody,\n siteVersion,\n })\n }\n\n const typography = await response.json()\n\n return typography\n }\n\n async getGlobalElement(\n globalElementId: string,\n siteVersion: SiteVersion | null,\n ): Promise<GlobalElement | null> {\n const response = await this.fetch(`v3/global-elements/${globalElementId}`, siteVersion)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return null\n\n throw new RestApiClientError(`Failed to get global element '${globalElementId}'`, response, {\n body: failedBody,\n siteVersion,\n })\n }\n\n const globalElement = await response.json()\n\n return globalElement\n }\n\n async getGlobalElements(\n globalElementIds: string[],\n siteVersion: SiteVersion | null,\n { locale }: { locale?: string | null } = {},\n ): Promise<GlobalElementWithLocalized[]> {\n const getGlobalElementsBatch = async (ids: string[]): Promise<GlobalElementWithLocalized[]> => {\n const url = new URL(`content/v1/global-elements/bulk`, this.apiOrigin)\n\n ids.forEach(id => url.searchParams.append('ids', id))\n if (locale != null) url.searchParams.set('locale', locale)\n\n const response = await this.fetch(url.pathname + url.search, siteVersion)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n\n throw new RestApiClientError(\n `Failed to get global elements for [${ids.join(', ')}]`,\n response,\n { body: failedBody, siteVersion, locale },\n )\n }\n\n return await response.json()\n }\n\n const batches = chunkRequestIds(globalElementIds)\n\n const results = await Promise.all(batches.map(getGlobalElementsBatch))\n\n return results.flat()\n }\n\n async getLocalizedGlobalElement(\n globalElementId: string,\n locale: string,\n siteVersion: SiteVersion | null,\n ): Promise<LocalizedGlobalElement | null> {\n const response = await this.fetch(\n `v3/localized-global-elements/${globalElementId}?locale=${locale}`,\n siteVersion,\n )\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return null\n\n throw new RestApiClientError(\n `Failed to get localized global element '${globalElementId}'`,\n response,\n { body: failedBody, siteVersion, locale },\n )\n }\n\n const localizedGlobalElement = await response.json()\n\n return localizedGlobalElement\n }\n\n async getTable(tableId: string): Promise<Table | null> {\n const response = await this.fetch(`v1/tables/${tableId}`, null)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return null\n\n throw new RestApiClientError(`Failed to get table '${tableId}'`, response, {\n body: failedBody,\n })\n }\n\n const table = await response.json()\n\n return table\n }\n\n async getFiles(fileIds: string[]): Promise<(File | null)[]> {\n if (fileIds.length === 0) return []\n\n const batches = chunkRequestIds(fileIds)\n\n const results = await Promise.all(\n batches.map(ids => this.getUnversionedResourcesBatch<File>('files', ids)),\n )\n\n return results.flat()\n }\n\n async getTables(tableIds: string[]): Promise<(Table | null)[]> {\n if (tableIds.length === 0) return []\n\n const batches = chunkRequestIds(tableIds)\n\n const results = await Promise.all(\n batches.map(ids => this.getUnversionedResourcesBatch<Table>('tables', ids)),\n )\n\n return results.flat()\n }\n\n private async getUnversionedResourcesBatch<T>(\n resource: 'files' | 'tables',\n ids: string[],\n ): Promise<(T | null)[]> {\n const url = new URL(`v1/${resource}/bulk`, this.apiOrigin)\n\n ids.forEach(id => url.searchParams.append('ids', id))\n\n const response = await this.fetch(url.pathname + url.search, null)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n\n throw new RestApiClientError(`Failed to get ${resource} for [${ids.join(', ')}]`, response, {\n body: failedBody,\n })\n }\n\n return await response.json()\n }\n\n async getPagePathnameSlices(\n pageIds: string[],\n siteVersion: SiteVersion | null,\n { locale }: { locale?: string | null },\n ): Promise<(PagePathnameSlice | null)[]> {\n if (pageIds.length === 0) return []\n\n const url = new URL(`v3/page-pathname-slices/bulk`, this.apiOrigin)\n\n pageIds.forEach(id => url.searchParams.append('ids', id))\n if (locale != null) url.searchParams.set('locale', locale)\n\n const response = await this.fetch(url.pathname + url.search, siteVersion)\n\n if (!response.ok) {\n const failedBody = await failedResponseBody(response)\n if (response.status === 404) return []\n\n throw new RestApiClientError(\n `Failed to get page pathname slice(s) for ${pageIds.join(', ')}`,\n response,\n { body: failedBody, siteVersion, locale },\n )\n }\n\n const json = await response.json()\n\n const pagePathnameSlices = Schema.pagePathnameSlices.parse(json)\n\n // We're mapping the basePageId to be the id, because we're still using the GraphQL\n // fragment as our APIResource. The id on the APIResource needs to match the pageId\n // so that we can find the corresponding page pathname slice when we call getPagePathnameSlice(pageId).\n // TODO: Update this once we move away from the GraphQL fragments.\n return pagePathnameSlices.map(pagePathnameSlice => {\n if (pagePathnameSlice == null) return null\n\n return {\n ...pagePathnameSlice,\n id: pagePathnameSlice.basePageId,\n localizedPathname: pagePathnameSlice.localizedPathname ?? null,\n }\n })\n }\n\n async getPagePathnameSlice(\n pageId: string,\n siteVersion: SiteVersion | null,\n { locale }: { locale?: string | null } = {},\n ): Promise<PagePathnameSlice | null> {\n const pagePathnameSlices = await this.getPagePathnameSlices([pageId], siteVersion, { locale })\n\n return pagePathnameSlices.at(0) ?? null\n }\n\n protected async fetch(\n path: string,\n siteVersion: SiteVersion | null,\n init?: RequestInit,\n ): Promise<Response> {\n const requestUrl = new URL(path, this.apiOrigin)\n\n const requestHeaders = new Headers({\n 'x-api-key': this.apiKey,\n 'makeswift-site-api-key': this.apiKey,\n 'makeswift-runtime-version': PACKAGE_VERSION,\n })\n\n if (siteVersion?.token) {\n requestUrl.searchParams.set('version', siteVersion.version)\n requestHeaders.set('makeswift-preview-token', siteVersion.token)\n }\n\n if (init?.headers) {\n new Headers(init.headers).forEach((value, key) => {\n requestHeaders.set(key, value)\n })\n }\n\n try {\n return await this._fetch(requestUrl.toString(), {\n ...init,\n headers: requestHeaders,\n ...(siteVersion != null ? { cache: 'no-store' } : {}),\n })\n } catch (error) {\n if (error instanceof HTTPError) return error.response\n throw error\n }\n }\n}\n\n// This function attempts to consume the response body of a failed response, and\n// returns either the parsed JSON or raw text. This is useful for logging more\n// detailed error information when an API request fails.\n//\n// Cloudflare Worker Note: The Cloudflare Worker runtime has automatic deadlock\n// prevention (in the form of auto-cancelling responses) that triggers when too\n// many response bodies are unconsumed. This applies for error responses as\n// well. As such, in this client we use this function to consume the response\n// body whenever the request fails, even if we don't end up logging the body\n// itself, to avoid hitting the deadlock prevention.\nexport async function failedResponseBody(response: Response): Promise<unknown> {\n try {\n const text = await response.text()\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n } catch (e) {\n return `Failed to extract response body: ${e}`\n }\n}\n\nfunction responseError(response: Response): string {\n return `${response.status} ${response.statusText}`\n}\n\nexport class RestApiClientError extends Error {\n readonly status: number\n\n constructor(message: string, response: Response, cause: Record<string, unknown>) {\n super(`${message}: ${responseError(response)}`, { cause })\n\n this.name = 'RestApiClientError'\n this.status = response.status\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAA4D;AAc5D,aAAwB;AAOxB,MAAM,2BAA2B;AAEjC,SAAS,gBAAgB,KAA2B;AAClD,QAAM,UAAsB,CAAC;AAE7B,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,0BAA0B;AAC7D,YAAQ,KAAK,IAAI,MAAM,GAAG,IAAI,wBAAwB,CAAC;AAAA,EACzD;AAEA,SAAO;AACT;AAEA,MAAM,qBAAqB;AAAA,EACzB,aAAa;AAAA,EACb,YAAY;AACd;AAEO,MAAM,uBAAuB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AQ,KAAK,OAAO,EAAE,QAAQ,CAAC,OAAO,QAAQ;AAChD,uBAAe,IAAI,KAAK,KAAK;AAAA,MAC/B,CAAC;AAAA,IACH;AAEA,QAAI;AACF,aAAO,MAAM,KAAK,OAAO,WAAW,SAAS,GAAG;AAAA,QAC9C,GAAG;AAAA,QACH,SAAS;AAAA,QACT,GAAI,eAAe,OAAO,EAAE,OAAO,WAAW,IAAI,CAAC;AAAA,MACrD,CAAC;AAAA,IACH,SAAS,OAAO;AACd,UAAI,iBAAiB;AAAW,eAAO,MAAM;AAC7C,YAAM;AAAA,IACR;AAAA,EACF;AACF;AAYA,eAAsB,mBAAmB,UAAsC;AAC7E,MAAI;AACF,UAAM,OAAO,MAAM,SAAS,KAAK;AACjC,QAAI;AACF,aAAO,KAAK,MAAM,IAAI;AAAA,IACxB,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF,SAAS,GAAG;AACV,WAAO,oCAAoC,CAAC;AAAA,EAC9C;AACF;AAEA,SAAS,cAAc,UAA4B;AACjD,SAAO,GAAG,SAAS,MAAM,IAAI,SAAS,UAAU;AAClD;AAEO,MAAM,2BAA2B,MAAM;AAAA,EACnC;AAAA,EAET,YAAY,SAAiB,UAAoB,OAAgC;AAC/E,UAAM,GAAG,OAAO,KAAK,cAAc,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;AAEzD,SAAK,OAAO;AACZ,SAAK,SAAS,SAAS;AAAA,EACzB;AACF;","names":["ky"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/api/types.ts"],"sourcesContent":["import {\n SwatchFragment as Swatch,\n FileFragment as File,\n TypographyFragment as Typography,\n PagePathnameSliceFragment,\n GlobalElementFragment as GlobalElement,\n LocalizedGlobalElementFragment as LocalizedGlobalElement,\n TableFragment
|
|
1
|
+
{"version":3,"sources":["../../../src/api/types.ts"],"sourcesContent":["import {\n SwatchFragment as Swatch,\n FileFragment as File,\n TypographyFragment as Typography,\n PagePathnameSliceFragment,\n GlobalElementFragment as GlobalElement,\n LocalizedGlobalElementFragment as LocalizedGlobalElement,\n TableFragment,\n SnippetFragment as Snippet,\n PageFragment as Page,\n SiteFragment as Site,\n} from './graphql/generated/types'\n\n// The REST `tables` endpoint returns each column's discriminator as `type` rather than the GraphQL\n// `__typename`.\ntype WithColumnType<C> = C extends { __typename: infer T }\n ? Omit<C, '__typename'> & { type: T }\n : never\n\ntype Table = Omit<TableFragment, 'columns'> & {\n columns: Array<WithColumnType<TableFragment['columns'][number]>>\n}\n\ntype PagePathnameSlice = PagePathnameSliceFragment & {\n basePageId?: string\n localizedPathname?: string | null\n}\n\nexport type {\n Swatch,\n File,\n Typography,\n PagePathnameSlice,\n GlobalElement,\n LocalizedGlobalElement,\n Table,\n Snippet,\n Page,\n Site,\n}\n\nexport type LocalizableAPIResource = PagePathnameSlice | LocalizedGlobalElement\n\nexport const LocalizableAPIResourceType: {\n [R in LocalizableAPIResource as R['__typename']]: R['__typename']\n} = {\n PagePathnameSlice: 'PagePathnameSlice',\n LocalizedGlobalElement: 'LocalizedGlobalElement',\n}\n\nexport type LocalizableAPIResourceType =\n (typeof LocalizableAPIResourceType)[keyof typeof LocalizableAPIResourceType]\n\nexport type APIResource =\n | LocalizableAPIResource\n | Swatch\n | File\n | Typography\n | GlobalElement\n | Table\n | Snippet\n | Page\n | Site\n\nexport const APIResourceType: { [R in APIResource as R['__typename']]: R['__typename'] } = {\n ...LocalizableAPIResourceType,\n Swatch: 'Swatch',\n File: 'File',\n Typography: 'Typography',\n GlobalElement: 'GlobalElement',\n Table: 'Table',\n Snippet: 'Snippet',\n Page: 'Page',\n Site: 'Site',\n}\n\nexport type APIResourceType = (typeof APIResourceType)[keyof typeof APIResourceType]\n\nexport type APIResourceByType<T extends APIResourceType> = Extract<APIResource, { __typename: T }>\n\nexport type APIResourceLocale<R extends APIResource | APIResourceType> = R extends\n | LocalizableAPIResource\n | LocalizableAPIResourceType\n ? string | null\n : never\n\nexport type HttpFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2CO,MAAM,6BAET;AAAA,EACF,mBAAmB;AAAA,EACnB,wBAAwB;AAC1B;AAgBO,MAAM,kBAA8E;AAAA,EACzF,GAAG;AAAA,EACH,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AACR;","names":[]}
|
|
@@ -28,7 +28,7 @@ async function manifestHandler(req, { apiKey, manifest }) {
|
|
|
28
28
|
return import_request_response.ApiResponse.json({ message: "Unauthorized" }, { status: 401 });
|
|
29
29
|
}
|
|
30
30
|
return import_request_response.ApiResponse.json({
|
|
31
|
-
version: "0.29.
|
|
31
|
+
version: "0.29.3-canary.1",
|
|
32
32
|
interactionMode: true,
|
|
33
33
|
clientSideNavigation: false,
|
|
34
34
|
elementFromPoint: false,
|
|
@@ -29,6 +29,7 @@ function componentDocumentToRootEmbeddedDocument({
|
|
|
29
29
|
name,
|
|
30
30
|
type,
|
|
31
31
|
description,
|
|
32
|
+
internal_MakeswiftBuilderData,
|
|
32
33
|
meta
|
|
33
34
|
}) {
|
|
34
35
|
const { data: rootElement, locale, id } = document;
|
|
@@ -51,7 +52,7 @@ function componentDocumentToRootEmbeddedDocument({
|
|
|
51
52
|
id,
|
|
52
53
|
type,
|
|
53
54
|
name,
|
|
54
|
-
meta: { ...meta, description },
|
|
55
|
+
meta: { ...meta, description, internal_MakeswiftBuilderData },
|
|
55
56
|
__type: import_read_only_documents.EMBEDDED_DOCUMENT_TYPE
|
|
56
57
|
};
|
|
57
58
|
return rootDocument;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/client/component-snapshot.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport { type CacheData } from '../api/api-resources-client'\n\nimport { EMBEDDED_DOCUMENT_TYPE
|
|
1
|
+
{"version":3,"sources":["../../../src/client/component-snapshot.ts"],"sourcesContent":["import { z } from 'zod'\n\nimport { type CacheData } from '../api/api-resources-client'\n\nimport {\n type Data,\n EMBEDDED_DOCUMENT_TYPE,\n type EmbeddedDocument,\n} from '../state/modules/read-only-documents'\n\nimport { deterministicUUID } from '../utils/deterministic-uuid'\n\nimport * as Schema from './schema/component-document'\n\nexport type MakeswiftComponentDocument = z.infer<typeof Schema.componentDocument>\nexport type MakeswiftComponentDocumentFallback = z.infer<typeof Schema.componentDocumentFallback>\n\nexport type MakeswiftComponentMetadata = {\n allowLocaleFallback: boolean\n requestedLocale: string | null\n}\n\nexport function componentDocumentToRootEmbeddedDocument({\n document,\n documentKey,\n name,\n type,\n description,\n internal_MakeswiftBuilderData,\n meta,\n}: {\n document: MakeswiftComponentDocument | MakeswiftComponentDocumentFallback\n documentKey: string\n name: string\n type: string\n description?: string\n /** For internal Makeswift builder use only */\n internal_MakeswiftBuilderData?: Data\n meta: MakeswiftComponentMetadata\n}): EmbeddedDocument {\n const { data: rootElement, locale, id } = document\n\n if (rootElement != null && rootElement.type !== type) {\n throw new Error(\n `Type \"${rootElement.type}\" does not match the expected type \"${type}\" from the snapshot`,\n )\n }\n\n const rootDocument: EmbeddedDocument = {\n key: documentKey,\n rootElement: rootElement ?? {\n // Fallback rootElement\n // Create a stable uuid so two different clients will have the same empty element data.\n // This is needed to make presence feature work for an element that is not yet created.\n key: deterministicUUID({ id, locale, seed: documentKey }),\n type,\n props: {},\n },\n locale,\n id,\n type,\n name,\n meta: { ...meta, description, internal_MakeswiftBuilderData },\n __type: EMBEDDED_DOCUMENT_TYPE,\n }\n\n return rootDocument\n}\n\nexport type MakeswiftComponentSnapshot = {\n document: MakeswiftComponentDocument | MakeswiftComponentDocumentFallback\n key: string\n cacheData: CacheData\n meta: MakeswiftComponentMetadata\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,iCAIO;AAEP,gCAAkC;AAY3B,SAAS,wCAAwC;AAAA,EACtD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GASqB;AACnB,QAAM,EAAE,MAAM,aAAa,QAAQ,GAAG,IAAI;AAE1C,MAAI,eAAe,QAAQ,YAAY,SAAS,MAAM;AACpD,UAAM,IAAI;AAAA,MACR,SAAS,YAAY,IAAI,uCAAuC,IAAI;AAAA,IACtE;AAAA,EACF;AAEA,QAAM,eAAiC;AAAA,IACrC,KAAK;AAAA,IACL,aAAa,eAAe;AAAA;AAAA;AAAA;AAAA,MAI1B,SAAK,6CAAkB,EAAE,IAAI,QAAQ,MAAM,YAAY,CAAC;AAAA,MACxD;AAAA,MACA,OAAO,CAAC;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,MAAM,EAAE,GAAG,MAAM,aAAa,8BAA8B;AAAA,IAC5D,QAAQ;AAAA,EACV;AAEA,SAAO;AACT;","names":[]}
|
package/dist/cjs/client/index.js
CHANGED
|
@@ -29,14 +29,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
29
29
|
var client_exports = {};
|
|
30
30
|
__export(client_exports, {
|
|
31
31
|
MakeswiftClient: () => MakeswiftClient,
|
|
32
|
-
SnippetLocation: () =>
|
|
32
|
+
SnippetLocation: () => import_types2.SnippetLocation,
|
|
33
33
|
componentDocumentToRootEmbeddedDocument: () => import_component_snapshot2.componentDocumentToRootEmbeddedDocument,
|
|
34
34
|
pageToRootDocument: () => import_page_snapshot2.pageToRootDocument
|
|
35
35
|
});
|
|
36
36
|
module.exports = __toCommonJS(client_exports);
|
|
37
|
-
var
|
|
37
|
+
var import_types = require("../api/types");
|
|
38
38
|
var import_api_resources_client = require("../api/api-resources-client");
|
|
39
|
-
var import_graphql_api_client = require("../api/graphql-api-client");
|
|
40
39
|
var import_rest_api_client = require("../api/rest-api-client");
|
|
41
40
|
var import_introspection = require("../prop-controllers/introspection");
|
|
42
41
|
var import_read_only_state = require("../state/read-only-state");
|
|
@@ -46,11 +45,10 @@ var import_deterministic_uuid = require("../utils/deterministic-uuid");
|
|
|
46
45
|
var import_pagination = require("../utils/pagination");
|
|
47
46
|
var import_isNonNullable = require("../utils/isNonNullable");
|
|
48
47
|
var Schema = __toESM(require("./schema"));
|
|
49
|
-
var
|
|
48
|
+
var import_types2 = require("../api/graphql/generated/types");
|
|
50
49
|
var import_component_snapshot2 = require("./component-snapshot");
|
|
51
50
|
var import_page_snapshot2 = require("./page-snapshot");
|
|
52
51
|
class MakeswiftClient extends import_rest_api_client.MakeswiftRestAPIClient {
|
|
53
|
-
graphqlClient;
|
|
54
52
|
runtime;
|
|
55
53
|
constructor(apiKey, {
|
|
56
54
|
runtime
|
|
@@ -66,9 +64,6 @@ Received "${apiKey}" instead.`
|
|
|
66
64
|
apiKey,
|
|
67
65
|
apiOrigin: runtime.apiOrigin
|
|
68
66
|
});
|
|
69
|
-
this.graphqlClient = new import_graphql_api_client.MakeswiftGraphQLApiClient({
|
|
70
|
-
endpoint: runtime.graphqlApiEndpoint
|
|
71
|
-
});
|
|
72
67
|
this.runtime = runtime;
|
|
73
68
|
}
|
|
74
69
|
getPagesInternal = async ({
|
|
@@ -181,11 +176,19 @@ Received "${apiKey}" instead.`
|
|
|
181
176
|
}
|
|
182
177
|
async getIntrospectedResources({
|
|
183
178
|
swatchIds,
|
|
184
|
-
|
|
179
|
+
fileIds,
|
|
180
|
+
tableIds
|
|
185
181
|
}, siteVersion) {
|
|
186
|
-
const
|
|
187
|
-
|
|
188
|
-
|
|
182
|
+
const [swatches, files, tables] = await Promise.all([
|
|
183
|
+
this.getSwatches(swatchIds, siteVersion),
|
|
184
|
+
this.getFiles(fileIds),
|
|
185
|
+
this.getTables(tableIds)
|
|
186
|
+
]);
|
|
187
|
+
return {
|
|
188
|
+
swatches,
|
|
189
|
+
files: files.map((file) => (0, import_api_resources_client.withTypename)(import_types.APIResourceType.File, file)),
|
|
190
|
+
tables: tables.map((table) => (0, import_api_resources_client.withTypename)(import_types.APIResourceType.Table, table))
|
|
191
|
+
};
|
|
189
192
|
}
|
|
190
193
|
async introspect(element, siteVersion, locale) {
|
|
191
194
|
const treeId = "root";
|
|
@@ -352,34 +355,34 @@ Received "${apiKey}" instead.`
|
|
|
352
355
|
const result = /* @__PURE__ */ new Map();
|
|
353
356
|
for (const [treeId, { cache: currentTreeCache }] of traversals) {
|
|
354
357
|
const apiResources = {
|
|
355
|
-
[
|
|
358
|
+
[import_types.APIResourceType.Swatch]: [...currentTreeCache.swatchIds].map((id) => ({
|
|
356
359
|
id,
|
|
357
360
|
value: swatches.find((swatch) => swatch?.id === id) ?? null
|
|
358
361
|
})),
|
|
359
|
-
[
|
|
362
|
+
[import_types.APIResourceType.File]: [...currentTreeCache.fileIds].map((id) => ({
|
|
360
363
|
id,
|
|
361
364
|
value: files.find((file) => file?.id === id) ?? null
|
|
362
365
|
})),
|
|
363
|
-
[
|
|
366
|
+
[import_types.APIResourceType.Typography]: [...currentTreeCache.typographyIds].map((id) => ({
|
|
364
367
|
id,
|
|
365
368
|
value: typographies.find((typography) => typography?.id === id) ?? null
|
|
366
369
|
})),
|
|
367
|
-
[
|
|
370
|
+
[import_types.APIResourceType.Table]: [...currentTreeCache.tableIds].map((id) => ({
|
|
368
371
|
id,
|
|
369
372
|
value: tables.find((table) => table?.id === id) ?? null
|
|
370
373
|
})),
|
|
371
|
-
[
|
|
374
|
+
[import_types.APIResourceType.PagePathnameSlice]: [...currentTreeCache.pageIds].map((id) => ({
|
|
372
375
|
id,
|
|
373
376
|
value: pagePathnames.find((pagePathnameSlice) => pagePathnameSlice?.id === id) ?? null,
|
|
374
377
|
locale
|
|
375
378
|
})),
|
|
376
|
-
[
|
|
379
|
+
[import_types.APIResourceType.GlobalElement]: [...currentTreeCache.globalElements.entries()].map(
|
|
377
380
|
([id, value]) => ({
|
|
378
381
|
id,
|
|
379
382
|
value
|
|
380
383
|
})
|
|
381
384
|
),
|
|
382
|
-
[
|
|
385
|
+
[import_types.APIResourceType.LocalizedGlobalElement]: [
|
|
383
386
|
...currentTreeCache.localizedGlobalElements.entries()
|
|
384
387
|
].map(([id, value]) => ({
|
|
385
388
|
id,
|