@webiny/sdk-frontend 6.6.0-alpha.1 → 6.6.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ import type { ContentClient, Document } from "@webiny/website-builder-sdk";
2
+ /**
3
+ * Register the CMS data loader on the SDK-level content-entry cache.
4
+ *
5
+ * Called by `resolveContentEntries` (server pre-pass) AND by `FrontendSdk.init()`
6
+ * (client bootstrap) so the `BindingsResolver` can resolve content-entry
7
+ * inputs in both environments.
8
+ */
9
+ export declare const ensureContentEntryLoader: () => void;
10
+ export type ResolveContentEntriesOptions = {
11
+ client?: ContentClient;
12
+ };
13
+ /**
14
+ * Server-side (RSC) pre-pass: resolves every `contentEntry` input into CMS
15
+ * entries and seeds the SDK-level `contentEntryCache`, or the given client's cache.
16
+ *
17
+ * Content-entry inputs are identified by the `type` field on each
18
+ * `InputValueBinding` — no component manifests or metadata required.
19
+ */
20
+ export declare function resolveContentEntries(document: Document | null, options?: ResolveContentEntriesOptions): Promise<void>;
@@ -0,0 +1,45 @@
1
+ import { contentEntryCache, isAlreadyResolved, resolveContentEntryValue } from "@webiny/website-builder-sdk";
2
+ import { contentSdk } from "@webiny/cms-sdk";
3
+ const ensureContentEntryLoader = ()=>{
4
+ if (!contentEntryCache.getLoader()) contentEntryCache.setLoader({
5
+ getEntry: (params)=>contentSdk.getEntry(params),
6
+ listEntries: (params)=>contentSdk.listEntries(params)
7
+ });
8
+ };
9
+ async function resolveContentEntries(document, options = {}) {
10
+ if (!document) return;
11
+ let cache = contentEntryCache;
12
+ if (options.client) cache = options.client.getContentEntryCache();
13
+ else ensureContentEntryLoader();
14
+ const loader = cache.getLoader();
15
+ if (!loader) throw new Error("The content client has no contentEntryLoader. Pass one in its config, bound to the client's tenant.");
16
+ const resolved = {};
17
+ const tasks = [];
18
+ for (const [elementId] of Object.entries(document.elements)){
19
+ const elementBindings = document.bindings[elementId] ?? {};
20
+ const inputBindings = elementBindings.inputs;
21
+ if (inputBindings) for (const [inputName, binding] of Object.entries(inputBindings)){
22
+ if (!binding || "contentEntry" !== binding.type) continue;
23
+ const rawValue = binding.static;
24
+ const list = binding.list ?? false;
25
+ const cacheKey = `${elementId}:${inputName}`;
26
+ if (isAlreadyResolved(rawValue, list)) {
27
+ cache.set(cacheKey, rawValue);
28
+ resolved[cacheKey] = rawValue;
29
+ continue;
30
+ }
31
+ tasks.push(resolveContentEntryValue(rawValue, list, loader).then((result)=>{
32
+ cache.set(cacheKey, result);
33
+ resolved[cacheKey] = result;
34
+ }));
35
+ }
36
+ }
37
+ await Promise.all(tasks);
38
+ if (Object.keys(resolved).length > 0) {
39
+ if (!document.__cache) document.__cache = {};
40
+ document.__cache.contentEntries = resolved;
41
+ }
42
+ }
43
+ export { ensureContentEntryLoader, resolveContentEntries };
44
+
45
+ //# sourceMappingURL=resolveContentEntries.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolveContentEntries.js","sources":["../src/resolveContentEntries.ts"],"sourcesContent":["import type { ContentClient, Document } from \"@webiny/website-builder-sdk\";\nimport {\n contentEntryCache,\n resolveContentEntryValue,\n isAlreadyResolved\n} from \"@webiny/website-builder-sdk\";\nimport { contentSdk } from \"@webiny/cms-sdk\";\n\n/**\n * Register the CMS data loader on the SDK-level content-entry cache.\n *\n * Called by `resolveContentEntries` (server pre-pass) AND by `FrontendSdk.init()`\n * (client bootstrap) so the `BindingsResolver` can resolve content-entry\n * inputs in both environments.\n */\nexport const ensureContentEntryLoader = () => {\n if (!contentEntryCache.getLoader()) {\n contentEntryCache.setLoader({\n getEntry: params => contentSdk.getEntry(params),\n listEntries: params => contentSdk.listEntries(params)\n });\n }\n};\n\nexport type ResolveContentEntriesOptions = {\n /*\n * Resolve with this content client's entry cache and loader instead of the\n * `contentEntryCache` singleton and the `@webiny/cms-sdk` singleton. The client\n * needs a `contentEntryLoader` in its config.\n */\n client?: ContentClient;\n};\n\n/**\n * Server-side (RSC) pre-pass: resolves every `contentEntry` input into CMS\n * entries and seeds the SDK-level `contentEntryCache`, or the given client's cache.\n *\n * Content-entry inputs are identified by the `type` field on each\n * `InputValueBinding` — no component manifests or metadata required.\n */\nexport async function resolveContentEntries(\n document: Document | null,\n options: ResolveContentEntriesOptions = {}\n): Promise<void> {\n if (!document) {\n return;\n }\n\n let cache = contentEntryCache;\n if (options.client) {\n cache = options.client.getContentEntryCache();\n } else {\n ensureContentEntryLoader();\n }\n\n const loader = cache.getLoader();\n if (!loader) {\n throw new Error(\n \"The content client has no contentEntryLoader. Pass one in its config, bound to the client's tenant.\"\n );\n }\n\n // Collect resolved entries so they can be embedded on the document and\n // travel through React serialisation from server to client.\n const resolved: Record<string, unknown> = {};\n const tasks: Promise<void>[] = [];\n\n for (const [elementId] of Object.entries(document.elements)) {\n const elementBindings = document.bindings[elementId] ?? {};\n const inputBindings = elementBindings.inputs;\n\n if (!inputBindings) {\n continue;\n }\n\n for (const [inputName, binding] of Object.entries(inputBindings)) {\n if (!binding || binding.type !== \"contentEntry\") {\n continue;\n }\n\n const rawValue = binding.static;\n const list = binding.list ?? false;\n const cacheKey = `${elementId}:${inputName}`;\n\n // Already-resolved entries (e.g. editor stored the full entry, not\n // a bare reference) are passed through directly.\n if (isAlreadyResolved(rawValue, list)) {\n cache.set(cacheKey, rawValue);\n resolved[cacheKey] = rawValue;\n continue;\n }\n\n tasks.push(\n resolveContentEntryValue(rawValue, list, loader).then(result => {\n cache.set(cacheKey, result);\n resolved[cacheKey] = result;\n })\n );\n }\n }\n\n await Promise.all(tasks);\n\n // Embed resolved entries on the document cache so the client\n // `BindingsResolver` can hydrate from them (the module-level\n // `contentEntryCache` singleton does not cross the server→client boundary).\n if (Object.keys(resolved).length > 0) {\n if (!document.__cache) {\n document.__cache = {};\n }\n document.__cache.contentEntries = resolved;\n }\n}\n"],"names":["ensureContentEntryLoader","contentEntryCache","params","contentSdk","resolveContentEntries","document","options","cache","loader","Error","resolved","tasks","elementId","Object","elementBindings","in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AG,CAACa,UAAUG;gBACpBb,QAAQ,CAACU,SAAS,GAAGG;YACzB;QAER;IACJ;IAEA,MAAMC,QAAQ,GAAG,CAACb;IAKlB,IAAIE,OAAO,IAAI,CAACH,UAAU,MAAM,GAAG,GAAG;QAClC,IAAI,CAACL,SAAS,OAAO,EACjBA,SAAS,OAAO,GAAG,CAAC;QAExBA,SAAS,OAAO,CAAC,cAAc,GAAGK;IACtC;AACJ"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,328 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { resolveContentEntries } from "./resolveContentEntries.js";
3
+ import { contentEntryCache } from "@webiny/website-builder-sdk";
4
+ const mockGetEntry = vi.fn();
5
+ const mockListEntries = vi.fn();
6
+ vi.mock("@webiny/cms-sdk", ()=>({
7
+ contentSdk: {
8
+ getEntry: (...args)=>mockGetEntry(...args),
9
+ listEntries: (...args)=>mockListEntries(...args)
10
+ }
11
+ }));
12
+ const entry = (id)=>({
13
+ id,
14
+ entryId: id,
15
+ values: {
16
+ title: `T${id}`
17
+ }
18
+ });
19
+ function makeDocument(overrides = {}) {
20
+ return {
21
+ id: "doc1",
22
+ version: 1,
23
+ state: {},
24
+ properties: {},
25
+ extensions: {},
26
+ metadata: {},
27
+ bindings: {},
28
+ elements: {},
29
+ ...overrides
30
+ };
31
+ }
32
+ beforeEach(()=>{
33
+ vi.clearAllMocks();
34
+ contentEntryCache.cache?.clear?.();
35
+ contentEntryCache.loader = void 0;
36
+ mockGetEntry.mockImplementation(async ({ entryId })=>entry(entryId));
37
+ mockListEntries.mockImplementation(async ()=>({
38
+ data: [
39
+ entry("q1"),
40
+ entry("q2")
41
+ ],
42
+ meta: {
43
+ cursor: "c1",
44
+ hasMoreItems: false,
45
+ totalCount: 2
46
+ }
47
+ }));
48
+ });
49
+ describe("resolveContentEntries — binding-type-based resolution", ()=>{
50
+ it("does nothing for a null document", async ()=>{
51
+ await resolveContentEntries(null);
52
+ expect(mockGetEntry).not.toHaveBeenCalled();
53
+ });
54
+ it("does nothing when no elements have content-entry bindings", async ()=>{
55
+ const doc = makeDocument({
56
+ elements: {
57
+ el1: {
58
+ id: "el1",
59
+ type: "Webiny/Element",
60
+ component: {
61
+ name: "MyComponent"
62
+ }
63
+ }
64
+ },
65
+ bindings: {
66
+ el1: {
67
+ inputs: {
68
+ text: {
69
+ id: "text",
70
+ type: "text",
71
+ static: "hello"
72
+ }
73
+ }
74
+ }
75
+ }
76
+ });
77
+ await resolveContentEntries(doc);
78
+ expect(mockGetEntry).not.toHaveBeenCalled();
79
+ expect(doc.__cache).toBeUndefined();
80
+ });
81
+ it("resolves a manual single content-entry input", async ()=>{
82
+ const doc = makeDocument({
83
+ elements: {
84
+ el1: {
85
+ id: "el1",
86
+ type: "Webiny/Element",
87
+ component: {
88
+ name: "MyComponent"
89
+ }
90
+ }
91
+ },
92
+ bindings: {
93
+ el1: {
94
+ inputs: {
95
+ article: {
96
+ id: "article",
97
+ type: "contentEntry",
98
+ static: {
99
+ id: "42",
100
+ modelId: "blog"
101
+ }
102
+ }
103
+ }
104
+ }
105
+ }
106
+ });
107
+ await resolveContentEntries(doc);
108
+ expect(mockGetEntry).toHaveBeenCalledWith({
109
+ modelId: "blog",
110
+ entryId: "42"
111
+ });
112
+ expect(doc.__cache?.contentEntries).toBeDefined();
113
+ expect(doc.__cache.contentEntries["el1:article"]).toEqual(entry("42"));
114
+ });
115
+ it("resolves a manual list content-entry input", async ()=>{
116
+ const doc = makeDocument({
117
+ elements: {
118
+ el1: {
119
+ id: "el1",
120
+ type: "Webiny/Element",
121
+ component: {
122
+ name: "MyComponent"
123
+ }
124
+ }
125
+ },
126
+ bindings: {
127
+ el1: {
128
+ inputs: {
129
+ articles: {
130
+ id: "articles",
131
+ type: "contentEntry",
132
+ list: true,
133
+ static: [
134
+ {
135
+ id: "1",
136
+ modelId: "blog"
137
+ },
138
+ {
139
+ id: "2",
140
+ modelId: "blog"
141
+ }
142
+ ]
143
+ }
144
+ }
145
+ }
146
+ }
147
+ });
148
+ await resolveContentEntries(doc);
149
+ expect(mockGetEntry).toHaveBeenCalledTimes(2);
150
+ const resolved = doc.__cache.contentEntries["el1:articles"];
151
+ expect(resolved).toEqual([
152
+ entry("1"),
153
+ entry("2")
154
+ ]);
155
+ });
156
+ it("resolves a query-mode content-entry input (modelId in value)", async ()=>{
157
+ const doc = makeDocument({
158
+ elements: {
159
+ el1: {
160
+ id: "el1",
161
+ type: "Webiny/Element",
162
+ component: {
163
+ name: "MyComponent"
164
+ }
165
+ }
166
+ },
167
+ bindings: {
168
+ el1: {
169
+ inputs: {
170
+ posts: {
171
+ id: "posts",
172
+ type: "contentEntry",
173
+ static: {
174
+ modelId: "blog",
175
+ limit: 5
176
+ }
177
+ }
178
+ }
179
+ }
180
+ }
181
+ });
182
+ await resolveContentEntries(doc);
183
+ expect(mockListEntries).toHaveBeenCalledWith(expect.objectContaining({
184
+ modelId: "blog",
185
+ limit: 5
186
+ }));
187
+ const resolved = doc.__cache.contentEntries["el1:posts"];
188
+ expect(resolved).toMatchObject({
189
+ items: [
190
+ entry("q1"),
191
+ entry("q2")
192
+ ],
193
+ pageInfo: expect.objectContaining({
194
+ totalCount: 2
195
+ })
196
+ });
197
+ });
198
+ it("passes through already-resolved entries without re-fetching", async ()=>{
199
+ const resolvedEntry = {
200
+ id: "42",
201
+ entryId: "42",
202
+ values: {
203
+ title: "Already resolved"
204
+ }
205
+ };
206
+ const doc = makeDocument({
207
+ elements: {
208
+ el1: {
209
+ id: "el1",
210
+ type: "Webiny/Element",
211
+ component: {
212
+ name: "MyComponent"
213
+ }
214
+ }
215
+ },
216
+ bindings: {
217
+ el1: {
218
+ inputs: {
219
+ article: {
220
+ id: "article",
221
+ type: "contentEntry",
222
+ static: resolvedEntry
223
+ }
224
+ }
225
+ }
226
+ }
227
+ });
228
+ await resolveContentEntries(doc);
229
+ expect(mockGetEntry).not.toHaveBeenCalled();
230
+ expect(doc.__cache.contentEntries["el1:article"]).toEqual(resolvedEntry);
231
+ });
232
+ it("handles multiple elements with content-entry inputs", async ()=>{
233
+ const doc = makeDocument({
234
+ elements: {
235
+ el1: {
236
+ id: "el1",
237
+ type: "Webiny/Element",
238
+ component: {
239
+ name: "Hero"
240
+ }
241
+ },
242
+ el2: {
243
+ id: "el2",
244
+ type: "Webiny/Element",
245
+ component: {
246
+ name: "Sidebar"
247
+ }
248
+ }
249
+ },
250
+ bindings: {
251
+ el1: {
252
+ inputs: {
253
+ featured: {
254
+ id: "featured",
255
+ type: "contentEntry",
256
+ static: {
257
+ id: "10",
258
+ modelId: "article"
259
+ }
260
+ }
261
+ }
262
+ },
263
+ el2: {
264
+ inputs: {
265
+ related: {
266
+ id: "related",
267
+ type: "contentEntry",
268
+ static: {
269
+ id: "20",
270
+ modelId: "article"
271
+ }
272
+ }
273
+ }
274
+ }
275
+ }
276
+ });
277
+ await resolveContentEntries(doc);
278
+ expect(mockGetEntry).toHaveBeenCalledTimes(2);
279
+ const resolved = doc.__cache.contentEntries;
280
+ expect(resolved["el1:featured"]).toEqual(entry("10"));
281
+ expect(resolved["el2:related"]).toEqual(entry("20"));
282
+ });
283
+ it("skips non-contentEntry bindings", async ()=>{
284
+ const doc = makeDocument({
285
+ elements: {
286
+ el1: {
287
+ id: "el1",
288
+ type: "Webiny/Element",
289
+ component: {
290
+ name: "Mixed"
291
+ }
292
+ }
293
+ },
294
+ bindings: {
295
+ el1: {
296
+ inputs: {
297
+ text: {
298
+ id: "text",
299
+ type: "text",
300
+ static: "hello"
301
+ },
302
+ number: {
303
+ id: "number",
304
+ type: "number",
305
+ static: 42
306
+ },
307
+ item: {
308
+ id: "item",
309
+ type: "contentEntry",
310
+ static: {
311
+ id: "5",
312
+ modelId: "blog"
313
+ }
314
+ }
315
+ }
316
+ }
317
+ }
318
+ });
319
+ await resolveContentEntries(doc);
320
+ expect(mockGetEntry).toHaveBeenCalledTimes(1);
321
+ expect(mockGetEntry).toHaveBeenCalledWith({
322
+ modelId: "blog",
323
+ entryId: "5"
324
+ });
325
+ });
326
+ });
327
+
328
+ //# sourceMappingURL=resolveContentEntries.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolveContentEntries.test.js","sources":["../src/resolveContentEntries.test.ts"],"sourcesContent":["import { describe, it, expect, vi, beforeEach } from \"vitest\";\nimport { resolveContentEntries } from \"./resolveContentEntries.js\";\nimport { contentEntryCache } from \"@webiny/website-builder-sdk\";\nimport type { Document } from \"@webiny/website-builder-sdk\";\n\n// Mock the CMS SDK so `ensureContentEntryLoader` wires up a controllable loader.\nconst mockGetEntry = vi.fn();\nconst mockListEntries = vi.fn();\n\nvi.mock(\"@webiny/cms-sdk\", () => ({\n contentSdk: {\n getEntry: (...args: unknown[]) => mockGetEntry(...args),\n listEntries: (...args: unknown[]) => mockListEntries(...args)\n }\n}));\n\nconst entry = (id: string) => ({ id, entryId: id, values: { title: `T${id}` } });\n\nfunction makeDocument(overrides: Partial<Document> = {}): Document {\n return {\n id: \"doc1\",\n version: 1,\n state: {},\n properties: {},\n extensions: {},\n metadata: {},\n bindings: {},\n elements: {},\n ...overrides\n };\n}\n\nbeforeEach(() => {\n vi.clearAllMocks();\n // Reset the singleton cache between tests.\n (contentEntryCache as any).cache?.clear?.();\n (contentEntryCache as any).loader = undefined;\n\n mockGetEntry.mockImplementation(async ({ entryId }: { entryId: string }) => entry(entryId));\n mockListEntries.mockImplementation(async () => ({\n data: [entry(\"q1\"), entry(\"q2\")],\n meta: { cursor: \"c1\", hasMoreItems: false, totalCount: 2 }\n }));\n});\n\ndescribe(\"resolveContentEntries — binding-type-based resolution\", () => {\n it(\"does nothing for a null document\", async () => {\n await resolveContentEntries(null);\n expect(mockGetEntry).not.toHaveBeenCalled();\n });\n\n it(\"does nothing when no elements have content-entry bindings\", async () => {\n const doc = makeDocument({\n elements: {\n el1: {\n id: \"el1\",\n type: \"Webiny/Element\",\n component: { name: \"MyComponent\" }\n }\n },\n bindings: {\n el1: {\n inputs: {\n text: { id: \"text\", type: \"text\", static: \"hello\" }\n }\n }\n }\n });\n\n await resolveContentEntries(doc);\n expect(mockGetEntry).not.toHaveBeenCalled();\n expect(doc.__cache).toBeUndefined();\n });\n\n it(\"resolves a manual single content-entry input\", async () => {\n const doc = makeDocument({\n elements: {\n el1: {\n id: \"el1\",\n type: \"Webiny/Element\",\n component: { name: \"MyComponent\" }\n }\n },\n bindings: {\n el1: {\n inputs: {\n article: {\n id: \"article\",\n type: \"contentEntry\",\n static: { id: \"42\", modelId: \"blog\" }\n }\n }\n }\n }\n });\n\n await resolveContentEntries(doc);\n\n expect(mockGetEntry).toHaveBeenCalledWith({ modelId: \"blog\", entryId: \"42\" });\n expect(doc.__cache?.contentEntries).toBeDefined();\n expect((doc.__cache!.contentEntries as Record<string, unknown>)[\"el1:article\"]).toEqual(\n entry(\"42\")\n );\n });\n\n it(\"resolves a manual list content-entry input\", async () => {\n const doc = makeDocument({\n elements: {\n el1: {\n id: \"el1\",\n type: \"Webiny/Element\",\n component: { name: \"MyComponent\" }\n }\n },\n bindings: {\n el1: {\n inputs: {\n articles: {\n id: \"articles\",\n type: \"contentEntry\",\n list: true,\n static: [\n { id: \"1\", modelId: \"blog\" },\n { id: \"2\", modelId: \"blog\" }\n ]\n }\n }\n }\n }\n });\n\n await resolveContentEntries(doc);\n\n expect(mockGetEntry).toHaveBeenCalledTimes(2);\n const resolved = (doc.__cache!.contentEntries as Record<string, unknown>)[\"el1:articles\"];\n expect(resolved).toEqual([entry(\"1\"), entry(\"2\")]);\n });\n\n it(\"resolves a query-mode content-entry input (modelId in value)\", async () => {\n const doc = makeDocument({\n elements: {\n el1: {\n id: \"el1\",\n type: \"Webiny/Element\",\n component: { name: \"MyComponent\" }\n }\n },\n bindings: {\n el1: {\n inputs: {\n posts: {\n id: \"posts\",\n type: \"contentEntry\",\n static: { modelId: \"blog\", limit: 5 }\n }\n }\n }\n }\n });\n\n await resolveContentEntries(doc);\n\n expect(mockListEntries).toHaveBeenCalledWith(\n expect.objectContaining({ modelId: \"blog\", limit: 5 })\n );\n const resolved = (doc.__cache!.contentEntries as Record<string, unknown>)[\"el1:posts\"];\n expect(resolved).toMatchObject({\n items: [entry(\"q1\"), entry(\"q2\")],\n pageInfo: expect.objectContaining({ totalCount: 2 })\n });\n });\n\n it(\"passes through already-resolved entries without re-fetching\", async () => {\n const resolvedEntry = { id: \"42\", entryId: \"42\", values: { title: \"Already resolved\" } };\n const doc = makeDocument({\n elements: {\n el1: {\n id: \"el1\",\n type: \"Webiny/Element\",\n component: { name: \"MyComponent\" }\n }\n },\n bindings: {\n el1: {\n inputs: {\n article: {\n id: \"article\",\n type: \"contentEntry\",\n static: resolvedEntry\n }\n }\n }\n }\n });\n\n await resolveContentEntries(doc);\n\n expect(mockGetEntry).not.toHaveBeenCalled();\n expect((doc.__cache!.contentEntries as Record<string, unknown>)[\"el1:article\"]).toEqual(\n resolvedEntry\n );\n });\n\n it(\"handles multiple elements with content-entry inputs\", async () => {\n const doc = makeDocument({\n elements: {\n el1: {\n id: \"el1\",\n type: \"Webiny/Element\",\n component: { name: \"Hero\" }\n },\n el2: {\n id: \"el2\",\n type: \"Webiny/Element\",\n component: { name: \"Sidebar\" }\n }\n },\n bindings: {\n el1: {\n inputs: {\n featured: {\n id: \"featured\",\n type: \"contentEntry\",\n static: { id: \"10\", modelId: \"article\" }\n }\n }\n },\n el2: {\n inputs: {\n related: {\n id: \"related\",\n type: \"contentEntry\",\n static: { id: \"20\", modelId: \"article\" }\n }\n }\n }\n }\n });\n\n await resolveContentEntries(doc);\n\n expect(mockGetEntry).toHaveBeenCalledTimes(2);\n const resolved = doc.__cache!.contentEntries as Record<string, unknown>;\n expect(resolved[\"el1:featured\"]).toEqual(entry(\"10\"));\n expect(resolved[\"el2:related\"]).toEqual(entry(\"20\"));\n });\n\n it(\"skips non-contentEntry bindings\", async () => {\n const doc = makeDocument({\n elements: {\n el1: {\n id: \"el1\",\n type: \"Webiny/Element\",\n component: { name: \"Mixed\" }\n }\n },\n bindings: {\n el1: {\n inputs: {\n text: { id: \"text\", type: \"text\", static: \"hello\" },\n number: { id: \"number\", type: \"number\", static: 42 },\n item: {\n id: \"item\",\n type: \"contentEntry\",\n static: { id: \"5\", modelId: \"blog\" }\n }\n }\n }\n }\n });\n\n await resolveContentEntries(doc);\n\n // Only the contentEntry input should be resolved.\n expect(mockGetEntry).toHaveBeenCalledTimes(1);\n expect(mockGetEntry).toHaveBeenCalledWith({ modelId: \"blog\", entryId: \"5\" });\n });\n});\n"],"names":["mockGetEntry","vi","mockListEntries","args","entry","id","makeDocument","overrides","beforeEach","contentEntryCache","undefined","entryId","describe","it","resolveContentEntries","expect","doc","resolved","resolvedEntry"],"mappings":";;;AAMA,MAAMA,eAAeC,GAAG,EAAE;AAC1B,MAAMC,kBAAkBD,GAAG,EAAE;AAE7BA,GAAG,IAAI,CAAC,mBAAmB,IAAO;QAC9B,YAAY;YACR,UAAU,CAAC,GAAGE,OAAoBH,gBAAgBG;YAClD,aAAa,CAAC,GAAGA,OAAoBD,mBAAmBC;QAC5D;IACJ;AAEA,MAAMC,QAAQ,CAACC,KAAgB;QAAEA;QAAI,SAASA;QAAI,QAAQ;YAAE,OAAO,CAAC,CAAC,EAAEA,IAAI;QAAC;IAAE;AAE9E,SAASC,aAAaC,YAA+B,CAAC,CAAC;IACnD,OAAO;QACH,IAAI;QACJ,SAAS;QACT,OAAO,CAAC;QACR,YAAY,CAAC;QACb,YAAY,CAAC;QACb,UAAU,CAAC;QACX,UAAU,CAAC;QACX,UAAU,CAAC;QACX,GAAGA,SAAS;IAChB;AACJ;AAEAC,WAAW;IACPP,GAAG,aAAa;IAEfQ,kBAAAA,KAA+B,EAAE;IACjCA,kBAAAA,MAAgC,GAAGC;IAEpCV,aAAa,kBAAkB,CAAC,OAAO,EAAEW,OAAO,EAAuB,GAAKP,MAAMO;IAClFT,gBAAgB,kBAAkB,CAAC,UAAa;YAC5C,MAAM;gBAACE,MAAM;gBAAOA,MAAM;aAAM;YAChC,MAAM;gBAAE,QAAQ;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,MAAM;4BAAQ,QAAQ;wBAAQ;wBAClD,QAAQ;4BAAE,IAAI;4BAAU,MAAM;4BAAU,QAAQ;wBAAG;wBACnD,MAAM;4BACF,IAAI;4BACJ,MAAM;4BACN,QAAQ;gCAAE,IAAI;gCAAK,SAAS;4BAAO;wBACvC;oBACJ;gBACJ;YACJ;QACJ;QAEA,MAAMQ,sBAAsBE;QAG5BD,OAAOf,cAAc,qBAAqB,CAAC;QAC3Ce,OAAOf,cAAc,oBAAoB,CAAC;YAAE,SAAS;YAAQ,SAAS;QAAI;IAC9E;AACJ"}
package/types.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { HeadersConfig } from "@webiny/sdk";
1
2
  import type { ComponentGroup, WebsiteBuilderThemeInput } from "@webiny/website-builder-sdk";
2
3
  export interface WbConfig {
3
4
  theme?: WebsiteBuilderThemeInput;
@@ -10,6 +11,8 @@ export interface ContentSdkConfig {
10
11
  endpoint: string;
11
12
  token: string;
12
13
  tenant?: string;
14
+ /** Extra headers sent with every API request; a function is called before each request. */
15
+ headers?: HeadersConfig;
13
16
  preview?: boolean;
14
17
  fetch?: typeof fetch;
15
18
  cms?: CmsConfig;
@@ -1,39 +0,0 @@
1
- import type { WebinyConfig } from "@webiny/sdk";
2
- import { Result, HttpError, ApiError, NetworkError } from "@webiny/sdk";
3
- export interface RemoteComponentEntry {
4
- id: string;
5
- name: string;
6
- label: string;
7
- bundledJs: string;
8
- bundledJsSha256: string;
9
- bundledCss: string;
10
- bundledCssSha256: string;
11
- sdkVersion: string;
12
- status: string;
13
- }
14
- export interface LoadComponentsOptions {
15
- fetchOptions?: RequestInit;
16
- }
17
- export interface HydrateComponentDependencies {
18
- sdk: unknown;
19
- React: unknown;
20
- }
21
- export interface HydrateComponentOptions {
22
- tenantId?: string;
23
- locale?: string;
24
- mode?: "server" | "browser";
25
- }
26
- export interface HydratedComponent {
27
- component: any;
28
- manifest: any;
29
- css: string;
30
- scopeClassName: string;
31
- }
32
- export declare class ComponentsSdk {
33
- private config;
34
- private fetchFn;
35
- constructor(config: WebinyConfig);
36
- loadComponents(options?: LoadComponentsOptions): Promise<Result<RemoteComponentEntry[], HttpError | ApiError | NetworkError>>;
37
- hydrateComponent(entry: RemoteComponentEntry, dependencies: HydrateComponentDependencies, options?: HydrateComponentOptions): HydratedComponent | null;
38
- scopeCss(rawCss: string, componentName: string): string;
39
- }
package/ComponentsSdk.js DELETED
@@ -1,146 +0,0 @@
1
- import { ApiError, HttpError, NetworkError, Result } from "@webiny/sdk";
2
- import * as __rspack_external_css_tree_6b21abdd from "css-tree";
3
- const LIST_REMOTE_COMPONENTS = `
4
- query ListRemoteComponents {
5
- remoteComponents {
6
- listRemoteComponents {
7
- data {
8
- id
9
- name
10
- label
11
- bundledJs
12
- bundledJsSha256
13
- bundledCss
14
- bundledCssSha256
15
- sdkVersion
16
- status
17
- }
18
- error {
19
- code
20
- message
21
- }
22
- }
23
- }
24
- }
25
- `;
26
- class ComponentsSdk {
27
- constructor(config){
28
- this.config = config;
29
- this.fetchFn = config.fetch ?? fetch;
30
- }
31
- async loadComponents(options) {
32
- const url = `${this.config.endpoint}/graphql`;
33
- const headers = {
34
- "Content-Type": "application/json",
35
- "x-tenant": this.config.tenant ?? "root",
36
- ...this.config.headers
37
- };
38
- if (this.config.token && !headers.Authorization) {
39
- const token = "function" == typeof this.config.token ? await this.config.token() : this.config.token;
40
- headers.Authorization = `Bearer ${token}`;
41
- }
42
- let response;
43
- try {
44
- response = await this.fetchFn(url, {
45
- method: "POST",
46
- headers,
47
- body: JSON.stringify({
48
- query: LIST_REMOTE_COMPONENTS
49
- }),
50
- ...options?.fetchOptions
51
- });
52
- } catch (error) {
53
- return Result.fail(new NetworkError(error instanceof Error ? error.message : "Network request failed"));
54
- }
55
- if (!response.ok) return Result.fail(new HttpError(response.status, `HTTP error! status: ${response.status}`));
56
- let json;
57
- try {
58
- json = await response.json();
59
- } catch {
60
- return Result.fail(new NetworkError("Failed to parse response JSON"));
61
- }
62
- if (json.errors) {
63
- const error = json.errors[0];
64
- return Result.fail(new ApiError(error?.message || "GraphQL error"));
65
- }
66
- const envelope = json.data?.remoteComponents?.listRemoteComponents;
67
- if (!envelope) return Result.fail(new ApiError("Unexpected response — is the remote-components API extension deployed?"));
68
- if (envelope.error) return Result.fail(new ApiError(envelope.error.message, envelope.error.code));
69
- return Result.ok(envelope.data ?? []);
70
- }
71
- hydrateComponent(entry, dependencies, options) {
72
- const runtimeSdk = {
73
- version: "1",
74
- dependencies: {
75
- sdk: dependencies.sdk,
76
- React: dependencies.React
77
- },
78
- environment: {
79
- tenantId: options?.tenantId ?? this.config.tenant ?? "root",
80
- locale: options?.locale ?? "en-US",
81
- mode: options?.mode ?? "browser"
82
- }
83
- };
84
- try {
85
- const fn = new Function(`
86
- var __remoteComponent__;
87
- ${entry.bundledJs}
88
- return __remoteComponent__;
89
- `);
90
- const mod = fn();
91
- const component = mod.createComponent(runtimeSdk);
92
- if (!component) return null;
93
- const scopeClass = toScopeClassName(entry.name);
94
- const R = dependencies.React;
95
- const OriginalComponent = component.component;
96
- const ScopedComponent = (props)=>R.createElement("div", {
97
- className: scopeClass
98
- }, R.createElement(OriginalComponent, props));
99
- ScopedComponent.displayName = `RemoteScope(${scopeClass})`;
100
- return {
101
- component: ScopedComponent,
102
- manifest: component.manifest,
103
- css: entry.bundledCss ?? "",
104
- scopeClassName: scopeClass
105
- };
106
- } catch (error) {
107
- console.error(`[ComponentsSdk] Failed to hydrate component "${entry.name}":`, error);
108
- return null;
109
- }
110
- }
111
- scopeCss(rawCss, componentName) {
112
- return scopeCss(rawCss, toScopeClassName(componentName));
113
- }
114
- }
115
- function toScopeClassName(name) {
116
- return `rc-${name.replace(/\//g, "-").toLowerCase()}`;
117
- }
118
- function scopeCss(rawCss, scopeName) {
119
- if (!rawCss) return "";
120
- try {
121
- const ast = __rspack_external_css_tree_6b21abdd.parse(rawCss);
122
- __rspack_external_css_tree_6b21abdd.walk(ast, {
123
- visit: "Rule",
124
- enter (node) {
125
- const selectorList = node.prelude;
126
- if (!selectorList || "SelectorList" !== selectorList.type) return;
127
- const newSelectors = new __rspack_external_css_tree_6b21abdd.List();
128
- selectorList.children.forEach((selector)=>{
129
- const raw = __rspack_external_css_tree_6b21abdd.generate(selector).trim();
130
- if (raw.startsWith(":root")) return void newSelectors.appendData(selector);
131
- const scoped = __rspack_external_css_tree_6b21abdd.parse(`.${scopeName} ${raw}`, {
132
- context: "selector"
133
- });
134
- newSelectors.appendData(scoped);
135
- });
136
- selectorList.children = newSelectors;
137
- }
138
- });
139
- return __rspack_external_css_tree_6b21abdd.generate(ast);
140
- } catch {
141
- return rawCss;
142
- }
143
- }
144
- export { ComponentsSdk };
145
-
146
- //# sourceMappingURL=ComponentsSdk.js.map