Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: prevent generating unused variables in resoures (#2929)
Bogdan Chadkin727978b2c9b5
diff --git a/apps/builder/app/builder/features/ai/ai-fetch-result.ts b/apps/builder/app/builder/features/ai/ai-fetch-result.tsindex aee573fc53..1fa6b5a551 100644--- a/apps/builder/app/builder/features/ai/ai-fetch-result.ts+++ b/apps/builder/app/builder/features/ai/ai-fetch-result.ts@@ -18,7 +18,6 @@ import { Instance, createScope, findTreeInstanceIds } from "@webstudio-is/sdk";import { computed } from "nanostores";import { getMapValuesByKeysSet } from "~/shared/array-utils";import {- $breakpoints,$dataSources,$instances,$project,@@ -249,7 +248,6 @@ const $jsx = computed($props,$dataSources,$registeredComponentMetas,- $breakpoints,$styles,$styleSourceSelections,],@@ -259,7 +257,6 @@ const $jsx = computed(props,dataSources,metas,- breakpoints,styles,styleSourceSelections) => {@@ -282,6 +279,7 @@ const $jsx = computed(instance,props,dataSources,+ usedDataSources: new Map(),indexesWithinAncestors,children: generateJsxChildren({scope,@@ -289,6 +287,7 @@ const $jsx = computed(instances,props,dataSources,+ usedDataSources: new Map(),indexesWithinAncestors,}),});diff --git a/packages/react-sdk/src/component-generator.test.ts b/packages/react-sdk/src/component-generator.test.tsindex 33baa80919..f4663d9cfe 100644--- a/packages/react-sdk/src/component-generator.test.ts+++ b/packages/react-sdk/src/component-generator.test.ts@@ -55,6 +55,7 @@ test("generate jsx element with children and without them", () => {]),props: new Map(),dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),children: "Children\n",})@@ -73,6 +74,7 @@ test("generate jsx element with children and without them", () => {instance: createInstance("image", "Image", []),props: new Map(),dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),children: "Children\n",})@@ -94,6 +96,7 @@ test("generate jsx element with namespaces components", () => {]),props: new Map(),dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),children: "Children\n",})@@ -112,6 +115,7 @@ test("generate jsx element with namespaces components", () => {instance: createInstance("image", "@webstudio-is/library:Image", []),props: new Map(),dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),children: "Children\n",})@@ -163,6 +167,7 @@ test("generate jsx element with literal props", () => {]),props,dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),children: "Children\n",})@@ -183,6 +188,7 @@ test("generate jsx element with literal props", () => {instance: createInstance("image", "Image", []),props,dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),children: "",})@@ -219,6 +225,7 @@ test("ignore asset and page props", () => {}),]),dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),children: "",})@@ -278,6 +285,7 @@ test("generate jsx element with data sources and action", () => {value: { type: "number", value: 0 },}),]),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),children: "",})@@ -312,6 +320,7 @@ test("generate jsx element with condition based on show prop", () => {}),]),dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),children: "",})@@ -336,6 +345,7 @@ test("generate jsx element with condition based on show prop", () => {}),]),dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),children: "",})@@ -361,6 +371,7 @@ test("generate jsx element with condition based on show prop", () => {value: { type: "boolean", value: false },}),]),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),children: "",})@@ -382,6 +393,7 @@ test("generate jsx element with index prop", () => {instance: createInstance("box", "Box", []),props: new Map(),dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map([["box", 5]]),children: "",})@@ -406,6 +418,7 @@ test("generate jsx children with text", () => {instances: new Map(),props: new Map(),dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),})).toEqual(@@ -436,6 +449,7 @@ test("generate jsx children with expression", () => {value: { type: "string", value: "world" },}),]),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),})).toEqual(@@ -468,6 +482,7 @@ test("generate jsx children with nested instances", () => {}),]),dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),})).toEqual(@@ -505,6 +520,7 @@ test("deduplicate base and namespaced components with same short name", () => {]),props: new Map(),dataSources: new Map(),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),})).toEqual(@@ -571,6 +587,7 @@ test("generate collection component as map", () => {value: "$ws$dataSource$dataSourceItem",}),]),+ usedDataSources: new Map(),indexesWithinAncestors: new Map(),})).toEqual(diff --git a/packages/react-sdk/src/component-generator.ts b/packages/react-sdk/src/component-generator.tsindex 35490db1a1..f0f80504ac 100644--- a/packages/react-sdk/src/component-generator.ts+++ b/packages/react-sdk/src/component-generator.ts@@ -37,7 +37,7 @@ const generateAction = ({scope: Scope;prop: Extract<Prop, { type: "action" }>;dataSources: DataSources;- usedDataSources?: DataSources;+ usedDataSources: DataSources;}) => {const setters = new Set<DataSource>();// important to fallback to empty argumets to render empty function@@ -55,7 +55,7 @@ const generateAction = ({const depId = decodeDataSourceVariable(identifier);const dep = depId ? dataSources.get(depId) : undefined;if (dep) {- usedDataSources?.set(dep.id, dep);+ usedDataSources.set(dep.id, dep);if (assignee) {setters.add(dep);}@@ -96,7 +96,7 @@ const generatePropValue = ({scope: Scope;prop: Prop;dataSources: DataSources;- usedDataSources?: DataSources;+ usedDataSources: DataSources;}) => {// ignore asset and page props which are handled by components internallyif (prop.type === "asset" || prop.type === "page") {@@ -117,7 +117,7 @@ const generatePropValue = ({if (dataSource === undefined) {return;}- usedDataSources?.set(dataSource.id, dataSource);+ usedDataSources.set(dataSource.id, dataSource);return scope.getName(dataSource.id, dataSource.name);}// inline expression to safely use collection item@@ -149,7 +149,7 @@ export const generateJsxElement = ({instance: Instance;props: Props;dataSources: DataSources;- usedDataSources?: DataSources;+ usedDataSources: DataSources;indexesWithinAncestors: IndexesWithinAncestors;children: string;classesMap?: Map<string, Array<string>>;@@ -276,7 +276,7 @@ export const generateJsxChildren = ({instances: Instances;props: Props;dataSources: DataSources;- usedDataSources?: DataSources;+ usedDataSources: DataSources;indexesWithinAncestors: IndexesWithinAncestors;classesMap?: Map<string, Array<string>>;}) => {@@ -295,6 +295,7 @@ export const generateJsxChildren = ({const expression = generateExpression({expression: child.value,dataSources,+ usedDataSources,scope,});generatedChildren = `{${expression}}\n`;diff --git a/packages/react-sdk/src/expression.ts b/packages/react-sdk/src/expression.tsindex 816151553b..83e1057f81 100644--- a/packages/react-sdk/src/expression.ts+++ b/packages/react-sdk/src/expression.ts@@ -193,7 +193,7 @@ export const generateExpression = ({}: {expression: string;dataSources: DataSources;- usedDataSources?: DataSources;+ usedDataSources: DataSources;scope: Scope;}) => {return validateExpression(expression, {diff --git a/packages/react-sdk/src/resources-generator.test.ts b/packages/react-sdk/src/resources-generator.test.tsindex d7b99b1f28..5749c921c6 100644--- a/packages/react-sdk/src/resources-generator.test.ts+++ b/packages/react-sdk/src/resources-generator.test.ts@@ -129,7 +129,7 @@ test("generate variable and use in resources loader", () => {);});-test("generate page params variable and use in resources loader", () => {+test("generate path params variable and use in resources loader", () => {expect(generateResourcesLoader({scope: createScope(),@@ -148,7 +148,7 @@ test("generate page params variable and use in resources loader", () => {{id: "variableParamsId",scopeInstanceId: "body",- name: "Page params",+ name: "Path Params",type: "parameter",},]),@@ -168,14 +168,14 @@ test("generate page params variable and use in resources loader", () => {import { loadResource } from "@webstudio-is/sdk";type Params = Record<string, string | undefined>export const loadResources = async (_props: { params: Params }) => {- const Pageparams = _props.params+ const PathParams = _props.paramsconst [variableName,] = await Promise.all([loadResource({id: "resourceId",name: "resourceName",- url: "https://my-json.com/" + Pageparams?.slug,+ url: "https://my-json.com/" + PathParams?.slug,method: "post",headers: [{ name: "Content-Type", value: "application/json" },@@ -209,3 +209,57 @@ test("generate empty resources loader", () => {`));});++test("prevent generating unused variables", () => {+ expect(+ generateResourcesLoader({+ scope: createScope(),+ page: { rootInstanceId: "body" } as Page,+ dataSources: toMap([+ {+ id: "unuseVariableId",+ scopeInstanceId: "body",+ name: "Unused Variable",+ type: "variable",+ value: { type: "string", value: "" },+ },+ ]),+ resources: new Map(),+ })+ ).toMatchInlineSnapshot(`+"type Params = Record<string, string | undefined>+export const loadResources = async (_props: { params: Params }) => {+return {+} as Record<string, unknown>+}+"+`);+});++test("prevent generating unused path params variable", () => {+ expect(+ generateResourcesLoader({+ scope: createScope(),+ page: {+ rootInstanceId: "body",+ pathParamsDataSourceId: "variableParamsId",+ } as Page,+ dataSources: toMap([+ {+ id: "variableParamsId",+ scopeInstanceId: "body",+ name: "Unused Path Params",+ type: "parameter",+ },+ ]),+ resources: new Map(),+ })+ ).toMatchInlineSnapshot(`+"type Params = Record<string, string | undefined>+export const loadResources = async (_props: { params: Params }) => {+return {+} as Record<string, unknown>+}+"+`);+});diff --git a/packages/react-sdk/src/resources-generator.ts b/packages/react-sdk/src/resources-generator.tsindex 0db25d6a15..7a14ef96fe 100644--- a/packages/react-sdk/src/resources-generator.ts+++ b/packages/react-sdk/src/resources-generator.ts@@ -12,27 +12,13 @@ export const generateResourcesLoader = ({dataSources: DataSources;resources: Resources;}) => {- let generatedVariables = "";let generatedOutput = "";let generatedLoaders = "";let hasResources = false;- for (const dataSource of dataSources.values()) {- if (dataSource.type === "variable") {- const name = scope.getName(dataSource.id, dataSource.name);- const value = JSON.stringify(dataSource.value.value);- generatedVariables += `let ${name} = ${value}\n`;- }-- if (dataSource.type === "parameter") {- // support only page path params parameter- if (dataSource.id !== page.pathParamsDataSourceId) {- continue;- }- const name = scope.getName(dataSource.id, dataSource.name);- generatedVariables += `const ${name} = _props.params\n`;- }+ const usedDataSources: DataSources = new Map();+ for (const dataSource of dataSources.values()) {if (dataSource.type === "resource") {const resource = resources.get(dataSource.resourceId);if (resource === undefined) {@@ -48,6 +34,7 @@ export const generateResourcesLoader = ({const url = generateExpression({expression: resource.url,dataSources,+ usedDataSources,scope,});generatedLoaders += `url: ${url},\n`;@@ -57,6 +44,7 @@ export const generateResourcesLoader = ({const value = generateExpression({expression: header.value,dataSources,+ usedDataSources,scope,});generatedLoaders += `{ name: "${header.name}", value: ${value} },\n`;@@ -67,6 +55,7 @@ export const generateResourcesLoader = ({const body = generateExpression({expression: resource.body,dataSources,+ usedDataSources,scope,});generatedLoaders += `body: ${body},\n`;@@ -75,14 +64,32 @@ export const generateResourcesLoader = ({}}+ let generatedVariables = "";+ for (const dataSource of usedDataSources.values()) {+ if (dataSource.type === "variable") {+ const name = scope.getName(dataSource.id, dataSource.name);+ const value = JSON.stringify(dataSource.value.value);+ generatedVariables += `let ${name} = ${value}\n`;+ }++ if (dataSource.type === "parameter") {+ // support only page path params parameter+ if (dataSource.id !== page.pathParamsDataSourceId) {+ continue;+ }+ const name = scope.getName(dataSource.id, dataSource.name);+ generatedVariables += `const ${name} = _props.params\n`;+ }+ }+let generated = "";if (hasResources) {generated += `import { loadResource } from "@webstudio-is/sdk";\n`;}generated += `type Params = Record<string, string | undefined>\n`;generated += `export const loadResources = async (_props: { params: Params }) => {\n`;+ generated += generatedVariables;if (hasResources) {- generated += generatedVariables;generated += `const [\n`;generated += generatedOutput;generated += `] = await Promise.all([\n`;