Skip to main content

tauri_utils/config_v1/
mod.rs

1// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! The Tauri configuration used at runtime.
6//!
7//! It is pulled from a `tauri.conf.json` file and the [`Config`] struct is generated at compile time.
8//!
9//! # Stability
10//! This is a core functionality that is not considered part of the stable API.
11//! If you use it, note that it may include breaking changes in the future.
12
13use semver::Version;
14use serde::{
15  Deserialize, Serialize, Serializer,
16  de::{Deserializer, Error as DeError, Visitor},
17};
18use serde_json::Value as JsonValue;
19use serde_with::skip_serializing_none;
20use url::Url;
21
22use std::{
23  collections::HashMap,
24  fmt::{self, Display},
25  fs::read_to_string,
26  path::PathBuf,
27  str::FromStr,
28};
29
30/// Items to help with parsing content into a [`Config`].
31pub mod parse;
32
33fn default_true() -> bool {
34  true
35}
36
37/// An URL to open on a Tauri webview window.
38#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
39#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
40#[serde(untagged)]
41#[non_exhaustive]
42pub enum WindowUrl {
43  /// An external URL.
44  External(Url),
45  /// The path portion of an app URL.
46  /// For instance, to load `tauri://localhost/users/john`,
47  /// you can simply provide `users/john` in this configuration.
48  App(PathBuf),
49}
50
51impl fmt::Display for WindowUrl {
52  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53    match self {
54      Self::External(url) => write!(f, "{url}"),
55      Self::App(path) => write!(f, "{}", path.display()),
56    }
57  }
58}
59
60impl Default for WindowUrl {
61  fn default() -> Self {
62    Self::App("index.html".into())
63  }
64}
65
66/// A bundle referenced by tauri-bundler.
67#[derive(Debug, PartialEq, Eq, Clone)]
68#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
69#[cfg_attr(feature = "schema", schemars(rename_all = "lowercase"))]
70pub enum BundleType {
71  /// The debian bundle (.deb).
72  Deb,
73  /// The AppImage bundle (.appimage).
74  AppImage,
75  /// The Microsoft Installer bundle (.msi).
76  Msi,
77  /// The NSIS bundle (.exe).
78  Nsis,
79  /// The macOS application bundle (.app).
80  App,
81  /// The Apple Disk Image bundle (.dmg).
82  Dmg,
83  /// The Tauri updater bundle.
84  Updater,
85}
86
87impl Display for BundleType {
88  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89    write!(
90      f,
91      "{}",
92      match self {
93        Self::Deb => "deb",
94        Self::AppImage => "appimage",
95        Self::Msi => "msi",
96        Self::Nsis => "nsis",
97        Self::App => "app",
98        Self::Dmg => "dmg",
99        Self::Updater => "updater",
100      }
101    )
102  }
103}
104
105impl Serialize for BundleType {
106  fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
107  where
108    S: Serializer,
109  {
110    serializer.serialize_str(self.to_string().as_ref())
111  }
112}
113
114impl<'de> Deserialize<'de> for BundleType {
115  fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
116  where
117    D: Deserializer<'de>,
118  {
119    let s = String::deserialize(deserializer)?;
120    match s.to_lowercase().as_str() {
121      "deb" => Ok(Self::Deb),
122      "appimage" => Ok(Self::AppImage),
123      "msi" => Ok(Self::Msi),
124      "nsis" => Ok(Self::Nsis),
125      "app" => Ok(Self::App),
126      "dmg" => Ok(Self::Dmg),
127      "updater" => Ok(Self::Updater),
128      _ => Err(DeError::custom(format!("unknown bundle target '{s}'"))),
129    }
130  }
131}
132
133/// Targets to bundle. Each value is case insensitive.
134#[derive(Debug, PartialEq, Eq, Clone, Default)]
135pub enum BundleTarget {
136  /// Bundle all targets.
137  #[default]
138  All,
139  /// A list of bundle targets.
140  List(Vec<BundleType>),
141  /// A single bundle target.
142  One(BundleType),
143}
144
145#[cfg(feature = "schema")]
146fn add_description(
147  mut schema: schemars::Schema,
148  description: impl Into<String>,
149) -> schemars::Schema {
150  let value = description.into();
151  if !value.is_empty() {
152    schema.insert("description".to_string(), serde_json::Value::String(value));
153  }
154  schema
155}
156
157#[cfg(feature = "schema")]
158impl schemars::JsonSchema for BundleTarget {
159  fn schema_name() -> std::borrow::Cow<'static, str> {
160    "BundleTarget".into()
161  }
162
163  fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
164    let any_of: Vec<serde_json::Value> = vec![
165      serde_json::json!({
166        "enum": ["all"],
167        "description": "Bundle all targets."
168      }),
169      serde_json::Value::from(add_description(
170        generator.subschema_for::<Vec<BundleType>>(),
171        "A list of bundle targets.",
172      )),
173      serde_json::Value::from(add_description(
174        generator.subschema_for::<BundleType>(),
175        "A single bundle target.",
176      )),
177    ];
178
179    schemars::json_schema!({
180      "anyOf": any_of,
181      "description": "Targets to bundle. Each value is case insensitive."
182    })
183  }
184}
185
186impl Serialize for BundleTarget {
187  fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
188  where
189    S: Serializer,
190  {
191    match self {
192      Self::All => serializer.serialize_str("all"),
193      Self::List(l) => l.serialize(serializer),
194      Self::One(t) => serializer.serialize_str(t.to_string().as_ref()),
195    }
196  }
197}
198
199impl<'de> Deserialize<'de> for BundleTarget {
200  fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
201  where
202    D: Deserializer<'de>,
203  {
204    #[derive(Deserialize, Serialize)]
205    #[serde(untagged)]
206    pub enum BundleTargetInner {
207      List(Vec<BundleType>),
208      One(BundleType),
209      All(String),
210    }
211
212    match BundleTargetInner::deserialize(deserializer)? {
213      BundleTargetInner::All(s) if s.to_lowercase() == "all" => Ok(Self::All),
214      BundleTargetInner::All(t) => Err(DeError::custom(format!("invalid bundle type {t}"))),
215      BundleTargetInner::List(l) => Ok(Self::List(l)),
216      BundleTargetInner::One(t) => Ok(Self::One(t)),
217    }
218  }
219}
220
221/// Configuration for AppImage bundles.
222///
223/// See more: https://tauri.app/v1/api/config#appimageconfig
224#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
225#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
226#[serde(rename_all = "camelCase", deny_unknown_fields)]
227pub struct AppImageConfig {
228  /// Include additional gstreamer dependencies needed for audio and video playback.
229  /// This increases the bundle size by ~15-35MB depending on your build system.
230  #[serde(default, alias = "bundle-media-framework")]
231  pub bundle_media_framework: bool,
232}
233
234/// Configuration for Debian (.deb) bundles.
235///
236/// See more: https://tauri.app/v1/api/config#debconfig
237#[skip_serializing_none]
238#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
239#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
240#[serde(rename_all = "camelCase", deny_unknown_fields)]
241pub struct DebConfig {
242  /// The list of deb dependencies your application relies on.
243  pub depends: Option<Vec<String>>,
244  /// The files to include on the package.
245  #[serde(default)]
246  pub files: HashMap<PathBuf, PathBuf>,
247  /// Path to a custom desktop file Handlebars template.
248  ///
249  /// Available variables: `categories`, `comment` (optional), `exec`, `icon` and `name`.
250  pub desktop_template: Option<PathBuf>,
251  /// Define the section in Debian Control file. See : https://www.debian.org/doc/debian-policy/ch-archive.html#s-subsections
252  pub section: Option<String>,
253  /// Change the priority of the Debian Package. By default, it is set to `optional`.
254  /// Recognized Priorities as of now are :  `required`, `important`, `standard`, `optional`, `extra`
255  pub priority: Option<String>,
256  /// Path of the uncompressed Changelog file, to be stored at /usr/share/doc/package-name/changelog.gz. See
257  /// https://www.debian.org/doc/debian-policy/ch-docs.html#changelog-files-and-release-notes
258  pub changelog: Option<PathBuf>,
259}
260
261fn de_minimum_system_version<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
262where
263  D: Deserializer<'de>,
264{
265  let version = Option::<String>::deserialize(deserializer)?;
266  match version {
267    Some(v) if v.is_empty() => Ok(minimum_system_version()),
268    e => Ok(e),
269  }
270}
271
272/// Configuration for the macOS bundles.
273///
274/// See more: https://tauri.app/v1/api/config#macconfig
275#[skip_serializing_none]
276#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
277#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
278#[serde(rename_all = "camelCase", deny_unknown_fields)]
279pub struct MacConfig {
280  /// A list of strings indicating any macOS X frameworks that need to be bundled with the application.
281  ///
282  /// If a name is used, ".framework" must be omitted and it will look for standard install locations. You may also use a path to a specific framework.
283  pub frameworks: Option<Vec<String>>,
284  /// A version string indicating the minimum macOS X version that the bundled application supports. Defaults to `10.13`.
285  ///
286  /// Setting it to `null` completely removes the `LSMinimumSystemVersion` field on the bundle's `Info.plist`
287  /// and the `MACOSX_DEPLOYMENT_TARGET` environment variable.
288  ///
289  /// An empty string is considered an invalid value so the default value is used.
290  #[serde(
291    deserialize_with = "de_minimum_system_version",
292    default = "minimum_system_version",
293    alias = "minimum-system-version"
294  )]
295  pub minimum_system_version: Option<String>,
296  /// Allows your application to communicate with the outside world.
297  /// It should be a lowercase, without port and protocol domain name.
298  #[serde(alias = "exception-domain")]
299  pub exception_domain: Option<String>,
300  /// The path to the license file to add to the DMG bundle.
301  pub license: Option<String>,
302  /// Identity to use for code signing.
303  #[serde(alias = "signing-identity")]
304  pub signing_identity: Option<String>,
305  /// Provider short name for notarization.
306  #[serde(alias = "provider-short-name")]
307  pub provider_short_name: Option<String>,
308  /// Path to the entitlements file.
309  pub entitlements: Option<String>,
310}
311
312impl Default for MacConfig {
313  fn default() -> Self {
314    Self {
315      frameworks: None,
316      minimum_system_version: minimum_system_version(),
317      exception_domain: None,
318      license: None,
319      signing_identity: None,
320      provider_short_name: None,
321      entitlements: None,
322    }
323  }
324}
325
326fn minimum_system_version() -> Option<String> {
327  Some("10.13".into())
328}
329
330/// Configuration for a target language for the WiX build.
331///
332/// See more: https://tauri.app/v1/api/config#wixlanguageconfig
333#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
334#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
335#[serde(rename_all = "camelCase", deny_unknown_fields)]
336pub struct WixLanguageConfig {
337  /// The path to a locale (`.wxl`) file. See <https://wixtoolset.org/documentation/manual/v3/howtos/ui_and_localization/build_a_localized_version.html>.
338  #[serde(alias = "locale-path")]
339  pub locale_path: Option<String>,
340}
341
342/// The languages to build using WiX.
343#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
344#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
345#[serde(untagged)]
346pub enum WixLanguage {
347  /// A single language to build, without configuration.
348  One(String),
349  /// A list of languages to build, without configuration.
350  List(Vec<String>),
351  /// A map of languages and its configuration.
352  Localized(HashMap<String, WixLanguageConfig>),
353}
354
355impl Default for WixLanguage {
356  fn default() -> Self {
357    Self::One("en-US".into())
358  }
359}
360
361/// Configuration for the MSI bundle using WiX.
362///
363/// See more: https://tauri.app/v1/api/config#wixconfig
364#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
365#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
366#[serde(rename_all = "camelCase", deny_unknown_fields)]
367pub struct WixConfig {
368  /// The installer languages to build. See <https://docs.microsoft.com/en-us/windows/win32/msi/localizing-the-error-and-actiontext-tables>.
369  #[serde(default)]
370  pub language: WixLanguage,
371  /// A custom .wxs template to use.
372  pub template: Option<PathBuf>,
373  /// A list of paths to .wxs files with WiX fragments to use.
374  #[serde(default, alias = "fragment-paths")]
375  pub fragment_paths: Vec<PathBuf>,
376  /// The ComponentGroup element ids you want to reference from the fragments.
377  #[serde(default, alias = "component-group-refs")]
378  pub component_group_refs: Vec<String>,
379  /// The Component element ids you want to reference from the fragments.
380  #[serde(default, alias = "component-refs")]
381  pub component_refs: Vec<String>,
382  /// The FeatureGroup element ids you want to reference from the fragments.
383  #[serde(default, alias = "feature-group-refs")]
384  pub feature_group_refs: Vec<String>,
385  /// The Feature element ids you want to reference from the fragments.
386  #[serde(default, alias = "feature-refs")]
387  pub feature_refs: Vec<String>,
388  /// The Merge element ids you want to reference from the fragments.
389  #[serde(default, alias = "merge-refs")]
390  pub merge_refs: Vec<String>,
391  /// Disables the Webview2 runtime installation after app install.
392  ///
393  /// Will be removed in v2, prefer the [`WindowsConfig::webview_install_mode`] option.
394  #[serde(default, alias = "skip-webview-install")]
395  pub skip_webview_install: bool,
396  /// The path to the license file to render on the installer.
397  ///
398  /// Must be an RTF file, so if a different extension is provided, we convert it to the RTF format.
399  pub license: Option<PathBuf>,
400  /// Create an elevated update task within Windows Task Scheduler.
401  #[serde(default, alias = "enable-elevated-update-task")]
402  pub enable_elevated_update_task: bool,
403  /// Path to a bitmap file to use as the installation user interface banner.
404  /// This bitmap will appear at the top of all but the first page of the installer.
405  ///
406  /// The required dimensions are 493px × 58px.
407  #[serde(alias = "banner-path")]
408  pub banner_path: Option<PathBuf>,
409  /// Path to a bitmap file to use on the installation user interface dialogs.
410  /// It is used on the welcome and completion dialogs.
411  ///
412  /// The required dimensions are 493px × 312px.
413  #[serde(alias = "dialog-image-path")]
414  pub dialog_image_path: Option<PathBuf>,
415}
416
417/// Compression algorithms used in the NSIS installer.
418///
419/// See <https://nsis.sourceforge.io/Reference/SetCompressor>
420#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
421#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
422#[serde(rename_all = "camelCase", deny_unknown_fields)]
423pub enum NsisCompression {
424  /// ZLIB uses the deflate algorithm, it is a quick and simple method. With the default compression level it uses about 300 KB of memory.
425  Zlib,
426  /// BZIP2 usually gives better compression ratios than ZLIB, but it is a bit slower and uses more memory. With the default compression level it uses about 4 MB of memory.
427  Bzip2,
428  /// LZMA (default) is a new compression method that gives very good compression ratios. The decompression speed is high (10-20 MB/s on a 2 GHz CPU), the compression speed is lower. The memory size that will be used for decompression is the dictionary size plus a few KBs, the default is 8 MB.
429  Lzma,
430}
431
432/// Configuration for the Installer bundle using NSIS.
433#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
434#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
435#[serde(rename_all = "camelCase", deny_unknown_fields)]
436pub struct NsisConfig {
437  /// A custom .nsi template to use.
438  pub template: Option<PathBuf>,
439  /// The path to the license file to render on the installer.
440  pub license: Option<PathBuf>,
441  /// The path to a bitmap file to display on the header of installers pages.
442  ///
443  /// The recommended dimensions are 150px x 57px.
444  #[serde(alias = "header-image")]
445  pub header_image: Option<PathBuf>,
446  /// The path to a bitmap file for the Welcome page and the Finish page.
447  ///
448  /// The recommended dimensions are 164px x 314px.
449  #[serde(alias = "sidebar-image")]
450  pub sidebar_image: Option<PathBuf>,
451  /// The path to an icon file used as the installer icon.
452  #[serde(alias = "install-icon")]
453  pub installer_icon: Option<PathBuf>,
454  /// Whether the installation will be for all users or just the current user.
455  #[serde(default, alias = "install-mode")]
456  pub install_mode: NSISInstallerMode,
457  /// A list of installer languages.
458  /// By default the OS language is used. If the OS language is not in the list of languages, the first language will be used.
459  /// To allow the user to select the language, set `display_language_selector` to `true`.
460  ///
461  /// See <https://github.com/kichik/nsis/tree/9465c08046f00ccb6eda985abbdbf52c275c6c4d/Contrib/Language%20files> for the complete list of languages.
462  pub languages: Option<Vec<String>>,
463  /// A key-value pair where the key is the language and the
464  /// value is the path to a custom `.nsh` file that holds the translated text for tauri's custom messages.
465  ///
466  /// See <https://github.com/tauri-apps/tauri/blob/dev/tooling/bundler/src/bundle/windows/templates/nsis-languages/English.nsh> for an example `.nsh` file.
467  ///
468  /// **Note**: the key must be a valid NSIS language and it must be added to [`NsisConfig`] languages array,
469  pub custom_language_files: Option<HashMap<String, PathBuf>>,
470  /// Whether to display a language selector dialog before the installer and uninstaller windows are rendered or not.
471  /// By default the OS language is selected, with a fallback to the first language in the `languages` array.
472  #[serde(default, alias = "display-language-selector")]
473  pub display_language_selector: bool,
474  /// Set the compression algorithm used to compress files in the installer.
475  ///
476  /// See <https://nsis.sourceforge.io/Reference/SetCompressor>
477  pub compression: Option<NsisCompression>,
478}
479
480/// Install Modes for the NSIS installer.
481#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Default)]
482#[serde(rename_all = "camelCase", deny_unknown_fields)]
483#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
484pub enum NSISInstallerMode {
485  /// Default mode for the installer.
486  ///
487  /// Install the app by default in a directory that doesn't require Administrator access.
488  ///
489  /// Installer metadata will be saved under the `HKCU` registry path.
490  #[default]
491  CurrentUser,
492  /// Install the app by default in the `Program Files` folder directory requires Administrator
493  /// access for the installation.
494  ///
495  /// Installer metadata will be saved under the `HKLM` registry path.
496  PerMachine,
497  /// Combines both modes and allows the user to choose at install time
498  /// whether to install for the current user or per machine. Note that this mode
499  /// will require Administrator access even if the user wants to install it for the current user only.
500  ///
501  /// Installer metadata will be saved under the `HKLM` or `HKCU` registry path based on the user's choice.
502  Both,
503}
504
505/// Install modes for the Webview2 runtime.
506/// Note that for the updater bundle [`Self::DownloadBootstrapper`] is used.
507///
508/// For more information see <https://tauri.app/v1/guides/building/windows>.
509#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
510#[serde(tag = "type", rename_all = "camelCase", deny_unknown_fields)]
511#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
512pub enum WebviewInstallMode {
513  /// Do not install the Webview2 as part of the Windows Installer.
514  Skip,
515  /// Download the bootstrapper and run it.
516  /// Requires an internet connection.
517  /// Results in a smaller installer size, but is not recommended on Windows 7.
518  DownloadBootstrapper {
519    /// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
520    #[serde(default = "default_true")]
521    silent: bool,
522  },
523  /// Embed the bootstrapper and run it.
524  /// Requires an internet connection.
525  /// Increases the installer size by around 1.8MB, but offers better support on Windows 7.
526  EmbedBootstrapper {
527    /// Instructs the installer to run the bootstrapper in silent mode. Defaults to `true`.
528    #[serde(default = "default_true")]
529    silent: bool,
530  },
531  /// Embed the offline installer and run it.
532  /// Does not require an internet connection.
533  /// Increases the installer size by around 127MB.
534  OfflineInstaller {
535    /// Instructs the installer to run the installer in silent mode. Defaults to `true`.
536    #[serde(default = "default_true")]
537    silent: bool,
538  },
539  /// Embed a fixed webview2 version and use it at runtime.
540  /// Increases the installer size by around 180MB.
541  FixedRuntime {
542    /// The path to the fixed runtime to use.
543    ///
544    /// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
545    /// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
546    path: PathBuf,
547  },
548}
549
550impl Default for WebviewInstallMode {
551  fn default() -> Self {
552    Self::DownloadBootstrapper { silent: true }
553  }
554}
555
556/// Windows bundler configuration.
557///
558/// See more: https://tauri.app/v1/api/config#windowsconfig
559#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
560#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
561#[serde(rename_all = "camelCase", deny_unknown_fields)]
562pub struct WindowsConfig {
563  /// Specifies the file digest algorithm to use for creating file signatures.
564  /// Required for code signing. SHA-256 is recommended.
565  #[serde(alias = "digest-algorithm")]
566  pub digest_algorithm: Option<String>,
567  /// Specifies the SHA1 hash of the signing certificate.
568  #[serde(alias = "certificate-thumbprint")]
569  pub certificate_thumbprint: Option<String>,
570  /// Server to use during timestamping.
571  #[serde(alias = "timestamp-url")]
572  pub timestamp_url: Option<String>,
573  /// Whether to use Time-Stamp Protocol (TSP, a.k.a. RFC 3161) for the timestamp server. Your code signing provider may
574  /// use a TSP timestamp server, like e.g. SSL.com does. If so, enable TSP by setting to true.
575  #[serde(default)]
576  pub tsp: bool,
577  /// The installation mode for the Webview2 runtime.
578  #[serde(default, alias = "webview-install-mode")]
579  pub webview_install_mode: WebviewInstallMode,
580  /// Path to the webview fixed runtime to use. Overwrites [`Self::webview_install_mode`] if set.
581  ///
582  /// Will be removed in v2, prefer the [`Self::webview_install_mode`] option.
583  ///
584  /// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
585  /// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
586  #[serde(alias = "webview-fixed-runtime-path")]
587  pub webview_fixed_runtime_path: Option<PathBuf>,
588  /// Validates a second app installation, blocking the user from installing an older version if set to `false`.
589  ///
590  /// For instance, if `1.2.1` is installed, the user won't be able to install app version `1.2.0` or `1.1.5`.
591  ///
592  /// The default value of this flag is `true`.
593  #[serde(default = "default_true", alias = "allow-downgrades")]
594  pub allow_downgrades: bool,
595  /// Configuration for the MSI generated with WiX.
596  pub wix: Option<WixConfig>,
597  /// Configuration for the installer generated with NSIS.
598  pub nsis: Option<NsisConfig>,
599}
600
601impl Default for WindowsConfig {
602  fn default() -> Self {
603    Self {
604      digest_algorithm: None,
605      certificate_thumbprint: None,
606      timestamp_url: None,
607      tsp: false,
608      webview_install_mode: Default::default(),
609      webview_fixed_runtime_path: None,
610      allow_downgrades: true,
611      wix: None,
612      nsis: None,
613    }
614  }
615}
616
617/// Definition for bundle resources.
618/// Can be either a list of paths to include or a map of source to target paths.
619#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
620#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
621#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
622pub enum BundleResources {
623  /// A list of paths to include.
624  List(Vec<String>),
625  /// A map of source to target paths.
626  Map(HashMap<String, String>),
627}
628
629/// Configuration for tauri-bundler.
630///
631/// See more: https://tauri.app/v1/api/config#bundleconfig
632#[skip_serializing_none]
633#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
634#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
635#[serde(rename_all = "camelCase", deny_unknown_fields)]
636pub struct BundleConfig {
637  /// Whether Tauri should bundle your application or just output the executable.
638  #[serde(default)]
639  pub active: bool,
640  /// The bundle targets, currently supports ["deb", "appimage", "nsis", "msi", "app", "dmg", "updater"] or "all".
641  #[serde(default)]
642  pub targets: BundleTarget,
643  /// The application identifier in reverse domain name notation (e.g. `com.tauri.example`).
644  /// This string must be unique across applications since it is used in system configurations like
645  /// the bundle ID and path to the webview data directory.
646  /// This string must contain only alphanumeric characters (A-Z, a-z, and 0-9), hyphens (-),
647  /// and periods (.).
648  pub identifier: String,
649  /// The application's publisher. Defaults to the second element in the identifier string.
650  /// Currently maps to the Manufacturer property of the Windows Installer.
651  pub publisher: Option<String>,
652  /// The app's icons
653  #[serde(default)]
654  pub icon: Vec<String>,
655  /// App resources to bundle.
656  /// Each resource is a path to a file or directory.
657  /// Glob patterns are supported.
658  pub resources: Option<BundleResources>,
659  /// A copyright string associated with your application.
660  pub copyright: Option<String>,
661  /// The application kind.
662  ///
663  /// Should be one of the following:
664  /// Business, DeveloperTool, Education, Entertainment, Finance, Game, ActionGame, AdventureGame, ArcadeGame, BoardGame, CardGame, CasinoGame, DiceGame, EducationalGame, FamilyGame, KidsGame, MusicGame, PuzzleGame, RacingGame, RolePlayingGame, SimulationGame, SportsGame, StrategyGame, TriviaGame, WordGame, GraphicsAndDesign, HealthcareAndFitness, Lifestyle, Medical, Music, News, Photography, Productivity, Reference, SocialNetworking, Sports, Travel, Utility, Video, Weather.
665  pub category: Option<String>,
666  /// A short description of your application.
667  #[serde(alias = "short-description")]
668  pub short_description: Option<String>,
669  /// A longer, multi-line description of the application.
670  #[serde(alias = "long-description")]
671  pub long_description: Option<String>,
672  /// Configuration for the AppImage bundle.
673  #[serde(default)]
674  pub appimage: AppImageConfig,
675  /// Configuration for the Debian bundle.
676  #[serde(default)]
677  pub deb: DebConfig,
678  /// Configuration for the macOS bundles.
679  #[serde(rename = "macOS", default)]
680  pub macos: MacConfig,
681  /// A list of—either absolute or relative—paths to binaries to embed with your application.
682  ///
683  /// Note that Tauri will look for system-specific binaries following the pattern "binary-name{-target-triple}{.system-extension}".
684  ///
685  /// E.g. for the external binary "my-binary", Tauri looks for:
686  ///
687  /// - "my-binary-x86_64-pc-windows-msvc.exe" for Windows
688  /// - "my-binary-x86_64-apple-darwin" for macOS
689  /// - "my-binary-x86_64-unknown-linux-gnu" for Linux
690  ///
691  /// so don't forget to provide binaries for all targeted platforms.
692  #[serde(alias = "external-bin")]
693  pub external_bin: Option<Vec<String>>,
694  /// Configuration for the Windows bundle.
695  #[serde(default)]
696  pub windows: WindowsConfig,
697}
698
699/// A CLI argument definition.
700#[skip_serializing_none]
701#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
702#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
703#[serde(rename_all = "camelCase", deny_unknown_fields)]
704pub struct CliArg {
705  /// The short version of the argument, without the preceding -.
706  ///
707  /// NOTE: Any leading `-` characters will be stripped, and only the first non-character will be used as the short version.
708  pub short: Option<char>,
709  /// The unique argument name
710  pub name: String,
711  /// The argument description which will be shown on the help information.
712  /// Typically, this is a short (one line) description of the arg.
713  pub description: Option<String>,
714  /// The argument long description which will be shown on the help information.
715  /// Typically this a more detailed (multi-line) message that describes the argument.
716  #[serde(alias = "long-description")]
717  pub long_description: Option<String>,
718  /// Specifies that the argument takes a value at run time.
719  ///
720  /// NOTE: values for arguments may be specified in any of the following methods
721  /// - Using a space such as -o value or --option value
722  /// - Using an equals and no space such as -o=value or --option=value
723  /// - Use a short and no space such as -ovalue
724  #[serde(default, alias = "takes-value")]
725  pub takes_value: bool,
726  /// Specifies that the argument may have an unknown number of multiple values. Without any other settings, this argument may appear only once.
727  ///
728  /// For example, --opt val1 val2 is allowed, but --opt val1 val2 --opt val3 is not.
729  ///
730  /// NOTE: Setting this requires `takes_value` to be set to true.
731  #[serde(default)]
732  pub multiple: bool,
733  /// Specifies that the argument may appear more than once.
734  /// For flags, this results in the number of occurrences of the flag being recorded. For example -ddd or -d -d -d would count as three occurrences.
735  /// For options or arguments that take a value, this does not affect how many values they can accept. (i.e. only one at a time is allowed)
736  ///
737  /// For example, --opt val1 --opt val2 is allowed, but --opt val1 val2 is not.
738  #[serde(default, alias = "multiple-occurrences")]
739  pub multiple_occurrences: bool,
740  /// Specifies how many values are required to satisfy this argument. For example, if you had a
741  /// `-f <file>` argument where you wanted exactly 3 'files' you would set
742  /// `number_of_values = 3`, and this argument wouldn't be satisfied unless the user provided
743  /// 3 and only 3 values.
744  ///
745  /// **NOTE:** Does *not* require `multiple_occurrences = true` to be set. Setting
746  /// `multiple_occurrences = true` would allow `-f <file> <file> <file> -f <file> <file> <file>` where
747  /// as *not* setting it would only allow one occurrence of this argument.
748  ///
749  /// **NOTE:** implicitly sets `takes_value = true` and `multiple_values = true`.
750  #[serde(alias = "number-of-values")]
751  pub number_of_values: Option<usize>,
752  /// Specifies a list of possible values for this argument.
753  /// At runtime, the CLI verifies that only one of the specified values was used, or fails with an error message.
754  #[serde(alias = "possible-values")]
755  pub possible_values: Option<Vec<String>>,
756  /// Specifies the minimum number of values for this argument.
757  /// For example, if you had a -f `<file>` argument where you wanted at least 2 'files',
758  /// you would set `minValues: 2`, and this argument would be satisfied if the user provided, 2 or more values.
759  #[serde(alias = "min-values")]
760  pub min_values: Option<usize>,
761  /// Specifies the maximum number of values are for this argument.
762  /// For example, if you had a -f `<file>` argument where you wanted up to 3 'files',
763  /// you would set .max_values(3), and this argument would be satisfied if the user provided, 1, 2, or 3 values.
764  #[serde(alias = "max-values")]
765  pub max_values: Option<usize>,
766  /// Sets whether or not the argument is required by default.
767  ///
768  /// - Required by default means it is required, when no other conflicting rules have been evaluated
769  /// - Conflicting rules take precedence over being required.
770  #[serde(default)]
771  pub required: bool,
772  /// Sets an arg that override this arg's required setting
773  /// i.e. this arg will be required unless this other argument is present.
774  #[serde(alias = "required-unless-present")]
775  pub required_unless_present: Option<String>,
776  /// Sets args that override this arg's required setting
777  /// i.e. this arg will be required unless all these other arguments are present.
778  #[serde(alias = "required-unless-present-all")]
779  pub required_unless_present_all: Option<Vec<String>>,
780  /// Sets args that override this arg's required setting
781  /// i.e. this arg will be required unless at least one of these other arguments are present.
782  #[serde(alias = "required-unless-present-any")]
783  pub required_unless_present_any: Option<Vec<String>>,
784  /// Sets a conflicting argument by name
785  /// i.e. when using this argument, the following argument can't be present and vice versa.
786  #[serde(alias = "conflicts-with")]
787  pub conflicts_with: Option<String>,
788  /// The same as conflictsWith but allows specifying multiple two-way conflicts per argument.
789  #[serde(alias = "conflicts-with-all")]
790  pub conflicts_with_all: Option<Vec<String>>,
791  /// Tets an argument by name that is required when this one is present
792  /// i.e. when using this argument, the following argument must be present.
793  pub requires: Option<String>,
794  /// Sts multiple arguments by names that are required when this one is present
795  /// i.e. when using this argument, the following arguments must be present.
796  #[serde(alias = "requires-all")]
797  pub requires_all: Option<Vec<String>>,
798  /// Allows a conditional requirement with the signature [arg, value]
799  /// the requirement will only become valid if `arg`'s value equals `${value}`.
800  #[serde(alias = "requires-if")]
801  pub requires_if: Option<Vec<String>>,
802  /// Allows specifying that an argument is required conditionally with the signature [arg, value]
803  /// the requirement will only become valid if the `arg`'s value equals `${value}`.
804  #[serde(alias = "requires-if-eq")]
805  pub required_if_eq: Option<Vec<String>>,
806  /// Requires that options use the --option=val syntax
807  /// i.e. an equals between the option and associated value.
808  #[serde(alias = "requires-equals")]
809  pub require_equals: Option<bool>,
810  /// The positional argument index, starting at 1.
811  ///
812  /// The index refers to position according to other positional argument.
813  /// It does not define position in the argument list as a whole. When utilized with multiple=true,
814  /// only the last positional argument may be defined as multiple (i.e. the one with the highest index).
815  #[cfg_attr(feature = "schema", validate(range(min = 1)))]
816  pub index: Option<usize>,
817}
818
819/// describes a CLI configuration
820///
821/// See more: https://tauri.app/v1/api/config#cliconfig
822#[skip_serializing_none]
823#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
824#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
825#[serde(rename_all = "camelCase", deny_unknown_fields)]
826pub struct CliConfig {
827  /// Command description which will be shown on the help information.
828  pub description: Option<String>,
829  /// Command long description which will be shown on the help information.
830  #[serde(alias = "long-description")]
831  pub long_description: Option<String>,
832  /// Adds additional help information to be displayed in addition to auto-generated help.
833  /// This information is displayed before the auto-generated help information.
834  /// This is often used for header information.
835  #[serde(alias = "before-help")]
836  pub before_help: Option<String>,
837  /// Adds additional help information to be displayed in addition to auto-generated help.
838  /// This information is displayed after the auto-generated help information.
839  /// This is often used to describe how to use the arguments, or caveats to be noted.
840  #[serde(alias = "after-help")]
841  pub after_help: Option<String>,
842  /// List of arguments for the command
843  pub args: Option<Vec<CliArg>>,
844  /// List of subcommands of this command
845  pub subcommands: Option<HashMap<String, CliConfig>>,
846}
847
848/// The window configuration object.
849///
850/// See more: https://tauri.app/v1/api/config#windowconfig
851#[skip_serializing_none]
852#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
853#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
854#[serde(rename_all = "camelCase", deny_unknown_fields)]
855pub struct WindowConfig {
856  /// The window identifier. It must be alphanumeric.
857  #[serde(default = "default_window_label")]
858  pub label: String,
859  /// The window webview URL.
860  #[serde(default)]
861  pub url: WindowUrl,
862  /// The user agent for the webview
863  #[serde(alias = "user-agent")]
864  pub user_agent: Option<String>,
865  /// Whether the file drop is enabled or not on the webview. By default it is enabled.
866  ///
867  /// Disabling it is required to use drag and drop on the frontend on Windows.
868  #[serde(default = "default_true", alias = "file-drop-enabled")]
869  pub file_drop_enabled: bool,
870  /// Whether or not the window starts centered or not.
871  #[serde(default)]
872  pub center: bool,
873  /// The horizontal position of the window's top left corner
874  pub x: Option<f64>,
875  /// The vertical position of the window's top left corner
876  pub y: Option<f64>,
877  /// The window width.
878  #[serde(default = "default_width")]
879  pub width: f64,
880  /// The window height.
881  #[serde(default = "default_height")]
882  pub height: f64,
883  /// The min window width.
884  #[serde(alias = "min-width")]
885  pub min_width: Option<f64>,
886  /// The min window height.
887  #[serde(alias = "min-height")]
888  pub min_height: Option<f64>,
889  /// The max window width.
890  #[serde(alias = "max-width")]
891  pub max_width: Option<f64>,
892  /// The max window height.
893  #[serde(alias = "max-height")]
894  pub max_height: Option<f64>,
895  /// Whether the window is resizable or not. When resizable is set to false, native window's maximize button is automatically disabled.
896  #[serde(default = "default_true")]
897  pub resizable: bool,
898  /// Whether the window's native maximize button is enabled or not.
899  /// If resizable is set to false, this setting is ignored.
900  ///
901  /// ## Platform-specific
902  ///
903  /// - **macOS:** Disables the "zoom" button in the window titlebar, which is also used to enter fullscreen mode.
904  /// - **Linux / iOS / Android:** Unsupported.
905  #[serde(default = "default_true")]
906  pub maximizable: bool,
907  /// Whether the window's native minimize button is enabled or not.
908  ///
909  /// ## Platform-specific
910  ///
911  /// - **Linux / iOS / Android:** Unsupported.
912  #[serde(default = "default_true")]
913  pub minimizable: bool,
914  /// Whether the window's native close button is enabled or not.
915  ///
916  /// ## Platform-specific
917  ///
918  /// - **Linux:** "GTK+ will do its best to convince the window manager not to show a close button.
919  ///   Depending on the system, this function may not have any effect when called on a window that is already visible"
920  /// - **iOS / Android:** Unsupported.
921  #[serde(default = "default_true")]
922  pub closable: bool,
923  /// The window title.
924  #[serde(default = "default_title")]
925  pub title: String,
926  /// Whether the window starts as fullscreen or not.
927  #[serde(default)]
928  pub fullscreen: bool,
929  /// Whether the window will be initially focused or not.
930  #[serde(default = "default_true")]
931  pub focus: bool,
932  /// Whether the window is transparent or not.
933  ///
934  /// Note that on `macOS` this requires the `macos-private-api` feature flag, enabled under `tauri > macOSPrivateApi`.
935  /// WARNING: Using private APIs on `macOS` prevents your application from being accepted to the `App Store`.
936  #[serde(default)]
937  pub transparent: bool,
938  /// Whether the window is maximized or not.
939  #[serde(default)]
940  pub maximized: bool,
941  /// Whether the window is visible or not.
942  #[serde(default = "default_true")]
943  pub visible: bool,
944  /// Whether the window should have borders and bars.
945  #[serde(default = "default_true")]
946  pub decorations: bool,
947  /// Whether the window should always be on top of other windows.
948  #[serde(default, alias = "always-on-top")]
949  pub always_on_top: bool,
950  /// Prevents the window contents from being captured by other apps.
951  #[serde(default, alias = "content-protected")]
952  pub content_protected: bool,
953  /// If `true`, hides the window icon from the taskbar on Windows and Linux.
954  #[serde(default, alias = "skip-taskbar")]
955  pub skip_taskbar: bool,
956  /// The initial window theme. Defaults to the system theme. Only implemented on Windows and macOS 10.14+.
957  pub theme: Option<Theme>,
958  /// The style of the macOS title bar.
959  #[serde(default, alias = "title-bar-style")]
960  pub title_bar_style: TitleBarStyle,
961  /// If `true`, sets the window title to be hidden on macOS.
962  #[serde(default, alias = "hidden-title")]
963  pub hidden_title: bool,
964  /// Whether clicking an inactive window also clicks through to the webview on macOS.
965  #[serde(default, alias = "accept-first-mouse")]
966  pub accept_first_mouse: bool,
967  /// Defines the window [tabbing identifier] for macOS.
968  ///
969  /// Windows with matching tabbing identifiers will be grouped together.
970  /// If the tabbing identifier is not set, automatic tabbing will be disabled.
971  ///
972  /// [tabbing identifier]: <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
973  #[serde(default, alias = "tabbing-identifier")]
974  pub tabbing_identifier: Option<String>,
975  /// Defines additional browser arguments on Windows. By default wry passes `--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection`
976  /// so if you use this method, you also need to disable these components by yourself if you want.
977  #[serde(default, alias = "additional-browser-args")]
978  pub additional_browser_args: Option<String>,
979}
980
981impl Default for WindowConfig {
982  fn default() -> Self {
983    Self {
984      label: default_window_label(),
985      url: WindowUrl::default(),
986      user_agent: None,
987      file_drop_enabled: true,
988      center: false,
989      x: None,
990      y: None,
991      width: default_width(),
992      height: default_height(),
993      min_width: None,
994      min_height: None,
995      max_width: None,
996      max_height: None,
997      resizable: true,
998      maximizable: true,
999      minimizable: true,
1000      closable: true,
1001      title: default_title(),
1002      fullscreen: false,
1003      focus: false,
1004      transparent: false,
1005      maximized: false,
1006      visible: true,
1007      decorations: true,
1008      always_on_top: false,
1009      content_protected: false,
1010      skip_taskbar: false,
1011      theme: None,
1012      title_bar_style: Default::default(),
1013      hidden_title: false,
1014      accept_first_mouse: false,
1015      tabbing_identifier: None,
1016      additional_browser_args: None,
1017    }
1018  }
1019}
1020
1021fn default_window_label() -> String {
1022  "main".to_string()
1023}
1024
1025fn default_width() -> f64 {
1026  800f64
1027}
1028
1029fn default_height() -> f64 {
1030  600f64
1031}
1032
1033fn default_title() -> String {
1034  "Tauri App".to_string()
1035}
1036
1037/// A Content-Security-Policy directive source list.
1038/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources>.
1039#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1040#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1041#[serde(rename_all = "camelCase", untagged)]
1042pub enum CspDirectiveSources {
1043  /// An inline list of CSP sources. Same as [`Self::List`], but concatenated with a space separator.
1044  Inline(String),
1045  /// A list of CSP sources. The collection will be concatenated with a space separator for the CSP string.
1046  List(Vec<String>),
1047}
1048
1049impl Default for CspDirectiveSources {
1050  fn default() -> Self {
1051    Self::List(Vec::new())
1052  }
1053}
1054
1055impl From<CspDirectiveSources> for Vec<String> {
1056  fn from(sources: CspDirectiveSources) -> Self {
1057    match sources {
1058      CspDirectiveSources::Inline(source) => source.split(' ').map(|s| s.to_string()).collect(),
1059      CspDirectiveSources::List(l) => l,
1060    }
1061  }
1062}
1063
1064impl CspDirectiveSources {
1065  /// Whether the given source is configured on this directive or not.
1066  pub fn contains(&self, source: &str) -> bool {
1067    match self {
1068      Self::Inline(s) => s.contains(&format!("{source} ")) || s.contains(&format!(" {source}")),
1069      Self::List(l) => l.contains(&source.into()),
1070    }
1071  }
1072
1073  /// Appends the given source to this directive.
1074  pub fn push<S: AsRef<str>>(&mut self, source: S) {
1075    match self {
1076      Self::Inline(s) => {
1077        s.push(' ');
1078        s.push_str(source.as_ref());
1079      }
1080      Self::List(l) => {
1081        l.push(source.as_ref().to_string());
1082      }
1083    }
1084  }
1085}
1086
1087/// A Content-Security-Policy definition.
1088/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
1089#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1090#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1091#[serde(rename_all = "camelCase", untagged)]
1092pub enum Csp {
1093  /// The entire CSP policy in a single text string.
1094  Policy(String),
1095  /// An object mapping a directive with its sources values as a list of strings.
1096  DirectiveMap(HashMap<String, CspDirectiveSources>),
1097}
1098
1099impl From<HashMap<String, CspDirectiveSources>> for Csp {
1100  fn from(map: HashMap<String, CspDirectiveSources>) -> Self {
1101    Self::DirectiveMap(map)
1102  }
1103}
1104
1105impl From<Csp> for HashMap<String, CspDirectiveSources> {
1106  fn from(csp: Csp) -> Self {
1107    match csp {
1108      Csp::Policy(policy) => {
1109        let mut map = HashMap::new();
1110        for directive in policy.split(';') {
1111          let mut tokens = directive.trim().split(' ');
1112          if let Some(directive) = tokens.next() {
1113            let sources = tokens.map(|s| s.to_string()).collect::<Vec<String>>();
1114            map.insert(directive.to_string(), CspDirectiveSources::List(sources));
1115          }
1116        }
1117        map
1118      }
1119      Csp::DirectiveMap(m) => m,
1120    }
1121  }
1122}
1123
1124impl Display for Csp {
1125  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1126    match self {
1127      Self::Policy(s) => write!(f, "{s}"),
1128      Self::DirectiveMap(m) => {
1129        let len = m.len();
1130        let mut i = 0;
1131        for (directive, sources) in m {
1132          let sources: Vec<String> = sources.clone().into();
1133          write!(f, "{} {}", directive, sources.join(" "))?;
1134          i += 1;
1135          if i != len {
1136            write!(f, "; ")?;
1137          }
1138        }
1139        Ok(())
1140      }
1141    }
1142  }
1143}
1144
1145/// The possible values for the `dangerous_disable_asset_csp_modification` config option.
1146#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1147#[serde(untagged)]
1148#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1149pub enum DisabledCspModificationKind {
1150  /// If `true`, disables all CSP modification.
1151  /// `false` is the default value and it configures Tauri to control the CSP.
1152  Flag(bool),
1153  /// Disables the given list of CSP directives modifications.
1154  List(Vec<String>),
1155}
1156
1157impl Default for DisabledCspModificationKind {
1158  fn default() -> Self {
1159    Self::Flag(false)
1160  }
1161}
1162
1163/// External command access definition.
1164#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1165#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1166#[serde(rename_all = "camelCase", deny_unknown_fields)]
1167pub struct RemoteDomainAccessScope {
1168  /// The URL scheme to allow. By default, all schemas are allowed.
1169  pub scheme: Option<String>,
1170  /// The domain to allow.
1171  pub domain: String,
1172  /// The list of window labels this scope applies to.
1173  pub windows: Vec<String>,
1174  /// The list of plugins that are allowed in this scope.
1175  /// The names should be without the `tauri-plugin-` prefix, for example `"store"` for `tauri-plugin-store`.
1176  #[serde(default)]
1177  pub plugins: Vec<String>,
1178  /// Enables access to the Tauri API.
1179  #[serde(default, rename = "enableTauriAPI", alias = "enable-tauri-api")]
1180  pub enable_tauri_api: bool,
1181}
1182
1183/// Security configuration.
1184///
1185/// See more: https://tauri.app/v1/api/config#securityconfig
1186#[skip_serializing_none]
1187#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1188#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1189#[serde(rename_all = "camelCase", deny_unknown_fields)]
1190pub struct SecurityConfig {
1191  /// The Content Security Policy that will be injected on all HTML files on the built application.
1192  /// If [`dev_csp`](#SecurityConfig.devCsp) is not specified, this value is also injected on dev.
1193  ///
1194  /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
1195  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
1196  pub csp: Option<Csp>,
1197  /// The Content Security Policy that will be injected on all HTML files on development.
1198  ///
1199  /// This is a really important part of the configuration since it helps you ensure your WebView is secured.
1200  /// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
1201  #[serde(alias = "dev-csp")]
1202  pub dev_csp: Option<Csp>,
1203  /// Freeze the `Object.prototype` when using the custom protocol.
1204  #[serde(default, alias = "freeze-prototype")]
1205  pub freeze_prototype: bool,
1206  /// Disables the Tauri-injected CSP sources.
1207  ///
1208  /// At compile time, Tauri parses all the frontend assets and changes the Content-Security-Policy
1209  /// to only allow loading of your own scripts and styles by injecting nonce and hash sources.
1210  /// This stricts your CSP, which may introduce issues when using along with other flexing sources.
1211  ///
1212  /// This configuration option allows both a boolean and a list of strings as value.
1213  /// A boolean instructs Tauri to disable the injection for all CSP injections,
1214  /// and a list of strings indicates the CSP directives that Tauri cannot inject.
1215  ///
1216  /// **WARNING:** Only disable this if you know what you are doing and have properly configured the CSP.
1217  /// Your application might be vulnerable to XSS attacks without this Tauri protection.
1218  #[serde(default, alias = "dangerous-disable-asset-csp-modification")]
1219  pub dangerous_disable_asset_csp_modification: DisabledCspModificationKind,
1220  /// Allow external domains to send command to Tauri.
1221  ///
1222  /// By default, external domains do not have access to `window.__TAURI__`, which means they cannot
1223  /// communicate with the commands defined in Rust. This prevents attacks where an externally
1224  /// loaded malicious or compromised sites could start executing commands on the user's device.
1225  ///
1226  /// This configuration allows a set of external domains to have access to the Tauri commands.
1227  /// When you configure a domain to be allowed to access the IPC, all subpaths are allowed. Subdomains are not allowed.
1228  ///
1229  /// **WARNING:** Only use this option if you either have internal checks against malicious
1230  /// external sites or you can trust the allowed external sites. You application might be
1231  /// vulnerable to dangerous Tauri command related attacks otherwise.
1232  #[serde(default, alias = "dangerous-remote-domain-ipc-access")]
1233  pub dangerous_remote_domain_ipc_access: Vec<RemoteDomainAccessScope>,
1234  /// Sets whether the custom protocols should use `http://<scheme>.localhost` instead of the default `https://<scheme>.localhost` on Windows.
1235  ///
1236  /// **WARNING:** Using a `http` scheme will allow mixed content when trying to fetch `http` endpoints and is therefore less secure but will match the behavior of the `<scheme>://localhost` protocols used on macOS and Linux.
1237  #[serde(default, alias = "dangerous-use-http-scheme")]
1238  pub dangerous_use_http_scheme: bool,
1239}
1240
1241/// Defines an allowlist type.
1242pub trait Allowlist {
1243  /// Returns all features associated with the allowlist struct.
1244  fn all_features() -> Vec<&'static str>;
1245  /// Returns the tauri features enabled on this allowlist.
1246  fn to_features(&self) -> Vec<&'static str>;
1247}
1248
1249macro_rules! check_feature {
1250  ($self:ident, $features:ident, $flag:ident, $feature_name: expr) => {
1251    if $self.$flag {
1252      $features.push($feature_name)
1253    }
1254  };
1255}
1256
1257/// Filesystem scope definition.
1258/// It is a list of glob patterns that restrict the API access from the webview.
1259///
1260/// Each pattern can start with a variable that resolves to a system base directory.
1261/// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
1262/// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
1263/// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`,
1264/// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
1265#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1266#[serde(untagged)]
1267#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1268pub enum FsAllowlistScope {
1269  /// A list of paths that are allowed by this scope.
1270  AllowedPaths(Vec<PathBuf>),
1271  /// A complete scope configuration.
1272  #[serde(rename_all = "camelCase")]
1273  Scope {
1274    /// A list of paths that are allowed by this scope.
1275    #[serde(default)]
1276    allow: Vec<PathBuf>,
1277    /// A list of paths that are not allowed by this scope.
1278    /// This gets precedence over the [`Self::Scope::allow`] list.
1279    #[serde(default)]
1280    deny: Vec<PathBuf>,
1281    /// Whether or not paths that contain components that start with a `.`
1282    /// will require that `.` appears literally in the pattern; `*`, `?`, `**`,
1283    /// or `[...]` will not match. This is useful because such files are
1284    /// conventionally considered hidden on Unix systems and it might be
1285    /// desirable to skip them when listing files.
1286    ///
1287    /// Defaults to `true` on Unix systems and `false` on Windows
1288    // dotfiles are not supposed to be exposed by default on unix
1289    #[serde(alias = "require-literal-leading-dot")]
1290    require_literal_leading_dot: Option<bool>,
1291  },
1292}
1293
1294impl Default for FsAllowlistScope {
1295  fn default() -> Self {
1296    Self::AllowedPaths(Vec::new())
1297  }
1298}
1299
1300/// Allowlist for the file system APIs.
1301///
1302/// See more: https://tauri.app/v1/api/config#fsallowlistconfig
1303#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1304#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1305#[serde(rename_all = "camelCase", deny_unknown_fields)]
1306pub struct FsAllowlistConfig {
1307  /// The access scope for the filesystem APIs.
1308  #[serde(default)]
1309  pub scope: FsAllowlistScope,
1310  /// Use this flag to enable all file system API features.
1311  #[serde(default)]
1312  pub all: bool,
1313  /// Read file from local filesystem.
1314  #[serde(default, alias = "read-file")]
1315  pub read_file: bool,
1316  /// Write file to local filesystem.
1317  #[serde(default, alias = "write-file")]
1318  pub write_file: bool,
1319  /// Read directory from local filesystem.
1320  #[serde(default, alias = "read-dir")]
1321  pub read_dir: bool,
1322  /// Copy file from local filesystem.
1323  #[serde(default, alias = "copy-file")]
1324  pub copy_file: bool,
1325  /// Create directory from local filesystem.
1326  #[serde(default, alias = "create-dir")]
1327  pub create_dir: bool,
1328  /// Remove directory from local filesystem.
1329  #[serde(default, alias = "remove-dir")]
1330  pub remove_dir: bool,
1331  /// Remove file from local filesystem.
1332  #[serde(default, alias = "remove-file")]
1333  pub remove_file: bool,
1334  /// Rename file from local filesystem.
1335  #[serde(default, alias = "rename-file")]
1336  pub rename_file: bool,
1337  /// Check if path exists on the local filesystem.
1338  #[serde(default)]
1339  pub exists: bool,
1340}
1341
1342impl Allowlist for FsAllowlistConfig {
1343  fn all_features() -> Vec<&'static str> {
1344    let allowlist = Self {
1345      scope: Default::default(),
1346      all: false,
1347      read_file: true,
1348      write_file: true,
1349      read_dir: true,
1350      copy_file: true,
1351      create_dir: true,
1352      remove_dir: true,
1353      remove_file: true,
1354      rename_file: true,
1355      exists: true,
1356    };
1357    let mut features = allowlist.to_features();
1358    features.push("fs-all");
1359    features
1360  }
1361
1362  fn to_features(&self) -> Vec<&'static str> {
1363    if self.all {
1364      vec!["fs-all"]
1365    } else {
1366      let mut features = Vec::new();
1367      check_feature!(self, features, read_file, "fs-read-file");
1368      check_feature!(self, features, write_file, "fs-write-file");
1369      check_feature!(self, features, read_dir, "fs-read-dir");
1370      check_feature!(self, features, copy_file, "fs-copy-file");
1371      check_feature!(self, features, create_dir, "fs-create-dir");
1372      check_feature!(self, features, remove_dir, "fs-remove-dir");
1373      check_feature!(self, features, remove_file, "fs-remove-file");
1374      check_feature!(self, features, rename_file, "fs-rename-file");
1375      check_feature!(self, features, exists, "fs-exists");
1376      features
1377    }
1378  }
1379}
1380
1381/// Allowlist for the window APIs.
1382///
1383/// See more: https://tauri.app/v1/api/config#windowallowlistconfig
1384#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1385#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1386#[serde(rename_all = "camelCase", deny_unknown_fields)]
1387pub struct WindowAllowlistConfig {
1388  /// Use this flag to enable all window API features.
1389  #[serde(default)]
1390  pub all: bool,
1391  /// Allows dynamic window creation.
1392  #[serde(default)]
1393  pub create: bool,
1394  /// Allows centering the window.
1395  #[serde(default)]
1396  pub center: bool,
1397  /// Allows requesting user attention on the window.
1398  #[serde(default, alias = "request-user-attention")]
1399  pub request_user_attention: bool,
1400  /// Allows setting the resizable flag of the window.
1401  #[serde(default, alias = "set-resizable")]
1402  pub set_resizable: bool,
1403  /// Allows setting whether the window's native maximize button is enabled or not.
1404  #[serde(default, alias = "set-maximizable")]
1405  pub set_maximizable: bool,
1406  /// Allows setting whether the window's native minimize button is enabled or not.
1407  #[serde(default, alias = "set-minimizable")]
1408  pub set_minimizable: bool,
1409  /// Allows setting whether the window's native close button is enabled or not.
1410  #[serde(default, alias = "set-closable")]
1411  pub set_closable: bool,
1412  /// Allows changing the window title.
1413  #[serde(default, alias = "set-title")]
1414  pub set_title: bool,
1415  /// Allows maximizing the window.
1416  #[serde(default)]
1417  pub maximize: bool,
1418  /// Allows unmaximizing the window.
1419  #[serde(default)]
1420  pub unmaximize: bool,
1421  /// Allows minimizing the window.
1422  #[serde(default)]
1423  pub minimize: bool,
1424  /// Allows unminimizing the window.
1425  #[serde(default)]
1426  pub unminimize: bool,
1427  /// Allows showing the window.
1428  #[serde(default)]
1429  pub show: bool,
1430  /// Allows hiding the window.
1431  #[serde(default)]
1432  pub hide: bool,
1433  /// Allows closing the window.
1434  #[serde(default)]
1435  pub close: bool,
1436  /// Allows setting the decorations flag of the window.
1437  #[serde(default, alias = "set-decorations")]
1438  pub set_decorations: bool,
1439  /// Allows setting the always_on_top flag of the window.
1440  #[serde(default, alias = "set-always-on-top")]
1441  pub set_always_on_top: bool,
1442  /// Allows preventing the window contents from being captured by other apps.
1443  #[serde(default, alias = "set-content-protected")]
1444  pub set_content_protected: bool,
1445  /// Allows setting the window size.
1446  #[serde(default, alias = "set-size")]
1447  pub set_size: bool,
1448  /// Allows setting the window minimum size.
1449  #[serde(default, alias = "set-min-size")]
1450  pub set_min_size: bool,
1451  /// Allows setting the window maximum size.
1452  #[serde(default, alias = "set-max-size")]
1453  pub set_max_size: bool,
1454  /// Allows changing the position of the window.
1455  #[serde(default, alias = "set-position")]
1456  pub set_position: bool,
1457  /// Allows setting the fullscreen flag of the window.
1458  #[serde(default, alias = "set-fullscreen")]
1459  pub set_fullscreen: bool,
1460  /// Allows focusing the window.
1461  #[serde(default, alias = "set-focus")]
1462  pub set_focus: bool,
1463  /// Allows changing the window icon.
1464  #[serde(default, alias = "set-icon")]
1465  pub set_icon: bool,
1466  /// Allows setting the skip_taskbar flag of the window.
1467  #[serde(default, alias = "set-skip-taskbar")]
1468  pub set_skip_taskbar: bool,
1469  /// Allows grabbing the cursor.
1470  #[serde(default, alias = "set-cursor-grab")]
1471  pub set_cursor_grab: bool,
1472  /// Allows setting the cursor visibility.
1473  #[serde(default, alias = "set-cursor-visible")]
1474  pub set_cursor_visible: bool,
1475  /// Allows changing the cursor icon.
1476  #[serde(default, alias = "set-cursor-icon")]
1477  pub set_cursor_icon: bool,
1478  /// Allows setting the cursor position.
1479  #[serde(default, alias = "set-cursor-position")]
1480  pub set_cursor_position: bool,
1481  /// Allows ignoring cursor events.
1482  #[serde(default, alias = "set-ignore-cursor-events")]
1483  pub set_ignore_cursor_events: bool,
1484  /// Allows start dragging on the window.
1485  #[serde(default, alias = "start-dragging")]
1486  pub start_dragging: bool,
1487  /// Allows opening the system dialog to print the window content.
1488  #[serde(default)]
1489  pub print: bool,
1490}
1491
1492impl Allowlist for WindowAllowlistConfig {
1493  fn all_features() -> Vec<&'static str> {
1494    let allowlist = Self {
1495      all: false,
1496      create: true,
1497      center: true,
1498      request_user_attention: true,
1499      set_resizable: true,
1500      set_maximizable: true,
1501      set_minimizable: true,
1502      set_closable: true,
1503      set_title: true,
1504      maximize: true,
1505      unmaximize: true,
1506      minimize: true,
1507      unminimize: true,
1508      show: true,
1509      hide: true,
1510      close: true,
1511      set_decorations: true,
1512      set_always_on_top: true,
1513      set_content_protected: false,
1514      set_size: true,
1515      set_min_size: true,
1516      set_max_size: true,
1517      set_position: true,
1518      set_fullscreen: true,
1519      set_focus: true,
1520      set_icon: true,
1521      set_skip_taskbar: true,
1522      set_cursor_grab: true,
1523      set_cursor_visible: true,
1524      set_cursor_icon: true,
1525      set_cursor_position: true,
1526      set_ignore_cursor_events: true,
1527      start_dragging: true,
1528      print: true,
1529    };
1530    let mut features = allowlist.to_features();
1531    features.push("window-all");
1532    features
1533  }
1534
1535  fn to_features(&self) -> Vec<&'static str> {
1536    if self.all {
1537      vec!["window-all"]
1538    } else {
1539      let mut features = Vec::new();
1540      check_feature!(self, features, create, "window-create");
1541      check_feature!(self, features, center, "window-center");
1542      check_feature!(
1543        self,
1544        features,
1545        request_user_attention,
1546        "window-request-user-attention"
1547      );
1548      check_feature!(self, features, set_resizable, "window-set-resizable");
1549      check_feature!(self, features, set_maximizable, "window-set-maximizable");
1550      check_feature!(self, features, set_minimizable, "window-set-minimizable");
1551      check_feature!(self, features, set_closable, "window-set-closable");
1552      check_feature!(self, features, set_title, "window-set-title");
1553      check_feature!(self, features, maximize, "window-maximize");
1554      check_feature!(self, features, unmaximize, "window-unmaximize");
1555      check_feature!(self, features, minimize, "window-minimize");
1556      check_feature!(self, features, unminimize, "window-unminimize");
1557      check_feature!(self, features, show, "window-show");
1558      check_feature!(self, features, hide, "window-hide");
1559      check_feature!(self, features, close, "window-close");
1560      check_feature!(self, features, set_decorations, "window-set-decorations");
1561      check_feature!(
1562        self,
1563        features,
1564        set_always_on_top,
1565        "window-set-always-on-top"
1566      );
1567      check_feature!(
1568        self,
1569        features,
1570        set_content_protected,
1571        "window-set-content-protected"
1572      );
1573      check_feature!(self, features, set_size, "window-set-size");
1574      check_feature!(self, features, set_min_size, "window-set-min-size");
1575      check_feature!(self, features, set_max_size, "window-set-max-size");
1576      check_feature!(self, features, set_position, "window-set-position");
1577      check_feature!(self, features, set_fullscreen, "window-set-fullscreen");
1578      check_feature!(self, features, set_focus, "window-set-focus");
1579      check_feature!(self, features, set_icon, "window-set-icon");
1580      check_feature!(self, features, set_skip_taskbar, "window-set-skip-taskbar");
1581      check_feature!(self, features, set_cursor_grab, "window-set-cursor-grab");
1582      check_feature!(
1583        self,
1584        features,
1585        set_cursor_visible,
1586        "window-set-cursor-visible"
1587      );
1588      check_feature!(self, features, set_cursor_icon, "window-set-cursor-icon");
1589      check_feature!(
1590        self,
1591        features,
1592        set_cursor_position,
1593        "window-set-cursor-position"
1594      );
1595      check_feature!(
1596        self,
1597        features,
1598        set_ignore_cursor_events,
1599        "window-set-ignore-cursor-events"
1600      );
1601      check_feature!(self, features, start_dragging, "window-start-dragging");
1602      check_feature!(self, features, print, "window-print");
1603      features
1604    }
1605  }
1606}
1607
1608/// A command allowed to be executed by the webview API.
1609#[derive(Debug, PartialEq, Eq, Clone, Serialize)]
1610#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1611pub struct ShellAllowedCommand {
1612  /// The name for this allowed shell command configuration.
1613  ///
1614  /// This name will be used inside of the webview API to call this command along with
1615  /// any specified arguments.
1616  pub name: String,
1617
1618  /// The command name.
1619  /// It can start with a variable that resolves to a system base directory.
1620  /// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
1621  /// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
1622  /// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`,
1623  /// `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.
1624  #[serde(rename = "cmd", default)] // use default just so the schema doesn't flag it as required
1625  pub command: PathBuf,
1626
1627  /// The allowed arguments for the command execution.
1628  #[serde(default)]
1629  pub args: ShellAllowedArgs,
1630
1631  /// If this command is a sidecar command.
1632  #[serde(default)]
1633  pub sidecar: bool,
1634}
1635
1636impl<'de> Deserialize<'de> for ShellAllowedCommand {
1637  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1638  where
1639    D: Deserializer<'de>,
1640  {
1641    #[derive(Deserialize)]
1642    struct InnerShellAllowedCommand {
1643      name: String,
1644      #[serde(rename = "cmd")]
1645      command: Option<PathBuf>,
1646      #[serde(default)]
1647      args: ShellAllowedArgs,
1648      #[serde(default)]
1649      sidecar: bool,
1650    }
1651
1652    let config = InnerShellAllowedCommand::deserialize(deserializer)?;
1653
1654    if !config.sidecar && config.command.is_none() {
1655      return Err(DeError::custom(
1656        "The shell scope `command` value is required.",
1657      ));
1658    }
1659
1660    Ok(ShellAllowedCommand {
1661      name: config.name,
1662      command: config.command.unwrap_or_default(),
1663      args: config.args,
1664      sidecar: config.sidecar,
1665    })
1666  }
1667}
1668
1669/// A set of command arguments allowed to be executed by the webview API.
1670///
1671/// A value of `true` will allow any arguments to be passed to the command. `false` will disable all
1672/// arguments. A list of [`ShellAllowedArg`] will set those arguments as the only valid arguments to
1673/// be passed to the attached command configuration.
1674#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1675#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1676#[serde(untagged, deny_unknown_fields)]
1677#[non_exhaustive]
1678pub enum ShellAllowedArgs {
1679  /// Use a simple boolean to allow all or disable all arguments to this command configuration.
1680  Flag(bool),
1681
1682  /// A specific set of [`ShellAllowedArg`] that are valid to call for the command configuration.
1683  List(Vec<ShellAllowedArg>),
1684}
1685
1686impl Default for ShellAllowedArgs {
1687  fn default() -> Self {
1688    Self::Flag(false)
1689  }
1690}
1691
1692/// A command argument allowed to be executed by the webview API.
1693#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1694#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1695#[serde(untagged, deny_unknown_fields)]
1696#[non_exhaustive]
1697pub enum ShellAllowedArg {
1698  /// A non-configurable argument that is passed to the command in the order it was specified.
1699  Fixed(String),
1700
1701  /// A variable that is set while calling the command from the webview API.
1702  ///
1703  Var {
1704    /// [regex] validator to require passed values to conform to an expected input.
1705    ///
1706    /// This will require the argument value passed to this variable to match the `validator` regex
1707    /// before it will be executed.
1708    ///
1709    /// [regex]: https://docs.rs/regex/latest/regex/#syntax
1710    validator: String,
1711  },
1712}
1713
1714/// Shell scope definition.
1715/// It is a list of command names and associated CLI arguments that restrict the API access from the webview.
1716#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1717#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1718pub struct ShellAllowlistScope(pub Vec<ShellAllowedCommand>);
1719
1720/// Defines the `shell > open` api scope.
1721#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
1722#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1723#[serde(untagged, deny_unknown_fields)]
1724#[non_exhaustive]
1725pub enum ShellAllowlistOpen {
1726  /// If the shell open API should be enabled.
1727  ///
1728  /// If enabled, the default validation regex (`^((mailto:\w+)|(tel:\w+)|(https?://\w+)).+`) is used.
1729  Flag(bool),
1730
1731  /// Enable the shell open API, with a custom regex that the opened path must match against.
1732  ///
1733  /// If using a custom regex to support a non-http(s) schema, care should be used to prevent values
1734  /// that allow flag-like strings to pass validation. e.g. `--enable-debugging`, `-i`, `/R`.
1735  Validate(String),
1736}
1737
1738impl Default for ShellAllowlistOpen {
1739  fn default() -> Self {
1740    Self::Flag(false)
1741  }
1742}
1743
1744/// Allowlist for the shell APIs.
1745///
1746/// See more: https://tauri.app/v1/api/config#shellallowlistconfig
1747#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1748#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1749#[serde(rename_all = "camelCase", deny_unknown_fields)]
1750pub struct ShellAllowlistConfig {
1751  /// Access scope for the binary execution APIs.
1752  /// Sidecars are automatically enabled.
1753  #[serde(default)]
1754  pub scope: ShellAllowlistScope,
1755  /// Use this flag to enable all shell API features.
1756  #[serde(default)]
1757  pub all: bool,
1758  /// Enable binary execution.
1759  #[serde(default)]
1760  pub execute: bool,
1761  /// Enable sidecar execution, allowing the JavaScript layer to spawn a sidecar command,
1762  /// an executable that is shipped with the application.
1763  /// For more information see <https://tauri.app/v1/guides/building/sidecar>.
1764  #[serde(default)]
1765  pub sidecar: bool,
1766  /// Open URL with the user's default application.
1767  #[serde(default)]
1768  pub open: ShellAllowlistOpen,
1769}
1770
1771impl Allowlist for ShellAllowlistConfig {
1772  fn all_features() -> Vec<&'static str> {
1773    let allowlist = Self {
1774      scope: Default::default(),
1775      all: false,
1776      execute: true,
1777      sidecar: true,
1778      open: ShellAllowlistOpen::Flag(true),
1779    };
1780    let mut features = allowlist.to_features();
1781    features.push("shell-all");
1782    features
1783  }
1784
1785  fn to_features(&self) -> Vec<&'static str> {
1786    if self.all {
1787      vec!["shell-all"]
1788    } else {
1789      let mut features = Vec::new();
1790      check_feature!(self, features, execute, "shell-execute");
1791      check_feature!(self, features, sidecar, "shell-sidecar");
1792
1793      if !matches!(self.open, ShellAllowlistOpen::Flag(false)) {
1794        features.push("shell-open")
1795      }
1796
1797      features
1798    }
1799  }
1800}
1801
1802/// Allowlist for the dialog APIs.
1803///
1804/// See more: https://tauri.app/v1/api/config#dialogallowlistconfig
1805#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1806#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1807#[serde(rename_all = "camelCase", deny_unknown_fields)]
1808pub struct DialogAllowlistConfig {
1809  /// Use this flag to enable all dialog API features.
1810  #[serde(default)]
1811  pub all: bool,
1812  /// Allows the API to open a dialog window to pick files.
1813  #[serde(default)]
1814  pub open: bool,
1815  /// Allows the API to open a dialog window to pick where to save files.
1816  #[serde(default)]
1817  pub save: bool,
1818  /// Allows the API to show a message dialog window.
1819  #[serde(default)]
1820  pub message: bool,
1821  /// Allows the API to show a dialog window with Yes/No buttons.
1822  #[serde(default)]
1823  pub ask: bool,
1824  /// Allows the API to show a dialog window with Ok/Cancel buttons.
1825  #[serde(default)]
1826  pub confirm: bool,
1827}
1828
1829impl Allowlist for DialogAllowlistConfig {
1830  fn all_features() -> Vec<&'static str> {
1831    let allowlist = Self {
1832      all: false,
1833      open: true,
1834      save: true,
1835      message: true,
1836      ask: true,
1837      confirm: true,
1838    };
1839    let mut features = allowlist.to_features();
1840    features.push("dialog-all");
1841    features
1842  }
1843
1844  fn to_features(&self) -> Vec<&'static str> {
1845    if self.all {
1846      vec!["dialog-all"]
1847    } else {
1848      let mut features = Vec::new();
1849      check_feature!(self, features, open, "dialog-open");
1850      check_feature!(self, features, save, "dialog-save");
1851      check_feature!(self, features, message, "dialog-message");
1852      check_feature!(self, features, ask, "dialog-ask");
1853      check_feature!(self, features, confirm, "dialog-confirm");
1854      features
1855    }
1856  }
1857}
1858
1859/// HTTP API scope definition.
1860/// It is a list of URLs that can be accessed by the webview when using the HTTP APIs.
1861/// The scoped URL is matched against the request URL using a glob pattern.
1862///
1863/// Examples:
1864/// - "https://*": allows all HTTPS urls
1865/// - "https://*.github.com/tauri-apps/tauri": allows any subdomain of "github.com" with the "tauri-apps/api" path
1866/// - "https://myapi.service.com/users/*": allows access to any URLs that begins with "https://myapi.service.com/users/"
1867#[allow(rustdoc::bare_urls)]
1868#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1869// TODO: in v2, parse into a String or a custom type that perserves the
1870// glob string because Url type will add a trailing slash
1871#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1872pub struct HttpAllowlistScope(pub Vec<Url>);
1873
1874/// Allowlist for the HTTP APIs.
1875///
1876/// See more: https://tauri.app/v1/api/config#httpallowlistconfig
1877#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1878#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1879#[serde(rename_all = "camelCase", deny_unknown_fields)]
1880pub struct HttpAllowlistConfig {
1881  /// The access scope for the HTTP APIs.
1882  #[serde(default)]
1883  pub scope: HttpAllowlistScope,
1884  /// Use this flag to enable all HTTP API features.
1885  #[serde(default)]
1886  pub all: bool,
1887  /// Allows making HTTP requests.
1888  #[serde(default)]
1889  pub request: bool,
1890}
1891
1892impl Allowlist for HttpAllowlistConfig {
1893  fn all_features() -> Vec<&'static str> {
1894    let allowlist = Self {
1895      scope: Default::default(),
1896      all: false,
1897      request: true,
1898    };
1899    let mut features = allowlist.to_features();
1900    features.push("http-all");
1901    features
1902  }
1903
1904  fn to_features(&self) -> Vec<&'static str> {
1905    if self.all {
1906      vec!["http-all"]
1907    } else {
1908      let mut features = Vec::new();
1909      check_feature!(self, features, request, "http-request");
1910      features
1911    }
1912  }
1913}
1914
1915/// Allowlist for the notification APIs.
1916///
1917/// See more: https://tauri.app/v1/api/config#notificationallowlistconfig
1918#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1919#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1920#[serde(rename_all = "camelCase", deny_unknown_fields)]
1921pub struct NotificationAllowlistConfig {
1922  /// Use this flag to enable all notification API features.
1923  #[serde(default)]
1924  pub all: bool,
1925}
1926
1927impl Allowlist for NotificationAllowlistConfig {
1928  fn all_features() -> Vec<&'static str> {
1929    let allowlist = Self { all: false };
1930    let mut features = allowlist.to_features();
1931    features.push("notification-all");
1932    features
1933  }
1934
1935  fn to_features(&self) -> Vec<&'static str> {
1936    if self.all {
1937      vec!["notification-all"]
1938    } else {
1939      vec![]
1940    }
1941  }
1942}
1943
1944/// Allowlist for the global shortcut APIs.
1945///
1946/// See more: https://tauri.app/v1/api/config#globalshortcutallowlistconfig
1947#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1948#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1949#[serde(rename_all = "camelCase", deny_unknown_fields)]
1950pub struct GlobalShortcutAllowlistConfig {
1951  /// Use this flag to enable all global shortcut API features.
1952  #[serde(default)]
1953  pub all: bool,
1954}
1955
1956impl Allowlist for GlobalShortcutAllowlistConfig {
1957  fn all_features() -> Vec<&'static str> {
1958    let allowlist = Self { all: false };
1959    let mut features = allowlist.to_features();
1960    features.push("global-shortcut-all");
1961    features
1962  }
1963
1964  fn to_features(&self) -> Vec<&'static str> {
1965    if self.all {
1966      vec!["global-shortcut-all"]
1967    } else {
1968      vec![]
1969    }
1970  }
1971}
1972
1973/// Allowlist for the OS APIs.
1974///
1975/// See more: https://tauri.app/v1/api/config#osallowlistconfig
1976#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
1977#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1978#[serde(rename_all = "camelCase", deny_unknown_fields)]
1979pub struct OsAllowlistConfig {
1980  /// Use this flag to enable all OS API features.
1981  #[serde(default)]
1982  pub all: bool,
1983}
1984
1985impl Allowlist for OsAllowlistConfig {
1986  fn all_features() -> Vec<&'static str> {
1987    let allowlist = Self { all: false };
1988    let mut features = allowlist.to_features();
1989    features.push("os-all");
1990    features
1991  }
1992
1993  fn to_features(&self) -> Vec<&'static str> {
1994    if self.all { vec!["os-all"] } else { vec![] }
1995  }
1996}
1997
1998/// Allowlist for the path APIs.
1999///
2000/// See more: https://tauri.app/v1/api/config#pathallowlistconfig
2001#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2002#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2003#[serde(rename_all = "camelCase", deny_unknown_fields)]
2004pub struct PathAllowlistConfig {
2005  /// Use this flag to enable all path API features.
2006  #[serde(default)]
2007  pub all: bool,
2008}
2009
2010impl Allowlist for PathAllowlistConfig {
2011  fn all_features() -> Vec<&'static str> {
2012    let allowlist = Self { all: false };
2013    let mut features = allowlist.to_features();
2014    features.push("path-all");
2015    features
2016  }
2017
2018  fn to_features(&self) -> Vec<&'static str> {
2019    if self.all { vec!["path-all"] } else { vec![] }
2020  }
2021}
2022
2023/// Allowlist for the custom protocols.
2024///
2025/// See more: https://tauri.app/v1/api/config#protocolallowlistconfig
2026#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2027#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2028#[serde(rename_all = "camelCase", deny_unknown_fields)]
2029pub struct ProtocolAllowlistConfig {
2030  /// The access scope for the asset protocol.
2031  #[serde(default, alias = "asset-scope")]
2032  pub asset_scope: FsAllowlistScope,
2033  /// Use this flag to enable all custom protocols.
2034  #[serde(default)]
2035  pub all: bool,
2036  /// Enables the asset protocol.
2037  #[serde(default)]
2038  pub asset: bool,
2039}
2040
2041impl Allowlist for ProtocolAllowlistConfig {
2042  fn all_features() -> Vec<&'static str> {
2043    let allowlist = Self {
2044      asset_scope: Default::default(),
2045      all: false,
2046      asset: true,
2047    };
2048    let mut features = allowlist.to_features();
2049    features.push("protocol-all");
2050    features
2051  }
2052
2053  fn to_features(&self) -> Vec<&'static str> {
2054    if self.all {
2055      vec!["protocol-all"]
2056    } else {
2057      let mut features = Vec::new();
2058      check_feature!(self, features, asset, "protocol-asset");
2059      features
2060    }
2061  }
2062}
2063
2064/// Allowlist for the process APIs.
2065///
2066/// See more: https://tauri.app/v1/api/config#processallowlistconfig
2067#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2068#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2069#[serde(rename_all = "camelCase", deny_unknown_fields)]
2070pub struct ProcessAllowlistConfig {
2071  /// Use this flag to enable all process APIs.
2072  #[serde(default)]
2073  pub all: bool,
2074  /// Enables the relaunch API.
2075  #[serde(default)]
2076  pub relaunch: bool,
2077  /// Dangerous option that allows macOS to relaunch even if the binary contains a symlink.
2078  ///
2079  /// This is due to macOS having less symlink protection. Highly recommended to not set this flag
2080  /// unless you have a very specific reason too, and understand the implications of it.
2081  #[serde(
2082    default,
2083    alias = "relaunchDangerousAllowSymlinkMacOS",
2084    alias = "relaunch-dangerous-allow-symlink-macos"
2085  )]
2086  pub relaunch_dangerous_allow_symlink_macos: bool,
2087  /// Enables the exit API.
2088  #[serde(default)]
2089  pub exit: bool,
2090}
2091
2092impl Allowlist for ProcessAllowlistConfig {
2093  fn all_features() -> Vec<&'static str> {
2094    let allowlist = Self {
2095      all: false,
2096      relaunch: true,
2097      relaunch_dangerous_allow_symlink_macos: false,
2098      exit: true,
2099    };
2100    let mut features = allowlist.to_features();
2101    features.push("process-all");
2102    features
2103  }
2104
2105  fn to_features(&self) -> Vec<&'static str> {
2106    if self.all {
2107      vec!["process-all"]
2108    } else {
2109      let mut features = Vec::new();
2110      check_feature!(self, features, relaunch, "process-relaunch");
2111      check_feature!(
2112        self,
2113        features,
2114        relaunch_dangerous_allow_symlink_macos,
2115        "process-relaunch-dangerous-allow-symlink-macos"
2116      );
2117      check_feature!(self, features, exit, "process-exit");
2118      features
2119    }
2120  }
2121}
2122
2123/// Allowlist for the clipboard APIs.
2124///
2125/// See more: https://tauri.app/v1/api/config#clipboardallowlistconfig
2126#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2127#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2128#[serde(rename_all = "camelCase", deny_unknown_fields)]
2129pub struct ClipboardAllowlistConfig {
2130  /// Use this flag to enable all clipboard APIs.
2131  #[serde(default)]
2132  pub all: bool,
2133  /// Enables the clipboard's `writeText` API.
2134  #[serde(default, alias = "writeText")]
2135  pub write_text: bool,
2136  /// Enables the clipboard's `readText` API.
2137  #[serde(default, alias = "readText")]
2138  pub read_text: bool,
2139}
2140
2141impl Allowlist for ClipboardAllowlistConfig {
2142  fn all_features() -> Vec<&'static str> {
2143    let allowlist = Self {
2144      all: false,
2145      write_text: true,
2146      read_text: true,
2147    };
2148    let mut features = allowlist.to_features();
2149    features.push("clipboard-all");
2150    features
2151  }
2152
2153  fn to_features(&self) -> Vec<&'static str> {
2154    if self.all {
2155      vec!["clipboard-all"]
2156    } else {
2157      let mut features = Vec::new();
2158      check_feature!(self, features, write_text, "clipboard-write-text");
2159      check_feature!(self, features, read_text, "clipboard-read-text");
2160      features
2161    }
2162  }
2163}
2164
2165/// Allowlist for the app APIs.
2166///
2167/// See more: https://tauri.app/v1/api/config#appallowlistconfig
2168#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2169#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2170#[serde(rename_all = "camelCase", deny_unknown_fields)]
2171pub struct AppAllowlistConfig {
2172  /// Use this flag to enable all app APIs.
2173  #[serde(default)]
2174  pub all: bool,
2175  /// Enables the app's `show` API.
2176  #[serde(default)]
2177  pub show: bool,
2178  /// Enables the app's `hide` API.
2179  #[serde(default)]
2180  pub hide: bool,
2181}
2182
2183impl Allowlist for AppAllowlistConfig {
2184  fn all_features() -> Vec<&'static str> {
2185    let allowlist = Self {
2186      all: false,
2187      show: true,
2188      hide: true,
2189    };
2190    let mut features = allowlist.to_features();
2191    features.push("app-all");
2192    features
2193  }
2194
2195  fn to_features(&self) -> Vec<&'static str> {
2196    if self.all {
2197      vec!["app-all"]
2198    } else {
2199      let mut features = Vec::new();
2200      check_feature!(self, features, show, "app-show");
2201      check_feature!(self, features, hide, "app-hide");
2202      features
2203    }
2204  }
2205}
2206
2207/// Allowlist configuration. The allowlist is a translation of the [Cargo allowlist features](https://docs.rs/tauri/latest/tauri/#cargo-allowlist-features).
2208///
2209/// # Notes
2210///
2211/// - Endpoints that don't have their own allowlist option are enabled by default.
2212/// - There is only "opt-in", no "opt-out". Setting an option to `false` has no effect.
2213///
2214/// # Examples
2215///
2216/// - * [`"app-all": true`](https://tauri.app/v1/api/config/#appallowlistconfig.all) will make the [hide](https://tauri.app/v1/api/js/app#hide) endpoint be available regardless of whether `hide` is set to `false` or `true` in the allowlist.
2217#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2218#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2219#[serde(rename_all = "camelCase", deny_unknown_fields)]
2220pub struct AllowlistConfig {
2221  /// Use this flag to enable all API features.
2222  #[serde(default)]
2223  pub all: bool,
2224  /// File system API allowlist.
2225  #[serde(default)]
2226  pub fs: FsAllowlistConfig,
2227  /// Window API allowlist.
2228  #[serde(default)]
2229  pub window: WindowAllowlistConfig,
2230  /// Shell API allowlist.
2231  #[serde(default)]
2232  pub shell: ShellAllowlistConfig,
2233  /// Dialog API allowlist.
2234  #[serde(default)]
2235  pub dialog: DialogAllowlistConfig,
2236  /// HTTP API allowlist.
2237  #[serde(default)]
2238  pub http: HttpAllowlistConfig,
2239  /// Notification API allowlist.
2240  #[serde(default)]
2241  pub notification: NotificationAllowlistConfig,
2242  /// Global shortcut API allowlist.
2243  #[serde(default, alias = "global-shortcut")]
2244  pub global_shortcut: GlobalShortcutAllowlistConfig,
2245  /// OS allowlist.
2246  #[serde(default)]
2247  pub os: OsAllowlistConfig,
2248  /// Path API allowlist.
2249  #[serde(default)]
2250  pub path: PathAllowlistConfig,
2251  /// Custom protocol allowlist.
2252  #[serde(default)]
2253  pub protocol: ProtocolAllowlistConfig,
2254  /// Process API allowlist.
2255  #[serde(default)]
2256  pub process: ProcessAllowlistConfig,
2257  /// Clipboard APIs allowlist.
2258  #[serde(default)]
2259  pub clipboard: ClipboardAllowlistConfig,
2260  /// App APIs allowlist.
2261  #[serde(default)]
2262  pub app: AppAllowlistConfig,
2263}
2264
2265impl Allowlist for AllowlistConfig {
2266  fn all_features() -> Vec<&'static str> {
2267    let mut features = vec!["api-all"];
2268    features.extend(FsAllowlistConfig::all_features());
2269    features.extend(WindowAllowlistConfig::all_features());
2270    features.extend(ShellAllowlistConfig::all_features());
2271    features.extend(DialogAllowlistConfig::all_features());
2272    features.extend(HttpAllowlistConfig::all_features());
2273    features.extend(NotificationAllowlistConfig::all_features());
2274    features.extend(GlobalShortcutAllowlistConfig::all_features());
2275    features.extend(OsAllowlistConfig::all_features());
2276    features.extend(PathAllowlistConfig::all_features());
2277    features.extend(ProtocolAllowlistConfig::all_features());
2278    features.extend(ProcessAllowlistConfig::all_features());
2279    features.extend(ClipboardAllowlistConfig::all_features());
2280    features.extend(AppAllowlistConfig::all_features());
2281    features
2282  }
2283
2284  fn to_features(&self) -> Vec<&'static str> {
2285    if self.all {
2286      vec!["api-all"]
2287    } else {
2288      let mut features = Vec::new();
2289      features.extend(self.fs.to_features());
2290      features.extend(self.window.to_features());
2291      features.extend(self.shell.to_features());
2292      features.extend(self.dialog.to_features());
2293      features.extend(self.http.to_features());
2294      features.extend(self.notification.to_features());
2295      features.extend(self.global_shortcut.to_features());
2296      features.extend(self.os.to_features());
2297      features.extend(self.path.to_features());
2298      features.extend(self.protocol.to_features());
2299      features.extend(self.process.to_features());
2300      features.extend(self.clipboard.to_features());
2301      features.extend(self.app.to_features());
2302      features
2303    }
2304  }
2305}
2306
2307/// The application pattern.
2308#[skip_serializing_none]
2309#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, Default)]
2310#[serde(rename_all = "lowercase", tag = "use", content = "options")]
2311#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2312pub enum PatternKind {
2313  /// Brownfield pattern.
2314  #[default]
2315  Brownfield,
2316  /// Isolation pattern. Recommended for security purposes.
2317  Isolation {
2318    /// The dir containing the index.html file that contains the secure isolation application.
2319    dir: PathBuf,
2320  },
2321}
2322
2323/// The Tauri configuration object.
2324///
2325/// See more: https://tauri.app/v1/api/config#tauriconfig
2326#[skip_serializing_none]
2327#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
2328#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2329#[serde(rename_all = "camelCase", deny_unknown_fields)]
2330pub struct TauriConfig {
2331  /// The pattern to use.
2332  #[serde(default)]
2333  pub pattern: PatternKind,
2334  /// The windows configuration.
2335  #[serde(default)]
2336  pub windows: Vec<WindowConfig>,
2337  /// The CLI configuration.
2338  pub cli: Option<CliConfig>,
2339  /// The bundler configuration.
2340  #[serde(default)]
2341  pub bundle: BundleConfig,
2342  /// The allowlist configuration.
2343  #[serde(default)]
2344  pub allowlist: AllowlistConfig,
2345  /// Security configuration.
2346  #[serde(default)]
2347  pub security: SecurityConfig,
2348  /// The updater configuration.
2349  #[serde(default)]
2350  pub updater: UpdaterConfig,
2351  /// Configuration for app system tray.
2352  #[serde(alias = "system-tray")]
2353  pub system_tray: Option<SystemTrayConfig>,
2354  /// MacOS private API configuration. Enables the transparent background API and sets the `fullScreenEnabled` preference to `true`.
2355  #[serde(rename = "macOSPrivateApi", alias = "macos-private-api", default)]
2356  pub macos_private_api: bool,
2357}
2358
2359/// A URL to an updater server.
2360///
2361/// The URL must use the `https` scheme on production.
2362#[skip_serializing_none]
2363#[derive(Debug, PartialEq, Eq, Clone, Serialize)]
2364#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2365pub struct UpdaterEndpoint(pub Url);
2366
2367impl std::fmt::Display for UpdaterEndpoint {
2368  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2369    write!(f, "{}", self.0)
2370  }
2371}
2372
2373impl<'de> Deserialize<'de> for UpdaterEndpoint {
2374  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2375  where
2376    D: Deserializer<'de>,
2377  {
2378    let url = Url::deserialize(deserializer)?;
2379    #[cfg(all(not(debug_assertions), not(feature = "schema")))]
2380    {
2381      if url.scheme() != "https" {
2382        return Err(serde::de::Error::custom(
2383          "The configured updater endpoint must use the `https` protocol.",
2384        ));
2385      }
2386    }
2387    Ok(Self(url))
2388  }
2389}
2390
2391/// Install modes for the Windows update.
2392#[derive(Debug, PartialEq, Eq, Clone, Default)]
2393#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2394#[cfg_attr(feature = "schema", schemars(rename_all = "camelCase"))]
2395pub enum WindowsUpdateInstallMode {
2396  /// Specifies there's a basic UI during the installation process, including a final dialog box at the end.
2397  BasicUi,
2398  /// The quiet mode means there's no user interaction required.
2399  /// Requires admin privileges if the installer does.
2400  Quiet,
2401  /// Specifies unattended mode, which means the installation only shows a progress bar.
2402  #[default]
2403  Passive,
2404  // to add more modes, we need to check if the updater relaunch makes sense
2405  // i.e. for a full UI mode, the user can also mark the installer to start the app
2406}
2407
2408impl Display for WindowsUpdateInstallMode {
2409  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2410    write!(
2411      f,
2412      "{}",
2413      match self {
2414        Self::BasicUi => "basicUI",
2415        Self::Quiet => "quiet",
2416        Self::Passive => "passive",
2417      }
2418    )
2419  }
2420}
2421
2422impl Serialize for WindowsUpdateInstallMode {
2423  fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2424  where
2425    S: Serializer,
2426  {
2427    serializer.serialize_str(self.to_string().as_ref())
2428  }
2429}
2430
2431impl<'de> Deserialize<'de> for WindowsUpdateInstallMode {
2432  fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2433  where
2434    D: Deserializer<'de>,
2435  {
2436    let s = String::deserialize(deserializer)?;
2437    match s.to_lowercase().as_str() {
2438      "basicui" => Ok(Self::BasicUi),
2439      "quiet" => Ok(Self::Quiet),
2440      "passive" => Ok(Self::Passive),
2441      _ => Err(DeError::custom(format!(
2442        "unknown update install mode '{s}'"
2443      ))),
2444    }
2445  }
2446}
2447
2448/// The updater configuration for Windows.
2449///
2450/// See more: https://tauri.app/v1/api/config#updaterwindowsconfig
2451#[skip_serializing_none]
2452#[derive(Debug, Default, PartialEq, Eq, Clone, Serialize, Deserialize)]
2453#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2454#[serde(rename_all = "camelCase", deny_unknown_fields)]
2455pub struct UpdaterWindowsConfig {
2456  /// Additional arguments given to the NSIS or WiX installer.
2457  #[serde(default, alias = "installer-args")]
2458  pub installer_args: Vec<String>,
2459  /// The installation mode for the update on Windows. Defaults to `passive`.
2460  #[serde(default, alias = "install-mode")]
2461  pub install_mode: WindowsUpdateInstallMode,
2462}
2463
2464/// The Updater configuration object.
2465///
2466/// See more: https://tauri.app/v1/api/config#updaterconfig
2467#[skip_serializing_none]
2468#[derive(Debug, PartialEq, Eq, Clone, Serialize)]
2469#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2470#[serde(rename_all = "camelCase", deny_unknown_fields)]
2471pub struct UpdaterConfig {
2472  /// Whether the updater is active or not.
2473  #[serde(default)]
2474  pub active: bool,
2475  /// Display built-in dialog or use event system if disabled.
2476  #[serde(default = "default_true")]
2477  pub dialog: bool,
2478  /// The updater endpoints. TLS is enforced on production.
2479  ///
2480  /// The updater URL can contain the following variables:
2481  /// - {{current_version}}: The version of the app that is requesting the update
2482  /// - {{target}}: The operating system name (one of `linux`, `windows` or `darwin`).
2483  /// - {{arch}}: The architecture of the machine (one of `x86_64`, `i686`, `aarch64` or `armv7`).
2484  ///
2485  /// # Examples
2486  /// - "https://my.cdn.com/latest.json": a raw JSON endpoint that returns the latest version and download links for each platform.
2487  /// - "https://updates.app.dev/{{target}}?version={{current_version}}&arch={{arch}}": a dedicated API with positional and query string arguments.
2488  #[allow(rustdoc::bare_urls)]
2489  pub endpoints: Option<Vec<UpdaterEndpoint>>,
2490  /// Signature public key.
2491  #[serde(default)] // use default just so the schema doesn't flag it as required
2492  pub pubkey: String,
2493  /// The Windows configuration for the updater.
2494  #[serde(default)]
2495  pub windows: UpdaterWindowsConfig,
2496}
2497
2498impl<'de> Deserialize<'de> for UpdaterConfig {
2499  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2500  where
2501    D: Deserializer<'de>,
2502  {
2503    #[derive(Deserialize)]
2504    struct InnerUpdaterConfig {
2505      #[serde(default)]
2506      active: bool,
2507      #[serde(default = "default_true")]
2508      dialog: bool,
2509      endpoints: Option<Vec<UpdaterEndpoint>>,
2510      pubkey: Option<String>,
2511      #[serde(default)]
2512      windows: UpdaterWindowsConfig,
2513    }
2514
2515    let config = InnerUpdaterConfig::deserialize(deserializer)?;
2516
2517    if config.active && config.pubkey.is_none() {
2518      return Err(DeError::custom(
2519        "The updater `pubkey` configuration is required.",
2520      ));
2521    }
2522
2523    Ok(UpdaterConfig {
2524      active: config.active,
2525      dialog: config.dialog,
2526      endpoints: config.endpoints,
2527      pubkey: config.pubkey.unwrap_or_default(),
2528      windows: config.windows,
2529    })
2530  }
2531}
2532
2533impl Default for UpdaterConfig {
2534  fn default() -> Self {
2535    Self {
2536      active: false,
2537      dialog: true,
2538      endpoints: None,
2539      pubkey: "".into(),
2540      windows: Default::default(),
2541    }
2542  }
2543}
2544
2545/// Configuration for application system tray icon.
2546///
2547/// See more: https://tauri.app/v1/api/config#systemtrayconfig
2548#[skip_serializing_none]
2549#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
2550#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2551#[serde(rename_all = "camelCase", deny_unknown_fields)]
2552pub struct SystemTrayConfig {
2553  /// Path to the default icon to use on the system tray.
2554  #[serde(alias = "icon-path")]
2555  pub icon_path: PathBuf,
2556  /// A Boolean value that determines whether the image represents a [template](https://developer.apple.com/documentation/appkit/nsimage/1520017-template?language=objc) image on macOS.
2557  #[serde(default, alias = "icon-as-template")]
2558  pub icon_as_template: bool,
2559  /// A Boolean value that determines whether the menu should appear when the tray icon receives a left click on macOS.
2560  #[serde(default = "default_true", alias = "menu-on-left-click")]
2561  pub menu_on_left_click: bool,
2562  /// Title for MacOS tray
2563  pub title: Option<String>,
2564}
2565
2566/// Defines the URL or assets to embed in the application.
2567#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2568#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2569#[serde(untagged, deny_unknown_fields)]
2570#[non_exhaustive]
2571pub enum AppUrl {
2572  /// The app's external URL, or the path to the directory containing the app assets.
2573  Url(WindowUrl),
2574  /// An array of files to embed on the app.
2575  Files(Vec<PathBuf>),
2576}
2577
2578impl std::fmt::Display for AppUrl {
2579  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2580    match self {
2581      Self::Url(url) => write!(f, "{url}"),
2582      Self::Files(files) => write!(f, "{}", serde_json::to_string(files).unwrap()),
2583    }
2584  }
2585}
2586
2587/// Describes the shell command to run before `tauri dev`.
2588#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2589#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2590#[serde(rename_all = "camelCase", untagged)]
2591pub enum BeforeDevCommand {
2592  /// Run the given script with the default options.
2593  Script(String),
2594  /// Run the given script with custom options.
2595  ScriptWithOptions {
2596    /// The script to execute.
2597    script: String,
2598    /// The current working directory.
2599    cwd: Option<String>,
2600    /// Whether `tauri dev` should wait for the command to finish or not. Defaults to `false`.
2601    #[serde(default)]
2602    wait: bool,
2603  },
2604}
2605
2606/// Describes a shell command to be executed when a CLI hook is triggered.
2607#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2608#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2609#[serde(rename_all = "camelCase", untagged)]
2610pub enum HookCommand {
2611  /// Run the given script with the default options.
2612  Script(String),
2613  /// Run the given script with custom options.
2614  ScriptWithOptions {
2615    /// The script to execute.
2616    script: String,
2617    /// The current working directory.
2618    cwd: Option<String>,
2619  },
2620}
2621
2622/// The Build configuration object.
2623///
2624/// See more: https://tauri.app/v1/api/config#buildconfig
2625#[skip_serializing_none]
2626#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
2627#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2628#[serde(rename_all = "camelCase", deny_unknown_fields)]
2629pub struct BuildConfig {
2630  /// The binary used to build and run the application.
2631  pub runner: Option<String>,
2632  /// The path to the application assets or URL to load in development.
2633  ///
2634  /// This is usually an URL to a dev server, which serves your application assets
2635  /// with live reloading. Most modern JavaScript bundlers provides a way to start a dev server by default.
2636  ///
2637  /// See [vite](https://vitejs.dev/guide/), [Webpack DevServer](https://webpack.js.org/configuration/dev-server/) and [sirv](https://github.com/lukeed/sirv)
2638  /// for examples on how to set up a dev server.
2639  #[serde(default = "default_dev_path", alias = "dev-path")]
2640  pub dev_path: AppUrl,
2641  /// The path to the application assets or URL to load in production.
2642  ///
2643  /// When a path relative to the configuration file is provided,
2644  /// it is read recursively and all files are embedded in the application binary.
2645  /// Tauri then looks for an `index.html` file unless you provide a custom window URL.
2646  ///
2647  /// You can also provide a list of paths to be embedded, which allows granular control over what files are added to the binary.
2648  /// In this case, all files are added to the root and you must reference it that way in your HTML files.
2649  ///
2650  /// When an URL is provided, the application won't have bundled assets
2651  /// and the application will load that URL by default.
2652  #[serde(default = "default_dist_dir", alias = "dist-dir")]
2653  pub dist_dir: AppUrl,
2654  /// A shell command to run before `tauri dev` kicks in.
2655  ///
2656  /// The TAURI_PLATFORM, TAURI_ARCH, TAURI_FAMILY, TAURI_PLATFORM_VERSION, TAURI_PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation.
2657  #[serde(alias = "before-dev-command")]
2658  pub before_dev_command: Option<BeforeDevCommand>,
2659  /// A shell command to run before `tauri build` kicks in.
2660  ///
2661  /// The TAURI_PLATFORM, TAURI_ARCH, TAURI_FAMILY, TAURI_PLATFORM_VERSION, TAURI_PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation.
2662  #[serde(alias = "before-build-command")]
2663  pub before_build_command: Option<HookCommand>,
2664  /// A shell command to run before the bundling phase in `tauri build` kicks in.
2665  ///
2666  /// The TAURI_PLATFORM, TAURI_ARCH, TAURI_FAMILY, TAURI_PLATFORM_VERSION, TAURI_PLATFORM_TYPE and TAURI_DEBUG environment variables are set if you perform conditional compilation.
2667  #[serde(alias = "before-bundle-command")]
2668  pub before_bundle_command: Option<HookCommand>,
2669  /// Features passed to `cargo` commands.
2670  pub features: Option<Vec<String>>,
2671  /// Whether we should inject the Tauri API on `window.__TAURI__` or not.
2672  #[serde(default, alias = "with-global-tauri")]
2673  pub with_global_tauri: bool,
2674}
2675
2676impl Default for BuildConfig {
2677  fn default() -> Self {
2678    Self {
2679      runner: None,
2680      dev_path: default_dev_path(),
2681      dist_dir: default_dist_dir(),
2682      before_dev_command: None,
2683      before_build_command: None,
2684      before_bundle_command: None,
2685      features: None,
2686      with_global_tauri: false,
2687    }
2688  }
2689}
2690
2691fn default_dev_path() -> AppUrl {
2692  AppUrl::Url(WindowUrl::External(
2693    Url::parse("http://localhost:8080").unwrap(),
2694  ))
2695}
2696
2697fn default_dist_dir() -> AppUrl {
2698  AppUrl::Url(WindowUrl::App("../dist".into()))
2699}
2700
2701#[derive(Debug, PartialEq, Eq)]
2702struct PackageVersion(String);
2703
2704impl<'d> serde::Deserialize<'d> for PackageVersion {
2705  fn deserialize<D: Deserializer<'d>>(deserializer: D) -> Result<PackageVersion, D::Error> {
2706    struct PackageVersionVisitor;
2707
2708    impl<'d> Visitor<'d> for PackageVersionVisitor {
2709      type Value = PackageVersion;
2710
2711      fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2712        write!(
2713          formatter,
2714          "a semver string or a path to a package.json file"
2715        )
2716      }
2717
2718      fn visit_str<E: DeError>(self, value: &str) -> Result<PackageVersion, E> {
2719        let path = PathBuf::from(value);
2720        if path.exists() {
2721          let json_str = read_to_string(&path)
2722            .map_err(|e| DeError::custom(format!("failed to read version JSON file: {e}")))?;
2723          let package_json: serde_json::Value = serde_json::from_str(&json_str)
2724            .map_err(|e| DeError::custom(format!("failed to read version JSON file: {e}")))?;
2725          if let Some(obj) = package_json.as_object() {
2726            let version = obj
2727              .get("version")
2728              .ok_or_else(|| DeError::custom("JSON must contain a `version` field"))?
2729              .as_str()
2730              .ok_or_else(|| {
2731                DeError::custom(format!("`{} > version` must be a string", path.display()))
2732              })?;
2733            Ok(PackageVersion(
2734              Version::from_str(version)
2735                .map_err(|_| DeError::custom("`package > version` must be a semver string"))?
2736                .to_string(),
2737            ))
2738          } else {
2739            Err(DeError::custom(
2740              "`package > version` value is not a path to a JSON object",
2741            ))
2742          }
2743        } else {
2744          Ok(PackageVersion(
2745            Version::from_str(value)
2746              .map_err(|_| DeError::custom("`package > version` must be a semver string"))?
2747              .to_string(),
2748          ))
2749        }
2750      }
2751    }
2752
2753    deserializer.deserialize_string(PackageVersionVisitor {})
2754  }
2755}
2756
2757/// The package configuration.
2758///
2759/// See more: https://tauri.app/v1/api/config#packageconfig
2760#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
2761#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2762#[serde(rename_all = "camelCase", deny_unknown_fields)]
2763pub struct PackageConfig {
2764  /// App name.
2765  #[serde(alias = "product-name")]
2766  #[cfg_attr(feature = "schema", schemars(regex(pattern = "^[^/\\:*?\"<>|]+$")))]
2767  pub product_name: Option<String>,
2768  /// App version. It is a semver version number or a path to a `package.json` file containing the `version` field. If removed the version number from `Cargo.toml` is used.
2769  #[serde(deserialize_with = "version_deserializer", default)]
2770  pub version: Option<String>,
2771}
2772
2773fn version_deserializer<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
2774where
2775  D: Deserializer<'de>,
2776{
2777  Option::<PackageVersion>::deserialize(deserializer).map(|v| v.map(|v| v.0))
2778}
2779
2780/// The Tauri configuration object.
2781/// It is read from a file where you can define your frontend assets,
2782/// configure the bundler, enable the app updater, define a system tray,
2783/// enable APIs via the allowlist and more.
2784///
2785/// The configuration file is generated by the
2786/// [`tauri init`](https://tauri.app/v1/api/cli#init) command that lives in
2787/// your Tauri application source directory (src-tauri).
2788///
2789/// Once generated, you may modify it at will to customize your Tauri application.
2790///
2791/// ## File Formats
2792///
2793/// By default, the configuration is defined as a JSON file named `tauri.conf.json`.
2794///
2795/// Tauri also supports JSON5 and TOML files via the `config-json5` and `config-toml` Cargo features, respectively.
2796/// The JSON5 file name must be either `tauri.conf.json` or `tauri.conf.json5`.
2797/// The TOML file name is `Tauri.toml`.
2798///
2799/// ## Platform-Specific Configuration
2800///
2801/// In addition to the default configuration file, Tauri can
2802/// read a platform-specific configuration from `tauri.linux.conf.json`,
2803/// `tauri.windows.conf.json`, and `tauri.macos.conf.json`
2804/// (or `Tauri.linux.toml`, `Tauri.windows.toml` and `Tauri.macos.toml` if the `Tauri.toml` format is used),
2805/// which gets merged with the main configuration object.
2806///
2807/// ## Configuration Structure
2808///
2809/// The configuration is composed of the following objects:
2810///
2811/// - [`package`](#packageconfig): Package settings
2812/// - [`tauri`](#tauriconfig): The Tauri config
2813/// - [`build`](#buildconfig): The build configuration
2814/// - [`plugins`](#pluginconfig): The plugins config
2815///
2816/// ```json title="Example tauri.config.json file"
2817/// {
2818///   "build": {
2819///     "beforeBuildCommand": "",
2820///     "beforeDevCommand": "",
2821///     "devPath": "../dist",
2822///     "distDir": "../dist"
2823///   },
2824///   "package": {
2825///     "productName": "tauri-app",
2826///     "version": "0.1.0"
2827///   },
2828///   "tauri": {
2829///     "allowlist": {
2830///       "all": true
2831///     },
2832///     "bundle": {},
2833///     "security": {
2834///       "csp": null
2835///     },
2836///     "updater": {
2837///       "active": false
2838///     },
2839///     "windows": [
2840///       {
2841///         "fullscreen": false,
2842///         "height": 600,
2843///         "resizable": true,
2844///         "title": "Tauri App",
2845///         "width": 800
2846///       }
2847///     ]
2848///   }
2849/// }
2850/// ```
2851#[allow(rustdoc::invalid_codeblock_attributes)]
2852#[skip_serializing_none]
2853#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
2854#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2855#[serde(rename_all = "camelCase", deny_unknown_fields)]
2856pub struct Config {
2857  /// The JSON schema for the Tauri config.
2858  #[serde(rename = "$schema")]
2859  pub schema: Option<String>,
2860  /// Package settings.
2861  #[serde(default)]
2862  pub package: PackageConfig,
2863  /// The Tauri configuration.
2864  #[serde(default)]
2865  pub tauri: TauriConfig,
2866  /// The build configuration.
2867  #[serde(default = "default_build")]
2868  pub build: BuildConfig,
2869  /// The plugins config.
2870  #[serde(default)]
2871  pub plugins: PluginConfig,
2872}
2873
2874/// The plugin configs holds a HashMap mapping a plugin name to its configuration object.
2875///
2876/// See more: https://tauri.app/v1/api/config#pluginconfig
2877#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
2878#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2879pub struct PluginConfig(pub HashMap<String, JsonValue>);
2880
2881fn default_build() -> BuildConfig {
2882  BuildConfig {
2883    runner: None,
2884    dev_path: default_dev_path(),
2885    dist_dir: default_dist_dir(),
2886    before_dev_command: None,
2887    before_build_command: None,
2888    before_bundle_command: None,
2889    features: None,
2890    with_global_tauri: false,
2891  }
2892}
2893
2894/// How the window title bar should be displayed on macOS.
2895#[derive(Debug, Clone, PartialEq, Eq, Default)]
2896#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2897pub enum TitleBarStyle {
2898  /// A normal title bar.
2899  #[default]
2900  Visible,
2901  /// Makes the title bar transparent, so the window background color is shown instead.
2902  ///
2903  /// Useful if you don't need to have actual HTML under the title bar. This lets you avoid the caveats of using `TitleBarStyle::Overlay`. Will be more useful when Tauri lets you set a custom window background color.
2904  Transparent,
2905  /// Shows the title bar as a transparent overlay over the window's content.
2906  ///
2907  /// Keep in mind:
2908  /// - The height of the title bar is different on different OS versions, which can lead to window the controls and title not being where you don't expect.
2909  /// - You need to define a custom drag region to make your window draggable, however due to a limitation you can't drag the window when it's not in focus <https://github.com/tauri-apps/tauri/issues/4316>.
2910  /// - The color of the window title depends on the system theme.
2911  Overlay,
2912}
2913
2914impl Serialize for TitleBarStyle {
2915  fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2916  where
2917    S: Serializer,
2918  {
2919    serializer.serialize_str(self.to_string().as_ref())
2920  }
2921}
2922
2923impl<'de> Deserialize<'de> for TitleBarStyle {
2924  fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2925  where
2926    D: Deserializer<'de>,
2927  {
2928    let s = String::deserialize(deserializer)?;
2929    Ok(match s.to_lowercase().as_str() {
2930      "transparent" => Self::Transparent,
2931      "overlay" => Self::Overlay,
2932      _ => Self::Visible,
2933    })
2934  }
2935}
2936
2937impl Display for TitleBarStyle {
2938  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2939    write!(
2940      f,
2941      "{}",
2942      match self {
2943        Self::Visible => "Visible",
2944        Self::Transparent => "Transparent",
2945        Self::Overlay => "Overlay",
2946      }
2947    )
2948  }
2949}
2950
2951/// System theme.
2952#[derive(Debug, Copy, Clone, PartialEq, Eq)]
2953#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2954#[non_exhaustive]
2955pub enum Theme {
2956  /// Light theme.
2957  Light,
2958  /// Dark theme.
2959  Dark,
2960}
2961
2962impl Serialize for Theme {
2963  fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2964  where
2965    S: Serializer,
2966  {
2967    serializer.serialize_str(self.to_string().as_ref())
2968  }
2969}
2970
2971impl<'de> Deserialize<'de> for Theme {
2972  fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2973  where
2974    D: Deserializer<'de>,
2975  {
2976    let s = String::deserialize(deserializer)?;
2977    Ok(match s.to_lowercase().as_str() {
2978      "dark" => Self::Dark,
2979      _ => Self::Light,
2980    })
2981  }
2982}
2983
2984impl Display for Theme {
2985  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2986    write!(
2987      f,
2988      "{}",
2989      match self {
2990        Self::Light => "light",
2991        Self::Dark => "dark",
2992      }
2993    )
2994  }
2995}
2996
2997#[cfg(test)]
2998mod test {
2999  use super::*;
3000
3001  // TODO: create a test that compares a config to a json config
3002
3003  #[test]
3004  // test all of the default functions
3005  fn test_defaults() {
3006    // get default tauri config
3007    let t_config = TauriConfig::default();
3008    // get default build config
3009    let b_config = BuildConfig::default();
3010    // get default dev path
3011    let d_path = default_dev_path();
3012    // get default window
3013    let d_windows: Vec<WindowConfig> = vec![];
3014    // get default bundle
3015    let d_bundle = BundleConfig::default();
3016    // get default updater
3017    let d_updater = UpdaterConfig::default();
3018
3019    // create a tauri config.
3020    let tauri = TauriConfig {
3021      pattern: Default::default(),
3022      windows: vec![],
3023      bundle: BundleConfig {
3024        active: false,
3025        targets: Default::default(),
3026        identifier: String::from(""),
3027        publisher: None,
3028        icon: Vec::new(),
3029        resources: None,
3030        copyright: None,
3031        category: None,
3032        short_description: None,
3033        long_description: None,
3034        appimage: Default::default(),
3035        deb: Default::default(),
3036        macos: Default::default(),
3037        external_bin: None,
3038        windows: Default::default(),
3039      },
3040      cli: None,
3041      updater: UpdaterConfig {
3042        active: false,
3043        dialog: true,
3044        pubkey: "".into(),
3045        endpoints: None,
3046        windows: Default::default(),
3047      },
3048      security: SecurityConfig {
3049        csp: None,
3050        dev_csp: None,
3051        freeze_prototype: false,
3052        dangerous_disable_asset_csp_modification: DisabledCspModificationKind::Flag(false),
3053        dangerous_remote_domain_ipc_access: Vec::new(),
3054        dangerous_use_http_scheme: false,
3055      },
3056      allowlist: AllowlistConfig::default(),
3057      system_tray: None,
3058      macos_private_api: false,
3059    };
3060
3061    // create a build config
3062    let build = BuildConfig {
3063      runner: None,
3064      dev_path: AppUrl::Url(WindowUrl::External(
3065        Url::parse("http://localhost:8080").unwrap(),
3066      )),
3067      dist_dir: AppUrl::Url(WindowUrl::App("../dist".into())),
3068      before_dev_command: None,
3069      before_build_command: None,
3070      before_bundle_command: None,
3071      features: None,
3072      with_global_tauri: false,
3073    };
3074
3075    // test the configs
3076    assert_eq!(t_config, tauri);
3077    assert_eq!(b_config, build);
3078    assert_eq!(d_bundle, tauri.bundle);
3079    assert_eq!(d_updater, tauri.updater);
3080    assert_eq!(
3081      d_path,
3082      AppUrl::Url(WindowUrl::External(
3083        Url::parse("http://localhost:8080").unwrap()
3084      ))
3085    );
3086    assert_eq!(d_windows, tauri.windows);
3087  }
3088}