Skip to content

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.

feat: support pasting cURL into resource URL (#3156)

Bogdan Chadkin3db9d3d8e878
diff --git a/apps/builder/app/builder/features/settings-panel/curl.test.ts b/apps/builder/app/builder/features/settings-panel/curl.test.ts
new file mode 100644
index 0000000000..92e877c8c9
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/curl.test.ts
@@ -0,0 +1,163 @@
+import { expect, test } from "@jest/globals";
+import { generateCurl, parseCurl } from "./curl";
+
+test("support url", () => {
+ const result = {
+ url: "https://my-url/hello-world",
+ method: "get",
+ headers: [],
+ };
+ expect(parseCurl(`curl https://my-url/hello-world`)).toEqual(result);
+ expect(parseCurl(`curl "https://my-url/hello-world"`)).toEqual(result);
+ expect(parseCurl(`curl 'https://my-url/hello-world'`)).toEqual(result);
+});
+
+test("support multiline", () => {
+ expect(
+ parseCurl(`curl \
+ 'https://my-url/hello-world'
+ `)
+ ).toEqual({
+ url: "https://my-url/hello-world",
+ method: "get",
+ headers: [],
+ });
+});
+
+test("skip when invalid", () => {
+ expect(parseCurl(``)).toEqual(undefined);
+ expect(parseCurl(` `)).toEqual(undefined);
+ expect(parseCurl(`something else`)).toEqual(undefined);
+ expect(parseCurl(`curl`)).toEqual(undefined);
+ expect(parseCurl(`curl `)).toEqual(undefined);
+});
+
+test("support method with --request and -X flags", () => {
+ const result = {
+ url: "https://my-url/hello-world",
+ method: "post",
+ headers: [],
+ };
+ expect(parseCurl(`curl --request post https://my-url/hello-world`)).toEqual(
+ result
+ );
+ expect(parseCurl(`curl https://my-url/hello-world -X POST`)).toEqual(result);
+ expect(
+ parseCurl(`curl --request put https://my-url/hello-world -X post`)
+ ).toEqual(result);
+ expect(
+ parseCurl(`curl -X put https://my-url/hello-world --request post`)
+ ).toEqual(result);
+});
+
+test("support headers with --header and -H flags", () => {
+ expect(
+ parseCurl(`curl https://my-url/hello-world --header "name: value"`)
+ ).toEqual({
+ url: "https://my-url/hello-world",
+ method: "get",
+ headers: [{ name: "name", value: "value" }],
+ });
+ expect(parseCurl(`curl https://my-url/hello-world -H "name: value"`)).toEqual(
+ {
+ url: "https://my-url/hello-world",
+ method: "get",
+ headers: [{ name: "name", value: "value" }],
+ }
+ );
+ expect(
+ parseCurl(
+ `curl https://my-url/hello-world --header="name:value1" -H "name : value2"`
+ )
+ ).toEqual({
+ url: "https://my-url/hello-world",
+ method: "get",
+ headers: [
+ { name: "name", value: "value1" },
+ { name: "name", value: "value2" },
+ ],
+ });
+});
+
+test("support text body", () => {
+ expect(
+ parseCurl(`curl https://my-url/hello-world --data '{"param":"value"}'`)
+ ).toEqual({
+ url: "https://my-url/hello-world",
+ method: "post",
+ headers: [],
+ body: `{"param":"value"}`,
+ });
+});
+
+test("support text body with explicit method", () => {
+ expect(
+ parseCurl(
+ `curl https://my-url/hello-world -X put --data '{"param":"value"}'`
+ )
+ ).toEqual({
+ url: "https://my-url/hello-world",
+ method: "put",
+ headers: [],
+ body: `{"param":"value"}`,
+ });
+});
+
+test("support json body", () => {
+ expect(
+ parseCurl(
+ `curl https://my-url/hello-world \
+ --header 'content-type: application/json' \
+ --data '{"param":"value"}'`
+ )
+ ).toEqual({
+ url: "https://my-url/hello-world",
+ method: "post",
+ headers: [{ name: "content-type", value: "application/json" }],
+ body: { param: "value" },
+ });
+});
+
+test("generate curl with json body", () => {
+ expect(
+ generateCurl({
+ url: "https://my-url.com",
+ method: "post",
+ headers: [{ name: "content-type", value: "application/json" }],
+ body: { param: "value" },
+ })
+ ).toMatchInlineSnapshot(`
+"curl "https://my-url.com" \\
+ --request post \\
+ --header "content-type: application/json" \\
+ --data "{\\"param\\":\\"value\\"}""
+`);
+});
+
+test("generate curl with text body", () => {
+ expect(
+ generateCurl({
+ url: "https://my-url.com",
+ method: "post",
+ headers: [],
+ body: "my data",
+ })
+ ).toMatchInlineSnapshot(`
+"curl "https://my-url.com" \\
+ --request post \\
+ --data "my data""
+`);
+});
+
+test("generate curl without body", () => {
+ expect(
+ generateCurl({
+ url: "https://my-url.com",
+ method: "post",
+ headers: [],
+ })
+ ).toMatchInlineSnapshot(`
+"curl "https://my-url.com" \\
+ --request post"
+`);
+});
diff --git a/apps/builder/app/builder/features/settings-panel/curl.ts b/apps/builder/app/builder/features/settings-panel/curl.ts
new file mode 100644
index 0000000000..890e668232
--- /dev/null
+++ b/apps/builder/app/builder/features/settings-panel/curl.ts
@@ -0,0 +1,93 @@
+import type { ResourceRequest } from "@webstudio-is/sdk";
+import { parseArgsStringToArgv } from "string-argv";
+import { parse as parseArgs } from "ultraflag";
+
+/*
+
+curl --request POST 'https://my-url/hello-world' \
+ --header 'Authorization: Bearer ACCESS_TOKEN' \
+ --header 'Content-Type: application/json' \
+ --data '{ "name":"Foo" }'
+
+*/
+
+const getMethod = (value: string): ResourceRequest["method"] => {
+ switch (value.toLowerCase()) {
+ case "post":
+ return "post";
+ case "put":
+ return "put";
+ case "delete":
+ return "delete";
+ default:
+ return "get";
+ }
+};
+
+type CurlRequest = Pick<ResourceRequest, "url" | "method" | "headers" | "body">;
+
+export const parseCurl = (curl: string): undefined | CurlRequest => {
+ const argv = parseArgsStringToArgv(curl);
+ if (argv.length === 0) {
+ return;
+ }
+ const args = parseArgs(argv, {
+ alias: {
+ X: ["request"],
+ H: ["header"],
+ },
+ string: ["request", "data"],
+ array: ["header", "H"],
+ });
+ // require at least 2 parameters and first is curl command
+ if (args._.length < 2 || args._[0] !== "curl") {
+ return;
+ }
+ const [_curl, url] = args._;
+ const defaultMethod = args.data ? "post" : "get";
+ const method = getMethod(args.request ?? defaultMethod);
+ let contentType: undefined | string;
+ const headers: ResourceRequest["headers"] = (
+ (args.header as string[]) ?? []
+ ).map((header) => {
+ // in case of invalid header fallback value to empty string
+ const [name, value = ""] = header.trim().split(/\s*:\s*/);
+ if (name.toLowerCase() === "content-type") {
+ contentType = value;
+ }
+ return { name, value };
+ });
+ let body: undefined | unknown = args.data;
+ if (args.data && contentType === "application/json") {
+ try {
+ body = JSON.parse(args.data);
+ } catch {
+ // empty block
+ }
+ }
+ return {
+ url: url as string,
+ method,
+ headers,
+ body,
+ };
+};
+
+export const generateCurl = (request: CurlRequest) => {
+ const args = [
+ `curl ${JSON.stringify(request.url)}`,
+ `--request ${request.method}`,
+ ];
+ for (const header of request.headers) {
+ args.push(`--header "${header.name}: ${header.value}"`);
+ }
+ if (request.body) {
+ let body = request.body;
+ // double serialize json
+ if (typeof request.body !== "string") {
+ body = JSON.stringify(body);
+ }
+ args.push(`--data ${JSON.stringify(body)}`);
+ }
+ return args.join(" \\\n ");
+};
diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
index f94e37ee79..999e1486c9 100644
--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx
@@ -24,9 +24,10 @@ import {
Select,
SmallIconButton,
TextArea,
+ Tooltip,
theme,
} from "@webstudio-is/design-system";
-import { DeleteIcon, PlusIcon } from "@webstudio-is/icons";
+import { DeleteIcon, InfoCircleIcon, PlusIcon } from "@webstudio-is/icons";
import { isFeatureEnabled } from "@webstudio-is/feature-flags";
import { humanizeString } from "~/shared/string-utils";
import { serverSyncStore } from "~/shared/sync";
@@ -49,6 +50,7 @@ import {
composeFields,
} from "~/shared/form-utils";
import { ExpressionEditor } from "~/builder/shared/expression-editor";
+import { parseCurl } from "./curl";
const validateHeaderName = (value: string) =>
value.trim().length === 0 ? "Header name is required" : undefined;
@@ -523,7 +525,21 @@ export const ResourceForm = forwardRef<
return (
<>
<Flex direction="column" css={{ gap: theme.spacing[3] }}>
- <Label htmlFor={urlId}>URL</Label>
+ <Label
+ htmlFor={urlId}
+ css={{ display: "flex", alignItems: "center", gap: theme.spacing[3] }}
+ >
+ URL
+ <Tooltip
+ content={
+ "You can paste a URL or cURL. cURL is a format that can be executed directly in your terminal because it contains the entire Resource configuration."
+ }
+ variant="wrapped"
+ disableHoverableContent={true}
+ >
+ <InfoCircleIcon tabIndex={0} />
+ </Tooltip>
+ </Label>
<BindingControl>
<InputErrorsTooltip
errors={urlField.error ? [urlField.error] : undefined}
@@ -537,9 +553,24 @@ export const ResourceForm = forwardRef<
evaluateExpressionWithinScope(urlField.value, scope)
)}
// update text value as string literal
- onChange={(event) =>
- urlField.onChange(JSON.stringify(event.target.value))
- }
+ onChange={(event) => {
+ const value = event.target.value;
+ const curl = parseCurl(value);
+ if (curl) {
+ // update all feilds when curl is paste into url field
+ urlField.onChange(JSON.stringify(curl.url));
+ setMethod(curl.method);
+ headersField.onChange(
+ curl.headers.map((header) => ({
+ name: header.name,
+ value: JSON.stringify(header.value),
+ }))
+ );
+ bodyField.onChange(JSON.stringify(curl.body));
+ } else {
+ urlField.onChange(JSON.stringify(value));
+ }
+ }}
onBlur={urlField.onBlur}
/>
</InputErrorsTooltip>
diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
index c2a9850b2a..cf60069354 100644
--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx
@@ -13,7 +13,7 @@ import {
useContext,
} from "react";
import { mergeRefs } from "@react-aria/utils";
-import { RefreshIcon } from "@webstudio-is/icons";
+import { CopyIcon, RefreshIcon } from "@webstudio-is/icons";
import {
Box,
Button,
@@ -45,6 +45,7 @@ import {
$areResourcesLoading,
$selectedInstanceSelector,
invalidateResource,
+ getComputedResource,
} from "~/shared/nano-states";
import { serverSyncStore } from "~/shared/sync";
import {
@@ -61,6 +62,7 @@ import {
EditorDialogControl,
} from "~/builder/shared/code-editor";
import { ResourceForm } from "./resource-panel";
+import { generateCurl } from "./curl";
/**
* convert value expression to js value
@@ -590,15 +592,37 @@ export const VariablePopoverTrigger = forwardRef<
<FloatingPanelPopoverTitle
actions={
variable.type === "resource" && (
- <Tooltip content="Refresh resource data" side="bottom">
- <Button
- aria-label="Refresh resource data"
- prefix={<RefreshIcon />}
- color="ghost"
- disabled={areResourcesLoading}
- onClick={() => invalidateResource(variable.resourceId)}
- />
- </Tooltip>
+ <>
+ <Tooltip
+ content="Copy resource as cURL command"
+ side="bottom"
+ >
+ <Button
+ aria-label="Copy resource as cURL command"
+ prefix={<CopyIcon />}
+ color="ghost"
+ onClick={() => {
+ const resourceRequest = getComputedResource(
+ variable.resourceId
+ );
+ if (resourceRequest) {
+ navigator.clipboard.writeText(
+ generateCurl(resourceRequest)
+ );
+ }
+ }}
+ />
+ </Tooltip>
+ <Tooltip content="Refresh resource data" side="bottom">
+ <Button
+ aria-label="Refresh resource data"
+ prefix={<RefreshIcon />}
+ color="ghost"
+ disabled={areResourcesLoading}
+ onClick={() => invalidateResource(variable.resourceId)}
+ />
+ </Tooltip>
+ </>
)
}
>
diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.ts
index fe36a7a844..0d606dceb1 100644
--- a/apps/builder/app/shared/nano-states/props.ts
+++ b/apps/builder/app/shared/nano-states/props.ts
@@ -514,15 +514,22 @@ const cacheByKeys = new Map<string, unknown>();
const $invalidator = atom(0);
-// bump index of resource to invaldate cache entry
-export const invalidateResource = (resourceId: Resource["id"]) => {
+export const getComputedResource = (resourceId: Resource["id"]) => {
const resources = $resources.get();
const resource = resources.get(resourceId);
if (resource === undefined) {
return;
}
const values = $loaderVariableValues.get();
- const request = computeResource(resource, values);
+ return computeResource(resource, values);
+};
+
+// bump index of resource to invaldate cache entry
+export const invalidateResource = (resourceId: Resource["id"]) => {
+ const request = getComputedResource(resourceId);
+ if (request === undefined) {
+ return;
+ }
const cacheKey = JSON.stringify(request);
cacheByKeys.delete(cacheKey);
// trigger invalidation
diff --git a/apps/builder/package.json b/apps/builder/package.json
index 10fcf48912..52a710d19d 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -111,8 +111,10 @@
"remix-island": "^0.2.0",
"shallow-equal": "^3.1.0",
"slugify": "^1.6.6",
+ "string-argv": "^0.3.2",
"strip-indent": "^4.0.0",
"title-case": "^4.1.0",
+ "ultraflag": "^0.1.0",
"untruncate-json": "^0.0.1",
"urlpattern-polyfill": "^9.0.0",
"use-debounce": "^9.0.4",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9b224e61b4..979f65d13a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -329,12 +329,18 @@ importers:
slugify:
specifier: ^1.6.6
version: 1.6.6
+ string-argv:
+ specifier: ^0.3.2
+ version: 0.3.2
strip-indent:
specifier: ^4.0.0
version: 4.0.0
title-case:
specifier: ^4.1.0
version: 4.1.0
+ ultraflag:
+ specifier: ^0.1.0
+ version: 0.1.0
untruncate-json:
specifier: ^0.0.1
version: 0.0.1
@@ -15642,6 +15648,11 @@ packages:
engines: {node: '>=0.6.19'}
dev: false
+ resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==}
+ engines: {node: '>=0.6.19'}
+ dev: false
+
resolution: {integrity: sha512-kJUvRUFK49aub+a7T1nNE66EJbZBMnBgoC1UbCZ5n6bsZKBRga4KgBRTMn/pFkeCZSYtNeSyMxPDM0AXWELk2A==}
dev: true
@@ -16342,6 +16353,10 @@ packages:
requiresBuild: true
optional: true
+ resolution: {integrity: sha512-F6J/7SZHkep//Ihd5N63b1ghzBUclZvFuSzsZgurFPS0h0Fj482mNdz8R9REm89ETSPPsPB9eJ3z7E52WkDMQw==}
+ dev: false
+
resolution: {integrity: sha512-XyWQowvP9CKZycKc/Zg9SYWrAWX/gJCE799AUTFqk8yC3tp44K1xWr3LoFF0MNEjClKOo1suCr5ASnoy+KltdA==}
engines: {node: '>=12'}