wrangler 1.21.0

Command-line interface for all things Cloudflare Workers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
pub mod build;
pub mod config;
pub mod dev;
pub mod generate;
pub mod init;
pub mod kv;
pub mod login;
pub mod logout;
pub mod preview;
pub mod publish;
pub mod r2;
pub mod route;
pub mod secret;
pub mod subdomain;
pub mod tail;
pub mod whoami;

pub mod exec {
    pub use super::build::build;
    pub use super::config::configure;
    pub use super::dev::dev;
    pub use super::generate::generate;
    pub use super::init::init;
    pub use super::kv::kv_bulk;
    pub use super::kv::kv_key;
    pub use super::kv::kv_namespace;
    pub use super::login::login;
    pub use super::logout::logout;
    pub use super::preview::preview;
    pub use super::publish::publish;
    pub use super::r2::r2_bucket;
    pub use super::route::route;
    pub use super::secret::secret;
    pub use super::subdomain::subdomain;
    pub use super::tail::tail;
    pub use super::whoami::whoami;
}

use std::net::IpAddr;
use std::path::PathBuf;
use std::str::FromStr;

use crate::commands::dev::Protocol;
use crate::commands::tail::websocket::TailFormat;
use crate::preview::HttpMethod;
use crate::settings::toml::migrations::{
    DurableObjectsMigration, Migration, MigrationTag, Migrations, RenameClass, TransferClass,
};
use crate::settings::toml::TargetType;

use clap::AppSettings;
use structopt::StructOpt;
use url::Url;

#[derive(Debug, Clone, StructOpt)]
#[structopt(
    name = "wrangler",
    author = "The Wrangler Team <wrangler@cloudflare.com>",
    setting = AppSettings::ArgRequiredElseHelp,
    setting = AppSettings::DeriveDisplayOrder,
    setting = AppSettings::VersionlessSubcommands,
)]
pub struct Cli {
    /// Toggle verbose output (when applicable)
    #[structopt(long, global = true)]
    pub verbose: bool,

    /// Path to configuration file.
    #[structopt(long, short = "c", default_value = "wrangler.toml", global = true)]
    pub config: PathBuf,

    /// Environment to perform a command on.
    #[structopt(name = "env", long, short = "e", global = true)]
    pub environment: Option<String>,

    #[structopt(subcommand)]
    pub command: Command,
}

#[derive(Debug, Clone, StructOpt)]
pub enum Command {
    /// Interact with your Workers KV Namespaces
    #[structopt(name = "kv:namespace", setting = AppSettings::SubcommandRequiredElseHelp)]
    KvNamespace(kv::KvNamespace),

    /// Individually manage Workers KV key-value pairs
    #[structopt(name = "kv:key", setting = AppSettings::SubcommandRequiredElseHelp)]
    KvKey(kv::KvKey),

    /// Interact with multiple Workers KV key-value pairs at once
    #[structopt(name = "kv:bulk", setting = AppSettings::SubcommandRequiredElseHelp)]
    KvBulk(kv::KvBulk),

    /// Interact with your Workers R2 Buckets
    #[structopt(setting = AppSettings::SubcommandRequiredElseHelp)]
    R2(r2::R2),

    /// List or delete worker routes.
    #[structopt(name = "route", setting = AppSettings::SubcommandRequiredElseHelp)]
    Route(route::Route),

    /// Generate a secret that can be referenced in the worker script
    #[structopt(name = "secret", setting = AppSettings::SubcommandRequiredElseHelp)]
    Secret(secret::Secret),

    /// Generate a new worker project
    Generate {
        /// The name of your worker!
        #[structopt(index = 1, default_value = "worker")]
        name: String,

        /// A link to a GitHub template! Defaults to https://github.com/cloudflare/worker-template
        #[structopt(index = 2)]
        template: Option<String>,

        /// The type of project you want generated
        #[structopt(name = "type", long, short = "t")]
        target_type: Option<TargetType>,

        /// Initializes a Workers Sites project. Overrides 'type' and 'template'
        #[structopt(long, short = "s")]
        site: bool,
    },

    /// Create a wrangler.toml for an existing project
    Init {
        /// The name of your worker!
        #[structopt(index = 1)]
        name: Option<String>,

        /// The type of project you want generated
        #[structopt(name = "type", long, short = "t")]
        target_type: Option<TargetType>,

        /// Initializes a Workers Sites project. Overrides `type` and `template`
        #[structopt(long, short = "s")]
        site: bool,
    },

    /// Build your worker
    Build,

    /// Preview your code temporarily on cloudflareworkers.com
    Preview {
        /// Type of request to preview your worker with (get, post)
        #[structopt(index = 1, default_value = "get")]
        method: HttpMethod,

        /// URL to open in the worker preview
        #[structopt(short = "u", long, default_value = "https://example.com")]
        url: Url,

        /// Body string to post to your preview worker request
        #[structopt(index = 2)]
        body: Option<String>,

        /// Watch your project for changes and update the preview automagically
        #[structopt(long)]
        watch: bool,

        /// Don't open the browser on preview
        #[structopt(long)]
        headless: bool,
    },

    /// Start a local server for developing your worker
    Dev {
        /// Host to forward requests to, defaults to the zone of project or to
        /// tutorial.cloudflareworkers.com if unauthenticated.
        #[structopt(long, short = "h")]
        host: Option<String>,

        /// IP to listen on. Defaults to 127.0.0.1
        #[structopt(long, short = "i")]
        ip: Option<IpAddr>,

        /// Port to listen on. Defaults to 8787
        #[structopt(long, short = "p")]
        port: Option<u16>,

        /// Sets the protocol on which the wrangler dev listens, by default this is http
        /// but can be set to https
        #[structopt(name = "local-protocol")]
        local_protocol: Option<Protocol>,

        /// Sets the protocol on which requests are sent to the host, by default this is https
        /// but can be set to http
        #[structopt(name = "upstream-protocol")]
        upstream_protocol: Option<Protocol>,

        /// Inspect the worker using Chrome DevTools
        #[structopt(long)]
        inspect: bool,

        /// Run wrangler dev unauthenticated
        #[structopt(long)]
        unauthenticated: bool,
    },

    /// Publish your worker to the orange cloud
    #[structopt(name = "publish")]
    Publish {
        /// [deprecated] alias of wrangler publish
        #[structopt(long, hidden = true)]
        release: bool,

        #[structopt(possible_value = "json")]
        output: Option<String>,

        #[structopt(flatten)]
        migration: AdhocMigration,
    },

    /// Authenticate Wrangler with a Cloudflare API Token or Global API Key
    #[structopt(name = "config")]
    Config {
        /// Use an email and global API key for authentication.
        /// This is not recommended; use API tokens (the default) if possible
        #[structopt(name = "api-key", long)]
        api_key: bool,
        /// Do not verify provided credentials before writing out Wrangler config file
        #[structopt(name = "no-verify", long)]
        no_verify: bool,
    },

    /// Configure your workers.dev subdomain
    #[structopt(name = "subdomain")]
    Subdomain {
        /// The subdomain on workers.dev you'd like to reserve
        #[structopt(name = "name", index = 1)]
        name: Option<String>,
    },

    /// Retrieve your user info and test your auth config
    #[structopt(name = "whoami")]
    Whoami,

    /// View a stream of logs from a published worker
    #[structopt(name = "tail")]
    Tail {
        /// Name of the worker to tail
        #[structopt(index = 1)]
        name: Option<String>,

        /// Output format for log messages
        #[structopt(long, short = "f", default_value = "json", possible_values = &["json", "pretty"])]
        format: TailFormat,

        /// Stops the tail after receiving the first log (useful for testing)
        #[structopt(long)]
        once: bool,

        /// Adds a sampling rate (0.01 for 1%)
        #[structopt(long = "sampling-rate", default_value = "1")]
        sampling_rate: f64,

        /// Filter by invocation status
        #[structopt(long, possible_values = &["ok", "error", "canceled"])]
        status: Vec<String>,

        /// Filter by HTTP method
        #[structopt(long)]
        method: Vec<String>,

        /// Filter by HTTP header
        #[structopt(long)]
        header: Vec<String>,

        /// Filter by IP address ("self" to filter your own IP address)
        #[structopt(long = "ip-address", parse(try_from_str = parse_ip_address))]
        ip_address: Vec<String>,

        /// Filter by a text match in console.log messages
        #[structopt(long)]
        search: Option<String>,

        /// Set the URL to forward log messages
        #[structopt(hidden = true)]
        url: Option<Url>,

        /// Deprecated, no longer used.
        #[structopt(hidden = true, long = "port", short = "p")]
        tunnel_port: Option<u16>,

        /// Deprecated, no longer used.
        #[structopt(hidden = true, long = "metrics")]
        metrics_port: Option<u16>,
    },

    /// Authenticate wrangler with your Cloudflare username and password
    #[structopt(name = "login")]
    Login {
        /// Allows to choose set of scopes
        #[structopt(name = "scopes", long, possible_values = login::SCOPES_LIST.as_ref())]
        scopes: Vec<String>,

        /// List all scopes
        #[structopt(name = "scopes-list", long)]
        scopes_list: bool,
    },

    /// Logout from your current authentication method and remove any configuration files.
    /// It does not logout if you have authenticated wrangler through environment variables.
    #[structopt(name = "logout")]
    Logout,
}

#[derive(Debug, Clone, StructOpt)]
pub struct AdhocMigration {
    /// Allow durable objects to be created from a class in your script
    #[structopt(name = "new-class", long, number_of_values = 1)]
    new_class: Vec<String>,

    /// Delete all durable objects associated with a class in your script
    #[structopt(name = "delete-class", long, number_of_values = 1)]
    delete_class: Vec<String>,

    /// Rename a durable object class
    #[structopt(name = "rename-class", long, number_of_values = 2, value_names(&["from class", "to class"]))]
    rename_class: Vec<String>,

    /// Transfer all durable objects associated with a class in another script to a class in
    /// this script
    #[structopt(name = "transfer-class", long, number_of_values = 3, value_names(&["from script", "from class", "to class"]))]
    transfer_class: Vec<String>,

    /// Specify the existing migration tag for the script.
    #[structopt(name = "old-tag", long)]
    old_tag: Option<String>,

    /// Specify the new migration tag for the script
    #[structopt(name = "new-tag", long)]
    new_tag: Option<String>,
}

impl AdhocMigration {
    pub fn into_migrations(self) -> Option<Migrations> {
        let migration = DurableObjectsMigration {
            new_classes: self.new_class,
            deleted_classes: self.delete_class,
            renamed_classes: self
                .rename_class
                .chunks_exact(2)
                .map(|chunk| {
                    let (from, to) = if let [from, to] = chunk {
                        (from.clone(), to.clone())
                    } else {
                        unreachable!("Chunks exact returned a slice with a length not equal to 2")
                    };

                    RenameClass { from, to }
                })
                .collect(),
            transferred_classes: self
                .transfer_class
                .chunks_exact(3)
                .map(|chunk| {
                    let (from_script, from, to) = if let [from_script, from, to] = chunk {
                        (from_script.clone(), from.clone(), to.clone())
                    } else {
                        unreachable!("Chunks exact returned a slice with a length not equal to 3")
                    };

                    TransferClass {
                        from,
                        from_script,
                        to,
                    }
                })
                .collect(),
        };
        let is_migration_empty = migration.new_classes.is_empty()
            && migration.deleted_classes.is_empty()
            && migration.renamed_classes.is_empty()
            && migration.transferred_classes.is_empty();

        if !is_migration_empty || self.old_tag.is_some() || self.new_tag.is_some() {
            let migration = if !is_migration_empty {
                Some(Migration {
                    durable_objects: migration,
                })
            } else {
                None
            };

            Some(Migrations::Adhoc {
                script_tag: MigrationTag::Unknown,
                provided_old_tag: self.old_tag,
                new_tag: self.new_tag,
                migration,
            })
        } else {
            None
        }
    }
}

fn parse_ip_address(input: &str) -> Result<String, anyhow::Error> {
    match input {
        "self" => Ok(String::from("self")),
        address => match IpAddr::from_str(address) {
            Ok(_) => Ok(address.to_owned()),
            Err(err) => anyhow::bail!("{}: {}", err, input),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rename_class(tag: &str) -> RenameClass {
        RenameClass {
            from: format!("renameFrom{}", tag),
            to: format!("renameTo{}", tag),
        }
    }

    fn transfer_class(tag: &str) -> TransferClass {
        TransferClass {
            from: format!("transferFromClass{}", tag),
            from_script: format!("transferFromScript{}", tag),
            to: format!("transferToClass{}", tag),
        }
    }

    #[test]
    fn adhoc_migration_parsing() {
        let command = Cli::from_iter(&[
            "wrangler",
            "publish",
            "--old-tag",
            "oldTag",
            "--new-tag",
            "newTag",
            "--new-class",
            "newA",
            "--new-class",
            "newB",
            "--delete-class",
            "deleteA",
            "--delete-class",
            "deleteB",
            "--rename-class",
            "renameFromA",
            "renameToA",
            "--rename-class",
            "renameFromB",
            "renameToB",
            "--transfer-class",
            "transferFromScriptA",
            "transferFromClassA",
            "transferToClassA",
            "--transfer-class",
            "transferFromScriptB",
            "transferFromClassB",
            "transferToClassB",
        ])
        .command;

        if let Command::Publish { migration, .. } = command {
            assert_eq!(
                migration.into_migrations(),
                Some(Migrations::Adhoc {
                    script_tag: MigrationTag::Unknown,
                    provided_old_tag: Some(String::from("oldTag")),
                    new_tag: Some(String::from("newTag")),
                    migration: Some(Migration {
                        durable_objects: DurableObjectsMigration {
                            new_classes: vec![String::from("newA"), String::from("newB")],
                            deleted_classes: vec![String::from("deleteA"), String::from("deleteB")],
                            renamed_classes: vec![rename_class("A"), rename_class("B")],
                            transferred_classes: vec![transfer_class("A"), transfer_class("B")],
                        }
                    })
                })
            );
        } else {
            assert!(false, "Unkown command {:?}", command)
        }
    }
}