@webiny/sdk-frontend 0.0.0-unstable.a4f3e4ea8b → 0.0.0-unstable.e9333b3f0b

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,39 @@
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
+ }
@@ -0,0 +1,165 @@
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
+ if (!mod) {
92
+ console.error(`[ComponentsSdk] "${entry.name}" defined no __remoteComponent__ — its bundle is not a component bundle.`);
93
+ return null;
94
+ }
95
+ if ("function" != typeof mod.createComponent) {
96
+ console.error(`[ComponentsSdk] "${entry.name}" exports no createComponent — found: ${Object.keys(mod).join(", ") || "nothing"}.`);
97
+ return null;
98
+ }
99
+ const component = mod.createComponent(runtimeSdk);
100
+ if (!component) {
101
+ console.error(`[ComponentsSdk] "${entry.name}" createComponent returned ${String(component)} — it builds nothing.`);
102
+ return null;
103
+ }
104
+ if (!component.component) {
105
+ console.error(`[ComponentsSdk] "${entry.name}" createComponent returned no component — keys: ${Object.keys(component).join(", ") || "none"}.`);
106
+ return null;
107
+ }
108
+ const scopeClass = toScopeClassName(entry.name);
109
+ const R = dependencies.React;
110
+ const OriginalComponent = component.component;
111
+ const ScopedComponent = (props)=>R.createElement("div", {
112
+ className: scopeClass
113
+ }, R.createElement(OriginalComponent, props));
114
+ ScopedComponent.displayName = `RemoteScope(${scopeClass})`;
115
+ return {
116
+ component: ScopedComponent,
117
+ manifest: {
118
+ ...component.manifest,
119
+ name: entry.name
120
+ },
121
+ css: entry.bundledCss ?? "",
122
+ scopeClassName: scopeClass
123
+ };
124
+ } catch (error) {
125
+ console.error(`[ComponentsSdk] Failed to hydrate component "${entry.name}":`, error);
126
+ return null;
127
+ }
128
+ }
129
+ scopeCss(rawCss, componentName) {
130
+ return scopeCss(rawCss, toScopeClassName(componentName));
131
+ }
132
+ }
133
+ function toScopeClassName(name) {
134
+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "component";
135
+ return `rc-${slug}`;
136
+ }
137
+ function scopeCss(rawCss, scopeName) {
138
+ if (!rawCss) return "";
139
+ try {
140
+ const ast = __rspack_external_css_tree_6b21abdd.parse(rawCss);
141
+ __rspack_external_css_tree_6b21abdd.walk(ast, {
142
+ visit: "Rule",
143
+ enter (node) {
144
+ const selectorList = node.prelude;
145
+ if (!selectorList || "SelectorList" !== selectorList.type) return;
146
+ const newSelectors = new __rspack_external_css_tree_6b21abdd.List();
147
+ selectorList.children.forEach((selector)=>{
148
+ const raw = __rspack_external_css_tree_6b21abdd.generate(selector).trim();
149
+ if (raw.startsWith(":root")) return void newSelectors.appendData(selector);
150
+ const scoped = __rspack_external_css_tree_6b21abdd.parse(`.${scopeName} ${raw}`, {
151
+ context: "selector"
152
+ });
153
+ newSelectors.appendData(scoped);
154
+ });
155
+ selectorList.children = newSelectors;
156
+ }
157
+ });
158
+ return __rspack_external_css_tree_6b21abdd.generate(ast);
159
+ } catch {
160
+ return rawCss;
161
+ }
162
+ }
163
+ export { ComponentsSdk };
164
+
165
+ //# sourceMappingURL=ComponentsSdk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ComponentsSdk.js","sources":["../src/ComponentsSdk.ts"],"sourcesContent":["import type { WebinyConfig } from \"@webiny/sdk\";\nimport { Result, HttpError, ApiError, NetworkError } from \"@webiny/sdk\";\n// @ts-expect-error No types available\nimport * as csstree from \"css-tree\";\n\nexport interface RemoteComponentEntry {\n id: string;\n name: string;\n label: string;\n bundledJs: string;\n bundledJsSha256: string;\n bundledCss: string;\n bundledCssSha256: string;\n sdkVersion: string;\n status: string;\n}\n\nexport interface LoadComponentsOptions {\n fetchOptions?: RequestInit;\n}\n\nexport interface HydrateComponentDependencies {\n sdk: unknown;\n React: unknown;\n}\n\nexport interface HydrateComponentOptions {\n tenantId?: string;\n locale?: string;\n mode?: \"server\" | \"browser\";\n}\n\nexport interface HydratedComponent {\n component: any;\n manifest: any;\n css: string;\n scopeClassName: string;\n}\n\nconst LIST_REMOTE_COMPONENTS = /* GraphQL */ `\n query ListRemoteComponents {\n remoteComponents {\n listRemoteComponents {\n data {\n id\n name\n label\n bundledJs\n bundledJsSha256\n bundledCss\n bundledCssSha256\n sdkVersion\n status\n }\n error {\n code\n message\n }\n }\n }\n }\n`;\n\ninterface ListRemoteComponentsResponse {\n remoteComponents: {\n listRemoteComponents: {\n data: RemoteComponentEntry[] | null;\n error: { code: string; message: string } | null;\n };\n };\n}\n\nexport class ComponentsSdk {\n private config: WebinyConfig;\n private fetchFn: typeof fetch;\n\n constructor(config: WebinyConfig) {\n this.config = config;\n this.fetchFn = config.fetch ?? fetch;\n }\n\n async loadComponents(\n options?: LoadComponentsOptions\n ): Promise<Result<RemoteComponentEntry[], HttpError | ApiError | NetworkError>> {\n const url = `${this.config.endpoint}/graphql`;\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"x-tenant\": this.config.tenant ?? \"root\",\n ...this.config.headers\n };\n\n if (this.config.token && !headers.Authorization) {\n const token =\n typeof this.config.token === \"function\"\n ? await this.config.token()\n : this.config.token;\n headers.Authorization = `Bearer ${token}`;\n }\n\n let response: Response;\n try {\n response = await this.fetchFn(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ query: LIST_REMOTE_COMPONENTS }),\n ...options?.fetchOptions\n });\n } catch (error) {\n return Result.fail(\n new NetworkError(error instanceof Error ? error.message : \"Network request failed\")\n );\n }\n\n if (!response.ok) {\n return Result.fail(\n new HttpError(response.status, `HTTP error! status: ${response.status}`)\n );\n }\n\n let json: { data?: ListRemoteComponentsResponse; errors?: Array<{ message: string }> };\n try {\n json = await response.json();\n } catch {\n return Result.fail(new NetworkError(\"Failed to parse response JSON\"));\n }\n\n if (json.errors) {\n const error = json.errors[0];\n return Result.fail(new ApiError(error?.message || \"GraphQL error\"));\n }\n\n const envelope = json.data?.remoteComponents?.listRemoteComponents;\n if (!envelope) {\n return Result.fail(\n new ApiError(\n \"Unexpected response — is the remote-components API extension deployed?\"\n )\n );\n }\n\n if (envelope.error) {\n return Result.fail(new ApiError(envelope.error.message, envelope.error.code));\n }\n\n return Result.ok(envelope.data ?? []);\n }\n\n hydrateComponent(\n entry: RemoteComponentEntry,\n dependencies: HydrateComponentDependencies,\n options?: HydrateComponentOptions\n ): HydratedComponent | null {\n const runtimeSdk = {\n version: \"1\" as const,\n dependencies: {\n sdk: dependencies.sdk,\n React: dependencies.React\n },\n environment: {\n tenantId: options?.tenantId ?? this.config.tenant ?? \"root\",\n locale: options?.locale ?? \"en-US\",\n mode: options?.mode ?? \"browser\"\n }\n };\n\n try {\n const fn = new Function(`\n var __remoteComponent__;\n ${entry.bundledJs}\n return __remoteComponent__;\n `);\n const mod = fn();\n\n /*\n * Each way this can fail says which one it was.\n *\n * These used to be one silent `if (!component) return null`, and callers drop a null —\n * the Next.js starter does `.filter(Boolean)` — so a component could vanish leaving no\n * error, no warning and no count anywhere. The only visible symptom was an \"Unknown\n * component\" warning later, from a different package, naming a component nothing had\n * said had failed. Three different causes presented identically.\n */\n if (!mod) {\n console.error(\n `[ComponentsSdk] \"${entry.name}\" defined no __remoteComponent__ — its bundle is not a component bundle.`\n );\n return null;\n }\n if (typeof mod.createComponent !== \"function\") {\n console.error(\n `[ComponentsSdk] \"${entry.name}\" exports no createComponent — found: ${Object.keys(mod).join(\", \") || \"nothing\"}.`\n );\n return null;\n }\n\n const component = mod.createComponent(runtimeSdk);\n if (!component) {\n console.error(\n `[ComponentsSdk] \"${entry.name}\" createComponent returned ${String(component)} — it builds nothing.`\n );\n return null;\n }\n if (!component.component) {\n console.error(\n `[ComponentsSdk] \"${entry.name}\" createComponent returned no component — keys: ${Object.keys(component).join(\", \") || \"none\"}.`\n );\n return null;\n }\n\n const scopeClass = toScopeClassName(entry.name);\n const R = dependencies.React as typeof import(\"react\");\n const OriginalComponent = component.component;\n\n const ScopedComponent = (props: Record<string, unknown>) =>\n R.createElement(\n \"div\",\n { className: scopeClass },\n R.createElement(OriginalComponent, props)\n );\n ScopedComponent.displayName = `RemoteScope(${scopeClass})`;\n\n return {\n component: ScopedComponent,\n /*\n * `entry.name` is the component's IDENTITY, not a label — it is what a page element\n * records and what the registry is keyed by, so it is the name a component must be\n * registered under or no page can resolve it.\n *\n * The name inside the bundle is whatever the source declared, which for a generated\n * component is the model's invention and for any component survives a later rename.\n * Promote renames on collision (\"Hero Banner (4)\"), and the server already treats the\n * promoted name as authoritative: `buildComponentManifest` overrides the manifest name\n * with it when persisting, and both bundler and runtime scope CSS by it. Re-deriving\n * the manifest here and keeping the bundle's name was the single place that\n * disagreed, and it made every page render nothing — 199 of 199 components\n * unresolvable, silently, while every stage reported success.\n *\n * So the rest of the manifest comes from the bundle, which is the authority on inputs\n * and defaults, and the name comes from the entry, which is the authority on identity.\n * A caller synthesising an entry is therefore declaring an identity, not labelling\n * one.\n */\n manifest: { ...component.manifest, name: entry.name },\n css: entry.bundledCss ?? \"\",\n scopeClassName: scopeClass\n };\n } catch (error) {\n console.error(`[ComponentsSdk] Failed to hydrate component \"${entry.name}\":`, error);\n return null;\n }\n }\n\n scopeCss(rawCss: string, componentName: string): string {\n return scopeCss(rawCss, toScopeClassName(componentName));\n }\n}\n\nfunction toScopeClassName(name: string): string {\n // Slugify to a valid CSS identifier: any run of non-alphanumerics (spaces, \"/\", punctuation) becomes\n // a single hyphen. This is the class the runtime puts on the component's wrapper element, and it MUST\n // match the class the bundlers scope the CSS to — otherwise a name like \"Testimonials with features\"\n // yields \"rc-testimonials with features\" (three classes) and the scoped styles never apply.\n const slug =\n name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"component\";\n return `rc-${slug}`;\n}\n\nfunction scopeCss(rawCss: string, scopeName: string): string {\n if (!rawCss) {\n return \"\";\n }\n\n try {\n const ast = csstree.parse(rawCss);\n\n csstree.walk(ast, {\n visit: \"Rule\",\n enter(node: any) {\n const selectorList = node.prelude;\n if (!selectorList || selectorList.type !== \"SelectorList\") {\n return;\n }\n\n const newSelectors = new csstree.List();\n\n selectorList.children.forEach((selector: any) => {\n const raw = csstree.generate(selector).trim();\n if (raw.startsWith(\":root\")) {\n newSelectors.appendData(selector);\n return;\n }\n\n const scoped = csstree.parse(`.${scopeName} ${raw}`, {\n context: \"selector\"\n });\n newSelectors.appendData(scoped);\n });\n\n selectorList.children = newSelectors;\n }\n });\n\n return csstree.generate(ast);\n } catch {\n return rawCss;\n }\n}\n"],"names":["LIST_REMOTE_COMPONENTS","ComponentsSdk","config","fetch","options","url","headers","token","response","JSON","error","Result","NetworkError","Error","HttpError","json","ApiError","envelope","entry","dependencies","runtimeSdk","fn","Function","mod","console","Object","component","String","scopeClass","toScopeClassName","R","OriginalComponent","ScopedComponent","props","rawCss","componentName","scopeCss","name","slug","scopeName","ast","csstree","node","selectorList","newSelectors","selector","raw","scoped"],"mappings":";;AAuCA,MAAMA,yBAAuC,CAAC;;;;;;;;;;;;;;;;;;;;;;AAsB9C,CAAC;AAWM,MAAMC;IAIT,YAAYC,MAAoB,CAAE;QAC9B,IAAI,CAAC,MAAM,GAAGA;QACd,IAAI,CAAC,OAAO,GAAGA,OAAO,KAAK,IAAIC;IACnC;IAEA,MAAM,eACFC,OAA+B,EAC6C;QAC5E,MAAMC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAE7C,MAAMC,UAAkC;YACpC,gBAAgB;YAChB,YAAY,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI;YAClC,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO;QAC1B;QAEA,IAAI,IAAI,CAAC,MAAM,CAAC,KAAK,IAAI,CAACA,QAAQ,aAAa,EAAE;YAC7C,MAAMC,QACF,AAA6B,cAA7B,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,GAClB,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,KACvB,IAAI,CAAC,MAAM,CAAC,KAAK;YAC3BD,QAAQ,aAAa,GAAG,CAAC,OAAO,EAAEC,OAAO;QAC7C;QAEA,IAAIC;QACJ,IAAI;YACAA,WAAW,MAAM,IAAI,CAAC,OAAO,CAACH,KAAK;gBAC/B,QAAQ;gBACRC;gB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dk } from "./ComponentsSdk.js";
3
+ const bundleDeclaring = (manifestName)=>`
4
+ __remoteComponent__ = {
5
+ createComponent: function (runtime) {
6
+ return {
7
+ component: function () { return null; },
8
+ manifest: { name: ${JSON.stringify(manifestName)}, label: "FAQ", inputs: [] }
9
+ };
10
+ }
11
+ };
12
+ `;
13
+ const entry = (name, bundledJs)=>({
14
+ id: "component-id",
15
+ name,
16
+ label: name,
17
+ bundledJs,
18
+ bundledJsSha256: "",
19
+ bundledCss: "",
20
+ bundledCssSha256: "",
21
+ sdkVersion: "1",
22
+ status: "published"
23
+ });
24
+ const sdk = ()=>new ComponentsSdk({
25
+ apiUrl: "https://example.test/graphql",
26
+ tenant: "root"
27
+ });
28
+ const dependencies = {
29
+ sdk: {},
30
+ React: {
31
+ createElement: ()=>null,
32
+ Fragment: null
33
+ }
34
+ };
35
+ describe("hydrateComponent — the name a component is registered under", ()=>{
36
+ it("registers under the entry's name, not the name inside the bundle", ()=>{
37
+ const hydrated = sdk().hydrateComponent(entry("2424Tulane/FAQ Section", bundleDeclaring("Custom/FaqSection")), dependencies);
38
+ expect(hydrated?.manifest.name).toBe("2424Tulane/FAQ Section");
39
+ });
40
+ it("keeps a collision rename, which the bundle cannot know about", ()=>{
41
+ const hydrated = sdk().hydrateComponent(entry("2424Tulane/Hero Banner (4)", bundleDeclaring("Custom/HeroBanner")), dependencies);
42
+ expect(hydrated?.manifest.name).toBe("2424Tulane/Hero Banner (4)");
43
+ });
44
+ it("takes the rest of the manifest from the bundle", ()=>{
45
+ const hydrated = sdk().hydrateComponent(entry("Site/Thing", bundleDeclaring("Custom/Thing")), dependencies);
46
+ expect(hydrated?.manifest.label).toBe("FAQ");
47
+ expect(hydrated?.manifest.inputs).toEqual([]);
48
+ });
49
+ it("scopes css by the same name it registers under", ()=>{
50
+ const hydrated = sdk().hydrateComponent(entry("2424Tulane/FAQ Section", bundleDeclaring("Custom/FaqSection")), dependencies);
51
+ expect(hydrated?.scopeClassName).toBe("rc-2424tulane-faq-section");
52
+ });
53
+ });
54
+ describe("hydrateComponent — saying why it failed", ()=>{
55
+ const failing = (bundle)=>{
56
+ const messages = [];
57
+ const original = console.error;
58
+ console.error = (...args)=>messages.push(args.map(String).join(" "));
59
+ try {
60
+ const result = sdk().hydrateComponent(entry("Site/Thing", bundle), dependencies);
61
+ return {
62
+ result,
63
+ messages
64
+ };
65
+ } finally{
66
+ console.error = original;
67
+ }
68
+ };
69
+ it("says so when the bundle defines no component", ()=>{
70
+ const { result, messages } = failing("var x = 1;");
71
+ expect(result).toBeNull();
72
+ expect(messages.join(" ")).toContain("defined no __remoteComponent__");
73
+ expect(messages.join(" ")).toContain("Site/Thing");
74
+ });
75
+ it("says so when the bundle exports no createComponent", ()=>{
76
+ const { result, messages } = failing("__remoteComponent__ = { somethingElse: 1 };");
77
+ expect(result).toBeNull();
78
+ expect(messages.join(" ")).toContain("exports no createComponent");
79
+ expect(messages.join(" ")).toContain("somethingElse");
80
+ });
81
+ it("says so when the factory builds nothing", ()=>{
82
+ const { result, messages } = failing("__remoteComponent__ = { createComponent: function () { return null; } };");
83
+ expect(result).toBeNull();
84
+ expect(messages.join(" ")).toContain("builds nothing");
85
+ });
86
+ it("says so when the factory returns no component", ()=>{
87
+ const { result, messages } = failing('__remoteComponent__ = { createComponent: function () { return { manifest: { name: "x" } }; } };');
88
+ expect(result).toBeNull();
89
+ expect(messages.join(" ")).toContain("returned no component");
90
+ expect(messages.join(" ")).toContain("manifest");
91
+ });
92
+ });
93
+
94
+ //# sourceMappingURL=ComponentsSdk.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ComponentsSdk.test.js","sources":["../src/ComponentsSdk.test.ts"],"sourcesContent":["import { describe, expect, it } from \"vitest\";\nimport { ComponentsSdk } from \"./ComponentsSdk.js\";\n\n/**\n * The bundle a real component produces, reduced to what hydration reads: a `createComponent` factory\n * returning a component and a manifest whose name is whatever the SOURCE declared. For a generated\n * component that is the model's invention (`Custom/FaqSection`), and it is never the name a page\n * references.\n */\nconst bundleDeclaring = (manifestName: string) => `\n __remoteComponent__ = {\n createComponent: function (runtime) {\n return {\n component: function () { return null; },\n manifest: { name: ${JSON.stringify(manifestName)}, label: \"FAQ\", inputs: [] }\n };\n }\n };\n`;\n\nconst entry = (name: string, bundledJs: string) =>\n ({\n id: \"component-id\",\n name,\n label: name,\n bundledJs,\n bundledJsSha256: \"\",\n bundledCss: \"\",\n bundledCssSha256: \"\",\n sdkVersion: \"1\",\n status: \"published\"\n }) as never;\n\nconst sdk = () =>\n new ComponentsSdk({ apiUrl: \"https://example.test/graphql\", tenant: \"root\" } as never);\n\nconst dependencies = {\n sdk: {},\n React: { createElement: () => null, Fragment: null }\n} as never;\n\ndescribe(\"hydrateComponent — the name a component is registered under\", () => {\n it(\"registers under the entry's name, not the name inside the bundle\", () => {\n /*\n * This is the invariant that failed silently: the registry is keyed by manifest.name, a page\n * element records the promoted name, and while these disagreed every page rendered nothing —\n * 199 of 199 components unresolvable with every stage reporting success.\n */\n const hydrated = sdk().hydrateComponent(\n entry(\"2424Tulane/FAQ Section\", bundleDeclaring(\"Custom/FaqSection\")),\n dependencies\n );\n\n expect(hydrated?.manifest.name).toBe(\"2424Tulane/FAQ Section\");\n });\n\n it(\"keeps a collision rename, which the bundle cannot know about\", () => {\n // Promote renames on collision; the bundle was built before that and says the original name.\n const hydrated = sdk().hydrateComponent(\n entry(\"2424Tulane/Hero Banner (4)\", bundleDeclaring(\"Custom/HeroBanner\")),\n dependencies\n );\n\n expect(hydrated?.manifest.name).toBe(\"2424Tulane/Hero Banner (4)\");\n });\n\n it(\"takes the rest of the manifest from the bundle\", () => {\n // The bundle is the authority on inputs and defaults; only identity comes from the entry.\n const hydrated = sdk().hydrateComponent(\n entry(\"Site/Thing\", bundleDeclaring(\"Custom/Thing\")),\n dependencies\n );\n\n expect(hydrated?.manifest.label).toBe(\"FAQ\");\n expect(hydrated?.manifest.inputs).toEqual([]);\n });\n\n it(\"scopes css by the same name it registers under\", () => {\n // These two disagreeing is what the defect looked like from the outside: styles applied to a\n // component nothing could resolve.\n const hydrated = sdk().hydrateComponent(\n entry(\"2424Tulane/FAQ Section\", bundleDeclaring(\"Custom/FaqSection\")),\n dependencies\n );\n\n expect(hydrated?.scopeClassName).toBe(\"rc-2424tulane-faq-section\");\n });\n});\n\ndescribe(\"hydrateComponent — saying why it failed\", () => {\n /*\n * Each of these used to be the same silent `return null`. Callers drop a null, so a component\n * vanished leaving no error, no warning and no count — and the only symptom was an \"Unknown\n * component\" warning later, from a different package, naming a component nothing had said failed.\n */\n const failing = (bundle: string) => {\n const messages: string[] = [];\n const original = console.error;\n console.error = (...args: unknown[]) => messages.push(args.map(String).join(\" \"));\n try {\n const result = sdk().hydrateComponent(entry(\"Site/Thing\", bundle), dependencies);\n return { result, messages };\n } finally {\n console.error = original;\n }\n };\n\n it(\"says so when the bundle defines no component\", () => {\n const { result, messages } = failing(\"var x = 1;\");\n\n expect(result).toBeNull();\n expect(messages.join(\" \")).toContain(\"defined no __remoteComponent__\");\n expect(messages.join(\" \")).toContain(\"Site/Thing\");\n });\n\n it(\"says so when the bundle exports no createComponent\", () => {\n const { result, messages } = failing(`__remoteComponent__ = { somethingElse: 1 };`);\n\n expect(result).toBeNull();\n expect(messages.join(\" \")).toContain(\"exports no createComponent\");\n expect(messages.join(\" \")).toContain(\"somethingElse\");\n });\n\n it(\"says so when the factory builds nothing\", () => {\n const { result, messages } = failing(\n `__remoteComponent__ = { createComponent: function () { return null; } };`\n );\n\n expect(result).toBeNull();\n expect(messages.join(\" \")).toContain(\"builds nothing\");\n });\n\n it(\"says so when the factory returns no component\", () => {\n const { result, messages } = failing(\n `__remoteComponent__ = { createComponent: function () { return { manifest: { name: \"x\" } }; } };`\n );\n\n expect(result).toBeNull();\n expect(messages.join(\" \")).toContain(\"returned no component\");\n expect(messages.join(\" \")).toContain(\"manifest\");\n });\n});\n"],"names":["bundleDeclaring","manifestName","JSON","entry","name","bundledJs","sdk","ComponentsSdk","dependencies","describe","it","hydr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webiny/theme-sdk";
2
3
  import { CmsSdk } from "./CmsSdk.js";
3
4
  import { WbSdk } from "./WbSdk.js";
5
+ import { ComponentsSdk } from "./ComponentsSdk.js";
4
6
  import type { ContentSdkConfig } from "./types.js";
5
7
  export declare class FrontendSdk {
6
8
  private sdk?;
7
9
  private get initialized();
8
10
  get cms(): CmsSdk;
9
11
  get wb(): WbSdk;
12
+ get theme(): ThemeSdk;
10
13
  get languages(): LanguagesSdk;
11
14
  get fileManager(): FileManagerSdk;
12
15
  get tenantManager(): TenantManagerSdk;
13
16
  get tasks(): TasksSdk;
14
17
  get webhooks(): WebhooksSdk;
18
+ get components(): ComponentsSdk;
15
19
  init(config: ContentSdkConfig): void;
16
20
  isEditing(): boolean;
17
21
  isServer(): boolean;
package/FrontendSdk.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { Webiny } from "@webiny/sdk";
2
2
  import { contentSdk, environment } from "@webiny/cms-sdk";
3
3
  import { contentSdk as website_builder_sdk_contentSdk } from "@webiny/website-builder-sdk";
4
+ import { ThemeSdk } from "@webiny/theme-sdk";
4
5
  import { ensureContentEntryLoader } from "./resolveContentEntries.js";
5
6
  import { CmsSdk } from "./CmsSdk.js";
6
7
  import { WbSdk } from "./WbSdk.js";
8
+ import { ComponentsSdk } from "./ComponentsSdk.js";
7
9
  class FrontendSdk {
8
10
  get initialized() {
9
11
  if (!this.sdk) throw new Error("SDK is not initialized. Call sdk.init() first.");
@@ -15,6 +17,9 @@ class FrontendSdk {
15
17
  get wb() {
16
18
  return this.initialized.wb;
17
19
  }
20
+ get theme() {
21
+ return this.initialized.theme;
22
+ }
18
23
  get languages() {
19
24
  return this.initialized.webiny.languages;
20
25
  }
@@ -30,6 +35,9 @@ class FrontendSdk {
30
35
  get webhooks() {
31
36
  return this.initialized.webiny.webhooks;
32
37
  }
38
+ get components() {
39
+ return this.initialized.components;
40
+ }
33
41
  init(config) {
34
42
  const webiny = new Webiny({
35
43
  endpoint: config.endpoint,
@@ -40,7 +48,22 @@ class FrontendSdk {
40
48
  this.sdk = {
41
49
  webiny,
42
50
  cms: new CmsSdk(webiny),
43
- wb: new WbSdk()
51
+ wb: new WbSdk(),
52
+ theme: new ThemeSdk({
53
+ apiHost: config.endpoint,
54
+ apiKey: config.token,
55
+ apiTenant: config.tenant,
56
+ fetch: config.fetch,
57
+ timeoutMs: config.theme?.timeoutMs,
58
+ sameOrigin: config.theme?.sameOrigin,
59
+ requestInit: config.theme?.requestInit
60
+ }),
61
+ components: new ComponentsSdk({
62
+ endpoint: config.endpoint,
63
+ token: config.token,
64
+ tenant: config.tenant || "root",
65
+ fetch: config.fetch
66
+ })
44
67
  };
45
68
  contentSdk.init({
46
69
  apiHost: config.endpoint,
@@ -1 +1 @@
1
- {"version":3,"file":"FrontendSdk.js","sources":["../src/FrontendSdk.ts"],"sourcesContent":["import { Webiny } from \"@webiny/sdk\";\nimport type {\n LanguagesSdk,\n FileManagerSdk,\n TenantManagerSdk,\n TasksSdk,\n WebhooksSdk\n} from \"@webiny/sdk\";\nimport { contentSdk as cmsContentSdk, environment as cmsEnvironment } from \"@webiny/cms-sdk\";\nimport { contentSdk as wbContentSdk } from \"@webiny/website-builder-sdk\";\nimport { ensureContentEntryLoader } from \"./resolveContentEntries.js\";\nimport { CmsSdk } from \"./CmsSdk.js\";\nimport { WbSdk } from \"./WbSdk.js\";\nimport type { ContentSdkConfig } from \"./types.js\";\n\ninterface InitializedSdk {\n webiny: Webiny;\n cms: CmsSdk;\n wb: WbSdk;\n}\n\nexport class FrontendSdk {\n private sdk?: InitializedSdk;\n\n private get initialized(): InitializedSdk {\n if (!this.sdk) {\n throw new Error(\"SDK is not initialized. Call sdk.init() first.\");\n }\n return this.sdk;\n }\n\n get cms(): CmsSdk {\n return this.initialized.cms;\n }\n\n get wb(): WbSdk {\n return this.initialized.wb;\n }\n\n get languages(): LanguagesSdk {\n return this.initialized.webiny.languages;\n }\n\n get fileManager(): FileManagerSdk {\n return this.initialized.webiny.fileManager;\n }\n\n get tenantManager(): TenantManagerSdk {\n return this.initialized.webiny.tenantManager;\n }\n\n get tasks(): TasksSdk {\n return this.initialized.webiny.tasks;\n }\n\n get webhooks(): WebhooksSdk {\n return this.initialized.webiny.webhooks;\n }\n\n init(config: ContentSdkConfig): void {\n const webiny = new Webiny({\n endpoint: config.endpoint,\n token: config.token,\n tenant: config.tenant || \"root\",\n fetch: config.fetch\n });\n\n this.sdk = {\n webiny,\n cms: new CmsSdk(webiny),\n wb: new WbSdk()\n };\n\n cmsContentSdk.init(\n {\n apiHost: config.endpoint,\n apiKey: config.token,\n apiTenant: config.tenant,\n preview: config.preview,\n fetch: config.fetch\n },\n webiny\n );\n\n wbContentSdk.init({\n apiHost: config.endpoint,\n apiKey: config.token,\n apiTenant: config.tenant ?? \"root\",\n preview: config.preview,\n theme: config.wb?.theme,\n previewParams: config.wb?.previewParams\n });\n\n if (config.wb?.componentGroups) {\n for (const group of config.wb.componentGroups) {\n this.sdk.wb.registerComponentGroup(group);\n }\n }\n\n // Bridge the CMS SDK into the content-entry cache so the\n // BindingsResolver can resolve content-entry inputs on both\n // server (via resolveContentEntries) and client (editor preview iframe).\n ensureContentEntryLoader();\n }\n\n isEditing(): boolean {\n return cmsEnvironment.isEditing();\n }\n\n isServer(): boolean {\n return cmsEnvironment.isServer();\n }\n\n isClient(): boolean {\n return cmsEnvironment.isClient();\n }\n}\n\nexport const sdk = new FrontendSdk();\n"],"names":["FrontendSdk","Error","config","webiny","Webiny","CmsSdk","WbSdk","cmsContentSdk","wbContentSdk","group","ensureContentEntryLoader","cmsEnvironment","sdk"],"mappings":";;;;;;AAqBO,MAAMA;IAGT,IAAY,cAA8B;QACtC,IAAI,CAAC,IAAI,CAAC,GAAG,EACT,MAAM,IAAIC,MAAM;QAEpB,OAAO,IAAI,CAAC,GAAG;IACnB;IAEA,IAAI,MAAc;QACd,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG;IAC/B;IAEA,IAAI,KAAY;QACZ,OAAO,IAAI,CAAC,WAAW,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AAAA,SAAwB;IACnC;IAEA,WAAoB;QAChB,OAAOA,YAAAA,QAAuB;IAClC;IAEA,WAAoB;QAChB,OAAOA,YAAAA,QAAuB;IAClC;AACJ;AAEO,MAAMC,MAAM,IAAIZ"}
1
+ {"version":3,"file":"FrontendSdk.js","sources":["../src/FrontendSdk.ts"],"sourcesContent":["import { Webiny } from \"@webiny/sdk\";\nimport type {\n LanguagesSdk,\n FileManagerSdk,\n TenantManagerSdk,\n TasksSdk,\n WebhooksSdk\n} from \"@webiny/sdk\";\nimport { contentSdk as cmsContentSdk, environment as cmsEnvironment } from \"@webiny/cms-sdk\";\nimport { contentSdk as wbContentSdk } from \"@webiny/website-builder-sdk\";\nimport { ThemeSdk } from \"@webiny/theme-sdk\";\nimport { ensureContentEntryLoader } from \"./resolveContentEntries.js\";\nimport { CmsSdk } from \"./CmsSdk.js\";\nimport { WbSdk } from \"./WbSdk.js\";\nimport { ComponentsSdk } from \"./ComponentsSdk.js\";\nimport type { ContentSdkConfig } from \"./types.js\";\n\ninterface InitializedSdk {\n webiny: Webiny;\n cms: CmsSdk;\n wb: WbSdk;\n theme: ThemeSdk;\n components: ComponentsSdk;\n}\n\nexport class FrontendSdk {\n private sdk?: InitializedSdk;\n\n private get initialized(): InitializedSdk {\n if (!this.sdk) {\n throw new Error(\"SDK is not initialized. Call sdk.init() first.\");\n }\n return this.sdk;\n }\n\n get cms(): CmsSdk {\n return this.initialized.cms;\n }\n\n get wb(): WbSdk {\n return this.initialized.wb;\n }\n\n get theme(): ThemeSdk {\n return this.initialized.theme;\n }\n\n get languages(): LanguagesSdk {\n return this.initialized.webiny.languages;\n }\n\n get fileManager(): FileManagerSdk {\n return this.initialized.webiny.fileManager;\n }\n\n get tenantManager(): TenantManagerSdk {\n return this.initialized.webiny.tenantManager;\n }\n\n get tasks(): TasksSdk {\n return this.initialized.webiny.tasks;\n }\n\n get webhooks(): WebhooksSdk {\n return this.initialized.webiny.webhooks;\n }\n\n get components(): ComponentsSdk {\n return this.initialized.components;\n }\n\n init(config: ContentSdkConfig): void {\n const webiny = new Webiny({\n endpoint: config.endpoint,\n token: config.token,\n tenant: config.tenant || \"root\",\n fetch: config.fetch\n });\n\n this.sdk = {\n webiny,\n cms: new CmsSdk(webiny),\n wb: new WbSdk(),\n // The theme client fetches artifacts over REST; it shares the same host/auth/fetch as every\n // other domain, plus its own timeout so SSR never hangs on theme resolution.\n theme: new ThemeSdk({\n apiHost: config.endpoint,\n apiKey: config.token,\n apiTenant: config.tenant,\n fetch: config.fetch,\n timeoutMs: config.theme?.timeoutMs,\n sameOrigin: config.theme?.sameOrigin,\n requestInit: config.theme?.requestInit\n }),\n components: new ComponentsSdk({\n endpoint: config.endpoint,\n token: config.token,\n tenant: config.tenant || \"root\",\n fetch: config.fetch\n })\n };\n\n cmsContentSdk.init(\n {\n apiHost: config.endpoint,\n apiKey: config.token,\n apiTenant: config.tenant,\n preview: config.preview,\n fetch: config.fetch\n },\n webiny\n );\n\n wbContentSdk.init({\n apiHost: config.endpoint,\n apiKey: config.token,\n apiTenant: config.tenant ?? \"root\",\n preview: config.preview,\n theme: config.wb?.theme,\n previewParams: config.wb?.previewParams\n });\n\n if (config.wb?.componentGroups) {\n for (const group of config.wb.componentGroups) {\n this.sdk.wb.registerComponentGroup(group);\n }\n }\n\n // Bridge the CMS SDK into the content-entry cache so the\n // BindingsResolver can resolve content-entry inputs on both\n // server (via resolveContentEntries) and client (editor preview iframe).\n ensureContentEntryLoader();\n }\n\n isEditing(): boolean {\n return cmsEnvironment.isEditing();\n }\n\n isServer(): boolean {\n return cmsEnvironment.isServer();\n }\n\n isClient(): boolean {\n return cmsEnvironment.isClient();\n }\n}\n\nexport const sdk = new FrontendSdk();\n"],"names":["FrontendSdk","Error","config","webiny","Webiny","CmsSdk","WbSdk","ThemeSdk","ComponentsSdk","cmsContentSdk","wbContentSdk","group","ensureContentEntryLoader","cmsEnvironment","sdk"],"mappings":";;;;;;;;AAyBO,MAAMA;IAGT,IAAY,cAA8B;QAC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AaA,OAAO,KAAK,EAAE;YAC/B;YACA,YAAY,IAAIM,cAAc;gBAC1B,UAAUN,OAAO,QAAQ;gBACzB,OAAOA,OAAO,KAAK;gBACnB,QAAQA,OAAO,MAAM,IAAI;gBACzB,OAAOA,OAAO,KAAK;YACvB;QACJ;QAEAO,WAAAA,IAAkB,CACd;YACI,SAASP,OAAO,QAAQ;YACxB,QAAQA,OAAO,KAAK;YACpB,WAAWA,OAAO,MAAM;YACxB,SAASA,OAAO,OAAO;YACvB,OAAOA,OAAO,KAAK;QACvB,GACAC;QAGJO,+BAAAA,IAAiB,CAAC;YACd,SAASR,OAAO,QAAQ;YACxB,QAAQA,OAAO,KAAK;YACpB,WAAWA,OAAO,MAAM,IAAI;YAC5B,SAASA,OAAO,OAAO;YACvB,OAAOA,OAAO,EAAE,EAAE;YAClB,eAAeA,OAAO,EAAE,EAAE;QAC9B;QAEA,IAAIA,OAAO,EAAE,EAAE,iBACX,KAAK,MAAMS,SAAST,OAAO,EAAE,CAAC,eAAe,CACzC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,sBAAsB,CAACS;QAO3CC;IACJ;IAEA,YAAqB;QACjB,OAAOC,YAAAA,SAAwB;IACnC;IAEA,WAAoB;QAChB,OAAOA,YAAAA,QAAuB;IAClC;IAEA,WAAoB;QAChB,OAAOA,YAAAA,QAAuB;IAClC;AACJ;AAEO,MAAMC,MAAM,IAAId"}
package/index.d.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  export { sdk, FrontendSdk } from "./FrontendSdk.js";
2
- export type { ContentSdkConfig, WbConfig, CmsConfig } from "./types.js";
2
+ export { ComponentsSdk } from "./ComponentsSdk.js";
3
+ export type { RemoteComponentEntry, LoadComponentsOptions, HydrateComponentDependencies, HydrateComponentOptions, HydratedComponent } from "./ComponentsSdk.js";
4
+ export type { ContentSdkConfig, WbConfig, CmsConfig, ThemeConfig } from "./types.js";
5
+ export { ThemeSdk, createThemeRewrite, createNuxtThemeRouteRules, THEME_ROUTE_PREFIX, THEME_ARTIFACT_PATHS, GOOGLE_FONTS_STATIC_ORIGIN } from "@webiny/theme-sdk";
6
+ export type { ThemeArtifactName, ThemePreview, ThemeJson, ThemeLinkTag, ThemeRewriteRule, ThemeNuxtRouteRules, ThemeWebhookPayload } from "@webiny/theme-sdk";
3
7
  export { Result, HttpError, ApiError, NetworkError, ValidationError } from "@webiny/sdk";
4
8
  export type { Language } from "@webiny/sdk";
5
9
  export type { CmsEntryData, CreateEntryParams, CreateCmsEntryData, UpdateEntryRevisionParams, UpdateCmsEntryData, DeleteEntryRevisionParams, PublishEntryRevisionParams, UnpublishEntryRevisionParams } from "@webiny/sdk";
package/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export { FrontendSdk, sdk } from "./FrontendSdk.js";
2
+ export { ComponentsSdk } from "./ComponentsSdk.js";
3
+ export { GOOGLE_FONTS_STATIC_ORIGIN, THEME_ARTIFACT_PATHS, THEME_ROUTE_PREFIX, ThemeSdk, createNuxtThemeRouteRules, createThemeRewrite } from "@webiny/theme-sdk";
2
4
  export { ApiError, HttpError, NetworkError, Result, ValidationError } from "@webiny/sdk";
3
5
  export { createComponent as createCmsComponent, resolveRefs } from "@webiny/cms-sdk";
4
6
  export { createComponent as createWbComponent, createTheme } from "@webiny/website-builder-sdk";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webiny/sdk-frontend",
3
- "version": "0.0.0-unstable.a4f3e4ea8b",
3
+ "version": "0.0.0-unstable.e9333b3f0b",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,14 +16,16 @@
16
16
  ],
17
17
  "license": "MIT",
18
18
  "dependencies": {
19
- "@webiny/cms-sdk": "0.0.0-unstable.a4f3e4ea8b",
20
- "@webiny/sdk": "0.0.0-unstable.a4f3e4ea8b",
21
- "@webiny/website-builder-sdk": "0.0.0-unstable.a4f3e4ea8b"
19
+ "@webiny/cms-sdk": "0.0.0-unstable.e9333b3f0b",
20
+ "@webiny/sdk": "0.0.0-unstable.e9333b3f0b",
21
+ "@webiny/theme-sdk": "0.0.0-unstable.e9333b3f0b",
22
+ "@webiny/website-builder-sdk": "0.0.0-unstable.e9333b3f0b",
23
+ "css-tree": "3.2.1"
22
24
  },
23
25
  "devDependencies": {
24
- "@webiny/build-tools": "0.0.0-unstable.a4f3e4ea8b",
26
+ "@webiny/build-tools": "0.0.0-unstable.e9333b3f0b",
25
27
  "typescript": "7.0.2",
26
- "vitest": "4.1.10"
28
+ "vitest": "4.1.11"
27
29
  },
28
30
  "webiny": {
29
31
  "publishFrom": "dist"
package/types.d.ts CHANGED
@@ -6,6 +6,24 @@ export interface WbConfig {
6
6
  }
7
7
  export interface CmsConfig {
8
8
  }
9
+ export interface ThemeConfig {
10
+ /**
11
+ * Ceiling on the theme JSON fetch. A themeless render beats a stalled one. Everything else the
12
+ * theme client needs (host, key, tenant, fetch) is shared from the top-level config.
13
+ */
14
+ timeoutMs?: number;
15
+ /**
16
+ * Emit artifact URLs as same-origin relative paths. Set only when the frontend proxies
17
+ * `/_webiny/theme/*` to the API (see `createThemeRewrite`).
18
+ */
19
+ sameOrigin?: boolean;
20
+ /**
21
+ * Extra `RequestInit` merged into theme fetches — e.g. Next.js `{ next: { revalidate: 60 } }`, which
22
+ * re-reads the theme JSON on a short timer. Stable URLs mean activation propagates within the CDN
23
+ * TTL on their own, so no cache tag or webhook is involved.
24
+ */
25
+ requestInit?: RequestInit;
26
+ }
9
27
  export interface ContentSdkConfig {
10
28
  endpoint: string;
11
29
  token: string;
@@ -14,4 +32,5 @@ export interface ContentSdkConfig {
14
32
  fetch?: typeof fetch;
15
33
  cms?: CmsConfig;
16
34
  wb?: WbConfig;
35
+ theme?: ThemeConfig;
17
36
  }