@makeswift/runtime 0.23.7 → 0.23.8-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.
Files changed (95) 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/draft-mode.js +78 -0
  6. package/dist/cjs/next/api-handler/handlers/draft-mode.js.map +1 -0
  7. package/dist/cjs/next/api-handler/handlers/manifest.js +1 -1
  8. package/dist/cjs/next/api-handler/handlers/preview-mode.js +71 -0
  9. package/dist/cjs/next/api-handler/handlers/preview-mode.js.map +1 -0
  10. package/dist/cjs/next/api-handler/handlers/proxy-draft-mode.js +2 -2
  11. package/dist/cjs/next/api-handler/handlers/proxy-draft-mode.js.map +1 -1
  12. package/dist/cjs/next/api-handler/handlers/proxy-preview-mode.js +2 -2
  13. package/dist/cjs/next/api-handler/handlers/proxy-preview-mode.js.map +1 -1
  14. package/dist/cjs/next/api-handler/index.js +20 -2
  15. package/dist/cjs/next/api-handler/index.js.map +1 -1
  16. package/dist/cjs/next/client.js +7 -6
  17. package/dist/cjs/next/client.js.map +1 -1
  18. package/dist/cjs/next/draft-mode/index.js +3 -3
  19. package/dist/cjs/next/draft-mode/index.js.map +1 -1
  20. package/dist/cjs/next/middleware/exceptions.js +59 -0
  21. package/dist/cjs/next/middleware/exceptions.js.map +1 -0
  22. package/dist/cjs/next/middleware/index.js +37 -0
  23. package/dist/cjs/next/middleware/index.js.map +1 -0
  24. package/dist/cjs/next/middleware/request-utils.js +167 -0
  25. package/dist/cjs/next/middleware/request-utils.js.map +1 -0
  26. package/dist/cjs/next/preview-mode.js +4 -9
  27. package/dist/cjs/next/preview-mode.js.map +1 -1
  28. package/dist/cjs/runtimes/react/components/RuntimeProvider.js +4 -2
  29. package/dist/cjs/runtimes/react/components/RuntimeProvider.js.map +1 -1
  30. package/dist/cjs/runtimes/react/host-api-client.js +5 -1
  31. package/dist/cjs/runtimes/react/host-api-client.js.map +1 -1
  32. package/dist/cjs/state/makeswift-api-client.js +21 -10
  33. package/dist/cjs/state/makeswift-api-client.js.map +1 -1
  34. package/dist/esm/api/react.js +28 -7
  35. package/dist/esm/api/react.js.map +1 -1
  36. package/dist/esm/api/site-version.js +10 -0
  37. package/dist/esm/api/site-version.js.map +1 -0
  38. package/dist/esm/next/api-handler/handlers/draft-mode.js +58 -0
  39. package/dist/esm/next/api-handler/handlers/draft-mode.js.map +1 -0
  40. package/dist/esm/next/api-handler/handlers/manifest.js +1 -1
  41. package/dist/esm/next/api-handler/handlers/preview-mode.js +51 -0
  42. package/dist/esm/next/api-handler/handlers/preview-mode.js.map +1 -0
  43. package/dist/esm/next/api-handler/handlers/proxy-draft-mode.js +1 -1
  44. package/dist/esm/next/api-handler/handlers/proxy-draft-mode.js.map +1 -1
  45. package/dist/esm/next/api-handler/handlers/proxy-preview-mode.js +1 -1
  46. package/dist/esm/next/api-handler/handlers/proxy-preview-mode.js.map +1 -1
  47. package/dist/esm/next/api-handler/index.js +24 -2
  48. package/dist/esm/next/api-handler/index.js.map +1 -1
  49. package/dist/esm/next/client.js +2 -1
  50. package/dist/esm/next/client.js.map +1 -1
  51. package/dist/esm/next/draft-mode/index.js +1 -1
  52. package/dist/esm/next/draft-mode/index.js.map +1 -1
  53. package/dist/esm/next/middleware/exceptions.js +29 -0
  54. package/dist/esm/next/middleware/exceptions.js.map +1 -0
  55. package/dist/esm/next/middleware/index.js +15 -0
  56. package/dist/esm/next/middleware/index.js.map +1 -0
  57. package/dist/esm/next/middleware/request-utils.js +146 -0
  58. package/dist/esm/next/middleware/request-utils.js.map +1 -0
  59. package/dist/esm/next/preview-mode.js +2 -5
  60. package/dist/esm/next/preview-mode.js.map +1 -1
  61. package/dist/esm/runtimes/react/components/RuntimeProvider.js +4 -2
  62. package/dist/esm/runtimes/react/components/RuntimeProvider.js.map +1 -1
  63. package/dist/esm/runtimes/react/host-api-client.js +5 -1
  64. package/dist/esm/runtimes/react/host-api-client.js.map +1 -1
  65. package/dist/esm/state/makeswift-api-client.js +21 -10
  66. package/dist/esm/state/makeswift-api-client.js.map +1 -1
  67. package/dist/types/api/react.d.ts +4 -1
  68. package/dist/types/api/react.d.ts.map +1 -1
  69. package/dist/types/api/site-version.d.ts +6 -0
  70. package/dist/types/api/site-version.d.ts.map +1 -0
  71. package/dist/types/next/api-handler/handlers/draft-mode.d.ts +20 -0
  72. package/dist/types/next/api-handler/handlers/draft-mode.d.ts.map +1 -0
  73. package/dist/types/next/api-handler/handlers/preview-mode.d.ts +20 -0
  74. package/dist/types/next/api-handler/handlers/preview-mode.d.ts.map +1 -0
  75. package/dist/types/next/api-handler/handlers/proxy-preview-mode.d.ts.map +1 -1
  76. package/dist/types/next/api-handler/index.d.ts +3 -1
  77. package/dist/types/next/api-handler/index.d.ts.map +1 -1
  78. package/dist/types/next/client.d.ts +1 -1
  79. package/dist/types/next/client.d.ts.map +1 -1
  80. package/dist/types/next/draft-mode/index.d.ts +2 -2
  81. package/dist/types/next/middleware/exceptions.d.ts +16 -0
  82. package/dist/types/next/middleware/exceptions.d.ts.map +1 -0
  83. package/dist/types/next/middleware/index.d.ts +2 -0
  84. package/dist/types/next/middleware/index.d.ts.map +1 -0
  85. package/dist/types/next/middleware/request-utils.d.ts +16 -0
  86. package/dist/types/next/middleware/request-utils.d.ts.map +1 -0
  87. package/dist/types/next/middleware/request-utils.test.d.ts +2 -0
  88. package/dist/types/next/middleware/request-utils.test.d.ts.map +1 -0
  89. package/dist/types/next/preview-mode.d.ts +3 -5
  90. package/dist/types/next/preview-mode.d.ts.map +1 -1
  91. package/dist/types/runtimes/react/components/RuntimeProvider.d.ts.map +1 -1
  92. package/dist/types/runtimes/react/host-api-client.d.ts.map +1 -1
  93. package/dist/types/state/makeswift-api-client.d.ts +2 -1
  94. package/dist/types/state/makeswift-api-client.d.ts.map +1 -1
  95. package/package.json +10 -1
@@ -0,0 +1,167 @@
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 request_utils_exports = {};
20
+ __export(request_utils_exports, {
21
+ createDraftRequest: () => createDraftRequest,
22
+ fetchDraftProxyResponse: () => fetchDraftProxyResponse,
23
+ getDraftSecret: () => getDraftSecret,
24
+ isDraftModeRequest: () => isDraftModeRequest,
25
+ isDraftRequest: () => isDraftRequest,
26
+ isPreviewModeRequest: () => isPreviewModeRequest
27
+ });
28
+ module.exports = __toCommonJS(request_utils_exports);
29
+ var import_server = require("next/server");
30
+ var import_exceptions = require("./exceptions");
31
+ var import_set_cookie_parser = require("set-cookie-parser");
32
+ const HeaderNames = {
33
+ DraftMode: "X-Makeswift-Draft-Mode",
34
+ PreviewMode: "X-Makeswift-Preview-Mode"
35
+ };
36
+ const SearchParams = {
37
+ DraftMode: "x-makeswift-draft-mode",
38
+ PreviewMode: "x-makeswift-preview-mode"
39
+ };
40
+ const CookieRequestEndpoints = {
41
+ DraftMode: "/api/makeswift/draft-mode",
42
+ PreviewMode: "/api/makeswift/preview-mode"
43
+ };
44
+ function getDraftModeSecret(request) {
45
+ return request.nextUrl.searchParams.get(SearchParams.DraftMode) ?? request.headers.get(HeaderNames.DraftMode) ?? null;
46
+ }
47
+ function getPreviewModeSecret(request) {
48
+ return request.nextUrl.searchParams.get(SearchParams.PreviewMode) ?? request.headers.get(HeaderNames.PreviewMode) ?? null;
49
+ }
50
+ function isDraftModeRequest(request) {
51
+ return getDraftModeSecret(request) != null;
52
+ }
53
+ function isPreviewModeRequest(request) {
54
+ return getPreviewModeSecret(request) != null;
55
+ }
56
+ function isDraftRequest(request) {
57
+ return isDraftModeRequest(request) || isPreviewModeRequest(request);
58
+ }
59
+ function getDraftSecret(request) {
60
+ const draftSecret = getDraftModeSecret(request);
61
+ const previewSecret = getPreviewModeSecret(request);
62
+ if (draftSecret != null && previewSecret != null) {
63
+ throw new import_exceptions.InvariantDraftRequestError(
64
+ "Request can't include draft mode and preview mode secrets"
65
+ );
66
+ }
67
+ return draftSecret ?? previewSecret;
68
+ }
69
+ async function fetchCookies(url, draftSecret) {
70
+ const requestUrl = new URL(url);
71
+ requestUrl.searchParams.set("secret", draftSecret);
72
+ const response = await fetch(requestUrl).then((res) => {
73
+ if (res.ok)
74
+ return res;
75
+ if (res.status === 401) {
76
+ throw new import_exceptions.UnauthorizedDraftRequestError(`Unauthorized draft request to ${url}`);
77
+ }
78
+ if (res.status === 404) {
79
+ throw new import_exceptions.MissingDraftEndpointError(
80
+ `Could not find draft endpoint at ${url}. Please make sure you properly registered a \`MakeswiftApiHandler\``
81
+ );
82
+ }
83
+ throw new import_exceptions.UnknownDraftFetchRequestError(
84
+ "Encountered unknown error while fetching draft cookies"
85
+ );
86
+ }).catch((err) => {
87
+ if (err instanceof import_exceptions.MiddlewareError)
88
+ throw err;
89
+ throw new import_exceptions.UnknownDraftFetchRequestError(
90
+ "Encountered unknown error while fetching draft cookies",
91
+ { cause: err }
92
+ );
93
+ });
94
+ const setCookieHeader = response.headers.getSetCookie();
95
+ if (setCookieHeader.length <= 0) {
96
+ throw new import_exceptions.UnparseableDraftCookieResponseError(
97
+ "Received empty draft cookies. If you're seeing this error, please report a bug to https://github.com/makeswift/makeswift"
98
+ );
99
+ }
100
+ try {
101
+ return (0, import_set_cookie_parser.parse)(setCookieHeader);
102
+ } catch (err) {
103
+ throw new import_exceptions.UnparseableDraftCookieResponseError(
104
+ "Could not parse draft cookies. If you're seeing this error, please report a bug to https://github.com/makeswift/makeswift",
105
+ { cause: err }
106
+ );
107
+ }
108
+ }
109
+ async function fetchDraftModeCookies(origin, draftSecret) {
110
+ return await fetchCookies(new URL(CookieRequestEndpoints.DraftMode, origin), draftSecret);
111
+ }
112
+ async function fetchPreviewModeCookies(origin, draftSecret) {
113
+ return await fetchCookies(new URL(CookieRequestEndpoints.PreviewMode, origin), draftSecret);
114
+ }
115
+ async function fetchDraftCookies(request, draftSecret) {
116
+ if (isDraftModeRequest(request)) {
117
+ return await fetchDraftModeCookies(request.nextUrl.origin, draftSecret);
118
+ } else if (isPreviewModeRequest(request)) {
119
+ return await fetchPreviewModeCookies(request.nextUrl.origin, draftSecret);
120
+ }
121
+ return [];
122
+ }
123
+ class MakeswiftDraftRequest extends import_server.NextRequest {
124
+ }
125
+ async function createDraftRequest(requestInit, apiKey) {
126
+ const requestSecret = getDraftSecret(requestInit);
127
+ if (requestSecret == null || requestSecret !== apiKey)
128
+ return null;
129
+ const draftCookies = await fetchDraftCookies(requestInit, requestSecret);
130
+ const draftRequest = new MakeswiftDraftRequest(requestInit, requestInit);
131
+ draftCookies.forEach(({ name, value }) => {
132
+ draftRequest.cookies.set(name, value);
133
+ });
134
+ draftRequest.nextUrl.searchParams.delete(SearchParams.DraftMode);
135
+ draftRequest.nextUrl.searchParams.delete(SearchParams.PreviewMode);
136
+ draftRequest.headers.delete(HeaderNames.DraftMode);
137
+ draftRequest.headers.delete(HeaderNames.PreviewMode);
138
+ return draftRequest;
139
+ }
140
+ async function fetchDraftProxyResponse(draftRequest) {
141
+ if (!(draftRequest instanceof MakeswiftDraftRequest)) {
142
+ throw new import_exceptions.InvalidProxyRequestInputError(
143
+ "Draft request must be instance of `MakeswiftDraftRequest`"
144
+ );
145
+ }
146
+ const proxyUrl = new URL(draftRequest.nextUrl, draftRequest.nextUrl.origin);
147
+ const proxyResponse = await fetch(proxyUrl, { headers: draftRequest.headers });
148
+ const response = new import_server.NextResponse(proxyResponse.body, {
149
+ headers: proxyResponse.headers,
150
+ status: proxyResponse.status
151
+ });
152
+ if (response.headers.has("content-encoding")) {
153
+ response.headers.delete("content-encoding");
154
+ response.headers.delete("content-length");
155
+ }
156
+ return response;
157
+ }
158
+ // Annotate the CommonJS export names for ESM import in node:
159
+ 0 && (module.exports = {
160
+ createDraftRequest,
161
+ fetchDraftProxyResponse,
162
+ getDraftSecret,
163
+ isDraftModeRequest,
164
+ isDraftRequest,
165
+ isPreviewModeRequest
166
+ });
167
+ //# sourceMappingURL=request-utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/next/middleware/request-utils.ts"],"sourcesContent":["import { NextRequest, NextResponse } from 'next/server'\nimport {\n InvalidProxyRequestInputError,\n InvariantDraftRequestError,\n MiddlewareError,\n MissingDraftEndpointError,\n UnauthorizedDraftRequestError,\n UnknownDraftFetchRequestError,\n UnparseableDraftCookieResponseError,\n} from './exceptions'\n\nimport { type Cookie, parse as parseSetCookie } from 'set-cookie-parser'\n\nconst HeaderNames = {\n DraftMode: 'X-Makeswift-Draft-Mode',\n PreviewMode: 'X-Makeswift-Preview-Mode',\n} as const\n\nconst SearchParams = {\n DraftMode: 'x-makeswift-draft-mode',\n PreviewMode: 'x-makeswift-preview-mode',\n} as const\n\nconst CookieRequestEndpoints = {\n DraftMode: '/api/makeswift/draft-mode',\n PreviewMode: '/api/makeswift/preview-mode',\n} as const\n\nfunction getDraftModeSecret(request: NextRequest): string | null {\n return (\n request.nextUrl.searchParams.get(SearchParams.DraftMode) ??\n request.headers.get(HeaderNames.DraftMode) ??\n null\n )\n}\n\nfunction getPreviewModeSecret(request: NextRequest): string | null {\n return (\n request.nextUrl.searchParams.get(SearchParams.PreviewMode) ??\n request.headers.get(HeaderNames.PreviewMode) ??\n null\n )\n}\n\nexport function isDraftModeRequest(request: NextRequest): boolean {\n return getDraftModeSecret(request) != null\n}\n\nexport function isPreviewModeRequest(request: NextRequest): boolean {\n return getPreviewModeSecret(request) != null\n}\n\nexport function isDraftRequest(request: NextRequest): boolean {\n return isDraftModeRequest(request) || isPreviewModeRequest(request)\n}\n\nexport function getDraftSecret(request: NextRequest): string | null {\n const draftSecret = getDraftModeSecret(request)\n const previewSecret = getPreviewModeSecret(request)\n if (draftSecret != null && previewSecret != null) {\n throw new InvariantDraftRequestError(\n \"Request can't include draft mode and preview mode secrets\",\n )\n }\n return draftSecret ?? previewSecret\n}\n\nasync function fetchCookies(url: URL, draftSecret: string): Promise<Cookie[]> {\n const requestUrl = new URL(url)\n requestUrl.searchParams.set('secret', draftSecret)\n\n const response = await fetch(requestUrl)\n .then(res => {\n if (res.ok) return res\n if (res.status === 401) {\n throw new UnauthorizedDraftRequestError(`Unauthorized draft request to ${url}`)\n }\n if (res.status === 404) {\n throw new MissingDraftEndpointError(\n `Could not find draft endpoint at ${url}. Please make sure you properly registered a \\`MakeswiftApiHandler\\``,\n )\n }\n throw new UnknownDraftFetchRequestError(\n 'Encountered unknown error while fetching draft cookies',\n )\n })\n .catch((err: unknown) => {\n if (err instanceof MiddlewareError) throw err\n throw new UnknownDraftFetchRequestError(\n 'Encountered unknown error while fetching draft cookies',\n { cause: err },\n )\n })\n\n const setCookieHeader = response.headers.getSetCookie()\n\n if (setCookieHeader.length <= 0) {\n throw new UnparseableDraftCookieResponseError(\n \"Received empty draft cookies. If you're seeing this error, please report a bug to https://github.com/makeswift/makeswift\",\n )\n }\n\n try {\n return parseSetCookie(setCookieHeader)\n } catch (err) {\n throw new UnparseableDraftCookieResponseError(\n \"Could not parse draft cookies. If you're seeing this error, please report a bug to https://github.com/makeswift/makeswift\",\n { cause: err },\n )\n }\n}\n\nasync function fetchDraftModeCookies(origin: string, draftSecret: string): Promise<Cookie[]> {\n return await fetchCookies(new URL(CookieRequestEndpoints.DraftMode, origin), draftSecret)\n}\n\nasync function fetchPreviewModeCookies(origin: string, draftSecret: string): Promise<Cookie[]> {\n return await fetchCookies(new URL(CookieRequestEndpoints.PreviewMode, origin), draftSecret)\n}\n\nasync function fetchDraftCookies(request: NextRequest, draftSecret: string): Promise<Cookie[]> {\n if (isDraftModeRequest(request)) {\n return await fetchDraftModeCookies(request.nextUrl.origin, draftSecret)\n } else if (isPreviewModeRequest(request)) {\n return await fetchPreviewModeCookies(request.nextUrl.origin, draftSecret)\n }\n\n return []\n}\n\nclass MakeswiftDraftRequest extends NextRequest {}\n\n/**\n * Creates a new `NextRequest` that can be used for fetching a working version\n * of the page (that will also bypass the Vercel cache). Returns `null` if the\n * given request does not have a draft secret that matches the `apiKey`.\n */\nexport async function createDraftRequest(\n requestInit: NextRequest,\n apiKey: string,\n): Promise<MakeswiftDraftRequest | null> {\n const requestSecret = getDraftSecret(requestInit)\n\n if (requestSecret == null || requestSecret !== apiKey) return null\n\n const draftCookies = await fetchDraftCookies(requestInit, requestSecret)\n\n // https://github.com/vercel/next.js/issues/52967#issuecomment-1644675602\n // if we don't pass request twice, headers are stripped\n const draftRequest = new MakeswiftDraftRequest(requestInit, requestInit)\n\n draftCookies.forEach(({ name, value }) => {\n draftRequest.cookies.set(name, value)\n })\n\n draftRequest.nextUrl.searchParams.delete(SearchParams.DraftMode)\n draftRequest.nextUrl.searchParams.delete(SearchParams.PreviewMode)\n draftRequest.headers.delete(HeaderNames.DraftMode)\n draftRequest.headers.delete(HeaderNames.PreviewMode)\n\n return draftRequest\n}\n\nexport async function fetchDraftProxyResponse(\n draftRequest: MakeswiftDraftRequest,\n): Promise<NextResponse> {\n if (!(draftRequest instanceof MakeswiftDraftRequest)) {\n throw new InvalidProxyRequestInputError(\n 'Draft request must be instance of `MakeswiftDraftRequest`',\n )\n }\n // Passing `draftRequest.nextUrl` to fetch directly won't work when deployed\n // on Vercel - it results in a `TypeError: Invalid URL` error. Constructing\n // the URL works.\n const proxyUrl = new URL(draftRequest.nextUrl, draftRequest.nextUrl.origin)\n const proxyResponse = await fetch(proxyUrl, { headers: draftRequest.headers })\n\n const response = new NextResponse(proxyResponse.body, {\n headers: proxyResponse.headers,\n status: proxyResponse.status,\n })\n\n // `fetch` automatically decompresses the response, but the response headers\n // will keep the `content-encoding` and `content-length` headers. This will\n // cause decoding issues if the client attempts to decompress the response\n // 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"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA0C;AAC1C,wBAQO;AAEP,+BAAqD;AAErD,MAAM,cAAc;AAAA,EAClB,WAAW;AAAA,EACX,aAAa;AACf;AAEA,MAAM,eAAe;AAAA,EACnB,WAAW;AAAA,EACX,aAAa;AACf;AAEA,MAAM,yBAAyB;AAAA,EAC7B,WAAW;AAAA,EACX,aAAa;AACf;AAEA,SAAS,mBAAmB,SAAqC;AAC/D,SACE,QAAQ,QAAQ,aAAa,IAAI,aAAa,SAAS,KACvD,QAAQ,QAAQ,IAAI,YAAY,SAAS,KACzC;AAEJ;AAEA,SAAS,qBAAqB,SAAqC;AACjE,SACE,QAAQ,QAAQ,aAAa,IAAI,aAAa,WAAW,KACzD,QAAQ,QAAQ,IAAI,YAAY,WAAW,KAC3C;AAEJ;AAEO,SAAS,mBAAmB,SAA+B;AAChE,SAAO,mBAAmB,OAAO,KAAK;AACxC;AAEO,SAAS,qBAAqB,SAA+B;AAClE,SAAO,qBAAqB,OAAO,KAAK;AAC1C;AAEO,SAAS,eAAe,SAA+B;AAC5D,SAAO,mBAAmB,OAAO,KAAK,qBAAqB,OAAO;AACpE;AAEO,SAAS,eAAe,SAAqC;AAClE,QAAM,cAAc,mBAAmB,OAAO;AAC9C,QAAM,gBAAgB,qBAAqB,OAAO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ACT;","names":["parseSetCookie"]}
@@ -18,20 +18,17 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var preview_mode_exports = {};
20
20
  __export(preview_mode_exports, {
21
- MakeswiftSiteVersion: () => MakeswiftSiteVersion,
22
21
  PreviewModeScript: () => PreviewModeScript,
23
- getMakeswiftSiteVersion: () => getMakeswiftSiteVersion,
24
- makeswiftSiteVersionSchema: () => makeswiftSiteVersionSchema
22
+ getMakeswiftSiteVersion: () => getMakeswiftSiteVersion
25
23
  });
26
24
  module.exports = __toCommonJS(preview_mode_exports);
27
25
  var import_jsx_runtime = require("react/jsx-runtime");
28
26
  var import_zod = require("zod");
29
27
  var import_react = require("../react");
30
- const makeswiftSiteVersionSchema = import_zod.z.enum(["Live", "Working"]);
31
- const MakeswiftSiteVersion = makeswiftSiteVersionSchema.Enum;
28
+ var import_site_version = require("../api/site-version");
32
29
  const makeswiftPreviewDataSchema = import_zod.z.object({
33
30
  makeswift: import_zod.z.literal(true),
34
- siteVersion: makeswiftSiteVersionSchema
31
+ siteVersion: import_site_version.makeswiftSiteVersionSchema
35
32
  });
36
33
  function getMakeswiftSiteVersion(previewData) {
37
34
  const result = makeswiftPreviewDataSchema.safeParse(previewData);
@@ -138,9 +135,7 @@ if (window.parent !== window) {
138
135
  }
139
136
  // Annotate the CommonJS export names for ESM import in node:
140
137
  0 && (module.exports = {
141
- MakeswiftSiteVersion,
142
138
  PreviewModeScript,
143
- getMakeswiftSiteVersion,
144
- makeswiftSiteVersionSchema
139
+ getMakeswiftSiteVersion
145
140
  });
146
141
  //# sourceMappingURL=preview-mode.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/next/preview-mode.tsx"],"sourcesContent":["import { PreviewData } from 'next'\nimport { z } from 'zod'\nimport { ActionTypes } from '../react'\n\nexport const makeswiftSiteVersionSchema = z.enum(['Live', 'Working'])\nexport const MakeswiftSiteVersion = makeswiftSiteVersionSchema.Enum\nexport type MakeswiftSiteVersion = z.infer<typeof makeswiftSiteVersionSchema>\n\nconst makeswiftPreviewDataSchema = z.object({\n makeswift: z.literal(true),\n siteVersion: makeswiftSiteVersionSchema,\n})\nexport type MakeswiftPreviewData = z.infer<typeof makeswiftPreviewDataSchema>\n\nexport function getMakeswiftSiteVersion(previewData: PreviewData): MakeswiftSiteVersion | null {\n const result = makeswiftPreviewDataSchema.safeParse(previewData)\n\n if (result.success) return result.data.siteVersion\n\n return null\n}\n\ntype Props = {\n isPreview?: boolean\n appOrigin?: string\n}\n\nexport function PreviewModeScript({\n isPreview = false,\n appOrigin = 'https://app.makeswift.com',\n}: Props) {\n const previewModeScript = `\nconst isPreview = ${isPreview}\nconst appOrigin = '${appOrigin.replace(\"'\", \"\\\\'\")}'\nconst searchParamName = 'x-makeswift-preview-mode'\nconst headerName = 'X-Makeswift-Preview-Mode'\nconst originalUrl = new URL(window.location.href)\n\nif (window.parent !== window) {\n window.addEventListener('message', event => {\n if (event.origin === appOrigin && event.data.type === 'makeswift_preview_mode') {\n const { secret } = event.data\n\n if (!isPreview && !originalUrl.searchParams.has(searchParamName)) {\n const url = new URL(originalUrl)\n\n url.searchParams.set(searchParamName, secret)\n\n window.location.replace(url)\n } else {\n const originalFetch = window.fetch\n\n window.fetch = function patchedFetch(resource, options) {\n const request = new Request(resource, options)\n\n if (new URL(request.url).origin !== window.location.origin) {\n return originalFetch.call(this, resource, options)\n }\n \n const newHeaders = new Headers(request.headers)\n newHeaders.set(headerName, secret)\n\n return originalFetch.call(\n this,\n new Request(request, { headers: newHeaders })\n )\n }\n }\n }\n })\n\n window.parent.postMessage({ type: 'makeswift_preview_mode' }, appOrigin)\n}\n\nif (originalUrl.searchParams.has(searchParamName)) {\n const url = new URL(originalUrl)\n\n url.searchParams.delete(searchParamName)\n\n window.history.replaceState(null, '', url)\n}\n`\n\n const makeswiftConnectionCheckScript = `\nconst appOrigin = '${appOrigin.replace(\"'\", \"\\\\'\")}'\n\nif (window.parent !== window) {\n window.addEventListener('message', event => {\n if (\n event.origin === appOrigin && \n event.data.type === '${ActionTypes.MAKESWIFT_CONNECTION_INIT}'\n ) {\n setInterval(() => {\n window.parent.postMessage({ \n type: '${ActionTypes.MAKESWIFT_CONNECTION_CHECK}',\n payload: { \n currentUrl: window.location.href \n }\n }, appOrigin)\n }, 20)\n }\n })\n\n window.parent.postMessage({ type: '${ActionTypes.MAKESWIFT_CONNECTION_INIT}' }, appOrigin)\n}\n`\n\n return (\n <>\n <script\n id=\"makeswift-preview-mode\"\n type=\"module\"\n dangerouslySetInnerHTML={{ __html: previewModeScript }}\n />\n <script\n id=\"makeswift-connection-check\"\n type=\"module\"\n dangerouslySetInnerHTML={{ __html: makeswiftConnectionCheckScript }}\n />\n </>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4GI;AA3GJ,iBAAkB;AAClB,mBAA4B;AAErB,MAAM,6BAA6B,aAAE,KAAK,CAAC,QAAQ,SAAS,CAAC;AAC7D,MAAM,uBAAuB,2BAA2B;AAG/D,MAAM,6BAA6B,aAAE,OAAO;AAAA,EAC1C,WAAW,aAAE,QAAQ,IAAI;AAAA,EACzB,aAAa;AACf,CAAC;AAGM,SAAS,wBAAwB,aAAuD;AAC7F,QAAM,SAAS,2BAA2B,UAAU,WAAW;AAE/D,MAAI,OAAO;AAAS,WAAO,OAAO,KAAK;AAEvC,SAAO;AACT;AAOO,SAAS,kBAAkB;AAAA,EAChC,YAAY;AAAA,EACZ,YAAY;AACd,GAAU;AACR,QAAM,oBAAoB;AAAA,oBACR,SAAS;AAAA,qBACR,UAAU,QAAQ,KAAK,KAAK,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkDhD,QAAM,iCAAiC;AAAA,qBACpB,UAAU,QAAQ,KAAK,KAAK,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAMrB,yBAAY,yBAAyB;AAAA;AAAA;AAAA;AAAA,mBAI/C,yBAAY,0BAA0B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uCASlB,yBAAY,yBAAyB;AAAA;AAAA;AAI1E,SACE,4EACE;AAAA;AAAA,MAAC;AAAA;AAAA,QACC,IAAG;AAAA,QACH,MAAK;AAAA,QACL,yBAAyB,EAAE,QAAQ,kBAAkB;AAAA;AAAA,IACvD;AAAA,IACA;AAAA,MAAC;AAAA;AAAA,QACC,IAAG;AAAA,QACH,MAAK;AAAA,QACL,yBAAyB,EAAE,QAAQ,+BAA+B;AAAA;AAAA,IACpE;AAAA,KACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../../../src/next/preview-mode.tsx"],"sourcesContent":["import { PreviewData } from 'next'\nimport { z } from 'zod'\nimport { ActionTypes } from '../react'\nimport { type MakeswiftSiteVersion, makeswiftSiteVersionSchema } from '../api/site-version'\n\nconst makeswiftPreviewDataSchema = z.object({\n makeswift: z.literal(true),\n siteVersion: makeswiftSiteVersionSchema,\n})\nexport type MakeswiftPreviewData = z.infer<typeof makeswiftPreviewDataSchema>\n\nexport function getMakeswiftSiteVersion(previewData: PreviewData): MakeswiftSiteVersion | null {\n const result = makeswiftPreviewDataSchema.safeParse(previewData)\n\n if (result.success) return result.data.siteVersion\n\n return null\n}\n\ntype Props = {\n isPreview?: boolean\n appOrigin?: string\n}\n\nexport function PreviewModeScript({\n isPreview = false,\n appOrigin = 'https://app.makeswift.com',\n}: Props) {\n const previewModeScript = `\nconst isPreview = ${isPreview}\nconst appOrigin = '${appOrigin.replace(\"'\", \"\\\\'\")}'\nconst searchParamName = 'x-makeswift-preview-mode'\nconst headerName = 'X-Makeswift-Preview-Mode'\nconst originalUrl = new URL(window.location.href)\n\nif (window.parent !== window) {\n window.addEventListener('message', event => {\n if (event.origin === appOrigin && event.data.type === 'makeswift_preview_mode') {\n const { secret } = event.data\n\n if (!isPreview && !originalUrl.searchParams.has(searchParamName)) {\n const url = new URL(originalUrl)\n\n url.searchParams.set(searchParamName, secret)\n\n window.location.replace(url)\n } else {\n const originalFetch = window.fetch\n\n window.fetch = function patchedFetch(resource, options) {\n const request = new Request(resource, options)\n\n if (new URL(request.url).origin !== window.location.origin) {\n return originalFetch.call(this, resource, options)\n }\n \n const newHeaders = new Headers(request.headers)\n newHeaders.set(headerName, secret)\n\n return originalFetch.call(\n this,\n new Request(request, { headers: newHeaders })\n )\n }\n }\n }\n })\n\n window.parent.postMessage({ type: 'makeswift_preview_mode' }, appOrigin)\n}\n\nif (originalUrl.searchParams.has(searchParamName)) {\n const url = new URL(originalUrl)\n\n url.searchParams.delete(searchParamName)\n\n window.history.replaceState(null, '', url)\n}\n`\n\n const makeswiftConnectionCheckScript = `\nconst appOrigin = '${appOrigin.replace(\"'\", \"\\\\'\")}'\n\nif (window.parent !== window) {\n window.addEventListener('message', event => {\n if (\n event.origin === appOrigin && \n event.data.type === '${ActionTypes.MAKESWIFT_CONNECTION_INIT}'\n ) {\n setInterval(() => {\n window.parent.postMessage({ \n type: '${ActionTypes.MAKESWIFT_CONNECTION_CHECK}',\n payload: { \n currentUrl: window.location.href \n }\n }, appOrigin)\n }, 20)\n }\n })\n\n window.parent.postMessage({ type: '${ActionTypes.MAKESWIFT_CONNECTION_INIT}' }, appOrigin)\n}\n`\n\n return (\n <>\n <script\n id=\"makeswift-preview-mode\"\n type=\"module\"\n dangerouslySetInnerHTML={{ __html: previewModeScript }}\n />\n <script\n id=\"makeswift-connection-check\"\n type=\"module\"\n dangerouslySetInnerHTML={{ __html: makeswiftConnection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AC;AAAA;AAAA,QACC,IAAG;AAAA,QACH,MAAK;AAAA,QACL,yBAAyB,EAAE,QAAQ,+BAA+B;AAAA;AAAA,IACpE;AAAA,KACF;AAEJ;","names":[]}
@@ -37,6 +37,7 @@ var import_react = require("react");
37
37
  var import_react2 = require("../../../api/react");
38
38
  var import_use_react_runtime = require("../hooks/use-react-runtime");
39
39
  var import_host_api_client = require("../host-api-client");
40
+ var import_site_version = require("../../../api/site-version");
40
41
  const LiveProvider = (0, import_react.lazy)(() => Promise.resolve().then(() => __toESM(require("./LiveProvider"))));
41
42
  const PreviewProvider = (0, import_react.lazy)(() => Promise.resolve().then(() => __toESM(require("./PreviewProvider"))));
42
43
  function ReactRuntimeProvider({
@@ -49,9 +50,10 @@ function ReactRuntimeProvider({
49
50
  const client = (0, import_react.useMemo)(
50
51
  () => new import_react2.MakeswiftHostApiClient({
51
52
  uri: new URL("graphql", apiOrigin).href,
52
- locale
53
+ locale,
54
+ siteVersion: previewMode ? import_site_version.MakeswiftSiteVersion.Working : import_site_version.MakeswiftSiteVersion.Live
53
55
  }),
54
- [apiOrigin, locale]
56
+ [apiOrigin, locale, previewMode]
55
57
  );
56
58
  const StoreProvider = previewMode ? PreviewProvider : LiveProvider;
57
59
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_use_react_runtime.ReactRuntimeContext.Provider, { value: runtime, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_host_api_client.MakeswiftHostApiClientProvider, { client, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StoreProvider, { children }) }) });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/runtimes/react/components/RuntimeProvider.tsx"],"sourcesContent":["'use client'\n\nimport { ReactNode, useMemo, lazy } from 'react'\n\nimport { MakeswiftHostApiClient } from '../../../api/react'\nimport { ReactRuntimeContext } from '../hooks/use-react-runtime'\nimport { ReactRuntime } from '../react-runtime'\nimport { MakeswiftHostApiClientProvider } from '../host-api-client'\n\nconst LiveProvider = lazy(() => import('./LiveProvider'))\nconst PreviewProvider = lazy(() => import('./PreviewProvider'))\n\nexport function ReactRuntimeProvider({\n children,\n runtime,\n previewMode,\n apiOrigin = 'https://api.makeswift.com',\n locale = undefined,\n}: {\n children: ReactNode\n runtime: ReactRuntime\n previewMode: boolean\n apiOrigin?: string\n locale?: string\n}) {\n const client = useMemo(\n () =>\n new MakeswiftHostApiClient({\n uri: new URL('graphql', apiOrigin).href,\n locale,\n }),\n [apiOrigin, locale],\n )\n\n const StoreProvider = previewMode ? PreviewProvider : LiveProvider\n\n return (\n <ReactRuntimeContext.Provider value={runtime}>\n <MakeswiftHostApiClientProvider client={client}>\n <StoreProvider>{children}</StoreProvider>\n </MakeswiftHostApiClientProvider>\n </ReactRuntimeContext.Provider>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAuCQ;AArCR,mBAAyC;AAEzC,IAAAA,gBAAuC;AACvC,+BAAoC;AAEpC,6BAA+C;AAE/C,MAAM,mBAAe,mBAAK,MAAM,6CAAO,gBAAgB,GAAC;AACxD,MAAM,sBAAkB,mBAAK,MAAM,6CAAO,mBAAmB,GAAC;AAEvD,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,EACZ,SAAS;AACX,GAMG;AACD,QAAM,aAAS;AAAA,IACb,MACE,IAAI,qCAAuB;AAAA,MACzB,KAAK,IAAI,IAAI,WAAW,SAAS,EAAE;AAAA,MACnC;AAAA,IACF,CAAC;AAAA,IACH,CAAC,WAAW,MAAM;AAAA,EACpB;AAEA,QAAM,gBAAgB,cAAc,kBAAkB;AAEtD,SACE,4CAAC,6CAAoB,UAApB,EAA6B,OAAO,SACnC,sDAAC,yDAA+B,QAC9B,sDAAC,iBAAe,UAAS,GAC3B,GACF;AAEJ;","names":["import_react"]}
1
+ {"version":3,"sources":["../../../../../src/runtimes/react/components/RuntimeProvider.tsx"],"sourcesContent":["'use client'\n\nimport { ReactNode, useMemo, lazy } from 'react'\n\nimport { MakeswiftHostApiClient } from '../../../api/react'\nimport { ReactRuntimeContext } from '../hooks/use-react-runtime'\nimport { ReactRuntime } from '../react-runtime'\nimport { MakeswiftHostApiClientProvider } from '../host-api-client'\nimport { MakeswiftSiteVersion } from '../../../api/site-version'\n\nconst LiveProvider = lazy(() => import('./LiveProvider'))\nconst PreviewProvider = lazy(() => import('./PreviewProvider'))\n\nexport function ReactRuntimeProvider({\n children,\n runtime,\n previewMode,\n apiOrigin = 'https://api.makeswift.com',\n locale = undefined,\n}: {\n children: ReactNode\n runtime: ReactRuntime\n previewMode: boolean\n apiOrigin?: string\n locale?: string\n}) {\n const client = useMemo(\n () =>\n new MakeswiftHostApiClient({\n uri: new URL('graphql', apiOrigin).href,\n locale,\n siteVersion: previewMode ? MakeswiftSiteVersion.Working : MakeswiftSiteVersion.Live,\n }),\n [apiOrigin, locale, previewMode],\n )\n\n const StoreProvider = previewMode ? PreviewProvider : LiveProvider\n\n return (\n <ReactRuntimeContext.Provider value={runtime}>\n <MakeswiftHostApiClientProvider client={client}>\n <StoreProvider>{children}</StoreProvider>\n </MakeswiftHostApiClientProvider>\n </ReactRuntimeContext.Provider>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAyCQ;AAvCR,mBAAyC;AAEzC,IAAAA,gBAAuC;AACvC,+BAAoC;AAEpC,6BAA+C;AAC/C,0BAAqC;AAErC,MAAM,mBAAe,mBAAK,MAAM,6CAAO,gBAAgB,GAAC;AACxD,MAAM,sBAAkB,mBAAK,MAAM,6CAAO,mBAAmB,GAAC;AAEvD,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,EACZ,SAAS;AACX,GAMG;AACD,QAAM,aAAS;AAAA,IACb,MACE,IAAI,qCAAuB;AAAA,MACzB,KAAK,IAAI,IAAI,WAAW,SAAS,EAAE;AAAA,MACnC;AAAA,MACA,aAAa,cAAc,yCAAqB,UAAU,yCAAqB;AAAA,IACjF,CAAC;AAAA,IACH,CAAC,WAAW,QAAQ,WAAW;AAAA,EACjC;AAEA,QAAM,gBAAgB,cAAc,kBAAkB;AAEtD,SACE,4CAAC,6CAAoB,UAApB,EAA6B,OAAO,SACnC,sDAAC,yDAA+B,QAC9B,sDAAC,iBAAe,UAAS,GAC3B,GACF;AAEJ;","names":["import_react"]}
@@ -26,8 +26,12 @@ module.exports = __toCommonJS(host_api_client_exports);
26
26
  var import_jsx_runtime = require("react/jsx-runtime");
27
27
  var import_react = require("react");
28
28
  var import_react2 = require("../../api/react");
29
+ var import_site_version = require("../../api/site-version");
29
30
  const Context = (0, import_react.createContext)(
30
- new import_react2.MakeswiftHostApiClient({ uri: "https://api.makeswift.com/graphql" })
31
+ new import_react2.MakeswiftHostApiClient({
32
+ uri: "https://api.makeswift.com/graphql",
33
+ siteVersion: import_site_version.MakeswiftSiteVersion.Live
34
+ })
31
35
  );
32
36
  function useMakeswiftHostApiClient() {
33
37
  return (0, import_react.useContext)(Context);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/runtimes/react/host-api-client.tsx"],"sourcesContent":["'use client'\n\nimport { ReactNode, createContext, useContext } from 'react'\nimport { MakeswiftHostApiClient } from '../../api/react'\n\nconst Context = createContext(\n new MakeswiftHostApiClient({ uri: 'https://api.makeswift.com/graphql' }),\n)\n\nexport function useMakeswiftHostApiClient(): MakeswiftHostApiClient {\n return useContext(Context)\n}\n\nexport function MakeswiftHostApiClientProvider({\n client,\n children,\n}: {\n client: MakeswiftHostApiClient\n children: ReactNode\n}) {\n return <Context.Provider value={client}>{children}</Context.Provider>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBS;AAlBT,mBAAqD;AACrD,IAAAA,gBAAuC;AAEvC,MAAM,cAAU;AAAA,EACd,IAAI,qCAAuB,EAAE,KAAK,oCAAoC,CAAC;AACzE;AAEO,SAAS,4BAAoD;AAClE,aAAO,yBAAW,OAAO;AAC3B;AAEO,SAAS,+BAA+B;AAAA,EAC7C;AAAA,EACA;AACF,GAGG;AACD,SAAO,4CAAC,QAAQ,UAAR,EAAiB,OAAO,QAAS,UAAS;AACpD;","names":["import_react"]}
1
+ {"version":3,"sources":["../../../../src/runtimes/react/host-api-client.tsx"],"sourcesContent":["'use client'\n\nimport { ReactNode, createContext, useContext } from 'react'\nimport { MakeswiftHostApiClient } from '../../api/react'\nimport { MakeswiftSiteVersion } from '../../api/site-version'\n\nconst Context = createContext(\n new MakeswiftHostApiClient({\n uri: 'https://api.makeswift.com/graphql',\n siteVersion: MakeswiftSiteVersion.Live,\n }),\n)\n\nexport function useMakeswiftHostApiClient(): MakeswiftHostApiClient {\n return useContext(Context)\n}\n\nexport function MakeswiftHostApiClientProvider({\n client,\n children,\n}: {\n client: MakeswiftHostApiClient\n children: ReactNode\n}) {\n return <Context.Provider value={client}>{children}</Context.Provider>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBS;AAtBT,mBAAqD;AACrD,IAAAA,gBAAuC;AACvC,0BAAqC;AAErC,MAAM,cAAU;AAAA,EACd,IAAI,qCAAuB;AAAA,IACzB,KAAK;AAAA,IACL,aAAa,yCAAqB;AAAA,EACpC,CAAC;AACH;AAEO,SAAS,4BAAoD;AAClE,aAAO,yBAAW,OAAO;AAC3B;AAEO,SAAS,+BAA+B;AAAA,EAC7C;AAAA,EACA;AACF,GAGG;AACD,SAAO,4CAAC,QAAQ,UAAR,EAAiB,OAAO,QAAS,UAAS;AACpD;","names":["import_react"]}
@@ -43,6 +43,7 @@ var LocalizedResourcesMap = __toESM(require("./modules/localized-resources-map")
43
43
  var import_actions = require("./actions");
44
44
  var import_api = require("../api");
45
45
  var import_site_published = require("../next/api-handler/handlers/webhook/site-published");
46
+ var import_site_version = require("../api/site-version");
46
47
  const reducer = (0, import_redux.combineReducers)({
47
48
  apiResources: APIResources.reducer,
48
49
  localizedResourcesMap: LocalizedResourcesMap.reducer
@@ -80,9 +81,12 @@ function getAPIResource(state, resourceType, resourceId, locale) {
80
81
  return APIResources.getAPIResource(state.apiResources, resourceType, resourceId, locale);
81
82
  }
82
83
  }
83
- async function fetchJson(url) {
84
+ async function fetchJson(url, siteVersion) {
84
85
  const response = await fetch(url, {
85
- headers: { "Content-Type": "application/json" },
86
+ headers: {
87
+ "Content-Type": "application/json",
88
+ [import_site_version.API_HANDLER_SITE_VERSION_HEADER]: siteVersion
89
+ },
86
90
  next: { tags: [import_site_published.MAKESWIFT_CACHE_TAG] }
87
91
  });
88
92
  if (response.status === 404)
@@ -96,7 +100,7 @@ async function fetchJson(url) {
96
100
  }
97
101
  return response.json();
98
102
  }
99
- function fetchAPIResource(resourceType, resourceId, locale) {
103
+ function fetchAPIResource(resourceType, resourceId, siteVersion, locale) {
100
104
  return async (dispatch, getState) => {
101
105
  const state = getState();
102
106
  if (getHasAPIResource(state, resourceType, resourceId, locale)) {
@@ -105,16 +109,22 @@ function fetchAPIResource(resourceType, resourceId, locale) {
105
109
  let resource;
106
110
  switch (resourceType) {
107
111
  case import_api.APIResourceType.Swatch:
108
- resource = await fetchJson(`/api/makeswift/swatches/${resourceId}`);
112
+ resource = await fetchJson(`/api/makeswift/swatches/${resourceId}`, siteVersion);
109
113
  break;
110
114
  case import_api.APIResourceType.File:
111
- resource = await fetchJson(`/api/makeswift/files/${resourceId}`);
115
+ resource = await fetchJson(`/api/makeswift/files/${resourceId}`, siteVersion);
112
116
  break;
113
117
  case import_api.APIResourceType.Typography:
114
- resource = await fetchJson(`/api/makeswift/typographies/${resourceId}`);
118
+ resource = await fetchJson(
119
+ `/api/makeswift/typographies/${resourceId}`,
120
+ siteVersion
121
+ );
115
122
  break;
116
123
  case import_api.APIResourceType.GlobalElement:
117
- resource = await fetchJson(`/api/makeswift/global-elements/${resourceId}`);
124
+ resource = await fetchJson(
125
+ `/api/makeswift/global-elements/${resourceId}`,
126
+ siteVersion
127
+ );
118
128
  break;
119
129
  case import_api.APIResourceType.LocalizedGlobalElement: {
120
130
  if (locale == null)
@@ -123,7 +133,8 @@ function fetchAPIResource(resourceType, resourceId, locale) {
123
133
  return null;
124
134
  }
125
135
  resource = await fetchJson(
126
- `/api/makeswift/localized-global-elements/${resourceId}/${locale}`
136
+ `/api/makeswift/localized-global-elements/${resourceId}/${locale}`,
137
+ siteVersion
127
138
  );
128
139
  dispatch(
129
140
  (0, import_actions.setLocalizedResourceId)({
@@ -138,11 +149,11 @@ function fetchAPIResource(resourceType, resourceId, locale) {
138
149
  const url = new URL(`/api/makeswift/page-pathname-slices/${resourceId}`, "http://n");
139
150
  if (locale != null)
140
151
  url.searchParams.set("locale", locale);
141
- resource = await fetchJson(url.pathname + url.search);
152
+ resource = await fetchJson(url.pathname + url.search, siteVersion);
142
153
  break;
143
154
  }
144
155
  case import_api.APIResourceType.Table:
145
- resource = await fetchJson(`/api/makeswift/tables/${resourceId}`);
156
+ resource = await fetchJson(`/api/makeswift/tables/${resourceId}`, siteVersion);
146
157
  break;
147
158
  default:
148
159
  resource = null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/state/makeswift-api-client.ts"],"sourcesContent":["import {\n applyMiddleware,\n createStore,\n combineReducers,\n type Dispatch as ReduxDispatch,\n type Store as ReduxStore,\n type Middleware,\n} from 'redux'\nimport thunk, { type ThunkAction, type ThunkDispatch } from 'redux-thunk'\n\nimport { composeWithDevToolsDevelopmentOnly } from '@redux-devtools/extension'\n\nimport { serializeState } from '../utils/serializeState'\n\nimport * as APIResources from './modules/api-resources'\nimport * as LocalizedResourcesMap from './modules/localized-resources-map'\nimport { type Action, ActionTypes, apiResourceFulfilled, setLocalizedResourceId } from './actions'\nimport {\n APIResourceType,\n type APIResource,\n type Swatch,\n type File,\n type Typography,\n type GlobalElement,\n type PagePathnameSlice,\n type Table,\n type LocalizedGlobalElement,\n type APIResourceLocale,\n} from '../api'\nimport { MAKESWIFT_CACHE_TAG } from '../next/api-handler/handlers/webhook/site-published'\n\nconst reducer = combineReducers({\n apiResources: APIResources.reducer,\n localizedResourcesMap: LocalizedResourcesMap.reducer,\n})\n\nexport type State = ReturnType<typeof reducer>\n\nexport type SerializedState = {\n apiResources: APIResources.SerializedState\n localizedResourcesMap: LocalizedResourcesMap.SerializedState\n}\n\nfunction getLocalizedResourceId(\n state: State,\n locale: string,\n resourceId: string,\n): string | undefined | null {\n return LocalizedResourcesMap.getLocalizedResourceId(\n state.localizedResourcesMap,\n locale,\n resourceId,\n )\n}\n\nexport function getHasAPIResource<T extends APIResourceType>(\n state: State,\n resourceType: APIResourceType,\n resourceId: string,\n locale?: APIResourceLocale<T>,\n): boolean {\n switch (resourceType) {\n case APIResourceType.LocalizedGlobalElement:\n if (locale == null) {\n console.error(`Attempt to access ${resourceType} ${resourceId} without a locale`)\n return false\n }\n\n const localizedId = getLocalizedResourceId(state, locale, resourceId)\n return (\n localizedId != null &&\n APIResources.getHasAPIResource(state.apiResources, resourceType, localizedId, locale)\n )\n\n default:\n return APIResources.getHasAPIResource(state.apiResources, resourceType, resourceId, locale)\n }\n}\n\nexport function getAPIResource<T extends APIResourceType>(\n state: State,\n resourceType: T,\n resourceId: string,\n locale?: APIResourceLocale<T>,\n): Extract<APIResource, { __typename: T }> | null {\n switch (resourceType) {\n case APIResourceType.LocalizedGlobalElement:\n if (locale == null) {\n console.error(`Attempt to access ${resourceType} ${resourceId} without a locale`)\n return null\n }\n\n const localizedId = getLocalizedResourceId(state, locale, resourceId)\n return localizedId != null\n ? APIResources.getAPIResource(state.apiResources, resourceType, localizedId, locale)\n : null\n\n default:\n return APIResources.getAPIResource(state.apiResources, resourceType, resourceId, locale)\n }\n}\n\ntype Thunk<ReturnType> = ThunkAction<ReturnType, State, unknown, Action>\n\nasync function fetchJson<T>(url: string): Promise<T | null> {\n const response = await fetch(url, {\n headers: { 'Content-Type': 'application/json' },\n next: { tags: [MAKESWIFT_CACHE_TAG] },\n })\n\n if (response.status === 404) return null\n\n if (!response.ok) throw new Error(response.statusText)\n\n if (response.headers.get('content-type')?.includes('application/json') !== true) {\n throw new Error(\n `Expected JSON response from \"${url}\" but got \"${response.headers.get('content-type')}\"`,\n )\n }\n\n return response.json()\n}\n\nexport function fetchAPIResource<T extends APIResourceType>(\n resourceType: T,\n resourceId: string,\n locale?: APIResourceLocale<T>,\n): Thunk<Promise<Extract<APIResource, { __typename: T }> | null>> {\n return async (dispatch, getState) => {\n const state = getState()\n\n if (getHasAPIResource(state, resourceType, resourceId, locale)) {\n return getAPIResource(state, resourceType, resourceId, locale)\n }\n\n let resource: APIResource | null\n\n switch (resourceType) {\n case APIResourceType.Swatch:\n resource = await fetchJson<Swatch>(`/api/makeswift/swatches/${resourceId}`)\n break\n\n case APIResourceType.File:\n resource = await fetchJson<File>(`/api/makeswift/files/${resourceId}`)\n break\n\n case APIResourceType.Typography:\n resource = await fetchJson<Typography>(`/api/makeswift/typographies/${resourceId}`)\n break\n\n case APIResourceType.GlobalElement:\n resource = await fetchJson<GlobalElement>(`/api/makeswift/global-elements/${resourceId}`)\n break\n\n case APIResourceType.LocalizedGlobalElement: {\n if (locale == null) throw new Error('Locale is required to fetch LocalizedGlobalElement')\n\n // If `getLocalizedResourceId` returns null, it means we have tried to fetch the resource,\n // but the resource is not available. If we haven't fetched it yet, it'll return undefined.\n if (getLocalizedResourceId(state, locale, resourceId) === null) {\n return null\n }\n\n resource = await fetchJson<LocalizedGlobalElement>(\n `/api/makeswift/localized-global-elements/${resourceId}/${locale}`,\n )\n\n dispatch(\n setLocalizedResourceId({\n locale,\n resourceId,\n localizedResourceId: resource?.id ?? null,\n }),\n )\n\n break\n }\n\n case APIResourceType.PagePathnameSlice: {\n const url = new URL(`/api/makeswift/page-pathname-slices/${resourceId}`, 'http://n')\n\n if (locale != null) url.searchParams.set('locale', locale)\n\n resource = await fetchJson<PagePathnameSlice>(url.pathname + url.search)\n break\n }\n\n case APIResourceType.Table:\n resource = await fetchJson<Table>(`/api/makeswift/tables/${resourceId}`)\n break\n\n default:\n resource = null\n }\n\n dispatch(apiResourceFulfilled(resourceType, resourceId, resource, locale))\n\n return resource as Extract<APIResource, { __typename: T }> | null\n }\n}\n\nexport type Dispatch = ThunkDispatch<State, unknown, Action>\n\nexport type Store = ReduxStore<State, Action> & { dispatch: Dispatch }\n\n// FIXME: this middleware can be removed once we've upgraded the builder\n// to always provide the locale when dispatching resource actions\nfunction defaultLocaleMiddleware(\n defaultLocale: string | undefined,\n): Middleware<Dispatch, State, Dispatch> {\n return () => (next: ReduxDispatch<Action>) => {\n return (action: Action): Action => {\n switch (action.type) {\n case ActionTypes.CHANGE_API_RESOURCE:\n case ActionTypes.EVICT_API_RESOURCE:\n case ActionTypes.SET_LOCALIZED_RESOURCE_ID: {\n const { locale } = action.payload\n return next({\n ...action,\n payload: { ...action.payload, locale: locale ?? defaultLocale },\n } as Action)\n }\n }\n\n return next(action)\n }\n }\n}\n\nexport function configureStore({\n defaultLocale,\n serializedState,\n}: {\n defaultLocale: string | undefined\n serializedState?: SerializedState\n}): Store {\n const composeEnhancers = composeWithDevToolsDevelopmentOnly({\n name: `API client store (${new Date().toISOString()})`,\n serialize: true,\n stateSanitizer: (state: any) => serializeState(state),\n actionsDenylist: [\n ActionTypes.BUILDER_POINTER_MOVE,\n ActionTypes.HANDLE_POINTER_MOVE,\n ActionTypes.ELEMENT_FROM_POINT_CHANGE,\n ],\n })\n\n return createStore(\n reducer,\n {\n apiResources: APIResources.getInitialState(serializedState?.apiResources),\n localizedResourcesMap: LocalizedResourcesMap.getInitialState(\n serializedState?.localizedResourcesMap,\n ),\n },\n composeEnhancers(applyMiddleware(thunk, defaultLocaleMiddleware(defaultLocale))),\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAOO;AACP,yBAA4D;AAE5D,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B;AAAA,QAC3C,iBAAiB;AAAA,MACnB;AAAA,IACF;AAAA,IACA,qBAAiB,8BAAgB,mBAAAA,SAAO,wBAAwB,aAAa,CAAC,CAAC;AAAA,EACjF;AACF;","names":["thunk"]}
1
+ {"version":3,"sources":["../../../src/state/makeswift-api-client.ts"],"sourcesContent":["import {\n applyMiddleware,\n createStore,\n combineReducers,\n type Dispatch as ReduxDispatch,\n type Store as ReduxStore,\n type Middleware,\n} from 'redux'\nimport thunk, { type ThunkAction, type ThunkDispatch } from 'redux-thunk'\n\nimport { composeWithDevToolsDevelopmentOnly } from '@redux-devtools/extension'\n\nimport { serializeState } from '../utils/serializeState'\n\nimport * as APIResources from './modules/api-resources'\nimport * as LocalizedResourcesMap from './modules/localized-resources-map'\nimport { type Action, ActionTypes, apiResourceFulfilled, setLocalizedResourceId } from './actions'\nimport {\n APIResourceType,\n type APIResource,\n type Swatch,\n type File,\n type Typography,\n type GlobalElement,\n type PagePathnameSlice,\n type Table,\n type LocalizedGlobalElement,\n type APIResourceLocale,\n} from '../api'\nimport { MAKESWIFT_CACHE_TAG } from '../next/api-handler/handlers/webhook/site-published'\nimport { API_HANDLER_SITE_VERSION_HEADER, MakeswiftSiteVersion } from '../api/site-version'\n\nconst reducer = combineReducers({\n apiResources: APIResources.reducer,\n localizedResourcesMap: LocalizedResourcesMap.reducer,\n})\n\nexport type State = ReturnType<typeof reducer>\n\nexport type SerializedState = {\n apiResources: APIResources.SerializedState\n localizedResourcesMap: LocalizedResourcesMap.SerializedState\n}\n\nfunction getLocalizedResourceId(\n state: State,\n locale: string,\n resourceId: string,\n): string | undefined | null {\n return LocalizedResourcesMap.getLocalizedResourceId(\n state.localizedResourcesMap,\n locale,\n resourceId,\n )\n}\n\nexport function getHasAPIResource<T extends APIResourceType>(\n state: State,\n resourceType: APIResourceType,\n resourceId: string,\n locale?: APIResourceLocale<T>,\n): boolean {\n switch (resourceType) {\n case APIResourceType.LocalizedGlobalElement:\n if (locale == null) {\n console.error(`Attempt to access ${resourceType} ${resourceId} without a locale`)\n return false\n }\n\n const localizedId = getLocalizedResourceId(state, locale, resourceId)\n return (\n localizedId != null &&\n APIResources.getHasAPIResource(state.apiResources, resourceType, localizedId, locale)\n )\n\n default:\n return APIResources.getHasAPIResource(state.apiResources, resourceType, resourceId, locale)\n }\n}\n\nexport function getAPIResource<T extends APIResourceType>(\n state: State,\n resourceType: T,\n resourceId: string,\n locale?: APIResourceLocale<T>,\n): Extract<APIResource, { __typename: T }> | null {\n switch (resourceType) {\n case APIResourceType.LocalizedGlobalElement:\n if (locale == null) {\n console.error(`Attempt to access ${resourceType} ${resourceId} without a locale`)\n return null\n }\n\n const localizedId = getLocalizedResourceId(state, locale, resourceId)\n return localizedId != null\n ? APIResources.getAPIResource(state.apiResources, resourceType, localizedId, locale)\n : null\n\n default:\n return APIResources.getAPIResource(state.apiResources, resourceType, resourceId, locale)\n }\n}\n\ntype Thunk<ReturnType> = ThunkAction<ReturnType, State, unknown, Action>\n\nasync function fetchJson<T>(url: string, siteVersion: MakeswiftSiteVersion): Promise<T | null> {\n const response = await fetch(url, {\n headers: {\n 'Content-Type': 'application/json',\n [API_HANDLER_SITE_VERSION_HEADER]: siteVersion,\n },\n next: { tags: [MAKESWIFT_CACHE_TAG] },\n })\n\n if (response.status === 404) return null\n\n if (!response.ok) throw new Error(response.statusText)\n\n if (response.headers.get('content-type')?.includes('application/json') !== true) {\n throw new Error(\n `Expected JSON response from \"${url}\" but got \"${response.headers.get('content-type')}\"`,\n )\n }\n\n return response.json()\n}\n\nexport function fetchAPIResource<T extends APIResourceType>(\n resourceType: T,\n resourceId: string,\n siteVersion: MakeswiftSiteVersion,\n locale?: APIResourceLocale<T>,\n): Thunk<Promise<Extract<APIResource, { __typename: T }> | null>> {\n return async (dispatch, getState) => {\n const state = getState()\n\n if (getHasAPIResource(state, resourceType, resourceId, locale)) {\n return getAPIResource(state, resourceType, resourceId, locale)\n }\n\n let resource: APIResource | null\n\n switch (resourceType) {\n case APIResourceType.Swatch:\n resource = await fetchJson<Swatch>(`/api/makeswift/swatches/${resourceId}`, siteVersion)\n break\n\n case APIResourceType.File:\n resource = await fetchJson<File>(`/api/makeswift/files/${resourceId}`, siteVersion)\n break\n\n case APIResourceType.Typography:\n resource = await fetchJson<Typography>(\n `/api/makeswift/typographies/${resourceId}`,\n siteVersion,\n )\n break\n\n case APIResourceType.GlobalElement:\n resource = await fetchJson<GlobalElement>(\n `/api/makeswift/global-elements/${resourceId}`,\n siteVersion,\n )\n break\n\n case APIResourceType.LocalizedGlobalElement: {\n if (locale == null) throw new Error('Locale is required to fetch LocalizedGlobalElement')\n\n // If `getLocalizedResourceId` returns null, it means we have tried to fetch the resource,\n // but the resource is not available. If we haven't fetched it yet, it'll return undefined.\n if (getLocalizedResourceId(state, locale, resourceId) === null) {\n return null\n }\n\n resource = await fetchJson<LocalizedGlobalElement>(\n `/api/makeswift/localized-global-elements/${resourceId}/${locale}`,\n siteVersion,\n )\n\n dispatch(\n setLocalizedResourceId({\n locale,\n resourceId,\n localizedResourceId: resource?.id ?? null,\n }),\n )\n\n break\n }\n\n case APIResourceType.PagePathnameSlice: {\n const url = new URL(`/api/makeswift/page-pathname-slices/${resourceId}`, 'http://n')\n\n if (locale != null) url.searchParams.set('locale', locale)\n\n resource = await fetchJson<PagePathnameSlice>(url.pathname + url.search, siteVersion)\n break\n }\n\n case APIResourceType.Table:\n resource = await fetchJson<Table>(`/api/makeswift/tables/${resourceId}`, siteVersion)\n break\n\n default:\n resource = null\n }\n\n dispatch(apiResourceFulfilled(resourceType, resourceId, resource, locale))\n\n return resource as Extract<APIResource, { __typename: T }> | null\n }\n}\n\nexport type Dispatch = ThunkDispatch<State, unknown, Action>\n\nexport type Store = ReduxStore<State, Action> & { dispatch: Dispatch }\n\n// FIXME: this middleware can be removed once we've upgraded the builder\n// to always provide the locale when dispatching resource actions\nfunction defaultLocaleMiddleware(\n defaultLocale: string | undefined,\n): Middleware<Dispatch, State, Dispatch> {\n return () => (next: ReduxDispatch<Action>) => {\n return (action: Action): Action => {\n switch (action.type) {\n case ActionTypes.CHANGE_API_RESOURCE:\n case ActionTypes.EVICT_API_RESOURCE:\n case ActionTypes.SET_LOCALIZED_RESOURCE_ID: {\n const { locale } = action.payload\n return next({\n ...action,\n payload: { ...action.payload, locale: locale ?? defaultLocale },\n } as Action)\n }\n }\n\n return next(action)\n }\n }\n}\n\nexport function configureStore({\n defaultLocale,\n serializedState,\n}: {\n defaultLocale: string | undefined\n serializedState?: SerializedState\n}): Store {\n const composeEnhancers = composeWithDevToolsDevelopmentOnly({\n name: `API client store (${new Date().toISOString()})`,\n serialize: true,\n stateSanitizer: (state: any) => serializeState(state),\n actionsDenylist: [\n ActionTypes.BUILDER_POINTER_MOVE,\n ActionTypes.HANDLE_POINTER_MOVE,\n ActionTypes.ELEMENT_FROM_POINT_CHANGE,\n ],\n })\n\n return createStore(\n reducer,\n {\n apiResources: APIResources.getInitialState(serializedState?.apiResources),\n localizedResourcesMap: LocalizedResourcesMap.getInitialState(\n serializedState?.localizedResourcesMap,\n ),\n },\n composeEnhancers(applyMiddleware(thunk, defaultLocaleMiddleware(defaultLocale))),\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAOO;AACP,yBAA4D;AAE5D,uBAAmD;AAEnD,4BAA+B;AAE/B,mBAA8B;AAC9B,4BAAuC;AACvC,qBAAuF;AACvF,iBAWO;AACP,4BAAoC;AACpC,0BAAsE;AAEtE,MAAM,cAAU,8BAAgB;AAAA,EAC9B,cAAc,aAAa;AAAA,EAC3B,uBAAuB,sBAAsB;AAC/C,CAAC;AASD,SAAS,uBACP,OACA,QACA,YAC2B;AAC3B,SAAO,sBAAsB;AAAA,IAC3B,MAAM;AAAA,IACN;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,kBACd,OACA,cACA,YACA,QACS;AACT,UAAQ,cAAc;AAAA,IACpB,KAA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B,yBAAyB,UAAU,IAAI,WAAW;AACpF;AAAA,MAEF;AACE,mBAAW;AAAA,IACf;AAEA,iBAAS,qCAAqB,cAAc,YAAY,UAAU,MAAM,CAAC;AAEzE,WAAO;AAAA,EACT;AACF;AAQA,SAAS,wBACP,eACuC;AACvC,SAAO,MAAM,CAAC,SAAgC;AAC5C,WAAO,CAAC,WAA2B;AACjC,cAAQ,OAAO,MAAM;AAAA,QACnB,KAAK,2BAAY;AAAA,QACjB,KAAK,2BAAY;AAAA,QACjB,KAAK,2BAAY,2BAA2B;AAC1C,gBAAM,EAAE,OAAO,IAAI,OAAO;AAC1B,iBAAO,KAAK;AAAA,YACV,GAAG;AAAA,YACH,SAAS,EAAE,GAAG,OAAO,SAAS,QAAQ,UAAU,cAAc;AAAA,UAChE,CAAW;AAAA,QACb;AAAA,MACF;AAEA,aAAO,KAAK,MAAM;AAAA,IACpB;AAAA,EACF;AACF;AAEO,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA;AACF,GAGU;AACR,QAAM,uBAAmB,qDAAmC;AAAA,IAC1D,MAAM,sBAAqB,oBAAI,KAAK,GAAE,YAAY,CAAC;AAAA,IACnD,WAAW;AAAA,IACX,gBAAgB,CAAC,cAAe,sCAAe,KAAK;AAAA,IACpD,iBAAiB;AAAA,MACf,2BAAY;AAAA,MACZ,2BAAY;AAAA,MACZ,2BAAY;AAAA,IACd;AAAA,EACF,CAAC;AAED,aAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,cAAc,aAAa,gBAAgB,iBAAiB,YAAY;AAAA,MACxE,uBAAuB,sBAAsB;AAAA,QAC3C,iBAAiB;AAAA,MACnB;AAAA,IACF;AAAA,IACA,qBAAiB,8BAAgB,mBAAAA,SAAO,wBAAwB,aAAa,CAAC,CAAC;AAAA,EACjF;AACF;","names":["thunk"]}
@@ -13,15 +13,22 @@ const CacheData = {
13
13
  }
14
14
  };
15
15
  class MakeswiftHostApiClient {
16
+ siteVersion;
16
17
  graphqlClient;
17
18
  makeswiftApiClient;
18
19
  subscribe;
19
- constructor({ uri, cacheData, locale }) {
20
+ constructor({
21
+ uri,
22
+ siteVersion,
23
+ cacheData,
24
+ locale
25
+ }) {
20
26
  this.graphqlClient = new GraphQLClient(uri);
21
27
  this.makeswiftApiClient = MakeswiftApiClient.configureStore({
22
28
  serializedState: cacheData,
23
29
  defaultLocale: locale
24
30
  });
31
+ this.siteVersion = siteVersion;
25
32
  this.subscribe = this.makeswiftApiClient.subscribe;
26
33
  }
27
34
  readSwatch(swatchId) {
@@ -33,7 +40,7 @@ class MakeswiftHostApiClient {
33
40
  }
34
41
  async fetchSwatch(swatchId) {
35
42
  return await this.makeswiftApiClient.dispatch(
36
- MakeswiftApiClient.fetchAPIResource(APIResourceType.Swatch, swatchId)
43
+ MakeswiftApiClient.fetchAPIResource(APIResourceType.Swatch, swatchId, this.siteVersion)
37
44
  );
38
45
  }
39
46
  resolveSwatch(swatchId) {
@@ -52,7 +59,7 @@ class MakeswiftHostApiClient {
52
59
  }
53
60
  async fetchFile(fileId) {
54
61
  return await this.makeswiftApiClient.dispatch(
55
- MakeswiftApiClient.fetchAPIResource(APIResourceType.File, fileId)
62
+ MakeswiftApiClient.fetchAPIResource(APIResourceType.File, fileId, this.siteVersion)
56
63
  );
57
64
  }
58
65
  resolveFile(fileId) {
@@ -71,7 +78,11 @@ class MakeswiftHostApiClient {
71
78
  }
72
79
  async fetchTypography(typographyId) {
73
80
  return await this.makeswiftApiClient.dispatch(
74
- MakeswiftApiClient.fetchAPIResource(APIResourceType.Typography, typographyId)
81
+ MakeswiftApiClient.fetchAPIResource(
82
+ APIResourceType.Typography,
83
+ typographyId,
84
+ this.siteVersion
85
+ )
75
86
  );
76
87
  }
77
88
  resolveTypography(typographyId) {
@@ -90,7 +101,11 @@ class MakeswiftHostApiClient {
90
101
  }
91
102
  async fetchGlobalElement(globalElementId) {
92
103
  return await this.makeswiftApiClient.dispatch(
93
- MakeswiftApiClient.fetchAPIResource(APIResourceType.GlobalElement, globalElementId)
104
+ MakeswiftApiClient.fetchAPIResource(
105
+ APIResourceType.GlobalElement,
106
+ globalElementId,
107
+ this.siteVersion
108
+ )
94
109
  );
95
110
  }
96
111
  readLocalizedGlobalElement({
@@ -112,6 +127,7 @@ class MakeswiftHostApiClient {
112
127
  MakeswiftApiClient.fetchAPIResource(
113
128
  APIResourceType.LocalizedGlobalElement,
114
129
  globalElementId,
130
+ this.siteVersion,
115
131
  locale
116
132
  )
117
133
  );
@@ -132,7 +148,12 @@ class MakeswiftHostApiClient {
132
148
  locale
133
149
  }) {
134
150
  return await this.makeswiftApiClient.dispatch(
135
- MakeswiftApiClient.fetchAPIResource(APIResourceType.PagePathnameSlice, pageId, locale)
151
+ MakeswiftApiClient.fetchAPIResource(
152
+ APIResourceType.PagePathnameSlice,
153
+ pageId,
154
+ this.siteVersion,
155
+ locale
156
+ )
136
157
  );
137
158
  }
138
159
  resolvePagePathnameSlice({
@@ -171,7 +192,7 @@ class MakeswiftHostApiClient {
171
192
  }
172
193
  async fetchTable(tableId) {
173
194
  return await this.makeswiftApiClient.dispatch(
174
- MakeswiftApiClient.fetchAPIResource(APIResourceType.Table, tableId)
195
+ MakeswiftApiClient.fetchAPIResource(APIResourceType.Table, tableId, this.siteVersion)
175
196
  );
176
197
  }
177
198
  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":"AACA,YAAY,wBAAwB;AACpC;AAAA,EACE;AAAA,OAWK;AACP,SAAS,qBAAqB;AAC9B,SAAS,iCAAiC;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,cAAc,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,gBAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,YAAY,UAA0C;AAC1D,WAAO,MAAM,KAAK,mBAAmB;AAAA,MACnC,mBAAmB,iBAAiB,gBAAgB,QAAQ,QAAQ;AAAA,IACtE;AAAA,EACF;AAAA,EAEA,cAAc,UAA6D;AACzE,WAAO,KAAK,gBAAgB,gBAAgB,QAAQ;AAAA,MAClD,IAAI;A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,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,UAAU,SAA+B;AACvC,WAAO,mBAAmB;AAAA,MACxB,KAAK,mBAAmB,SAAS;AAAA,MACjC,gBAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,WAAW,SAAwC;AACvD,WAAO,MAAM,KAAK,mBAAmB;AAAA,MACnC,mBAAmB,iBAAiB,gBAAgB,OAAO,OAAO;AAAA,IACpE;AAAA,EACF;AAAA,EAEA,MAAM,kBAAkB,SAAiB,SAA6B;AACpE,UAAM,KAAK,cAAc,QAGvB,2BAA2B,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,gBAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,SAAS,QAA6B;AACpC,WAAO,mBAAmB;AAAA,MACxB,KAAK,mBAAmB,SAAS;AAAA,MACjC,gBAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,YAAY,WAAmC;AAC7C,WAAO,mBAAmB;AAAA,MACxB,KAAK,mBAAmB,SAAS;AAAA,MACjC,gBAAgB;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":"AACA,YAAY,wBAAwB;AACpC;AAAA,EACE;AAAA,OAWK;AACP,SAAS,qBAAqB;AAC9B,SAAS,iCAAiC;AASnC,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,EACA;AAAA,EAEA,YAAY;AAAA,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AO,MAAM,KAAK,mBAAmB;AAAA,MACnC,mBAAmB,iBAAiB,gBAAgB,OAAO,SAAS,KAAK,WAAW;AAAA,IACtF;AAAA,EACF;AAAA,EAEA,MAAM,kBAAkB,SAAiB,SAA6B;AACpE,UAAM,KAAK,cAAc,QAGvB,2BAA2B,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,gBAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,SAAS,QAA6B;AACpC,WAAO,mBAAmB;AAAA,MACxB,KAAK,mBAAmB,SAAS;AAAA,MACjC,gBAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,YAAY,WAAmC;AAC7C,WAAO,mBAAmB;AAAA,MACxB,KAAK,mBAAmB,SAAS;AAAA,MACjC,gBAAgB;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,10 @@
1
+ import { z } from "zod";
2
+ const makeswiftSiteVersionSchema = z.enum(["Live", "Working"]);
3
+ const MakeswiftSiteVersion = makeswiftSiteVersionSchema.Enum;
4
+ const API_HANDLER_SITE_VERSION_HEADER = "X-Makeswift-Site-Version";
5
+ export {
6
+ API_HANDLER_SITE_VERSION_HEADER,
7
+ MakeswiftSiteVersion,
8
+ makeswiftSiteVersionSchema
9
+ };
10
+ //# 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,SAAS,SAAS;AAEX,MAAM,6BAA6B,EAAE,KAAK,CAAC,QAAQ,SAAS,CAAC;AAC7D,MAAM,uBAAuB,2BAA2B;AAGxD,MAAM,kCAAkC;","names":[]}