@makeswift/runtime 0.23.7 → 0.23.8-canary.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.
Files changed (62) hide show
  1. package/dist/cjs/api/react.js +28 -7
  2. package/dist/cjs/api/react.js.map +1 -1
  3. package/dist/cjs/api/site-version.js +36 -0
  4. package/dist/cjs/api/site-version.js.map +1 -0
  5. package/dist/cjs/next/api-handler/handlers/manifest.js +1 -1
  6. package/dist/cjs/next/api-handler/handlers/proxy-draft-mode.js +2 -2
  7. package/dist/cjs/next/api-handler/handlers/proxy-draft-mode.js.map +1 -1
  8. package/dist/cjs/next/api-handler/handlers/proxy-preview-mode.js +2 -2
  9. package/dist/cjs/next/api-handler/handlers/proxy-preview-mode.js.map +1 -1
  10. package/dist/cjs/next/api-handler/index.js +12 -2
  11. package/dist/cjs/next/api-handler/index.js.map +1 -1
  12. package/dist/cjs/next/client.js +7 -6
  13. package/dist/cjs/next/client.js.map +1 -1
  14. package/dist/cjs/next/draft-mode/index.js +3 -3
  15. package/dist/cjs/next/draft-mode/index.js.map +1 -1
  16. package/dist/cjs/next/preview-mode.js +4 -9
  17. package/dist/cjs/next/preview-mode.js.map +1 -1
  18. package/dist/cjs/runtimes/react/components/RuntimeProvider.js +4 -2
  19. package/dist/cjs/runtimes/react/components/RuntimeProvider.js.map +1 -1
  20. package/dist/cjs/runtimes/react/host-api-client.js +5 -1
  21. package/dist/cjs/runtimes/react/host-api-client.js.map +1 -1
  22. package/dist/cjs/state/makeswift-api-client.js +21 -10
  23. package/dist/cjs/state/makeswift-api-client.js.map +1 -1
  24. package/dist/esm/api/react.js +28 -7
  25. package/dist/esm/api/react.js.map +1 -1
  26. package/dist/esm/api/site-version.js +10 -0
  27. package/dist/esm/api/site-version.js.map +1 -0
  28. package/dist/esm/next/api-handler/handlers/manifest.js +1 -1
  29. package/dist/esm/next/api-handler/handlers/proxy-draft-mode.js +1 -1
  30. package/dist/esm/next/api-handler/handlers/proxy-draft-mode.js.map +1 -1
  31. package/dist/esm/next/api-handler/handlers/proxy-preview-mode.js +1 -1
  32. package/dist/esm/next/api-handler/handlers/proxy-preview-mode.js.map +1 -1
  33. package/dist/esm/next/api-handler/index.js +16 -2
  34. package/dist/esm/next/api-handler/index.js.map +1 -1
  35. package/dist/esm/next/client.js +2 -1
  36. package/dist/esm/next/client.js.map +1 -1
  37. package/dist/esm/next/draft-mode/index.js +1 -1
  38. package/dist/esm/next/draft-mode/index.js.map +1 -1
  39. package/dist/esm/next/preview-mode.js +2 -5
  40. package/dist/esm/next/preview-mode.js.map +1 -1
  41. package/dist/esm/runtimes/react/components/RuntimeProvider.js +4 -2
  42. package/dist/esm/runtimes/react/components/RuntimeProvider.js.map +1 -1
  43. package/dist/esm/runtimes/react/host-api-client.js +5 -1
  44. package/dist/esm/runtimes/react/host-api-client.js.map +1 -1
  45. package/dist/esm/state/makeswift-api-client.js +21 -10
  46. package/dist/esm/state/makeswift-api-client.js.map +1 -1
  47. package/dist/types/api/react.d.ts +4 -1
  48. package/dist/types/api/react.d.ts.map +1 -1
  49. package/dist/types/api/site-version.d.ts +6 -0
  50. package/dist/types/api/site-version.d.ts.map +1 -0
  51. package/dist/types/next/api-handler/handlers/proxy-preview-mode.d.ts.map +1 -1
  52. package/dist/types/next/api-handler/index.d.ts.map +1 -1
  53. package/dist/types/next/client.d.ts +1 -1
  54. package/dist/types/next/client.d.ts.map +1 -1
  55. package/dist/types/next/draft-mode/index.d.ts +2 -2
  56. package/dist/types/next/preview-mode.d.ts +3 -5
  57. package/dist/types/next/preview-mode.d.ts.map +1 -1
  58. package/dist/types/runtimes/react/components/RuntimeProvider.d.ts.map +1 -1
  59. package/dist/types/runtimes/react/host-api-client.d.ts.map +1 -1
  60. package/dist/types/state/makeswift-api-client.d.ts +2 -1
  61. package/dist/types/state/makeswift-api-client.d.ts.map +1 -1
  62. package/package.json +2 -2
@@ -45,15 +45,22 @@ const CacheData = {
45
45
  }
46
46
  };
47
47
  class MakeswiftHostApiClient {
48
+ siteVersion;
48
49
  graphqlClient;
49
50
  makeswiftApiClient;
50
51
  subscribe;
51
- constructor({ uri, cacheData, locale }) {
52
+ constructor({
53
+ uri,
54
+ siteVersion,
55
+ cacheData,
56
+ locale
57
+ }) {
52
58
  this.graphqlClient = new import_client.GraphQLClient(uri);
53
59
  this.makeswiftApiClient = MakeswiftApiClient.configureStore({
54
60
  serializedState: cacheData,
55
61
  defaultLocale: locale
56
62
  });
63
+ this.siteVersion = siteVersion;
57
64
  this.subscribe = this.makeswiftApiClient.subscribe;
58
65
  }
59
66
  readSwatch(swatchId) {
@@ -65,7 +72,7 @@ class MakeswiftHostApiClient {
65
72
  }
66
73
  async fetchSwatch(swatchId) {
67
74
  return await this.makeswiftApiClient.dispatch(
68
- MakeswiftApiClient.fetchAPIResource(import_types.APIResourceType.Swatch, swatchId)
75
+ MakeswiftApiClient.fetchAPIResource(import_types.APIResourceType.Swatch, swatchId, this.siteVersion)
69
76
  );
70
77
  }
71
78
  resolveSwatch(swatchId) {
@@ -84,7 +91,7 @@ class MakeswiftHostApiClient {
84
91
  }
85
92
  async fetchFile(fileId) {
86
93
  return await this.makeswiftApiClient.dispatch(
87
- MakeswiftApiClient.fetchAPIResource(import_types.APIResourceType.File, fileId)
94
+ MakeswiftApiClient.fetchAPIResource(import_types.APIResourceType.File, fileId, this.siteVersion)
88
95
  );
89
96
  }
90
97
  resolveFile(fileId) {
@@ -103,7 +110,11 @@ class MakeswiftHostApiClient {
103
110
  }
104
111
  async fetchTypography(typographyId) {
105
112
  return await this.makeswiftApiClient.dispatch(
106
- MakeswiftApiClient.fetchAPIResource(import_types.APIResourceType.Typography, typographyId)
113
+ MakeswiftApiClient.fetchAPIResource(
114
+ import_types.APIResourceType.Typography,
115
+ typographyId,
116
+ this.siteVersion
117
+ )
107
118
  );
108
119
  }
109
120
  resolveTypography(typographyId) {
@@ -122,7 +133,11 @@ class MakeswiftHostApiClient {
122
133
  }
123
134
  async fetchGlobalElement(globalElementId) {
124
135
  return await this.makeswiftApiClient.dispatch(
125
- MakeswiftApiClient.fetchAPIResource(import_types.APIResourceType.GlobalElement, globalElementId)
136
+ MakeswiftApiClient.fetchAPIResource(
137
+ import_types.APIResourceType.GlobalElement,
138
+ globalElementId,
139
+ this.siteVersion
140
+ )
126
141
  );
127
142
  }
128
143
  readLocalizedGlobalElement({
@@ -144,6 +159,7 @@ class MakeswiftHostApiClient {
144
159
  MakeswiftApiClient.fetchAPIResource(
145
160
  import_types.APIResourceType.LocalizedGlobalElement,
146
161
  globalElementId,
162
+ this.siteVersion,
147
163
  locale
148
164
  )
149
165
  );
@@ -164,7 +180,12 @@ class MakeswiftHostApiClient {
164
180
  locale
165
181
  }) {
166
182
  return await this.makeswiftApiClient.dispatch(
167
- MakeswiftApiClient.fetchAPIResource(import_types.APIResourceType.PagePathnameSlice, pageId, locale)
183
+ MakeswiftApiClient.fetchAPIResource(
184
+ import_types.APIResourceType.PagePathnameSlice,
185
+ pageId,
186
+ this.siteVersion,
187
+ locale
188
+ )
168
189
  );
169
190
  }
170
191
  resolvePagePathnameSlice({
@@ -203,7 +224,7 @@ class MakeswiftHostApiClient {
203
224
  }
204
225
  async fetchTable(tableId) {
205
226
  return await this.makeswiftApiClient.dispatch(
206
- MakeswiftApiClient.fetchAPIResource(import_types.APIResourceType.Table, tableId)
227
+ MakeswiftApiClient.fetchAPIResource(import_types.APIResourceType.Table, tableId, this.siteVersion)
207
228
  );
208
229
  }
209
230
  async createTableRecord(tableId, columns) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/api/react.ts"],"sourcesContent":["import { type FetchableValue } from '@makeswift/controls'\nimport * as MakeswiftApiClient from '../state/makeswift-api-client'\nimport {\n APIResourceType,\n File,\n GlobalElement,\n LocalizedGlobalElement,\n Page,\n PagePathnameSlice,\n Site,\n Snippet,\n Swatch,\n Table,\n Typography,\n} from './types'\nimport { GraphQLClient } from './graphql/client'\nimport { CreateTableRecordMutation } from './graphql/documents'\nimport {\n CreateTableRecordMutationResult,\n CreateTableRecordMutationVariables,\n} from './graphql/generated/types'\n\nexport type CacheData = MakeswiftApiClient.SerializedState\n\nexport const CacheData = {\n empty(): CacheData {\n return {\n apiResources: {},\n localizedResourcesMap: {},\n }\n },\n}\n\n/**\n * NOTE(miguel): This \"client\" is used to fetch Makeswift API resources needed for the host. For\n * example, swatches, files, typographies, etc. Ideally it's internal to the runtime and is only\n * used by controls to transform API references to API resources.\n *\n * Moreover, its use should be reserved for the builder only, since for live pages all Makeswift\n * API resources should be embedded in the \"page snapshot\". In the builder, this client serves the\n * purpose of sending requests for API resources and keeping a cache so that changes that happen in\n * the builder, like modifying a swatch, can be sent via `postMessage` to the host and the cache can\n * immediately update the value and re-render.\n *\n * Furthermore, the API resources requested shouldn't be requested directly from the Makeswift API\n * as that would require those resources to not be authenticated since the requests come from the\n * browser when running the host. Instead, the requests should go to the host directly, at the\n * Makeswift API endpoint (i.g., `/api/makeswift/[...makeswift]` dynamic route) where the host's\n * API key can be used, securely, in the server. For this reason, this client should really be a\n * client of the host's API, not Makeswift's, intended to build and continuously maintain a realtime\n * snapshot for use in the builder, not the lives pages.\n */\nexport class MakeswiftHostApiClient {\n graphqlClient: GraphQLClient\n makeswiftApiClient: MakeswiftApiClient.Store\n subscribe: MakeswiftApiClient.Store['subscribe']\n\n constructor({ uri, cacheData, locale }: { uri: string; cacheData?: CacheData; locale?: string }) {\n this.graphqlClient = new GraphQLClient(uri)\n this.makeswiftApiClient = MakeswiftApiClient.configureStore({\n serializedState: cacheData,\n defaultLocale: locale,\n })\n\n this.subscribe = this.makeswiftApiClient.subscribe\n }\n\n readSwatch(swatchId: string): Swatch | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.Swatch,\n swatchId,\n )\n }\n\n async fetchSwatch(swatchId: string): Promise<Swatch | null> {\n return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(APIResourceType.Swatch, swatchId),\n )\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 readFile(fileId: string): File | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.File,\n fileId,\n )\n }\n\n async fetchFile(fileId: string): Promise<File | null> {\n return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(APIResourceType.File, fileId),\n )\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 readTypography(typographyId: string): Typography | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.Typography,\n typographyId,\n )\n }\n\n async fetchTypography(typographyId: string): Promise<Typography | null> {\n return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(APIResourceType.Typography, 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 readGlobalElement(globalElementId: string): GlobalElement | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.GlobalElement,\n globalElementId,\n )\n }\n\n async fetchGlobalElement(globalElementId: string): Promise<GlobalElement | null> {\n return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(APIResourceType.GlobalElement, globalElementId),\n )\n }\n\n readLocalizedGlobalElement({\n globalElementId,\n locale,\n }: {\n globalElementId: string\n locale: string\n }): LocalizedGlobalElement | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.LocalizedGlobalElement,\n globalElementId,\n locale,\n )\n }\n\n async fetchLocalizedGlobalElement({\n globalElementId,\n locale,\n }: {\n globalElementId: string\n locale: string\n }): Promise<LocalizedGlobalElement | null> {\n return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(\n APIResourceType.LocalizedGlobalElement,\n globalElementId,\n locale,\n ),\n )\n }\n\n readPagePathnameSlice({\n pageId,\n locale,\n }: {\n pageId: string\n locale: string | null\n }): PagePathnameSlice | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.PagePathnameSlice,\n pageId,\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 return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(APIResourceType.PagePathnameSlice, pageId, 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 readTable(tableId: string): Table | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.Table,\n tableId,\n )\n }\n\n async fetchTable(tableId: string): Promise<Table | null> {\n return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(APIResourceType.Table, tableId),\n )\n }\n\n async createTableRecord(tableId: string, columns: any): Promise<void> {\n await this.graphqlClient.request<\n CreateTableRecordMutationResult,\n CreateTableRecordMutationVariables\n >(CreateTableRecordMutation, { input: { data: { tableId, columns } } })\n }\n\n readSite(siteId: string): Site | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.Site,\n siteId,\n )\n }\n\n readPage(pageId: string): Page | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.Page,\n pageId,\n )\n }\n\n readSnippet(snippetId: string): Snippet | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.Snippet,\n snippetId,\n )\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,yBAAoC;AACpC,mBAYO;AACP,oBAA8B;AAC9B,uBAA0C;AAQnC,MAAM,YAAY;AAAA,EACvB,QAAmB;AACjB,WAAO;AAAA,MACL,cAAc,CAAC;AAAA,MACf,uBAAuB,CAAC;AAAA,IAC1B;AAAA,EACF;AACF;AAqBO,MAAM,uBAAuB;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,EAAE,KAAK,WAAW,OAAO,GAA4D;AAC/F,SAAK,gBAAgB,IAAI,4BAAc,GAAG;AAC1C,SAAK,qBAAqB,mBAAmB,eAAe;AAAA,MAC1D,iBAAiB;AAAA,MACjB,eAAe;AAAA,IACjB,CAAC;AAED,SAAK,YAAY,KAAK,mBAAmB;AAAA,EAC3C;AAAA,EAEA,WAAW,UAAiC;AAC1C,WAAO,mBAAmB;AAAA,MACxB,KAAK,mBAAmB,SAAS;AAAA,MACjC,6BAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,YAAY,UAA0C;AAC1D,WAAO,MAAM,KAAK,mBAAmB;AAAA,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AmB,SAAS;AAAA,MACjC,6BAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/api/react.ts"],"sourcesContent":["import { type FetchableValue } from '@makeswift/controls'\nimport * as MakeswiftApiClient from '../state/makeswift-api-client'\nimport {\n APIResourceType,\n File,\n GlobalElement,\n LocalizedGlobalElement,\n Page,\n PagePathnameSlice,\n Site,\n Snippet,\n Swatch,\n Table,\n Typography,\n} from './types'\nimport { GraphQLClient } from './graphql/client'\nimport { CreateTableRecordMutation } from './graphql/documents'\nimport {\n CreateTableRecordMutationResult,\n CreateTableRecordMutationVariables,\n} from './graphql/generated/types'\nimport { MakeswiftSiteVersion } from './site-version'\n\nexport type CacheData = MakeswiftApiClient.SerializedState\n\nexport const CacheData = {\n empty(): CacheData {\n return {\n apiResources: {},\n localizedResourcesMap: {},\n }\n },\n}\n\n/**\n * NOTE(miguel): This \"client\" is used to fetch Makeswift API resources needed for the host. For\n * example, swatches, files, typographies, etc. Ideally it's internal to the runtime and is only\n * used by controls to transform API references to API resources.\n *\n * Moreover, its use should be reserved for the builder only, since for live pages all Makeswift\n * API resources should be embedded in the \"page snapshot\". In the builder, this client serves the\n * purpose of sending requests for API resources and keeping a cache so that changes that happen in\n * the builder, like modifying a swatch, can be sent via `postMessage` to the host and the cache can\n * immediately update the value and re-render.\n *\n * Furthermore, the API resources requested shouldn't be requested directly from the Makeswift API\n * as that would require those resources to not be authenticated since the requests come from the\n * browser when running the host. Instead, the requests should go to the host directly, at the\n * Makeswift API endpoint (i.g., `/api/makeswift/[...makeswift]` dynamic route) where the host's\n * API key can be used, securely, in the server. For this reason, this client should really be a\n * client of the host's API, not Makeswift's, intended to build and continuously maintain a realtime\n * snapshot for use in the builder, not the lives pages.\n */\nexport class MakeswiftHostApiClient {\n siteVersion: MakeswiftSiteVersion\n graphqlClient: GraphQLClient\n makeswiftApiClient: MakeswiftApiClient.Store\n subscribe: MakeswiftApiClient.Store['subscribe']\n\n constructor({\n uri,\n siteVersion,\n cacheData,\n locale,\n }: {\n uri: string\n siteVersion: MakeswiftSiteVersion\n cacheData?: CacheData\n locale?: string\n }) {\n this.graphqlClient = new GraphQLClient(uri)\n this.makeswiftApiClient = MakeswiftApiClient.configureStore({\n serializedState: cacheData,\n defaultLocale: locale,\n })\n this.siteVersion = siteVersion\n this.subscribe = this.makeswiftApiClient.subscribe\n }\n\n readSwatch(swatchId: string): Swatch | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.Swatch,\n swatchId,\n )\n }\n\n async fetchSwatch(swatchId: string): Promise<Swatch | null> {\n return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(APIResourceType.Swatch, swatchId, this.siteVersion),\n )\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 readFile(fileId: string): File | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.File,\n fileId,\n )\n }\n\n async fetchFile(fileId: string): Promise<File | null> {\n return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(APIResourceType.File, fileId, this.siteVersion),\n )\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 readTypography(typographyId: string): Typography | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.Typography,\n typographyId,\n )\n }\n\n async fetchTypography(typographyId: string): Promise<Typography | null> {\n return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(\n APIResourceType.Typography,\n typographyId,\n this.siteVersion,\n ),\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 readGlobalElement(globalElementId: string): GlobalElement | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.GlobalElement,\n globalElementId,\n )\n }\n\n async fetchGlobalElement(globalElementId: string): Promise<GlobalElement | null> {\n return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(\n APIResourceType.GlobalElement,\n globalElementId,\n this.siteVersion,\n ),\n )\n }\n\n readLocalizedGlobalElement({\n globalElementId,\n locale,\n }: {\n globalElementId: string\n locale: string\n }): LocalizedGlobalElement | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.LocalizedGlobalElement,\n globalElementId,\n locale,\n )\n }\n\n async fetchLocalizedGlobalElement({\n globalElementId,\n locale,\n }: {\n globalElementId: string\n locale: string\n }): Promise<LocalizedGlobalElement | null> {\n return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(\n APIResourceType.LocalizedGlobalElement,\n globalElementId,\n this.siteVersion,\n locale,\n ),\n )\n }\n\n readPagePathnameSlice({\n pageId,\n locale,\n }: {\n pageId: string\n locale: string | null\n }): PagePathnameSlice | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.PagePathnameSlice,\n pageId,\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 return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(\n APIResourceType.PagePathnameSlice,\n pageId,\n this.siteVersion,\n locale,\n ),\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 readTable(tableId: string): Table | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.Table,\n tableId,\n )\n }\n\n async fetchTable(tableId: string): Promise<Table | null> {\n return await this.makeswiftApiClient.dispatch(\n MakeswiftApiClient.fetchAPIResource(APIResourceType.Table, tableId, this.siteVersion),\n )\n }\n\n async createTableRecord(tableId: string, columns: any): Promise<void> {\n await this.graphqlClient.request<\n CreateTableRecordMutationResult,\n CreateTableRecordMutationVariables\n >(CreateTableRecordMutation, { input: { data: { tableId, columns } } })\n }\n\n readSite(siteId: string): Site | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.Site,\n siteId,\n )\n }\n\n readPage(pageId: string): Page | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.Page,\n pageId,\n )\n }\n\n readSnippet(snippetId: string): Snippet | null {\n return MakeswiftApiClient.getAPIResource(\n this.makeswiftApiClient.getState(),\n APIResourceType.Snippet,\n snippetId,\n )\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,yBAAoC;AACpC,mBAYO;AACP,oBAA8B;AAC9B,uBAA0C;AASnC,MAAM,YAAY;AAAA,EAC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,IAC/C;AAAA,EACF;AAAA,EAEA,UAAU,SAA+B;AACvC,WAAO,mBAAmB;AAAA,MACxB,KAAK,mBAAmB,SAAS;AAAA,MACjC,6BAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,WAAW,SAAwC;AACvD,WAAO,MAAM,KAAK,mBAAmB;AAAA,MACnC,mBAAmB,iBAAiB,6BAAgB,OAAO,SAAS,KAAK,WAAW;AAAA,IACtF;AAAA,EACF;AAAA,EAEA,MAAM,kBAAkB,SAAiB,SAA6B;AACpE,UAAM,KAAK,cAAc,QAGvB,4CAA2B,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,QAAQ,EAAE,EAAE,CAAC;AAAA,EACxE;AAAA,EAEA,SAAS,QAA6B;AACpC,WAAO,mBAAmB;AAAA,MACxB,KAAK,mBAAmB,SAAS;AAAA,MACjC,6BAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,SAAS,QAA6B;AACpC,WAAO,mBAAmB;AAAA,MACxB,KAAK,mBAAmB,SAAS;AAAA,MACjC,6BAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,YAAY,WAAmC;AAC7C,WAAO,mBAAmB;AAAA,MACxB,KAAK,mBAAmB,SAAS;AAAA,MACjC,6BAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var site_version_exports = {};
20
+ __export(site_version_exports, {
21
+ API_HANDLER_SITE_VERSION_HEADER: () => API_HANDLER_SITE_VERSION_HEADER,
22
+ MakeswiftSiteVersion: () => MakeswiftSiteVersion,
23
+ makeswiftSiteVersionSchema: () => makeswiftSiteVersionSchema
24
+ });
25
+ module.exports = __toCommonJS(site_version_exports);
26
+ var import_zod = require("zod");
27
+ const makeswiftSiteVersionSchema = import_zod.z.enum(["Live", "Working"]);
28
+ const MakeswiftSiteVersion = makeswiftSiteVersionSchema.Enum;
29
+ const API_HANDLER_SITE_VERSION_HEADER = "X-Makeswift-Site-Version";
30
+ // Annotate the CommonJS export names for ESM import in node:
31
+ 0 && (module.exports = {
32
+ API_HANDLER_SITE_VERSION_HEADER,
33
+ MakeswiftSiteVersion,
34
+ makeswiftSiteVersionSchema
35
+ });
36
+ //# sourceMappingURL=site-version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/api/site-version.ts"],"sourcesContent":["import { z } from 'zod'\n\nexport const makeswiftSiteVersionSchema = z.enum(['Live', 'Working'])\nexport const MakeswiftSiteVersion = makeswiftSiteVersionSchema.Enum\nexport type MakeswiftSiteVersion = z.infer<typeof makeswiftSiteVersionSchema>\n\nexport const API_HANDLER_SITE_VERSION_HEADER = 'X-Makeswift-Site-Version'\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAkB;AAEX,MAAM,6BAA6B,aAAE,KAAK,CAAC,QAAQ,SAAS,CAAC;AAC7D,MAAM,uBAAuB,2BAA2B;AAGxD,MAAM,kCAAkC;","names":[]}
@@ -37,7 +37,7 @@ async function handler(...args) {
37
37
  const supportsDraftMode = (0, import_ts_pattern.match)(args).with(routeHandlerPattern, () => true).with(apiRoutePattern, () => false).exhaustive();
38
38
  const supportsWebhook = (0, import_ts_pattern.match)(args).with(routeHandlerPattern, () => true).with(apiRoutePattern, () => false).exhaustive();
39
39
  const body = {
40
- version: "0.23.7",
40
+ version: "0.23.8-canary.0",
41
41
  previewMode: supportsPreviewMode,
42
42
  draftMode: supportsDraftMode,
43
43
  interactionMode: true,
@@ -25,7 +25,7 @@ var import_server = require("next/server");
25
25
  var import_ts_pattern = require("ts-pattern");
26
26
  var import_headers = require("next/headers");
27
27
  var import_draft_mode = require("../../draft-mode");
28
- var import_preview_mode = require("../../preview-mode");
28
+ var import_site_version = require("../../../api/site-version");
29
29
  const routeHandlerPattern = [import_ts_pattern.P.instanceOf(Request), import_ts_pattern.P.any, import_ts_pattern.P.any];
30
30
  const apiRoutePattern = [import_ts_pattern.P.any, import_ts_pattern.P.any, import_ts_pattern.P.any];
31
31
  async function proxyDraftMode(...args) {
@@ -37,7 +37,7 @@ async function proxyDraftModeRouteHandler(request, _context, { apiKey }) {
37
37
  return new import_server.NextResponse("Unauthorized", { status: 401 });
38
38
  const draftModeData = {
39
39
  makeswift: true,
40
- siteVersion: import_preview_mode.MakeswiftSiteVersion.Working
40
+ siteVersion: import_site_version.MakeswiftSiteVersion.Working
41
41
  };
42
42
  const draft = await (0, import_headers.draftMode)();
43
43
  draft.enable();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/next/api-handler/handlers/proxy-draft-mode.ts"],"sourcesContent":["import { NextApiRequest, NextApiResponse } from 'next'\nimport { NextRequest, NextResponse } from 'next/server'\nimport { P, match } from 'ts-pattern'\nimport { cookies, draftMode } from 'next/headers'\n\nimport { MAKESWIFT_DRAFT_MODE_DATA_COOKIE, MakeswiftDraftData } from '../../draft-mode'\nimport { MakeswiftSiteVersion } from '../../preview-mode'\n\ntype Context = { params: { [key: string]: string | string[] } }\n\ntype ProxyDraftModeError = string\n\ntype ProxyResponse = { __brand: 'ProxyResponse' }\n\nexport type ProxyDraftModeResponse = ProxyDraftModeError | ProxyResponse\n\ntype ProxyDraftModeHandlerArgs =\n | [request: NextRequest, context: Context, params: { apiKey: string }]\n | [req: NextApiRequest, res: NextApiResponse<ProxyDraftModeResponse>, params: { apiKey: string }]\n\nconst routeHandlerPattern = [P.instanceOf(Request), P.any, P.any] as const\nconst apiRoutePattern = [P.any, P.any, P.any] as const\n\nexport default async function proxyDraftMode(\n request: NextRequest,\n context: Context,\n { apiKey }: { apiKey: string },\n): Promise<NextResponse<ProxyDraftModeResponse>>\nexport default async function proxyDraftMode(\n req: NextApiRequest,\n res: NextApiResponse<ProxyDraftModeResponse>,\n { apiKey }: { apiKey: string },\n): Promise<void>\nexport default async function proxyDraftMode(\n ...args: ProxyDraftModeHandlerArgs\n): Promise<NextResponse<ProxyDraftModeResponse> | void> {\n return match(args)\n .with(routeHandlerPattern, args => proxyDraftModeRouteHandler(...args))\n .with(apiRoutePattern, args => proxyDraftModeApiRouteHandler(...args))\n .exhaustive()\n}\n\nasync function proxyDraftModeRouteHandler(\n request: NextRequest,\n _context: Context,\n { apiKey }: { apiKey: string },\n): Promise<NextResponse<ProxyDraftModeResponse>> {\n const secret =\n request.nextUrl.searchParams.get('x-makeswift-draft-mode') ??\n request.headers.get('X-Makeswift-Draft-Mode')\n\n if (secret !== apiKey) return new NextResponse('Unauthorized', { status: 401 })\n\n const draftModeData: MakeswiftDraftData = {\n makeswift: true,\n siteVersion: MakeswiftSiteVersion.Working,\n }\n\n const draft = await draftMode()\n draft.enable()\n\n const proxyUrl = request.nextUrl.clone()\n\n if (process.env.MAKESWIFT_DRAFT_MODE_PROXY_FORCE_HTTP == null) {\n proxyUrl.protocol = request.headers.get('x-forwarded-proto') ?? request.nextUrl.protocol\n } else {\n proxyUrl.protocol = 'http'\n }\n\n const forwardingHost = request.headers.get('x-forwarded-host') ?? request.headers.get('host')\n if (forwardingHost) {\n proxyUrl.host = forwardingHost\n }\n\n proxyUrl.searchParams.delete('x-makeswift-draft-mode')\n\n const proxyHeaders = new Headers(request.headers)\n proxyHeaders.delete('X-Makeswift-Draft-Mode')\n\n const proxyRequest = new NextRequest(proxyUrl, { headers: proxyHeaders })\n const draftModeCookie = (await cookies()).get('__prerender_bypass')\n if (draftModeCookie) {\n proxyRequest.cookies.set(draftModeCookie)\n proxyRequest.cookies.set(MAKESWIFT_DRAFT_MODE_DATA_COOKIE, JSON.stringify(draftModeData))\n }\n\n draft.disable()\n\n const proxyResponse = await fetch(proxyRequest)\n\n const response = new NextResponse<ProxyResponse>(proxyResponse.body, {\n headers: proxyResponse.headers,\n status: proxyResponse.status,\n })\n\n // `fetch` automatically decompresses the response, but the response headers will keep the\n // `content-encoding` and `content-length` headers. This will cause decoding issues if the client\n // attempts to decompress the response again. To prevent this, we remove these headers.\n //\n // See https://github.com/nodejs/undici/issues/2514.\n if (response.headers.has('content-encoding')) {\n response.headers.delete('content-encoding')\n response.headers.delete('content-length')\n }\n\n return response\n}\n\nasync function proxyDraftModeApiRouteHandler(\n _req: NextApiRequest,\n res: NextApiResponse<ProxyDraftModeResponse>,\n {}: { apiKey: string },\n): Promise<void> {\n const message =\n 'Cannot request draft endpoint from an API handler registered in `pages`. Move your Makeswift API handler to the `app` directory'\n console.error(message)\n return res.status(500).send(message)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAA0C;AAC1C,wBAAyB;AACzB,qBAAmC;AAEnC,wBAAqE;AACrE,0BAAqC;AAcrC,MAAM,sBAAsB,CAAC,oBAAE,WAAW,OAAO,GAAG,oBAAE,KAAK,oBAAE,GAAG;AAChE,MAAM,kBAAkB,CAAC,oBAAE,KAAK,oBAAE,KAAK,oBAAE,GAAG;AAY5C,eAAO,kBACF,MACmD;AACtD,aAAO,yBAAM,IAAI,EACd,KAAK,qBAAqB,CAAAA,UAAQ,2BAA2B,GAAGA,KAAI,CAAC,EACrE,KAAK,iBAAiB,CAAAA,UAAQ,8BAA8B,GAA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I,SAAS,QAAQ,IAAI,kBAAkB,GAAG;AAC5C,aAAS,QAAQ,OAAO,kBAAkB;AAC1C,aAAS,QAAQ,OAAO,gBAAgB;AAAA,EAC1C;AAEA,SAAO;AACT;AAEA,eAAe,8BACb,MACA,KACA,CAAC,GACc;AACf,QAAM,UACJ;AACF,UAAQ,MAAM,OAAO;AACrB,SAAO,IAAI,OAAO,GAAG,EAAE,KAAK,OAAO;AACrC;","names":["args"]}
1
+ {"version":3,"sources":["../../../../../src/next/api-handler/handlers/proxy-draft-mode.ts"],"sourcesContent":["import { NextApiRequest, NextApiResponse } from 'next'\nimport { NextRequest, NextResponse } from 'next/server'\nimport { P, match } from 'ts-pattern'\nimport { cookies, draftMode } from 'next/headers'\n\nimport { MAKESWIFT_DRAFT_MODE_DATA_COOKIE, MakeswiftDraftData } from '../../draft-mode'\nimport { MakeswiftSiteVersion } from '../../../api/site-version'\n\ntype Context = { params: { [key: string]: string | string[] } }\n\ntype ProxyDraftModeError = string\n\ntype ProxyResponse = { __brand: 'ProxyResponse' }\n\nexport type ProxyDraftModeResponse = ProxyDraftModeError | ProxyResponse\n\ntype ProxyDraftModeHandlerArgs =\n | [request: NextRequest, context: Context, params: { apiKey: string }]\n | [req: NextApiRequest, res: NextApiResponse<ProxyDraftModeResponse>, params: { apiKey: string }]\n\nconst routeHandlerPattern = [P.instanceOf(Request), P.any, P.any] as const\nconst apiRoutePattern = [P.any, P.any, P.any] as const\n\nexport default async function proxyDraftMode(\n request: NextRequest,\n context: Context,\n { apiKey }: { apiKey: string },\n): Promise<NextResponse<ProxyDraftModeResponse>>\nexport default async function proxyDraftMode(\n req: NextApiRequest,\n res: NextApiResponse<ProxyDraftModeResponse>,\n { apiKey }: { apiKey: string },\n): Promise<void>\nexport default async function proxyDraftMode(\n ...args: ProxyDraftModeHandlerArgs\n): Promise<NextResponse<ProxyDraftModeResponse> | void> {\n return match(args)\n .with(routeHandlerPattern, args => proxyDraftModeRouteHandler(...args))\n .with(apiRoutePattern, args => proxyDraftModeApiRouteHandler(...args))\n .exhaustive()\n}\n\nasync function proxyDraftModeRouteHandler(\n request: NextRequest,\n _context: Context,\n { apiKey }: { apiKey: string },\n): Promise<NextResponse<ProxyDraftModeResponse>> {\n const secret =\n request.nextUrl.searchParams.get('x-makeswift-draft-mode') ??\n request.headers.get('X-Makeswift-Draft-Mode')\n\n if (secret !== apiKey) return new NextResponse('Unauthorized', { status: 401 })\n\n const draftModeData: MakeswiftDraftData = {\n makeswift: true,\n siteVersion: MakeswiftSiteVersion.Working,\n }\n\n const draft = await draftMode()\n draft.enable()\n\n const proxyUrl = request.nextUrl.clone()\n\n if (process.env.MAKESWIFT_DRAFT_MODE_PROXY_FORCE_HTTP == null) {\n proxyUrl.protocol = request.headers.get('x-forwarded-proto') ?? request.nextUrl.protocol\n } else {\n proxyUrl.protocol = 'http'\n }\n\n const forwardingHost = request.headers.get('x-forwarded-host') ?? request.headers.get('host')\n if (forwardingHost) {\n proxyUrl.host = forwardingHost\n }\n\n proxyUrl.searchParams.delete('x-makeswift-draft-mode')\n\n const proxyHeaders = new Headers(request.headers)\n proxyHeaders.delete('X-Makeswift-Draft-Mode')\n\n const proxyRequest = new NextRequest(proxyUrl, { headers: proxyHeaders })\n const draftModeCookie = (await cookies()).get('__prerender_bypass')\n if (draftModeCookie) {\n proxyRequest.cookies.set(draftModeCookie)\n proxyRequest.cookies.set(MAKESWIFT_DRAFT_MODE_DATA_COOKIE, JSON.stringify(draftModeData))\n }\n\n draft.disable()\n\n const proxyResponse = await fetch(proxyRequest)\n\n const response = new NextResponse<ProxyResponse>(proxyResponse.body, {\n headers: proxyResponse.headers,\n status: proxyResponse.status,\n })\n\n // `fetch` automatically decompresses the response, but the response headers will keep the\n // `content-encoding` and `content-length` headers. This will cause decoding issues if the client\n // attempts to decompress the response again. To prevent this, we remove these headers.\n //\n // See https://github.com/nodejs/undici/issues/2514.\n if (response.headers.has('content-encoding')) {\n response.headers.delete('content-encoding')\n response.headers.delete('content-length')\n }\n\n return response\n}\n\nasync function proxyDraftModeApiRouteHandler(\n _req: NextApiRequest,\n res: NextApiResponse<ProxyDraftModeResponse>,\n {}: { apiKey: string },\n): Promise<void> {\n const message =\n 'Cannot request draft endpoint from an API handler registered in `pages`. Move your Makeswift API handler to the `app` directory'\n console.error(message)\n return res.status(500).send(message)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAA0C;AAC1C,wBAAyB;AACzB,qBAAmC;AAEnC,wBAAqE;AACrE,0BAAqC;AAcrC,MAAM,sBAAsB,CAAC,oBAAE,WAAW,OAAO,GAAG,oBAAE,KAAK,oBAAE,GAAG;AAChE,MAAM,kBAAkB,CAAC,oBAAE,KAAK,oBAAE,KAAK,oBAAE,GAAG;AAY5C,eAAO,kBACF,MACmD;AACtD,aAAO,yBAAM,IAAI,EACd,KAAK,qBAAqB,CAAAA,UAAQ,2BAA2B,GAAGA,KAAI,CAAC,EACrE,KAAK,iBAAiB,CAAAA,UAAQ,8BAA8B,GAAGA,KAAI,CAAC,EACpE,WAAW;AAChB;AAEA,eAAe,2BACb,SACA,UACA,EAAE,OAAO,GACsC;AAC/C,QAAM,SACJ,QAAQ,QAAQ,aAAa,IAAI,wBAAwB,KACzD,QAAQ,QAAQ,IAAI,wBAAwB;AAE9C,MAAI,WAAW;AAAQ,WAAO,IAAI,2BAAa,gBAAgB,EAAE,QAAQ,IAAI,CAAC;AAE9E,QAAM,gBAAoC;AAAA,IACxC,WAAW;AAAA,IACX,aAAa,yCAAqB;AAAA,EACpC;AAEA,QAAM,QAAQ,UAAM,0BAAU;AAC9B,QAAM,OAAO;AAEb,QAAM,WAAW,QAAQ,QAAQ,MAAM;AAEvC,MAAI,QAAQ,IAAI,yCAAyC,MAAM;AAC7D,aAAS,WAAW,QAAQ,QAAQ,IAAI,mBAAmB,KAAK,QAAQ,QAAQ;AAAA,EAClF,OAAO;AACL,aAAS,WAAW;AAAA,EACtB;AAEA,QAAM,iBAAiB,QAAQ,QAAQ,IAAI,kBAAkB,KAAK,QAAQ,QAAQ,IAAI,MAAM;AAC5F,MAAI,gBAAgB;AAClB,aAAS,OAAO;AAAA,EAClB;AAEA,WAAS,aAAa,OAAO,wBAAwB;AAErD,QAAM,eAAe,IAAI,QAAQ,QAAQ,OAAO;AAChD,eAAa,OAAO,wBAAwB;AAE5C,QAAM,eAAe,IAAI,0BAAY,UAAU,EAAE,SAAS,aAAa,CAAC;AACxE,QAAM,mBAAmB,UAAM,wBAAQ,GAAG,IAAI,oBAAoB;AAClE,MAAI,iBAAiB;AACnB,iBAAa,QAAQ,IAAI,eAAe;AACxC,iBAAa,QAAQ,IAAI,oDAAkC,KAAK,UAAU,aAAa,CAAC;AAAA,EAC1F;AAEA,QAAM,QAAQ;AAEd,QAAM,gBAAgB,MAAM,MAAM,YAAY;AAE9C,QAAM,WAAW,IAAI,2BAA4B,cAAc,MAAM;AAAA,IACnE,SAAS,cAAc;AAAA,IACvB,QAAQ,cAAc;AAAA,EACxB,CAAC;AAOD,MAAI,SAAS,QAAQ,IAAI,kBAAkB,GAAG;AAC5C,aAAS,QAAQ,OAAO,kBAAkB;AAC1C,aAAS,QAAQ,OAAO,gBAAgB;AAAA,EAC1C;AAEA,SAAO;AACT;AAEA,eAAe,8BACb,MACA,KACA,CAAC,GACc;AACf,QAAM,UACJ;AACF,UAAQ,MAAM,OAAO;AACrB,SAAO,IAAI,OAAO,GAAG,EAAE,KAAK,OAAO;AACrC;","names":["args"]}
@@ -21,9 +21,9 @@ __export(proxy_preview_mode_exports, {
21
21
  default: () => proxyPreviewMode
22
22
  });
23
23
  module.exports = __toCommonJS(proxy_preview_mode_exports);
24
- var import_preview_mode = require("../../preview-mode");
25
24
  var import_server = require("next/server");
26
25
  var import_ts_pattern = require("ts-pattern");
26
+ var import_site_version = require("../../../api/site-version");
27
27
  const routeHandlerPattern = [import_ts_pattern.P.instanceOf(Request), import_ts_pattern.P.any, import_ts_pattern.P.any];
28
28
  const apiRoutePattern = [import_ts_pattern.P.any, import_ts_pattern.P.any, import_ts_pattern.P.any];
29
29
  function mapRequestHeadersToHeaders(requestHeaders) {
@@ -74,7 +74,7 @@ async function proxyPreviewModeApiRouteHandler(req, res, { apiKey }) {
74
74
  const previewData = {
75
75
  makeswift: true,
76
76
  // This will eventually be dynamic
77
- siteVersion: import_preview_mode.MakeswiftSiteVersion.Working
77
+ siteVersion: import_site_version.MakeswiftSiteVersion.Working
78
78
  };
79
79
  const setCookie = res.setPreviewData(previewData).getHeader("set-cookie");
80
80
  res.removeHeader("set-cookie");
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/next/api-handler/handlers/proxy-preview-mode.ts"],"sourcesContent":["import { NextApiRequest, NextApiResponse } from 'next'\nimport { MakeswiftPreviewData, MakeswiftSiteVersion } from '../../preview-mode'\nimport { NextRequest, NextResponse } from 'next/server'\nimport { P, match } from 'ts-pattern'\n\ntype Context = { params: { [key: string]: string | string[] } }\n\ntype ProxyPreviewModeError = string\n\ntype ProxyResponse = { __brand: 'ProxyResponse' }\n\nexport type ProxyPreviewModeResponse = ProxyPreviewModeError | ProxyResponse\n\ntype ProxyPreviewModeHandlerArgs =\n | [request: NextRequest, context: Context, params: { apiKey: string }]\n | [\n req: NextApiRequest,\n res: NextApiResponse<ProxyPreviewModeResponse>,\n params: { apiKey: string },\n ]\n\nconst routeHandlerPattern = [P.instanceOf(Request), P.any, P.any] as const\nconst apiRoutePattern = [P.any, P.any, P.any] as const\n\nfunction mapRequestHeadersToHeaders(requestHeaders: NextApiRequest['headers']): Headers {\n const headers = new Headers()\n\n Object.entries(requestHeaders).forEach(([key, value]) => {\n match(value)\n .with(P.array(P.string), value => value.map(val => headers.append(key, val)))\n .with(P.string, value => headers.set(key, value))\n })\n\n return headers\n}\n\nfunction mapRequestToProxyUrl(req: NextApiRequest): URL {\n const isForwardedProtoHttps = match(req.headers['x-forwarded-proto'])\n .with(P.string, x => x.split(','))\n .with(P.array(P.string), x => x)\n .otherwise(() => [])\n .includes('https')\n\n const isForwardedSSL = match(req.headers['x-forwarded-ssl'])\n .with('on', () => true)\n .otherwise(() => false)\n\n const proto = isForwardedProtoHttps || isForwardedSSL ? 'https' : 'http'\n\n return new URL(`${proto}://${req.headers.host}${req.url}`)\n}\n\nexport default async function proxyPreviewMode(\n request: NextRequest,\n context: Context,\n { apiKey }: { apiKey: string },\n): Promise<NextResponse<ProxyPreviewModeResponse>>\nexport default async function proxyPreviewMode(\n req: NextApiRequest,\n res: NextApiResponse<ProxyPreviewModeResponse>,\n { apiKey }: { apiKey: string },\n): Promise<void>\nexport default async function proxyPreviewMode(\n ...args: ProxyPreviewModeHandlerArgs\n): Promise<NextResponse<ProxyPreviewModeResponse> | void> {\n return match(args)\n .with(routeHandlerPattern, args => proxyPreviewModeRouteHandler(...args))\n .with(apiRoutePattern, args => proxyPreviewModeApiRouteHandler(...args))\n .exhaustive()\n}\n\nasync function proxyPreviewModeRouteHandler(\n _request: NextRequest,\n _context: Context,\n {}: { apiKey: string },\n): Promise<NextResponse<ProxyPreviewModeResponse>> {\n const message =\n 'Cannot request preview endpoint from an API handler registered in `app`. Move your Makeswift API handler to the `pages/api` directory'\n console.error(message)\n return NextResponse.json(message, { status: 500 })\n}\n\nasync function proxyPreviewModeApiRouteHandler(\n req: NextApiRequest,\n res: NextApiResponse<ProxyPreviewModeResponse>,\n { apiKey }: { apiKey: string },\n): Promise<void> {\n if (req.query.secret !== apiKey) return res.status(401).send('Unauthorized')\n if (req.headers.host == null) return res.status(400).send('Bad Request')\n\n // TODO: This is a hack to get the locale from the request.\n // Next.js strips the locale from the req.url, and there's no official way to get the locale\n // from an API route: https://github.com/vercel/next.js/discussions/21798.\n // The current workaround is to get the locale from an internal object: RequestMeta,\n // https://github.com/vercel/next.js/blob/a0d1d728b9003f12c9df6c5e9a33bc4c33cef0ab/packages/next/src/server/request-meta.ts\n // One possible way to properly fix this is by updating how we do preview mode. For example,\n // by using partitioned cookies instead of a proxy.\n const NextRequestMetaSymbol = Reflect.ownKeys(req).find(\n key =>\n key.toString() === 'Symbol(NextRequestMeta)' ||\n key.toString() === 'Symbol(NextInternalRequestMeta)',\n ) as keyof NextApiRequest | undefined\n\n if (NextRequestMetaSymbol) {\n const nextRequestMeta = req[NextRequestMetaSymbol]\n const initUrl = nextRequestMeta?.__NEXT_INIT_URL ?? nextRequestMeta?.initURL\n const isLocaleStripped =\n nextRequestMeta?.__nextStrippedLocale ?? nextRequestMeta?.didStripLocale\n\n try {\n if (isLocaleStripped && initUrl) req.url = new URL(initUrl).pathname\n } catch {}\n }\n\n const proxyHeaders = mapRequestHeadersToHeaders(req.headers)\n const proxyUrl = mapRequestToProxyUrl(req)\n\n proxyUrl.searchParams.delete('x-makeswift-preview-mode')\n proxyHeaders.delete('x-makeswift-preview-mode')\n // The following headers are Next.js-specific and are removed to prevent Next.js from\n // short-circuiting requests, breaking routing.\n proxyHeaders.delete('x-invoke-path')\n proxyHeaders.delete('x-invoke-query')\n\n const previewData: MakeswiftPreviewData = {\n makeswift: true,\n // This will eventually be dynamic\n siteVersion: MakeswiftSiteVersion.Working,\n }\n\n const setCookie = res.setPreviewData(previewData).getHeader('set-cookie')\n res.removeHeader('set-cookie')\n\n if (!Array.isArray(setCookie)) return res.status(500).send('Internal Server Error')\n\n setCookie.forEach(cookie => proxyHeaders.append('cookie', cookie))\n\n const response = await fetch(proxyUrl, {\n headers: proxyHeaders,\n })\n\n response.headers.forEach((value, name) => {\n res.setHeader(name, value)\n })\n\n res.statusCode = response.status\n res.statusMessage = response.statusText\n\n // `fetch` automatically decompresses the response, but the response headers will keep the\n // `content-encoding` and `content-length` headers. This will cause decoding issues if the client\n // attempts to decompress the response again. To prevent this, we remove these headers.\n //\n // See https://github.com/nodejs/undici/issues/2514.\n if (res.hasHeader('content-encoding')) {\n res.removeHeader('content-encoding')\n res.removeHeader('content-length')\n }\n\n const arrayBuffer = await response.arrayBuffer()\n\n res.write(new Uint8Array(arrayBuffer))\n res.end()\n}\n"],"mappings":";;;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U,QAAQ,YAAU,aAAa,OAAO,UAAU,MAAM,CAAC;AAEjE,QAAM,WAAW,MAAM,MAAM,UAAU;AAAA,IACrC,SAAS;AAAA,EACX,CAAC;AAED,WAAS,QAAQ,QAAQ,CAAC,OAAO,SAAS;AACxC,QAAI,UAAU,MAAM,KAAK;AAAA,EAC3B,CAAC;AAED,MAAI,aAAa,SAAS;AAC1B,MAAI,gBAAgB,SAAS;AAO7B,MAAI,IAAI,UAAU,kBAAkB,GAAG;AACrC,QAAI,aAAa,kBAAkB;AACnC,QAAI,aAAa,gBAAgB;AAAA,EACnC;AAEA,QAAM,cAAc,MAAM,SAAS,YAAY;AAE/C,MAAI,MAAM,IAAI,WAAW,WAAW,CAAC;AACrC,MAAI,IAAI;AACV;","names":["value","args"]}
1
+ {"version":3,"sources":["../../../../../src/next/api-handler/handlers/proxy-preview-mode.ts"],"sourcesContent":["import { NextApiRequest, NextApiResponse } from 'next'\nimport { MakeswiftPreviewData } from '../../preview-mode'\nimport { NextRequest, NextResponse } from 'next/server'\nimport { P, match } from 'ts-pattern'\nimport { MakeswiftSiteVersion } from '../../../api/site-version'\n\ntype Context = { params: { [key: string]: string | string[] } }\n\ntype ProxyPreviewModeError = string\n\ntype ProxyResponse = { __brand: 'ProxyResponse' }\n\nexport type ProxyPreviewModeResponse = ProxyPreviewModeError | ProxyResponse\n\ntype ProxyPreviewModeHandlerArgs =\n | [request: NextRequest, context: Context, params: { apiKey: string }]\n | [\n req: NextApiRequest,\n res: NextApiResponse<ProxyPreviewModeResponse>,\n params: { apiKey: string },\n ]\n\nconst routeHandlerPattern = [P.instanceOf(Request), P.any, P.any] as const\nconst apiRoutePattern = [P.any, P.any, P.any] as const\n\nfunction mapRequestHeadersToHeaders(requestHeaders: NextApiRequest['headers']): Headers {\n const headers = new Headers()\n\n Object.entries(requestHeaders).forEach(([key, value]) => {\n match(value)\n .with(P.array(P.string), value => value.map(val => headers.append(key, val)))\n .with(P.string, value => headers.set(key, value))\n })\n\n return headers\n}\n\nfunction mapRequestToProxyUrl(req: NextApiRequest): URL {\n const isForwardedProtoHttps = match(req.headers['x-forwarded-proto'])\n .with(P.string, x => x.split(','))\n .with(P.array(P.string), x => x)\n .otherwise(() => [])\n .includes('https')\n\n const isForwardedSSL = match(req.headers['x-forwarded-ssl'])\n .with('on', () => true)\n .otherwise(() => false)\n\n const proto = isForwardedProtoHttps || isForwardedSSL ? 'https' : 'http'\n\n return new URL(`${proto}://${req.headers.host}${req.url}`)\n}\n\nexport default async function proxyPreviewMode(\n request: NextRequest,\n context: Context,\n { apiKey }: { apiKey: string },\n): Promise<NextResponse<ProxyPreviewModeResponse>>\nexport default async function proxyPreviewMode(\n req: NextApiRequest,\n res: NextApiResponse<ProxyPreviewModeResponse>,\n { apiKey }: { apiKey: string },\n): Promise<void>\nexport default async function proxyPreviewMode(\n ...args: ProxyPreviewModeHandlerArgs\n): Promise<NextResponse<ProxyPreviewModeResponse> | void> {\n return match(args)\n .with(routeHandlerPattern, args => proxyPreviewModeRouteHandler(...args))\n .with(apiRoutePattern, args => proxyPreviewModeApiRouteHandler(...args))\n .exhaustive()\n}\n\nasync function proxyPreviewModeRouteHandler(\n _request: NextRequest,\n _context: Context,\n {}: { apiKey: string },\n): Promise<NextResponse<ProxyPreviewModeResponse>> {\n const message =\n 'Cannot request preview endpoint from an API handler registered in `app`. Move your Makeswift API handler to the `pages/api` directory'\n console.error(message)\n return NextResponse.json(message, { status: 500 })\n}\n\nasync function proxyPreviewModeApiRouteHandler(\n req: NextApiRequest,\n res: NextApiResponse<ProxyPreviewModeResponse>,\n { apiKey }: { apiKey: string },\n): Promise<void> {\n if (req.query.secret !== apiKey) return res.status(401).send('Unauthorized')\n if (req.headers.host == null) return res.status(400).send('Bad Request')\n\n // TODO: This is a hack to get the locale from the request.\n // Next.js strips the locale from the req.url, and there's no official way to get the locale\n // from an API route: https://github.com/vercel/next.js/discussions/21798.\n // The current workaround is to get the locale from an internal object: RequestMeta,\n // https://github.com/vercel/next.js/blob/a0d1d728b9003f12c9df6c5e9a33bc4c33cef0ab/packages/next/src/server/request-meta.ts\n // One possible way to properly fix this is by updating how we do preview mode. For example,\n // by using partitioned cookies instead of a proxy.\n const NextRequestMetaSymbol = Reflect.ownKeys(req).find(\n key =>\n key.toString() === 'Symbol(NextRequestMeta)' ||\n key.toString() === 'Symbol(NextInternalRequestMeta)',\n ) as keyof NextApiRequest | undefined\n\n if (NextRequestMetaSymbol) {\n const nextRequestMeta = req[NextRequestMetaSymbol]\n const initUrl = nextRequestMeta?.__NEXT_INIT_URL ?? nextRequestMeta?.initURL\n const isLocaleStripped =\n nextRequestMeta?.__nextStrippedLocale ?? nextRequestMeta?.didStripLocale\n\n try {\n if (isLocaleStripped && initUrl) req.url = new URL(initUrl).pathname\n } catch {}\n }\n\n const proxyHeaders = mapRequestHeadersToHeaders(req.headers)\n const proxyUrl = mapRequestToProxyUrl(req)\n\n proxyUrl.searchParams.delete('x-makeswift-preview-mode')\n proxyHeaders.delete('x-makeswift-preview-mode')\n // The following headers are Next.js-specific and are removed to prevent Next.js from\n // short-circuiting requests, breaking routing.\n proxyHeaders.delete('x-invoke-path')\n proxyHeaders.delete('x-invoke-query')\n\n const previewData: MakeswiftPreviewData = {\n makeswift: true,\n // This will eventually be dynamic\n siteVersion: MakeswiftSiteVersion.Working,\n }\n\n const setCookie = res.setPreviewData(previewData).getHeader('set-cookie')\n res.removeHeader('set-cookie')\n\n if (!Array.isArray(setCookie)) return res.status(500).send('Internal Server Error')\n\n setCookie.forEach(cookie => proxyHeaders.append('cookie', cookie))\n\n const response = await fetch(proxyUrl, {\n headers: proxyHeaders,\n })\n\n response.headers.forEach((value, name) => {\n res.setHeader(name, value)\n })\n\n res.statusCode = response.status\n res.statusMessage = response.statusText\n\n // `fetch` automatically decompresses the response, but the response headers will keep the\n // `content-encoding` and `content-length` headers. This will cause decoding issues if the client\n // attempts to decompress the response again. To prevent this, we remove these headers.\n //\n // See https://github.com/nodejs/undici/issues/2514.\n if (res.hasHeader('content-encoding')) {\n res.removeHeader('content-encoding')\n res.removeHeader('content-length')\n }\n\n const arrayBuffer = await response.arrayBuffer()\n\n res.write(new Uint8Array(arrayBuffer))\n res.end()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,oBAA0C;AAC1C,wBAAyB;AACzB,0BAAqC;AAkBrC,MAAM,sBAAsB,CAAC,oBAAE,WAAW,OAAO,GAAG,oBAAE,KAAK,oBAAE,GAAG;AAChE,MAAM,kBAAkB,CAAC,oBAAE,KAAK,oBAAE,KAAK,oBAAE,GAAG;AAE5C,SAAS,2BAA2B,gBAAoD;AACtF,QAAM,UAAU,IAAI,QAAQ;AAE5B,SAAO,QAAQ,cAAc,EAAE,QAAQ,CAAC,CAAC,KAAK,KAAK,MAAM;AACvD,iCAAM,KAAK,EACR,KAAK,oBAAE,MAAM,oBAAE,MAAM,GAAG,CAAAA,WAASA,OAAM,IAAI,SAAO,QAAQ,OAAO,KAAK,GAAG,CAAC,CAAC,EAC3E,KAAK,oBAAE,QAAQ,CAAAA,WAAS,QAAQ,IAAI,KAAKA,MAAK,CAAC;AAAA,EACpD,CAAC;AAED,SAAO;AACT;AAEA,SAAS,qBAAqB,KAA0B;AACtD,QAAM,4BAAwB,yBAAM,IAAI,QAAQ,mBAAmB,CAAC,EACjE,KAAK,oBAAE,QAAQ,OAAK,EAAE,MAAM,GAAG,CAAC,EAChC,KAAK,oBAAE,MAAM,oBAAE,MAAM,GAAG,OAAK,CAAC,EAC9B,UAAU,MAAM,CAAC,CAAC,EAClB,SAAS,OAAO;AAEnB,QAAM,qBAAiB,yBAAM,IAAI,QAAQ,iBAAiB,CAAC,EACxD,KAAK,MAAM,MAAM,IAAI,EACrB,UAAU,MAAM,KAAK;AAExB,QAAM,QAAQ,yBAAyB,iBAAiB,UAAU;AAElE,SAAO,IAAI,IAAI,GAAG,KAAK,MAAM,IAAI,QAAQ,IAAI,GAAG,IAAI,GAAG,EAAE;AAC3D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AAU,YAAY;AACxE,MAAI,aAAa,YAAY;AAE7B,MAAI,CAAC,MAAM,QAAQ,SAAS;AAAG,WAAO,IAAI,OAAO,GAAG,EAAE,KAAK,uBAAuB;AAElF,YAAU,QAAQ,YAAU,aAAa,OAAO,UAAU,MAAM,CAAC;AAEjE,QAAM,WAAW,MAAM,MAAM,UAAU;AAAA,IACrC,SAAS;AAAA,EACX,CAAC;AAED,WAAS,QAAQ,QAAQ,CAAC,OAAO,SAAS;AACxC,QAAI,UAAU,MAAM,KAAK;AAAA,EAC3B,CAAC;AAED,MAAI,aAAa,SAAS;AAC1B,MAAI,gBAAgB,SAAS;AAO7B,MAAI,IAAI,UAAU,kBAAkB,GAAG;AACrC,QAAI,aAAa,kBAAkB;AACnC,QAAI,aAAa,gBAAgB;AAAA,EACnC;AAEA,QAAM,cAAc,MAAM,SAAS,YAAY;AAE/C,MAAI,MAAM,IAAI,WAAW,WAAW,CAAC;AACrC,MAAI,IAAI;AACV;","names":["value","args"]}
@@ -45,7 +45,7 @@ var import_translatable_data = __toESM(require("./handlers/translatable-data"));
45
45
  var import_merge_translated_data = __toESM(require("./handlers/merge-translated-data"));
46
46
  var import_webhook = __toESM(require("./handlers/webhook"));
47
47
  var import_ts_pattern = require("ts-pattern");
48
- var import_draft_mode = require("../draft-mode");
48
+ var import_site_version = require("../../api/site-version");
49
49
  function apiRequestParams(request) {
50
50
  return Promise.resolve(request.query);
51
51
  }
@@ -84,6 +84,16 @@ Received "${apiKey}" instead.`
84
84
  return await makeswiftApiHandler(...args2);
85
85
  }).exhaustive();
86
86
  };
87
+ function getSiteVersionFromRequest(args) {
88
+ const header = (0, import_ts_pattern.match)(args).with(
89
+ routeHandlerPattern,
90
+ ([request]) => request.headers.get(import_site_version.API_HANDLER_SITE_VERSION_HEADER)
91
+ ).with(apiRoutePattern, ([req]) => req.headers[import_site_version.API_HANDLER_SITE_VERSION_HEADER.toLowerCase()]).exhaustive();
92
+ const parsed = import_site_version.makeswiftSiteVersionSchema.safeParse(header);
93
+ if (!parsed.success)
94
+ return import_site_version.MakeswiftSiteVersion.Live;
95
+ return parsed.data;
96
+ }
87
97
  async function makeswiftApiHandler(...args) {
88
98
  const params = (0, import_ts_pattern.match)(args).with(routeHandlerPattern, ([, context]) => context.params).with(apiRoutePattern, ([req]) => apiRequestParams(req)).exhaustive();
89
99
  const { makeswift } = await params;
@@ -95,7 +105,7 @@ Read more about dynamic catch-all routes here: https://nextjs.org/docs/routing/d
95
105
  );
96
106
  }
97
107
  const client = new import_client.Makeswift(apiKey, { apiOrigin, runtime });
98
- const siteVersion = await (0, import_ts_pattern.match)(args).with(routeHandlerPattern, () => (0, import_draft_mode.getSiteVersion)()).with(apiRoutePattern, ([req]) => import_client.Makeswift.getSiteVersion(req.previewData)).exhaustive();
108
+ const siteVersion = getSiteVersionFromRequest(args);
99
109
  const action = "/" + makeswift.join("/");
100
110
  const matches = (pattern) => (0, import_path_to_regexp.match)(pattern, { decode: decodeURIComponent })(action);
101
111
  let m;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/next/api-handler/index.ts"],"sourcesContent":["import Cors from 'cors'\nimport { NextApiRequest, NextApiResponse } from 'next'\nimport { NextRequest, NextResponse } from 'next/server'\nimport { Match, match as matchPattern } from 'path-to-regexp'\nimport { APIResource } from '../../api'\nimport { Makeswift } from '../client'\n\nimport elementTree, { ElementTreeResponse } from './handlers/element-tree'\nimport fonts, { Font, FontsResponse, GetFonts } from './handlers/fonts'\nimport manifest, { Manifest, ManifestResponse } from './handlers/manifest'\nimport proxyPreviewMode, { ProxyPreviewModeResponse } from './handlers/proxy-preview-mode'\nimport proxyDraftMode, { ProxyDraftModeResponse } from './handlers/proxy-draft-mode'\nimport { revalidate, RevalidationResponse } from './handlers/revalidate'\nimport translatableData, { TranslatableDataResponse } from './handlers/translatable-data'\nimport mergeTranslatedData, { TranslatedDataResponse } from './handlers/merge-translated-data'\nimport webhook from './handlers/webhook'\nimport { WebhookResponseBody } from './handlers/webhook/types'\nimport { ReactRuntime } from '../../react'\nimport { P, match } from 'ts-pattern'\nimport { getSiteVersion } from '../draft-mode'\n\nexport type { Manifest, Font }\n\ntype Context = { params: { [key: string]: string | string[] } }\n\ntype MakeswiftApiHandlerConfig = {\n appOrigin?: string\n apiOrigin?: string\n getFonts?: GetFonts\n runtime: ReactRuntime\n}\n\ntype NotFoundError = { message: string }\n\nexport type MakeswiftApiHandlerResponse =\n | ManifestResponse\n | RevalidationResponse\n | ProxyPreviewModeResponse\n | ProxyDraftModeResponse\n | FontsResponse\n | ElementTreeResponse\n | TranslatableDataResponse\n | TranslatedDataResponse\n | APIResource\n | NotFoundError\n | WebhookResponseBody\n\ntype MakeswiftApiHandlerArgs =\n | [NextRequest, Context]\n | [NextApiRequest, NextApiResponse<MakeswiftApiHandlerResponse>]\n\nfunction apiRequestParams(request: NextApiRequest): Promise<NextApiRequest['query']> {\n // `NextApiRequest.query` prop became async in Next.js 15, but it's not reflected in the type definition;\n // force-casting it to a `Promise` manually\n return Promise.resolve(request.query)\n}\n\nexport function MakeswiftApiHandler(\n apiKey: string,\n {\n appOrigin = 'https://app.makeswift.com',\n apiOrigin = 'https://api.makeswift.com',\n getFonts,\n runtime,\n }: MakeswiftApiHandlerConfig,\n): (...args: MakeswiftApiHandlerArgs) => Promise<NextResponse<MakeswiftApiHandlerResponse> | void> {\n const cors = Cors({ origin: appOrigin })\n\n if (typeof apiKey !== 'string') {\n throw new Error(\n 'The Makeswift Next.js API handler must be passed a valid Makeswift site API key: ' +\n \"`MakeswiftApiHandler('<makeswift_site_api_key>')`\\n\" +\n `Received \"${apiKey}\" instead.`,\n )\n }\n\n const routeHandlerPattern = [P.instanceOf(Request), P.any] as const\n const apiRoutePattern = [P.any, P.any] as const\n\n return function handler(\n ...args: MakeswiftApiHandlerArgs\n ): Promise<NextResponse<MakeswiftApiHandlerResponse> | void> {\n return match(args)\n .with(routeHandlerPattern, async args => {\n const response = await makeswiftApiHandler(...args)\n\n response.headers.append('Access-Control-Allow-Origin', appOrigin)\n response.headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')\n response.headers.append('Access-Control-Allow-Headers', 'Content-Type, Authorization')\n\n return response\n })\n .with(apiRoutePattern, async args => {\n const [req, res] = args\n\n await new Promise<void>((resolve, reject) => {\n cors(req, res, err => {\n if (err instanceof Error) reject(err)\n else resolve()\n })\n })\n\n return await makeswiftApiHandler(...args)\n })\n .exhaustive()\n }\n\n async function makeswiftApiHandler(\n request: NextRequest,\n context: Context,\n ): Promise<NextResponse<MakeswiftApiHandlerResponse>>\n async function makeswiftApiHandler(\n req: NextApiRequest,\n res: NextApiResponse<MakeswiftApiHandlerResponse>,\n ): Promise<void>\n async function makeswiftApiHandler(\n ...args: MakeswiftApiHandlerArgs\n ): Promise<NextResponse<MakeswiftApiHandlerResponse> | void> {\n const params = match(args)\n .with(routeHandlerPattern, ([, context]) => context.params)\n .with(apiRoutePattern, ([req]) => apiRequestParams(req))\n .exhaustive()\n\n const { makeswift } = await params\n\n if (!Array.isArray(makeswift)) {\n throw new Error(\n 'The Makeswift Next.js API handler must be used in a dynamic catch-all route named `[...makeswift]`.\\n' +\n `Received \"${makeswift}\" for the \\`makeswift\\` param instead.\\n` +\n 'Read more about dynamic catch-all routes here: https://nextjs.org/docs/routing/dynamic-routes#catch-all-routes',\n )\n }\n\n const client = new Makeswift(apiKey, { apiOrigin, runtime })\n const siteVersion = await match(args)\n .with(routeHandlerPattern, () => getSiteVersion())\n .with(apiRoutePattern, ([req]) => Makeswift.getSiteVersion(req.previewData))\n .exhaustive()\n const action = '/' + makeswift.join('/')\n const matches = <T extends object>(pattern: string): Match<T> =>\n matchPattern<T>(pattern, { decode: decodeURIComponent })(action)\n\n let m\n\n if (matches('/manifest')) {\n return match(args)\n .with(routeHandlerPattern, args => manifest(...args, { apiKey }))\n .with(apiRoutePattern, args => manifest(...args, { apiKey }))\n .exhaustive()\n }\n\n if (matches('/revalidate')) {\n return match(args)\n .with(routeHandlerPattern, args => revalidate(...args, { apiKey }))\n .with(apiRoutePattern, args => revalidate(...args, { apiKey }))\n .exhaustive()\n }\n\n if (matches('/proxy-preview-mode')) {\n return match(args)\n .with(routeHandlerPattern, args => proxyPreviewMode(...args, { apiKey }))\n .with(apiRoutePattern, args => proxyPreviewMode(...args, { apiKey }))\n .exhaustive()\n }\n\n if (matches('/proxy-draft-mode')) {\n return match(args)\n .with(routeHandlerPattern, args => proxyDraftMode(...args, { apiKey }))\n .with(apiRoutePattern, args => proxyDraftMode(...args, { apiKey }))\n .exhaustive()\n }\n\n if (matches('/fonts')) {\n return match(args)\n .with(routeHandlerPattern, args => fonts(...args, { getFonts }))\n .with(apiRoutePattern, args => fonts(...args, { getFonts }))\n .exhaustive()\n }\n\n if (matches('/element-tree')) {\n return match(args)\n .with(routeHandlerPattern, args => elementTree(...args, runtime))\n .with(apiRoutePattern, args => elementTree(...args, runtime))\n .exhaustive()\n }\n\n if (matches('/translatable-data')) {\n return match(args)\n .with(routeHandlerPattern, args => translatableData(...args, client))\n .with(apiRoutePattern, args => translatableData(...args, client))\n .exhaustive()\n }\n\n if (matches('/merge-translated-data')) {\n return match(args)\n .with(routeHandlerPattern, args => mergeTranslatedData(...args, client))\n .with(apiRoutePattern, args => mergeTranslatedData(...args, client))\n .exhaustive()\n }\n\n if (matches('/webhook')) {\n return match(args)\n .with(routeHandlerPattern, args => webhook(...args, { apiKey }))\n .with(apiRoutePattern, args => webhook(...args, { apiKey }))\n .exhaustive()\n }\n\n const handleResource = <T extends APIResource>(\n resource: T | null,\n ): NextResponse<MakeswiftApiHandlerResponse> | void => {\n const status = resource === null ? 404 : 200\n const body = resource === null ? { message: 'Not Found' } : resource\n\n return match(args)\n .with(routeHandlerPattern, () => NextResponse.json(body, { status }))\n .with(apiRoutePattern, ([, res]) => res.status(status).json(body))\n .exhaustive()\n }\n\n if ((m = matches<{ id: string }>('/swatches/:id'))) {\n return client.getSwatch(m.params.id, siteVersion).then(handleResource)\n }\n\n if ((m = matches<{ id: string }>('/files/:id'))) {\n return client.getFile(m.params.id).then(handleResource)\n }\n\n if ((m = matches<{ id: string }>('/typographies/:id'))) {\n return client.getTypography(m.params.id, siteVersion).then(handleResource)\n }\n\n if ((m = matches<{ id: string }>('/global-elements/:id'))) {\n return client.getGlobalElement(m.params.id, siteVersion).then(handleResource)\n }\n\n if (\n (m = matches<{ globalElementId: string; locale: string }>(\n '/localized-global-elements/:globalElementId/:locale',\n ))\n ) {\n return client\n .getLocalizedGlobalElement(m.params.globalElementId, m.params.locale, siteVersion)\n .then(handleResource)\n }\n\n if ((m = matches<{ id: string }>('/page-pathname-slices/:id'))) {\n const localeParam = match(args)\n .with(routeHandlerPattern, ([request]) => request.nextUrl.searchParams.get('locale'))\n .with(apiRoutePattern, ([req]) => req.query.locale)\n .exhaustive()\n const locale = typeof localeParam === 'string' ? localeParam : undefined\n\n return client.getPagePathnameSlice(m.params.id, siteVersion, { locale }).then(handleResource)\n }\n\n if ((m = matches<{ id: string }>('/tables/:id'))) {\n return client.getTable(m.params.id).then(handleResource)\n }\n\n const status = 404\n const body = { message: 'Not Found' }\n\n return match(args)\n .with(routeHandlerPattern, () => NextResponse.json(body, { status }))\n .with(apiRoutePattern, ([, res]) => res.status(status).json(body))\n .exhaustive()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAiB;AAEjB,oBAA0C;AAC1C,4BAA6C;AAE7C,oBAA0B;AAE1B,0BAAiD;AACjD,mBAAqD;AACrD,sBAAqD;AACrD,gCAA2D;AAC3D,8BAAuD;AACvD,wBAAiD;AACjD,+BAA2D;AAC3D,mCAA4D;AAC5D,qBAAoB;AAGpB,wBAAyB;AACzB,wBAA+B;AAgC/B,SAAS,iBAAiB,SAA2D;AAGnF,SAAO,QAAQ,QAAQ,QAAQ,KAAK;AACtC;AAEO,SAAS,oBACd,QACA;AAAA,EACE,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ;AAA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AAC,CAAC,OAAO,MAAM,QAAQ,QAAQ,aAAa,IAAI,QAAQ,CAAC,EACnF,KAAK,iBAAiB,CAAC,CAAC,GAAG,MAAM,IAAI,MAAM,MAAM,EACjD,WAAW;AACd,YAAM,SAAS,OAAO,gBAAgB,WAAW,cAAc;AAE/D,aAAO,OAAO,qBAAqB,EAAE,OAAO,IAAI,aAAa,EAAE,OAAO,CAAC,EAAE,KAAK,cAAc;AAAA,IAC9F;AAEA,QAAK,IAAI,QAAwB,aAAa,GAAI;AAChD,aAAO,OAAO,SAAS,EAAE,OAAO,EAAE,EAAE,KAAK,cAAc;AAAA,IACzD;AAEA,UAAM,SAAS;AACf,UAAM,OAAO,EAAE,SAAS,YAAY;AAEpC,eAAO,yBAAM,IAAI,EACd,KAAK,qBAAqB,MAAM,2BAAa,KAAK,MAAM,EAAE,OAAO,CAAC,CAAC,EACnE,KAAK,iBAAiB,CAAC,CAAC,EAAE,GAAG,MAAM,IAAI,OAAO,MAAM,EAAE,KAAK,IAAI,CAAC,EAChE,WAAW;AAAA,EAChB;AACF;","names":["Cors","args","matchPattern","manifest","proxyPreviewMode","proxyDraftMode","fonts","elementTree","translatableData","mergeTranslatedData","webhook","status","body"]}
1
+ {"version":3,"sources":["../../../../src/next/api-handler/index.ts"],"sourcesContent":["import Cors from 'cors'\nimport { NextApiRequest, NextApiResponse } from 'next'\nimport { NextRequest, NextResponse } from 'next/server'\nimport { Match, match as matchPattern } from 'path-to-regexp'\nimport { APIResource } from '../../api'\nimport { Makeswift } from '../client'\n\nimport elementTree, { ElementTreeResponse } from './handlers/element-tree'\nimport fonts, { Font, FontsResponse, GetFonts } from './handlers/fonts'\nimport manifest, { Manifest, ManifestResponse } from './handlers/manifest'\nimport proxyPreviewMode, { ProxyPreviewModeResponse } from './handlers/proxy-preview-mode'\nimport proxyDraftMode, { ProxyDraftModeResponse } from './handlers/proxy-draft-mode'\nimport { revalidate, RevalidationResponse } from './handlers/revalidate'\nimport translatableData, { TranslatableDataResponse } from './handlers/translatable-data'\nimport mergeTranslatedData, { TranslatedDataResponse } from './handlers/merge-translated-data'\nimport webhook from './handlers/webhook'\nimport { WebhookResponseBody } from './handlers/webhook/types'\nimport { ReactRuntime } from '../../react'\nimport { P, match } from 'ts-pattern'\nimport {\n API_HANDLER_SITE_VERSION_HEADER,\n MakeswiftSiteVersion,\n makeswiftSiteVersionSchema,\n} from '../../api/site-version'\n\nexport type { Manifest, Font }\n\ntype Context = { params: { [key: string]: string | string[] } }\n\ntype MakeswiftApiHandlerConfig = {\n appOrigin?: string\n apiOrigin?: string\n getFonts?: GetFonts\n runtime: ReactRuntime\n}\n\ntype NotFoundError = { message: string }\n\nexport type MakeswiftApiHandlerResponse =\n | ManifestResponse\n | RevalidationResponse\n | ProxyPreviewModeResponse\n | ProxyDraftModeResponse\n | FontsResponse\n | ElementTreeResponse\n | TranslatableDataResponse\n | TranslatedDataResponse\n | APIResource\n | NotFoundError\n | WebhookResponseBody\n\ntype MakeswiftApiHandlerArgs =\n | [NextRequest, Context]\n | [NextApiRequest, NextApiResponse<MakeswiftApiHandlerResponse>]\n\nfunction apiRequestParams(request: NextApiRequest): Promise<NextApiRequest['query']> {\n // `NextApiRequest.query` prop became async in Next.js 15, but it's not reflected in the type definition;\n // force-casting it to a `Promise` manually\n return Promise.resolve(request.query)\n}\n\nexport function MakeswiftApiHandler(\n apiKey: string,\n {\n appOrigin = 'https://app.makeswift.com',\n apiOrigin = 'https://api.makeswift.com',\n getFonts,\n runtime,\n }: MakeswiftApiHandlerConfig,\n): (...args: MakeswiftApiHandlerArgs) => Promise<NextResponse<MakeswiftApiHandlerResponse> | void> {\n const cors = Cors({ origin: appOrigin })\n\n if (typeof apiKey !== 'string') {\n throw new Error(\n 'The Makeswift Next.js API handler must be passed a valid Makeswift site API key: ' +\n \"`MakeswiftApiHandler('<makeswift_site_api_key>')`\\n\" +\n `Received \"${apiKey}\" instead.`,\n )\n }\n\n const routeHandlerPattern = [P.instanceOf(Request), P.any] as const\n const apiRoutePattern = [P.any, P.any] as const\n\n return function handler(\n ...args: MakeswiftApiHandlerArgs\n ): Promise<NextResponse<MakeswiftApiHandlerResponse> | void> {\n return match(args)\n .with(routeHandlerPattern, async args => {\n const response = await makeswiftApiHandler(...args)\n\n response.headers.append('Access-Control-Allow-Origin', appOrigin)\n response.headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')\n response.headers.append('Access-Control-Allow-Headers', 'Content-Type, Authorization')\n\n return response\n })\n .with(apiRoutePattern, async args => {\n const [req, res] = args\n\n await new Promise<void>((resolve, reject) => {\n cors(req, res, err => {\n if (err instanceof Error) reject(err)\n else resolve()\n })\n })\n\n return await makeswiftApiHandler(...args)\n })\n .exhaustive()\n }\n\n function getSiteVersionFromRequest(args: MakeswiftApiHandlerArgs): MakeswiftSiteVersion {\n const header = match(args)\n .with(routeHandlerPattern, ([request]) =>\n request.headers.get(API_HANDLER_SITE_VERSION_HEADER),\n )\n .with(apiRoutePattern, ([req]) => req.headers[API_HANDLER_SITE_VERSION_HEADER.toLowerCase()])\n .exhaustive()\n\n const parsed = makeswiftSiteVersionSchema.safeParse(header)\n if (!parsed.success) return MakeswiftSiteVersion.Live\n return parsed.data\n }\n\n async function makeswiftApiHandler(\n request: NextRequest,\n context: Context,\n ): Promise<NextResponse<MakeswiftApiHandlerResponse>>\n async function makeswiftApiHandler(\n req: NextApiRequest,\n res: NextApiResponse<MakeswiftApiHandlerResponse>,\n ): Promise<void>\n async function makeswiftApiHandler(\n ...args: MakeswiftApiHandlerArgs\n ): Promise<NextResponse<MakeswiftApiHandlerResponse> | void> {\n const params = match(args)\n .with(routeHandlerPattern, ([, context]) => context.params)\n .with(apiRoutePattern, ([req]) => apiRequestParams(req))\n .exhaustive()\n\n const { makeswift } = await params\n\n if (!Array.isArray(makeswift)) {\n throw new Error(\n 'The Makeswift Next.js API handler must be used in a dynamic catch-all route named `[...makeswift]`.\\n' +\n `Received \"${makeswift}\" for the \\`makeswift\\` param instead.\\n` +\n 'Read more about dynamic catch-all routes here: https://nextjs.org/docs/routing/dynamic-routes#catch-all-routes',\n )\n }\n\n const client = new Makeswift(apiKey, { apiOrigin, runtime })\n const siteVersion = getSiteVersionFromRequest(args)\n const action = '/' + makeswift.join('/')\n const matches = <T extends object>(pattern: string): Match<T> =>\n matchPattern<T>(pattern, { decode: decodeURIComponent })(action)\n\n let m\n\n if (matches('/manifest')) {\n return match(args)\n .with(routeHandlerPattern, args => manifest(...args, { apiKey }))\n .with(apiRoutePattern, args => manifest(...args, { apiKey }))\n .exhaustive()\n }\n\n if (matches('/revalidate')) {\n return match(args)\n .with(routeHandlerPattern, args => revalidate(...args, { apiKey }))\n .with(apiRoutePattern, args => revalidate(...args, { apiKey }))\n .exhaustive()\n }\n\n if (matches('/proxy-preview-mode')) {\n return match(args)\n .with(routeHandlerPattern, args => proxyPreviewMode(...args, { apiKey }))\n .with(apiRoutePattern, args => proxyPreviewMode(...args, { apiKey }))\n .exhaustive()\n }\n\n if (matches('/proxy-draft-mode')) {\n return match(args)\n .with(routeHandlerPattern, args => proxyDraftMode(...args, { apiKey }))\n .with(apiRoutePattern, args => proxyDraftMode(...args, { apiKey }))\n .exhaustive()\n }\n\n if (matches('/fonts')) {\n return match(args)\n .with(routeHandlerPattern, args => fonts(...args, { getFonts }))\n .with(apiRoutePattern, args => fonts(...args, { getFonts }))\n .exhaustive()\n }\n\n if (matches('/element-tree')) {\n return match(args)\n .with(routeHandlerPattern, args => elementTree(...args, runtime))\n .with(apiRoutePattern, args => elementTree(...args, runtime))\n .exhaustive()\n }\n\n if (matches('/translatable-data')) {\n return match(args)\n .with(routeHandlerPattern, args => translatableData(...args, client))\n .with(apiRoutePattern, args => translatableData(...args, client))\n .exhaustive()\n }\n\n if (matches('/merge-translated-data')) {\n return match(args)\n .with(routeHandlerPattern, args => mergeTranslatedData(...args, client))\n .with(apiRoutePattern, args => mergeTranslatedData(...args, client))\n .exhaustive()\n }\n\n if (matches('/webhook')) {\n return match(args)\n .with(routeHandlerPattern, args => webhook(...args, { apiKey }))\n .with(apiRoutePattern, args => webhook(...args, { apiKey }))\n .exhaustive()\n }\n\n const handleResource = <T extends APIResource>(\n resource: T | null,\n ): NextResponse<MakeswiftApiHandlerResponse> | void => {\n const status = resource === null ? 404 : 200\n const body = resource === null ? { message: 'Not Found' } : resource\n\n return match(args)\n .with(routeHandlerPattern, () => NextResponse.json(body, { status }))\n .with(apiRoutePattern, ([, res]) => res.status(status).json(body))\n .exhaustive()\n }\n\n if ((m = matches<{ id: string }>('/swatches/:id'))) {\n return client.getSwatch(m.params.id, siteVersion).then(handleResource)\n }\n\n if ((m = matches<{ id: string }>('/files/:id'))) {\n return client.getFile(m.params.id).then(handleResource)\n }\n\n if ((m = matches<{ id: string }>('/typographies/:id'))) {\n return client.getTypography(m.params.id, siteVersion).then(handleResource)\n }\n\n if ((m = matches<{ id: string }>('/global-elements/:id'))) {\n return client.getGlobalElement(m.params.id, siteVersion).then(handleResource)\n }\n\n if (\n (m = matches<{ globalElementId: string; locale: string }>(\n '/localized-global-elements/:globalElementId/:locale',\n ))\n ) {\n return client\n .getLocalizedGlobalElement(m.params.globalElementId, m.params.locale, siteVersion)\n .then(handleResource)\n }\n\n if ((m = matches<{ id: string }>('/page-pathname-slices/:id'))) {\n const localeParam = match(args)\n .with(routeHandlerPattern, ([request]) => request.nextUrl.searchParams.get('locale'))\n .with(apiRoutePattern, ([req]) => req.query.locale)\n .exhaustive()\n const locale = typeof localeParam === 'string' ? localeParam : undefined\n\n return client.getPagePathnameSlice(m.params.id, siteVersion, { locale }).then(handleResource)\n }\n\n if ((m = matches<{ id: string }>('/tables/:id'))) {\n return client.getTable(m.params.id).then(handleResource)\n }\n\n const status = 404\n const body = { message: 'Not Found' }\n\n return match(args)\n .with(routeHandlerPattern, () => NextResponse.json(body, { status }))\n .with(apiRoutePattern, ([, res]) => res.status(status).json(body))\n .exhaustive()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA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O,MAAM,EAAE,KAAK,IAAI,CAAC,EAChE,WAAW;AAAA,EAChB;AACF;","names":["Cors","args","matchPattern","manifest","proxyPreviewMode","proxyDraftMode","fonts","elementTree","translatableData","mergeTranslatedData","webhook","status","body"]}
@@ -31,6 +31,7 @@ var import_react = require("../api/react");
31
31
  var import_introspection = require("../prop-controllers/introspection");
32
32
  var import_react_page = require("../state/react-page");
33
33
  var import_preview_mode = require("./preview-mode");
34
+ var import_site_version = require("../api/site-version");
34
35
  var import_pagination = require("./utils/pagination");
35
36
  var import_deterministic_uuid = require("../utils/deterministic-uuid");
36
37
  var import_controls = require("@makeswift/controls");
@@ -172,10 +173,10 @@ class Makeswift {
172
173
  graphqlClient;
173
174
  runtime;
174
175
  static getSiteVersion(previewData) {
175
- return (0, import_preview_mode.getMakeswiftSiteVersion)(previewData) ?? import_preview_mode.MakeswiftSiteVersion.Live;
176
+ return (0, import_preview_mode.getMakeswiftSiteVersion)(previewData) ?? import_site_version.MakeswiftSiteVersion.Live;
176
177
  }
177
178
  static getPreviewMode(previewData) {
178
- return (0, import_preview_mode.getMakeswiftSiteVersion)(previewData) === import_preview_mode.MakeswiftSiteVersion.Working;
179
+ return (0, import_preview_mode.getMakeswiftSiteVersion)(previewData) === import_site_version.MakeswiftSiteVersion.Working;
179
180
  }
180
181
  constructor(apiKey, { apiOrigin = "https://api.makeswift.com", runtime }) {
181
182
  if (typeof apiKey !== "string") {
@@ -195,7 +196,7 @@ Received "${apiKey}" instead.`
195
196
  this.graphqlClient = new import_client.GraphQLClient(new URL("graphql", apiOrigin).href);
196
197
  this.runtime = runtime;
197
198
  }
198
- async fetch(path, siteVersion = import_preview_mode.MakeswiftSiteVersion.Live, init) {
199
+ async fetch(path, siteVersion = import_site_version.MakeswiftSiteVersion.Live, init) {
199
200
  const response = await fetch(new URL(path, this.apiOrigin).toString(), {
200
201
  ...init,
201
202
  headers: {
@@ -204,7 +205,7 @@ Received "${apiKey}" instead.`
204
205
  "Makeswift-Site-Version": siteVersion,
205
206
  ...init?.headers
206
207
  },
207
- ...siteVersion === import_preview_mode.MakeswiftSiteVersion.Working ? { cache: "no-store" } : {},
208
+ ...siteVersion === import_site_version.MakeswiftSiteVersion.Working ? { cache: "no-store" } : {},
208
209
  next: {
209
210
  ...init?.next,
210
211
  tags: [...init?.next?.tags ?? [], import_site_published.MAKESWIFT_CACHE_TAG]
@@ -213,7 +214,7 @@ Received "${apiKey}" instead.`
213
214
  return response;
214
215
  }
215
216
  getPagesInternal = async ({
216
- siteVersion = import_preview_mode.MakeswiftSiteVersion.Live,
217
+ siteVersion = import_site_version.MakeswiftSiteVersion.Live,
217
218
  ...params
218
219
  } = {}) => {
219
220
  const queryParams = getPagesQueryParams(params);
@@ -233,7 +234,7 @@ Received "${apiKey}" instead.`
233
234
  };
234
235
  getPages = (0, import_pagination.toIterablePaginationResult)(this.getPagesInternal);
235
236
  async getPage(pathname, {
236
- siteVersion = import_preview_mode.MakeswiftSiteVersion.Live,
237
+ siteVersion = import_site_version.MakeswiftSiteVersion.Live,
237
238
  locale: localeInput
238
239
  } = {}) {
239
240
  const url = new URL(`v2/pages/${encodeURIComponent(pathname)}`, this.apiOrigin);