From 9ad3cab77889320fd071d101daa21050ceebcd31 Mon Sep 17 00:00:00 2001 From: Kian Newman-Hazel Date: Fri, 18 Oct 2024 13:36:47 +0100 Subject: [PATCH] [Docs Site] Add WranglerCommand component --- scripts/wrangler-commands-json.ts | 195 + src/components/WranglerCommand.astro | 70 + src/components/index.ts | 3 +- src/content/config.ts | 5 + .../tutorials/deploy-aig-worker.mdx | 2 +- .../components/wrangler-command.mdx | 11 + .../tutorials/build-a-jamstack-app/index.mdx | 2 +- .../index.mdx | 6 +- .../index.mdx | 4 +- .../openai-function-calls-workers/index.mdx | 2 +- .../docs/workers/wrangler/commands.mdx | 1595 +------- .../docs/workers/wrangler/configuration.mdx | 2 +- .../docs/workers/wrangler/deprecations.mdx | 2 +- .../docs/workers/wrangler/environments.mdx | 2 +- src/content/wrangler-commands/index.json | 3583 +++++++++++++++++ src/schemas/index.ts | 1 + src/schemas/wrangler-commands.ts | 25 + 17 files changed, 4009 insertions(+), 1501 deletions(-) create mode 100644 scripts/wrangler-commands-json.ts create mode 100644 src/components/WranglerCommand.astro create mode 100644 src/content/docs/style-guide/components/wrangler-command.mdx create mode 100644 src/content/wrangler-commands/index.json create mode 100644 src/schemas/wrangler-commands.ts diff --git a/scripts/wrangler-commands-json.ts b/scripts/wrangler-commands-json.ts new file mode 100644 index 00000000000000..6ad7f8d7feff79 --- /dev/null +++ b/scripts/wrangler-commands-json.ts @@ -0,0 +1,195 @@ +import { execSync } from "child_process"; +import { writeFileSync } from "fs"; + +const TWO_OR_MORE_SPACES_REGEX = /[^\S\r\n]{2,}/; +const WORDS_IN_BRACKETS_REGEX = /\[([\s\S]+?)\]|\{([\s\S]+?)\}|<([\s\S]+?)>/g; +const COMMANDS_REGEX = /(?:\r?\n){2}COMMANDS\r?\n/; +const POSITIONALS_REGEX = /(?:\r?\n){2}POSITIONALS\r?\n/; +const GLOBAL_FLAGS_REGEX = /(?:\r?\n){2}GLOBAL FLAGS\r?\n/; +const OPTIONS_REGEX = /(?:\r?\n){2}OPTIONS\r?\n/; +const EXAMPLES_REGEX = /(?:\r?\n){2}EXAMPLES\r?\n/; +const HELP_END = + "Please report any issues to https://github.com/cloudflare/workers-sdk/issues/new/choose"; + +function run(cmd: string) { + return execSync(cmd).toString(); +} + +function removePositionalsFromCommand(str: string) { + const matches = str.matchAll(WORDS_IN_BRACKETS_REGEX); + + if (matches) { + let line = str; + + for (const match of matches) { + const start = line.indexOf(match[0]); + const end = start + match[0].length; + + line = (line.substring(0, start) + line.substring(end)).trim(); + } + + return line; + } + + return str; +} + +function handlePositionals(str: string) { + const start = str.match(POSITIONALS_REGEX); + const end = str.match(GLOBAL_FLAGS_REGEX); + + if (!start || !end) { + throw new Error("Oops"); + } + + const output = str.substring( + str.indexOf(start[0]) + start[0].length, + str.indexOf(end[0]), + ); + + let lines = output.split("\n"); + + lines = lines.filter(Boolean); + lines = lines.map((x) => x.trim()); + + return lines.map((x) => { + const [name, description, type] = x.split(TWO_OR_MORE_SPACES_REGEX); + + return { + name, + description, + type, + }; + }); +} + +function handleOptions(str: string) { + const start = str.match(OPTIONS_REGEX); + const end = str.match(EXAMPLES_REGEX) ?? str.length; + + if (!start || !end) { + throw new Error("Oops"); + } + + const output = str.substring( + str.indexOf(start[0]) + start[0].length, + typeof end === "number" ? end : str.indexOf(end[0]), + ); + + let lines = output.split("\n"); + + lines = lines.filter(Boolean); + lines = lines.map((x) => x.trim()); + + const options: string[] = []; + let multiLineBuffer: string[] = []; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + + const isOptionLine = line.startsWith("-"); + const isLastLine = i + 1 === lines.length; + + if (isOptionLine || isLastLine) { + if (isLastLine) { + options.push([...multiLineBuffer, line].join("\n")); + } else { + const nextLineIsOptionLine = lines[i + 1].startsWith("-"); + + if (nextLineIsOptionLine) { + options.push(line); + continue; + } + } + } + + multiLineBuffer.push(line); + } + + return options + .filter((x) => !x.includes("--------------------")) + .map((x) => { + let [flags, ...rest] = x.split(/[^\S\r\n]{2,}/); + let description = rest.join("\n"); + + const match = description.match(/\[.*\]/g); + + let type; + if (match) { + [type] = match; + + const start = description.indexOf(type); + const end = start + type.length; + + description = + description.substring(0, start) + description.substring(end); + } + + return { + flags, + description, + type, + }; + }); +} + +function handleSubcommands(str: string) { + const start = str.match(COMMANDS_REGEX); + const end = str.match(GLOBAL_FLAGS_REGEX); + + const isNamespace = start && end; + + if (isNamespace) { + const output = str.substring( + str.indexOf(start[0]) + start[0].length, + str.indexOf(end[0]), + ); + + let lines = output.split("\n"); + + lines = lines.filter(Boolean); + lines = lines.map((x) => x.trim()); + lines = lines.map((x) => x.split(TWO_OR_MORE_SPACES_REGEX).at(0) as string); + lines = lines.map(removePositionalsFromCommand); + + if (lines) { + for (const line of lines) { + handleSubcommands(run(`${line} --help`)); + } + } + } else { + const [example, _, description] = str.split("\n"); + const command = removePositionalsFromCommand(example); + + json[command] = { + example, + description, + }; + + const hasPositionals = str.indexOf("POSITIONALS") !== -1; + const hasOptions = str.indexOf("OPTIONS") !== -1; + + if (hasPositionals) { + json[command]["positionals"] = handlePositionals(str); + } + + if (hasOptions) { + json[command]["options"] = handleOptions(str); + } + } +} + +const json: Record = {}; + +function main() { + const topLevelHelp = run("wrangler --help"); + + handleSubcommands(topLevelHelp); + + writeFileSync( + "./src/content/wrangler-commands/index.json", + JSON.stringify(json, null, "\t"), + ); +} + +await main(); diff --git a/src/components/WranglerCommand.astro b/src/components/WranglerCommand.astro new file mode 100644 index 00000000000000..5b334cabc09203 --- /dev/null +++ b/src/components/WranglerCommand.astro @@ -0,0 +1,70 @@ +--- +import { z } from "astro:schema"; +import { Code } from "@astrojs/starlight/components"; +import Type from "./Type.astro"; +import AnchorHeading from "./AnchorHeading.astro"; +import { marked } from "marked"; +import { getEntry } from "astro:content"; +import MetaInfo from "./MetaInfo.astro"; + +type Props = z.infer; + +const props = z.object({ + cmd: z.string(), +}); + +const { cmd } = props.parse(Astro.props); + +const depth = cmd.split(" ").length > 1 ? 3 : 2; + +const command = (await getEntry("wrangler-commands", "index")).data[ + `wrangler ${cmd}` +]; + +if (!command) { + throw new Error(`Unable to find info for ${cmd}`); +} +--- + + + +

{command.description}

+ + + +{ + command["positionals"]?.length && ( + <> +

Positionals

+
    + {command["positionals"].map((x) => ( +
  • + {x.name} + +

    {x.description}

    +
  • + ))} +
+ + ) +} + +{ + command["options"]?.length && ( + <> +

Options

+
    + {command["options"].map((x) => ( +
  • + {x.flags} + + + {x.meta && } +
  • + ))} +
+ + ) +} diff --git a/src/components/index.ts b/src/components/index.ts index 88ff2baf89c120..6f823090fb18dc 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -50,10 +50,11 @@ export { default as ThreeCardGrid } from "./ThreeCardGrid.astro"; export { default as TroubleshootingList } from "./TroubleshootingList.astro"; export { default as TunnelCalculator } from "./TunnelCalculator.astro"; export { default as Type } from "./Type.astro"; -export { default as TypeScriptExample } from "./TypeScriptExample.astro" +export { default as TypeScriptExample } from "./TypeScriptExample.astro"; export { default as WorkersArchitectureDiagram } from "./WorkersArchitectureDiagram.astro"; export { default as WorkersIsolateDiagram } from "./WorkersIsolateDiagram.astro"; export { default as WorkerStarter } from "./WorkerStarter.astro"; +export { default as WranglerCommand } from "./WranglerCommand.astro"; export { default as YouTube } from "./YouTube.astro"; // Taken from Astro diff --git a/src/content/config.ts b/src/content/config.ts index 3a0c07abccc3f2..eb7cd3af28c507 100644 --- a/src/content/config.ts +++ b/src/content/config.ts @@ -12,6 +12,7 @@ import { learningPathsSchema, videosSchema, workersAiSchema, + wranglerCommandsSchema, } from "~/schemas"; const partialSchema = z.object({ @@ -74,4 +75,8 @@ export const collections = { schema: appsSchema, type: "data", }), + "wrangler-commands": defineCollection({ + schema: wranglerCommandsSchema, + type: "data", + }), }; diff --git a/src/content/docs/ai-gateway/tutorials/deploy-aig-worker.mdx b/src/content/docs/ai-gateway/tutorials/deploy-aig-worker.mdx index 6022599fe79fd9..11e3e6f3f8240f 100644 --- a/src/content/docs/ai-gateway/tutorials/deploy-aig-worker.mdx +++ b/src/content/docs/ai-gateway/tutorials/deploy-aig-worker.mdx @@ -94,7 +94,7 @@ export default { }; ``` -To make this work, you need to use [`wrangler secret put`](/workers/wrangler/commands/#put-3) to set your `OPENAI_API_KEY`. This will save the API key to your environment so your Worker can access it when deployed. This key is the API key you created earlier in the OpenAI dashboard: +To make this work, you need to use [`wrangler secret put`](/workers/wrangler/commands/#secret-put) to set your `OPENAI_API_KEY`. This will save the API key to your environment so your Worker can access it when deployed. This key is the API key you created earlier in the OpenAI dashboard: ```sh title="Save your API key to your Workers env" npx wrangler secret put OPENAI_API_KEY diff --git a/src/content/docs/style-guide/components/wrangler-command.mdx b/src/content/docs/style-guide/components/wrangler-command.mdx new file mode 100644 index 00000000000000..dc753866c55c73 --- /dev/null +++ b/src/content/docs/style-guide/components/wrangler-command.mdx @@ -0,0 +1,11 @@ +--- +title: Wrangler command +--- + +This component reads from a JSON file that is created by parsing the `--help` output of Wrangler commands. + +```mdx live +import { WranglerCommand } from "~/components"; + + +``` \ No newline at end of file diff --git a/src/content/docs/workers/tutorials/build-a-jamstack-app/index.mdx b/src/content/docs/workers/tutorials/build-a-jamstack-app/index.mdx index 5cb3989db1e892..acc87d6403ab9d 100644 --- a/src/content/docs/workers/tutorials/build-a-jamstack-app/index.mdx +++ b/src/content/docs/workers/tutorials/build-a-jamstack-app/index.mdx @@ -81,7 +81,7 @@ For the remainder of this tutorial you will complete each task, iterating on you To begin, you need to understand how to populate your todo list with actual data. To do this, use [Cloudflare Workers KV](/kv/) — a key-value store that you can access inside of your Worker to read and write data. -To get started with KV, set up a namespace. All of your cached data will be stored inside that namespace and, with configuration, you can access that namespace inside the Worker with a predefined variable. Use Wrangler to create a new namespace called `TODOS` with the [`kv:namespace create` command](/workers/wrangler/commands/#create-3) and get the associated namespace ID by running the following command in your terminal: +To get started with KV, set up a namespace. All of your cached data will be stored inside that namespace and, with configuration, you can access that namespace inside the Worker with a predefined variable. Use Wrangler to create a new namespace called `TODOS` with the [`kv:namespace create` command](/workers/wrangler/commands/#kv-namespace-create) and get the associated namespace ID by running the following command in your terminal: ```sh title="Create a new KV namespace" npx wrangler kv:namespace create "TODOS" --preview diff --git a/src/content/docs/workers/tutorials/create-finetuned-chatgpt-ai-models-with-r2/index.mdx b/src/content/docs/workers/tutorials/create-finetuned-chatgpt-ai-models-with-r2/index.mdx index 63c2ccafd444b0..461370ad5601dd 100644 --- a/src/content/docs/workers/tutorials/create-finetuned-chatgpt-ai-models-with-r2/index.mdx +++ b/src/content/docs/workers/tutorials/create-finetuned-chatgpt-ai-models-with-r2/index.mdx @@ -71,7 +71,7 @@ cd finetune-chatgpt-model Next, upload the fine-tune document to R2. R2 is a key-value store that allows you to store and retrieve files from within your Workers application. You will use [Wrangler](/workers/wrangler) to create a new R2 bucket. -To create a new R2 bucket use the [`wrangler r2 bucket create`](/workers/wrangler/commands/#create-2) command. Note that you are logged in with your Cloudflare account. If not logged in via Wrangler, use the [`wrangler login`](/workers/wrangler/commands/#login) command. +To create a new R2 bucket use the [`wrangler r2 bucket create`](/workers/wrangler/commands/#r2-bucket-create) command. Note that you are logged in with your Cloudflare account. If not logged in via Wrangler, use the [`wrangler login`](/workers/wrangler/commands/#login) command. ```sh npx wrangler r2 bucket create @@ -79,7 +79,7 @@ npx wrangler r2 bucket create Replace `` with your desired bucket name. Note that bucket names must be lowercase and can only contain dashes. -Next, upload a file using the [`wrangler r2 object put`](/workers/wrangler/commands/#put-2) command. +Next, upload a file using the [`wrangler r2 object put`](/workers/wrangler/commands/#r2-object-put) command. ```sh npx wrangler r2 object put -f @@ -233,7 +233,7 @@ app.get("/jobs", async (c) => { After you have created your Worker application and added the required functions, deploy the application. -Before you deploy, you must set the `OPENAI_API_KEY` [secret](/workers/configuration/secrets/) for your application. Do this by running the [`wrangler secret put`](/workers/wrangler/commands/#put-3) command: +Before you deploy, you must set the `OPENAI_API_KEY` [secret](/workers/configuration/secrets/) for your application. Do this by running the [`wrangler secret put`](/workers/wrangler/commands/#secret-put) command: ```sh npx wrangler secret put OPENAI_API_KEY diff --git a/src/content/docs/workers/tutorials/github-sms-notifications-using-twilio/index.mdx b/src/content/docs/workers/tutorials/github-sms-notifications-using-twilio/index.mdx index fa0f520a04bcb6..742195771957f1 100644 --- a/src/content/docs/workers/tutorials/github-sms-notifications-using-twilio/index.mdx +++ b/src/content/docs/workers/tutorials/github-sms-notifications-using-twilio/index.mdx @@ -147,7 +147,7 @@ function checkSignature(text, headers, githubSecretToken) { } ``` -To make this work, you need to use [`wrangler secret put`](/workers/wrangler/commands/#put-3) to set your `GITHUB_SECRET_TOKEN`. This token is the secret you picked earlier when configuring you GitHub webhook: +To make this work, you need to use [`wrangler secret put`](/workers/wrangler/commands/#secret-put) to set your `GITHUB_SECRET_TOKEN`. This token is the secret you picked earlier when configuring you GitHub webhook: ```sh npx wrangler secret put GITHUB_SECRET_TOKEN @@ -197,7 +197,7 @@ async function sendText(accountSid, authToken, message) { } ``` -To make this work, you need to set some secrets to hide your `ACCOUNT_SID` and `AUTH_TOKEN` from the source code. You can set secrets with [`wrangler secret put`](/workers/wrangler/commands/#put-3) in your command line. +To make this work, you need to set some secrets to hide your `ACCOUNT_SID` and `AUTH_TOKEN` from the source code. You can set secrets with [`wrangler secret put`](/workers/wrangler/commands/#secret-put) in your command line. ```sh npx wrangler secret put TWILIO_ACCOUNT_SID diff --git a/src/content/docs/workers/tutorials/openai-function-calls-workers/index.mdx b/src/content/docs/workers/tutorials/openai-function-calls-workers/index.mdx index c53c8e7cae2569..12cb60df2b1a69 100644 --- a/src/content/docs/workers/tutorials/openai-function-calls-workers/index.mdx +++ b/src/content/docs/workers/tutorials/openai-function-calls-workers/index.mdx @@ -98,7 +98,7 @@ async fetch(request, env, ctx) { }, ``` -Use [`wrangler secret put`](/workers/wrangler/commands/#put-3) to set `OPENAI_API_KEY`. This [secret's](/workers/configuration/secrets/) value is the API key you created earlier in the OpenAI dashboard: +Use [`wrangler secret put`](/workers/wrangler/commands/#secret-put) to set `OPENAI_API_KEY`. This [secret's](/workers/configuration/secrets/) value is the API key you created earlier in the OpenAI dashboard: ```sh npx wrangler secret put diff --git a/src/content/docs/workers/wrangler/commands.mdx b/src/content/docs/workers/wrangler/commands.mdx index 3346194f55b6e1..644d896394b3a1 100644 --- a/src/content/docs/workers/wrangler/commands.mdx +++ b/src/content/docs/workers/wrangler/commands.mdx @@ -7,13 +7,12 @@ head: description: Create, develop, and deploy your Cloudflare Workers with Wrangler commands. --- -import { TabItem, Tabs, Render, Type, MetaInfo } from "~/components"; +import { TabItem, Tabs, Render, Type, MetaInfo, WranglerCommand, PackageManagers } from "~/components"; Wrangler offers a number of commands to manage your Cloudflare Workers. - [`docs`](#docs) - Open this page in your default browser. - [`init`](#init) - Create a new project from a variety of web frameworks and templates. (Deprecated — use `npm create cloudflare@latest` instead) -- [`generate`](#generate) - Create a Wrangler project using an existing [Workers template](https://github.com/cloudflare/worker-template). - [`d1`](#d1) - Interact with D1. - [`vectorize`](#vectorize) - Interact with Vectorize indexes. - [`hyperdrive`](#hyperdrive) - Manage your Hyperdrives. @@ -68,25 +67,7 @@ wrangler [PARAMETERS] [OPTIONS] Since Cloudflare recommends [installing Wrangler locally](/workers/wrangler/install-and-update/) in your project(rather than globally), the way to run Wrangler will depend on your specific setup and package manager. - - -```sh -npx wrangler [PARAMETERS] [OPTIONS] -``` - - - -```sh -yarn wrangler [PARAMETERS] [OPTIONS] -``` - - - -```sh -pnpm wrangler [PARAMETERS] [OPTIONS] -``` - - + You can add Wrangler commands that you use often as scripts in your project's `package.json` file: @@ -103,148 +84,35 @@ You can add Wrangler commands that you use often as scripts in your project's `p You can then run them using your package manager of choice: - - -```sh -npm run deploy -``` - - - -```sh -yarn run deploy -``` - - - -```sh -pnpm run deploy -``` - - + --- -## `docs` - -Open the Cloudflare developer documentation in your default browser. - -```txt -wrangler docs [] -``` - -- `COMMAND` - - The Wrangler command you want to learn more about. This opens your default browser to the section of the documentation that describes the command. - -## `init` + -:::note + +:::caution The `init` command will be removed in a future version. Please use `npm create cloudflare@latest` instead. - -::: - -Create a new project via the [create-cloudflare-cli (C3) tool](/workers/get-started/guide/#1-create-a-new-worker-project). A variety of web frameworks are available to choose from as well as templates. Dependencies are installed by default, with the option to deploy your project immediately. - -```txt -wrangler init [] [OPTIONS] -``` - -- `NAME` - - The name of the Workers project. This is both the directory name and `name` property in the generated `wrangler.toml` [configuration](/workers/wrangler/configuration/) file. -- `--yes` - - Answer yes to any prompts for new projects. -- `--from-dash` - - Fetch a Worker initialized from the dashboard. This is done by passing the flag and the Worker name. `wrangler init --from-dash `. - - The `--from-dash` command will not automatically sync changes made to the dashboard after the command is used. Therefore, it is recommended that you continue using the CLI. - ---- - -## `generate` - -:::note - -This command has been deprecated as of [Wrangler v3](/workers/wrangler/migration/update-v2-to-v3/) and will be removed in a future version. - ::: -Create a new project using an existing [Workers template](https://github.com/cloudflare/workers-sdk/tree/main/templates/worker). - -```txt -wrangler generate [] [TEMPLATE] -``` - -- `NAME` - - The name of the Workers project. This is both the directory name and `name` property in the generated `wrangler.toml` [configuration](/workers/wrangler/configuration/) file. -- `TEMPLATE` - - The URL of a GitHub template, with a default [worker-template](https://github.com/cloudflare/worker-template). Browse a list of available templates on the [cloudflare/workers-sdk](https://github.com/cloudflare/workers-sdk/tree/main/templates#usage) repository. - --- ## `d1` Interact with Cloudflare's D1 service. -### `create` - -Creates a new D1 database, and provides the binding and UUID that you will put in your `wrangler.toml` file. - -```txt -wrangler d1 create [OPTIONS] -``` - -- `DATABASE_NAME` - - The name of the new D1 database. -- `--location` - - Provide an optional [location hint](/d1/configuration/data-location/) for your database leader. - - Available options include `weur` (Western Europe), `eeur` (Eastern Europe), `apac` (Asia Pacific), `oc` (Oceania), `wnam` (Western North America), and `enam` (Eastern North America). + -### `info` + -Get information about a D1 database, including the current database size and state. + -```txt -wrangler d1 info [OPTIONS] -``` - -- `DATABASE_NAME` - - The name of the D1 database to get information about. -- `--json` - - Return output as JSON rather than a table. - -### `list` - -List all D1 databases in your account. - -```txt -wrangler d1 list [OPTIONS] -``` - -- `--json` - - Return output as JSON rather than a table. + -### `delete` - -Delete a D1 database. - -```txt -wrangler d1 delete [OPTIONS] -``` - -- `DATABASE_NAME` - - The name of the D1 database to delete. -- `-y, --skip-confirmation` - - Skip deletion confirmation prompt. - -### `execute` - -Execute a query on a D1 database. - -```txt -wrangler d1 execute [OPTIONS] -``` + :::note @@ -252,81 +120,13 @@ You must provide either `--command` or `--file` for this command to run successf ::: -- `DATABASE_NAME` - - The name of the D1 database to execute a query on. -- `--command` - - The SQL query you wish to execute. -- `--file` - - Path to the SQL file you wish to execute. -- `-y, --yes` - - Answer `yes` to any prompts. -- `--local` - - Execute commands/files against a local database for use with [wrangler dev](#dev). -- `--remote` - - Execute commands/files against a remote D1 database for use with [wrangler dev --remote](#dev). -- `--persist-to` - - Specify directory to use for local persistence (for use in combination with `--local`). -- `--json` - - Return output as JSON rather than a table. -- `--preview` - - Execute commands/files against a preview D1 database (as defined by `preview_database_id` in [Wrangler.toml](/workers/wrangler/configuration/#d1-databases)). -- `--batch-size` - - Number of queries to send in a single batch. - -### `export` - -Export a D1 database or table's schema and/or content to a `.sql` file. - -```txt -wrangler d1 export [OPTIONS] -``` - -- `DATABASE_NAME` - - The name of the D1 database to export. -- `--remote` - - Execute commands/files against a remote D1 database for use with [wrangler dev --remote](#dev). -- `--output` - - Path to the SQL file for your export. -- `--table` - - The name of the table within a D1 database to export. -- `--no-data` - - Controls whether export SQL file contains database data. Note that `--no-data=true` is not recommended due to a known wrangler limitation that intreprets the value as false. -- `--no-schema` - - Controls whether export SQL file contains database schema. Note that `--no-schema=true` is not recommended due to a known wrangler limitation that intreprets the value as false. - -### `time-travel restore` - -Restore a database to a specific point-in-time using [Time Travel](/d1/reference/time-travel/). - -```txt -wrangler d1 time-travel restore [OPTIONS] -``` - -- `DATABASE_NAME` - - The name of the D1 database to execute a query on. -- `--bookmark` - - A D1 bookmark representing the state of a database at a specific point in time. -- `--timestamp` - - A UNIX timestamp or JavaScript date-time `string` within the last 30 days. -- `--json` - - Return output as JSON rather than a table. - -### `time-travel info` + -Inspect the current state of a database for a specific point-in-time using [Time Travel](/d1/reference/time-travel/). + -```txt -wrangler d1 time-travel info [OPTIONS] -``` + -- `DATABASE_NAME` - - The name of the D1 database to execute a query on. -- `--timestamp` - - A UNIX timestamp or JavaScript date-time `string` within the last 30 days. -- `--json` b - - Return output as JSON rather than a table. - -### `backup create` + :::caution @@ -335,16 +135,7 @@ This command only works on databases created during D1's alpha period. You can c This command will not work on databases that are created during the beta period, or after general availability (GA). Refer to [Time Travel](/d1/reference/time-travel/) in the D1 documentation for more information on D1's approach to backup and restores for databases created during the beta/GA period. ::: -Initiate a D1 backup. - -```txt -wrangler d1 backup create -``` - -- `DATABASE_NAME` - - The name of the D1 database to backup. - -### `backup list` + :::caution @@ -353,16 +144,7 @@ This command only works on databases created during D1's alpha period. You can c This command will not work on databases that are created during the beta period, or after general availability (GA). Refer to [Time Travel](/d1/reference/time-travel/) in the D1 documentation for more information on D1's approach to backup and restores for databases created during the beta/GA period. ::: -List all available backups. - -```txt -wrangler d1 backup list -``` - -- `DATABASE_NAME` - - The name of the D1 database to list the backups of. - -### `backup restore` + :::caution @@ -371,105 +153,20 @@ This command only works on databases created during D1's alpha period. You can c This command will not work on databases that are created during the beta period, or after general availability (GA). Refer to [Time Travel](/d1/reference/time-travel/) in the D1 documentation for more information on D1's approach to backup and restores for databases created during the beta/GA period. ::: -Restore a backup into a D1 database. - -```txt -wrangler d1 backup restore -``` - -- `DATABASE_NAME` - - The name of the D1 database to restore the backup into. -- `BACKUP_ID` - - The ID of the backup you wish to restore. - -### `backup download` + :::caution This command only works on databases created during D1's alpha period. You can check which version your database uses with `wrangler d1 info `. -This command will not work on databases that are created during the beta period, or after general availability (GA). To download existing data of a beta/GA database to your local machine refer to the `wrangler d1 export` command. Refer to [Time Travel](/d1/reference/time-travel/) in the D1 documentation for more information on D1's approach to backups for databases created during the beta/GA period. +This command will not work on databases that are created during the beta period, or after general availability (GA). Refer to [Time Travel](/d1/reference/time-travel/) in the D1 documentation for more information on D1's approach to backup and restores for databases created during the beta/GA period. ::: -Download existing data to your local machine. - -```txt -wrangler d1 backup download -``` - -- `DATABASE_NAME` - - The name of the D1 database you wish to download the backup of. -- `BACKUP_ID` - - The ID of the backup you wish to download. -- `--output` - - The `.sqlite3` file to write to (defaults to `'..sqlite3'`). - -### `migrations create` + -Create a new migration. + -This will generate a new versioned file inside the `migrations` folder. Name your migration file as a description of your change. This will make it easier for you to find your migration in the `migrations` folder. An example filename looks like: - -`0000_create_user_table.sql` - -The filename will include a version number and the migration name you specify below. - -```txt -wrangler d1 migrations create -``` - -- `DATABASE_NAME` - - The name of the D1 database you wish to create a migration for. -- `MIGRATION_NAME` - - A descriptive name for the migration you wish to create. - -### `migrations list` - -View a list of unapplied migration files. - -```txt -wrangler d1 migrations list [OPTIONS] -``` - -- `DATABASE_NAME` - - The name of the D1 database you wish to list unapplied migrations for. -- `--local` - - Show the list of unapplied migration files on your locally persisted D1 database. -- `--remote` - - Show the list of unapplied migration files on your remote D1 database. -- `--persist-to` - - Specify directory to use for local persistence (for use in combination with `--local`). -- `--preview` - - Show the list of unapplied migration files on your preview D1 database (as defined by `preview_database_id` in [`wrangler.toml`](/workers/wrangler/configuration/#d1-databases)). - -### `migrations apply` - -Apply any unapplied migrations. - -This command will prompt you to confirm the migrations you are about to apply. Confirm that you would like to proceed. After, a backup will be captured. - -The progress of each migration will be printed in the console. - -When running the apply command in a CI/CD environment or another non-interactive command line, the confirmation step will be skipped, but the backup will still be captured. - -If applying a migration results in an error, this migration will be rolled back, and the previous successful migration will remain applied. - -```txt -wrangler d1 migrations apply [OPTIONS] -``` - -- `DATABASE_NAME` - - The name of the D1 database you wish to apply your migrations on. -- `--local` - - Execute any unapplied migrations on your locally persisted D1 database. -- `--remote` - - Execute any unapplied migrations on your remote D1 database. -- `--persist-to` - - Specify directory to use for local persistence (for use in combination with `--local`). -- `--preview` - - Execute any unapplied migrations on your preview D1 database (as defined by `preview_database_id` in [`wrangler.toml`](/workers/wrangler/configuration/#d1-databases)). -- `--batch-size` - - Number of queries to send in a single batch. + --- @@ -485,204 +182,35 @@ Manage [Hyperdrive](/hyperdrive/) database configurations. Interact with a [Vectorize](/vectorize/) vector database. -### `create` - -Creates a new vector index, and provides the binding and name that you will put in your `wrangler.toml` file. - -```sh -npx wrangler vectorize create [--dimensions=] [--metric=] [--description=] -``` - -- `INDEX_NAME` - - The name of the new index to create. Must be unique for an account and cannot be changed after creation or reused after the deletion of an index. -- `--dimensions` - - The vector dimension width to configure the index for. Cannot be changed after creation. -- `--metric` - - The distance metric to use for calculating vector distance. Must be one of `cosine`, `euclidean`, or `dot-product`. -- `--description` - - A description for your index. -- `--deprecated-v1` - - Create a legacy Vectorize index. Please note that legacy Vectorize indexes are on a [deprecation path](/vectorize/reference/transition-vectorize-legacy). - -### `list` - -List all Vectorize indexes in your account, including the configured dimensions and distance metric. - -```sh -npx wrangler vectorize list -``` - -- `--deprecated-v1` - - List legacy Vectorize indexes. Please note that legacy Vectorize indexes are on a [deprecation path](/vectorize/reference/transition-vectorize-legacy). - -### `get` - -Get details about an individual index, including its configuration. + -```sh -npx wrangler vectorize get -``` - -- `INDEX_NAME` - - The name of the index to fetch details for. -- `--deprecated-v1` - - Get a legacy Vectorize index. Please note that legacy Vectorize indexes are on a [deprecation path](/vectorize/reference/transition-vectorize-legacy). - -### `info` - -Get some additional information about an individual index, including the vector count and details about the last processed mutation. - -```sh -npx wrangler vectorize info -``` - -- `INDEX_NAME` - - The name of the index to fetch details for. - -### `delete` - -Delete a Vectorize index. - -```sh -npx wrangler vectorize delete [OPTIONS] -``` - -- `INDEX_NAME` - - The name of the Vectorize index to delete. -- `--force` - - Skip confirmation when deleting the index (Note: This is not a recoverable operation). -- `--deprecated-v1` - - Delete a legacy Vectorize index. Please note that legacy Vectorize indexes are on a [deprecation path](/vectorize/reference/transition-vectorize-legacy). - -### `insert` - -Insert vectors into an index. - -```sh -npx wrangler vectorize insert [OPTIONS] -``` - -- `INDEX_NAME` - - The name of the Vectorize index to upsert vectors in. -- `--file` - - A file containing the vectors to insert in newline-delimited JSON (JSON) format. -- `--batch-size` - - The number of vectors to insert at a time (default: `1000`). -- `--deprecated-v1` - - Insert into a legacy Vectorize index. Please note that legacy Vectorize indexes are on a [deprecation path](/vectorize/reference/transition-vectorize-legacy). - -### `upsert` - -Upsert vectors into an index. Existing vectors in the index would be overwritten. - -```sh -npx wrangler vectorize upsert [OPTIONS] -``` - -- `INDEX_NAME` - - The name of the Vectorize index to upsert vectors in. -- `--file` - - A file containing the vectors to insert in newline-delimited JSON (JSON) format. -- `--batch-size` - - The number of vectors to insert at a time (default: `5000`). - -### `query` - -Query a Vectorize index for similar vectors. - -```sh -npx wrangler vectorize query [OPTIONS] -``` - -- `INDEX_NAME` - - The name of the Vectorize index to query. -- `--vector` - - Vector against which the Vectorize index is queried. -- `--top-k` - - The number of vectors to query (default: `5`). -- `--return-values` - - Enable to return vector values in the response (default: `false`). -- `--return-metadata` - - Enable to return vector metadata in the response. Must be one of `none`, `indexed`, or `all` (default: `none`). -- `--namespace` - - Query response to only include vectors from this namespace. -- `--filter` - - Filter vectors based on this metadata filter. Example: `'{ 'p1': 'abc', 'p2': { '$ne': true }, 'p3': 10, 'p4': false, 'nested.p5': 'abcd' }'` - -### `get-vectors` - -Fetch vectors from a Vectorize index using the provided ids. - -```sh -npx wrangler vectorize get-vectors [OPTIONS] -``` + -- `INDEX_NAME` - - The name of the Vectorize index from which vectors need to be fetched. -- `--ids` - - List of ids for which vectors must be fetched. + -### `delete-vectors` + -Delete vectors in a Vectorize index using the provided ids. + -```sh -npx wrangler vectorize delete-vectors [OPTIONS] -``` - -- `INDEX_NAME` - - The name of the Vectorize index from which vectors need to be deleted. -- `--ids` - - List of ids corresponding to the vectors that must be deleted. - -### `create-metadata-index` - -Enable metadata filtering on the specified property. - -```sh -npx wrangler vectorize create-metadata-index [OPTIONS] -``` - -- `INDEX_NAME` - - The name of the Vectorize index for which metadata index needs to be created. -- `--property-name` - - Metadata property for which metadata filtering should be enabled. -- `--type` - - Data type of the property. Must be one of `string`, `number`, or `boolean`. + -### `list-metadata-index` + -List metadata properties on which metadata filtering is enabled. + -```sh -npx wrangler vectorize list-metadata-index [OPTIONS] -``` - -- `INDEX_NAME` - - The name of the Vectorize index for which metadata indexes needs to be fetched. + -### `delete-metadata-index` + -Disable metadata filtering on the specified property. + -```sh -npx wrangler vectorize delete-metadata-index [OPTIONS] -``` + -- `INDEX_NAME` - - The name of the Vectorize index for which metadata index needs to be disabled. -- `--property-name` - - Metadata property for which metadata filtering should be disabled. + --- -## `dev` - -Start a local server for developing your Worker. - -```txt -wrangler dev [