Dev loop: debug-only page scripts from disk + tab rebuild on change (waybetter-host devloop, page_script!), generic devmode watcher, waybetter dev, buildRuntime watch, template scripts
This commit is contained in:
parent
4740e6b2db
commit
8da1f1b20e
11 changed files with 377 additions and 26 deletions
|
|
@ -404,8 +404,10 @@ fn in_site(site: &SiteSpec, hooks: &dyn SiteHooks, url: &Url) -> bool {
|
||||||
/// Reconciles native tab webviews with the shell's panes: creates missing ones, positions and
|
/// Reconciles native tab webviews with the shell's panes: creates missing ones, positions and
|
||||||
/// shows/hides all of them, and closes webviews whose tab no longer exists.
|
/// shows/hides all of them, and closes webviews whose tab no longer exists.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLayout>, viewport: Option<[f64; 2]>) -> Result<(), String> {
|
pub(crate) async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLayout>, viewport: Option<[f64; 2]>) -> Result<(), String> {
|
||||||
shell_only(&webview)?;
|
shell_only(&webview)?;
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
crate::devloop::remember_layout(&items, viewport);
|
||||||
let hooks = host_state(&app).hooks.clone();
|
let hooks = host_state(&app).hooks.clone();
|
||||||
let window = webview.window();
|
let window = webview.window();
|
||||||
// Kept current by the window's resize events (host::follow_window_resizes): no blocking
|
// Kept current by the window's resize events (host::follow_window_resizes): no blocking
|
||||||
|
|
@ -1106,6 +1108,8 @@ impl App {
|
||||||
});
|
});
|
||||||
tauri_app.manage(Page(Mutex::new(PageState { plugins, features, settings, modes })));
|
tauri_app.manage(Page(Mutex::new(PageState { plugins, features, settings, modes })));
|
||||||
tauri_app.manage(Host { config, hooks });
|
tauri_app.manage(Host { config, hooks });
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
crate::devloop::start(&handle);
|
||||||
if let Some(setup) = setup {
|
if let Some(setup) = setup {
|
||||||
setup(&handle)?;
|
setup(&handle)?;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
116
crates/waybetter-host/src/devloop.rs
Normal file
116
crates/waybetter-host/src/devloop.rs
Normal file
|
|
@ -0,0 +1,116 @@
|
||||||
|
//! The debug dev loop: an app's page scripts are read from disk whenever a tab's init scripts are
|
||||||
|
//! built, and when one of those files changes every tab webview is rebuilt on its current URL, so
|
||||||
|
//! the new script is injected within a second or two without restarting the app.
|
||||||
|
//!
|
||||||
|
//! This module exists only in debug builds (`cfg(debug_assertions)`, see `lib.rs`); release builds
|
||||||
|
//! contain no file read, no path string and no watcher. An app names its files with
|
||||||
|
//! [`page_script!`](crate::page_script) in `SiteHooks::init_scripts`; the files it names are the ones
|
||||||
|
//! watched. Change detection is `devmode`'s debounced signature watcher (a file must keep its
|
||||||
|
//! size and modification time for `DEBOUNCE`, so a half-written bundle never loads).
|
||||||
|
//!
|
||||||
|
//! Why the tabs are rebuilt rather than reloaded: a webview's document-start scripts are fixed at
|
||||||
|
//! creation, so a plain reload would run the old copy. The rebuild reuses `tabs_sync`'s
|
||||||
|
//! profile-change path (close, then create with the current init scripts) on the shell's last
|
||||||
|
//! layout, with each tab's live URL, so route and layout are kept (scroll position is not).
|
||||||
|
|
||||||
|
use crate::app::{self, tabs_sync};
|
||||||
|
use crate::devmode::{self, Watcher};
|
||||||
|
use crate::{host, policy, tabs::TabLayout};
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::Instant;
|
||||||
|
use tauri::{AppHandle, Manager};
|
||||||
|
|
||||||
|
/// Marks a tab's recorded profile as stale so `tabs_sync` rebuilds its webview.
|
||||||
|
const STALE: &str = "\u{0}dev-reload";
|
||||||
|
|
||||||
|
static FILES: Mutex<BTreeSet<PathBuf>> = Mutex::new(BTreeSet::new());
|
||||||
|
static LAYOUT: Mutex<Option<(Vec<TabLayout>, Option<[f64; 2]>)>> = Mutex::new(None);
|
||||||
|
|
||||||
|
/// `path` read from disk (and watched from now on), or `embedded` when it is missing or empty.
|
||||||
|
pub fn from_disk(path: &str, embedded: &str) -> String {
|
||||||
|
let path = PathBuf::from(path);
|
||||||
|
let read = std::fs::read_to_string(&path).ok().filter(|text| !text.trim().is_empty());
|
||||||
|
if let Ok(mut files) = FILES.lock() {
|
||||||
|
files.insert(path);
|
||||||
|
}
|
||||||
|
read.unwrap_or_else(|| embedded.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The shell's latest layout (from `tabs_sync`), to rebuild the tabs from.
|
||||||
|
pub(crate) fn remember_layout(items: &[TabLayout], viewport: Option<[f64; 2]>) {
|
||||||
|
if let Ok(mut layout) = LAYOUT.lock() {
|
||||||
|
*layout = Some((items.to_vec(), viewport));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts the watcher thread (debug builds, from the host's setup).
|
||||||
|
pub(crate) fn start(app: &AppHandle) {
|
||||||
|
let app = app.clone();
|
||||||
|
std::thread::Builder::new().name("wb-dev-loop".into()).spawn(move || watch_loop(app)).ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scan() -> BTreeMap<PathBuf, devmode::Signature> {
|
||||||
|
let files = FILES.lock().map(|files| files.clone()).unwrap_or_default();
|
||||||
|
files.into_iter().filter_map(|path| devmode::signature(&path).map(|sig| (path, sig))).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn watch_loop(app: AppHandle) {
|
||||||
|
let mut watcher: Watcher<PathBuf> = Watcher::new();
|
||||||
|
let mut known = 0;
|
||||||
|
loop {
|
||||||
|
std::thread::sleep(devmode::POLL);
|
||||||
|
let current = scan();
|
||||||
|
// A newly named file (the first tab just built its scripts) becomes part of the baseline.
|
||||||
|
if current.len() != known {
|
||||||
|
known = current.len();
|
||||||
|
watcher.reset();
|
||||||
|
}
|
||||||
|
let changes = watcher.observe(Instant::now(), current);
|
||||||
|
if !changes.is_empty() {
|
||||||
|
let names: Vec<String> = changes.iter().filter_map(|change| change.target().file_name()).map(|name| name.to_string_lossy().into_owned()).collect();
|
||||||
|
let started = Instant::now();
|
||||||
|
reload_tabs(&app);
|
||||||
|
eprintln!("[wayBetter dev] {} changed: tabs rebuilt in {} ms", names.join(", "), started.elapsed().as_millis());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rebuilds every tab webview (fresh init scripts) on its current URL.
|
||||||
|
fn reload_tabs(app: &AppHandle) {
|
||||||
|
let Some((mut items, viewport)) = LAYOUT.lock().ok().and_then(|layout| layout.clone()) else { return };
|
||||||
|
let Some(shell) = app.get_webview(policy::SHELL_LABEL) else { return };
|
||||||
|
for item in &mut items {
|
||||||
|
let Some(tab) = host::tab_webview(app, &item.id) else { continue };
|
||||||
|
if let Ok(url) = tab.url() {
|
||||||
|
if matches!(url.scheme(), "http" | "https") {
|
||||||
|
item.url = url.to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(mut data) = app::profiles(app) {
|
||||||
|
data.tab_profiles.insert(policy::tab_label(&item.id), STALE.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Err(error) = tauri::async_runtime::block_on(tabs_sync(shell, app.clone(), items, viewport)) {
|
||||||
|
eprintln!("[wayBetter dev] tab rebuild failed: {error}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn from_disk_reads_the_file_and_falls_back_to_the_embedded_copy() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let file = dir.path().join("runtime.js");
|
||||||
|
let path = file.to_str().unwrap();
|
||||||
|
assert_eq!(from_disk(path, "embedded"), "embedded", "missing file");
|
||||||
|
std::fs::write(&file, " \n").unwrap();
|
||||||
|
assert_eq!(from_disk(path, "embedded"), "embedded", "empty file");
|
||||||
|
std::fs::write(&file, "fresh();").unwrap();
|
||||||
|
assert_eq!(from_disk(path, "embedded"), "fresh();");
|
||||||
|
assert!(scan().contains_key(&file), "a named file is watched");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -61,21 +61,23 @@ pub struct Signature {
|
||||||
pub modified: Option<SystemTime>,
|
pub modified: Option<SystemTime>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A stable change of one watched key (a [`Target`] for developer mode; the debug page-script
|
||||||
|
/// reload keys its files by path).
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub enum Change {
|
pub enum Change<K = Target> {
|
||||||
Changed(Target),
|
Changed(K),
|
||||||
Removed(Target),
|
Removed(K),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Change {
|
impl<K> Change<K> {
|
||||||
pub fn target(&self) -> &Target {
|
pub fn target(&self) -> &K {
|
||||||
match self {
|
match self {
|
||||||
Change::Changed(target) | Change::Removed(target) => target,
|
Change::Changed(target) | Change::Removed(target) => target,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn signature(path: &Path) -> Option<Signature> {
|
pub fn signature(path: &Path) -> Option<Signature> {
|
||||||
let meta = fs::metadata(path).ok()?;
|
let meta = fs::metadata(path).ok()?;
|
||||||
meta.is_file().then(|| Signature { len: meta.len(), modified: meta.modified().ok() })
|
meta.is_file().then(|| Signature { len: meta.len(), modified: meta.modified().ok() })
|
||||||
}
|
}
|
||||||
|
|
@ -103,25 +105,30 @@ pub fn scan(plugins_dir: &Path, theme_file: Option<&Path>) -> BTreeMap<Target, S
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The debounced change detector. The first scan is the baseline (nothing is "changed" at start).
|
/// The debounced change detector. The first scan is the baseline (nothing is "changed" at start).
|
||||||
#[derive(Default)]
|
pub struct Watcher<K: Ord + Clone = Target> {
|
||||||
pub struct Watcher {
|
known: Option<BTreeMap<K, Signature>>,
|
||||||
known: Option<BTreeMap<Target, Signature>>,
|
|
||||||
/// Target → (signature seen, since when), for changes not yet stable.
|
/// Target → (signature seen, since when), for changes not yet stable.
|
||||||
pending: BTreeMap<Target, (Option<Signature>, Instant)>,
|
pending: BTreeMap<K, (Option<Signature>, Instant)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Watcher {
|
impl<K: Ord + Clone> Default for Watcher<K> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { known: None, pending: BTreeMap::new() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<K: Ord + Clone> Watcher<K> {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self::default()
|
Self::default()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds one scan; returns the changes that became stable, in reload order.
|
/// Feeds one scan; returns the changes that became stable, in reload order.
|
||||||
pub fn observe(&mut self, now: Instant, scan: BTreeMap<Target, Signature>) -> Vec<Change> {
|
pub fn observe(&mut self, now: Instant, scan: BTreeMap<K, Signature>) -> Vec<Change<K>> {
|
||||||
let Some(known) = self.known.as_mut() else {
|
let Some(known) = self.known.as_mut() else {
|
||||||
self.known = Some(scan);
|
self.known = Some(scan);
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
};
|
};
|
||||||
let mut targets: Vec<Target> = known.keys().cloned().collect();
|
let mut targets: Vec<K> = known.keys().cloned().collect();
|
||||||
for target in scan.keys() {
|
for target in scan.keys() {
|
||||||
if !known.contains_key(target) {
|
if !known.contains_key(target) {
|
||||||
targets.push(target.clone());
|
targets.push(target.clone());
|
||||||
|
|
@ -141,7 +148,7 @@ impl Watcher {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut ready = Vec::new();
|
let mut ready = Vec::new();
|
||||||
let stable: Vec<Target> = self
|
let stable: Vec<K> = self
|
||||||
.pending
|
.pending
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|(_, (_, since))| now.duration_since(*since) >= DEBOUNCE)
|
.filter(|(_, (_, since))| now.duration_since(*since) >= DEBOUNCE)
|
||||||
|
|
@ -171,7 +178,7 @@ impl Watcher {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Theme first (so plugins read the new `--wb-*` values), then custom CSS, then plugins by name.
|
/// Theme first (so plugins read the new `--wb-*` values), then custom CSS, then plugins by name.
|
||||||
pub fn reload_order(mut changes: Vec<Change>) -> Vec<Change> {
|
pub fn reload_order<K: Ord>(mut changes: Vec<Change<K>>) -> Vec<Change<K>> {
|
||||||
changes.sort_by(|a, b| a.target().cmp(b.target()));
|
changes.sort_by(|a, b| a.target().cmp(b.target()));
|
||||||
changes
|
changes
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,8 @@
|
||||||
//! shows, its page color and delivery script) over a site's built-in themes.
|
//! shows, its page color and delivery script) over a site's built-in themes.
|
||||||
//! - [`workspaces`]: saved tab/pane/deck layouts, bounded and well-formed (never evaluated).
|
//! - [`workspaces`]: saved tab/pane/deck layouts, bounded and well-formed (never evaluated).
|
||||||
//! - [`devmode`]: developer mode's debounced watcher of plugins, custom CSS and a theme file.
|
//! - [`devmode`]: developer mode's debounced watcher of plugins, custom CSS and a theme file.
|
||||||
|
//! - `devloop` (debug builds with `app` only): page scripts read from disk and every tab rebuilt when
|
||||||
|
//! one changes; an app names its files with [`page_script!`].
|
||||||
//! - [`settings`]: the shell's settings (home page, where links open, session restore) and the page's
|
//! - [`settings`]: the shell's settings (home page, where links open, session restore) and the page's
|
||||||
//! feature flags, as validated data and the scripts that hand them to site tabs.
|
//! feature flags, as validated data and the scripts that hand them to site tabs.
|
||||||
//! - [`modes`]: the onboarding mode the owner started from (the presets are the app's feature table).
|
//! - [`modes`]: the onboarding mode the owner started from (the presets are the app's feature table).
|
||||||
|
|
@ -74,7 +76,55 @@ pub mod zoom;
|
||||||
|
|
||||||
#[cfg(feature = "app")]
|
#[cfg(feature = "app")]
|
||||||
pub mod app;
|
pub mod app;
|
||||||
|
#[cfg(all(feature = "app", debug_assertions))]
|
||||||
|
pub mod devloop;
|
||||||
#[cfg(feature = "tauri")]
|
#[cfg(feature = "tauri")]
|
||||||
pub mod host;
|
pub mod host;
|
||||||
#[cfg(all(feature = "tauri", feature = "net"))]
|
#[cfg(all(feature = "tauri", feature = "net"))]
|
||||||
pub mod updater;
|
pub mod updater;
|
||||||
|
|
||||||
|
/// An app's page script for `SiteHooks::init_scripts`: `$embedded` (an `include_str!`) in every
|
||||||
|
/// build, except that a debug build reads `$file` (relative to the app crate's manifest directory)
|
||||||
|
/// from disk each time and falls back to the embedded copy when it is missing. The files named
|
||||||
|
/// this way are watched: a change rebuilds every tab (`devloop`). In a release build the disk arm
|
||||||
|
/// is not compiled at all: the expansion is `$embedded.to_owned()`, `$file` appears nowhere.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! page_script {
|
||||||
|
($embedded:expr, $file:literal) => {{
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
{
|
||||||
|
$crate::devloop::from_disk(concat!(env!("CARGO_MANIFEST_DIR"), "/", $file), $embedded)
|
||||||
|
}
|
||||||
|
#[cfg(not(debug_assertions))]
|
||||||
|
{
|
||||||
|
($embedded).to_owned()
|
||||||
|
}
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod release_guard {
|
||||||
|
/// Release builds must not contain the dev loop: every mention of it in this crate is behind
|
||||||
|
/// `cfg(debug_assertions)` (checked on the source, so it also holds when only debug is built).
|
||||||
|
#[test]
|
||||||
|
fn every_devloop_mention_is_debug_only() {
|
||||||
|
for (file, source) in [("lib.rs", include_str!("lib.rs")), ("app.rs", include_str!("app.rs"))] {
|
||||||
|
let lines: Vec<&str> = source.lines().collect();
|
||||||
|
for (index, line) in lines.iter().enumerate() {
|
||||||
|
let code = line.trim_start();
|
||||||
|
if code.starts_with("//") || !(code.contains("devloop::") || code.starts_with("pub mod devloop")) || code.contains("$crate::devloop") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let gated = (index.saturating_sub(2)..index).any(|before| lines[before].contains("debug_assertions"));
|
||||||
|
assert!(gated, "{file}:{}: devloop used outside cfg(debug_assertions)", index + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `cargo test --release`: the macro is just the embedded text.
|
||||||
|
#[cfg(not(debug_assertions))]
|
||||||
|
#[test]
|
||||||
|
fn release_page_script_is_the_embedded_copy() {
|
||||||
|
assert_eq!(crate::page_script!("embedded", "no/such/file.js"), "embedded");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ pub const EVENT_PROFILES_CHANGED: &str = "profiles-changed";
|
||||||
pub const EVENT_OPEN_PANEL: &str = "open-panel";
|
pub const EVENT_OPEN_PANEL: &str = "open-panel";
|
||||||
|
|
||||||
/// One pane as the shell lays it out (`tabs_sync`).
|
/// One pane as the shell lays it out (`tabs_sync`).
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct TabLayout {
|
pub struct TabLayout {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
|
|
|
||||||
|
|
@ -530,7 +530,8 @@ function desktopRs(o) {
|
||||||
' // The runtime\'s words in the owner\'s language from the first paint (the site only).',
|
' // The runtime\'s words in the owner\'s language from the first paint (the site only).',
|
||||||
' app::i18n_page_script(app),',
|
' app::i18n_page_script(app),',
|
||||||
' // The runtime checks the origin itself and stays inert on other sites.',
|
' // The runtime checks the origin itself and stays inert on other sites.',
|
||||||
' RUNTIME.to_owned(),',
|
' // Debug builds read the file from disk and rebuild the tabs when `npm run dev` rebuilds it.',
|
||||||
|
' waybetter_host::page_script!(RUNTIME, "runtime/runtime.js"),',
|
||||||
' ]',
|
' ]',
|
||||||
' }',
|
' }',
|
||||||
'',
|
'',
|
||||||
|
|
@ -1143,11 +1144,12 @@ function buildMjs() {
|
||||||
'// page Tauri serves from dist/: the wayBetter shell frame, bundled with its styles), both with',
|
'// page Tauri serves from dist/: the wayBetter shell frame, bundled with its styles), both with',
|
||||||
"// `waybetter/build`, and writes the shell's first-frame script.",
|
"// `waybetter/build`, and writes the shell's first-frame script.",
|
||||||
"import { copyFileSync, mkdirSync, writeFileSync } from 'node:fs';",
|
"import { copyFileSync, mkdirSync, writeFileSync } from 'node:fs';",
|
||||||
"import { buildRuntime } from 'waybetter/build';",
|
"import { buildRuntime, watchRequested } from 'waybetter/build';",
|
||||||
"import { bootScript } from 'waybetter/shell/frame/boot';",
|
"import { bootScript } from 'waybetter/shell/frame/boot';",
|
||||||
'',
|
'',
|
||||||
"mkdirSync('dist', { recursive: true });",
|
"mkdirSync('dist', { recursive: true });",
|
||||||
`await buildRuntime({ entry: 'src/runtime/main.ts', outfile: ${str(APP_OUTPUTS.runtime)} });`,
|
"// `node scripts/build.mjs --watch` (npm run dev) keeps rebuilding the runtime; a debug app reloads its tabs.",
|
||||||
|
`await buildRuntime({ entry: 'src/runtime/main.ts', outfile: ${str(APP_OUTPUTS.runtime)}, watch: watchRequested() });`,
|
||||||
'await buildRuntime({',
|
'await buildRuntime({',
|
||||||
" entry: 'src/shell/main.tsx',",
|
" entry: 'src/shell/main.tsx',",
|
||||||
" outfile: 'dist/shell.js',",
|
" outfile: 'dist/shell.js',",
|
||||||
|
|
@ -1162,7 +1164,7 @@ function buildMjs() {
|
||||||
"writeFileSync('dist/boot.js', bootScript());",
|
"writeFileSync('dist/boot.js', bootScript());",
|
||||||
"copyFileSync('src/shell/index.html', 'dist/index.html');",
|
"copyFileSync('src/shell/index.html', 'dist/index.html');",
|
||||||
"copyFileSync('src-tauri/icons/icon.png', 'dist/icon.png');",
|
"copyFileSync('src-tauri/icons/icon.png', 'dist/icon.png');",
|
||||||
"console.log('built dist/ and " + APP_OUTPUTS.runtime + "');",
|
"console.log(watchRequested() ? 'watching " + APP_OUTPUTS.runtime + "' : 'built dist/ and " + APP_OUTPUTS.runtime + "');",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1184,6 +1186,8 @@ function readme(o) {
|
||||||
'npm install',
|
'npm install',
|
||||||
'npm run build # dist/ (shell) and ' + APP_OUTPUTS.runtime + ' (page runtime)',
|
'npm run build # dist/ (shell) and ' + APP_OUTPUTS.runtime + ' (page runtime)',
|
||||||
'npm run tauri dev # the app',
|
'npm run tauri dev # the app',
|
||||||
|
'npm run dev # the app with the dev loop: a saved runtime change reloads the tabs (debug build)',
|
||||||
|
'npm run dev:stable # the same, and Rust changes do not restart the app',
|
||||||
'npm run test:rust # site adapter + plugin host tests, headless',
|
'npm run test:rust # site adapter + plugin host tests, headless',
|
||||||
'```',
|
'```',
|
||||||
'',
|
'',
|
||||||
|
|
@ -1259,6 +1263,8 @@ export function appFiles(o) {
|
||||||
build: 'node scripts/build.mjs',
|
build: 'node scripts/build.mjs',
|
||||||
typecheck: 'tsc -p tsconfig.json',
|
typecheck: 'tsc -p tsconfig.json',
|
||||||
tauri: 'tauri',
|
tauri: 'tauri',
|
||||||
|
dev: 'waybetter dev --watch "node scripts/build.mjs --watch"',
|
||||||
|
'dev:stable': 'waybetter dev --stable --watch "node scripts/build.mjs --watch"',
|
||||||
'desktop:build': 'waybetter build-env -- tauri build',
|
'desktop:build': 'waybetter build-env -- tauri build',
|
||||||
'privacy:scan': 'waybetter privacy-scan --tracked .',
|
'privacy:scan': 'waybetter privacy-scan --tracked .',
|
||||||
'test:rust': 'cargo test --manifest-path src-tauri/Cargo.toml --no-default-features',
|
'test:rust': 'cargo test --manifest-path src-tauri/Cargo.toml --no-default-features',
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,10 @@
|
||||||
// The `waybetter` command: `waybetter store build|sign|verify` (cli/store.mjs),
|
// The `waybetter` command: `waybetter store build|sign|verify` (cli/store.mjs),
|
||||||
// `waybetter release windows|macos` (cli/release.mjs), `waybetter i18n check|extract`
|
// `waybetter release windows|macos` (cli/release.mjs), `waybetter i18n check|extract`
|
||||||
// (cli/i18n.mjs), `waybetter privacy-scan` (cli/privacy.mjs) and `waybetter build-env`
|
// (cli/i18n.mjs), `waybetter privacy-scan` (cli/privacy.mjs) and `waybetter build-env`
|
||||||
// (cli/buildenv.mjs).
|
// (cli/buildenv.mjs), `waybetter dev` (cli/dev.mjs: watchers + tauri dev).
|
||||||
import { readFileSync } from 'node:fs';
|
import { readFileSync } from 'node:fs';
|
||||||
import { BUILD_ENV_USAGE, buildEnvCommand } from '../cli/buildenv.mjs';
|
import { BUILD_ENV_USAGE, buildEnvCommand } from '../cli/buildenv.mjs';
|
||||||
|
import { DEV_USAGE, devCommand } from '../cli/dev.mjs';
|
||||||
import { I18N_USAGE, i18nCommand } from '../cli/i18n.mjs';
|
import { I18N_USAGE, i18nCommand } from '../cli/i18n.mjs';
|
||||||
import { PRIVACY_USAGE, privacyCommand } from '../cli/privacy.mjs';
|
import { PRIVACY_USAGE, privacyCommand } from '../cli/privacy.mjs';
|
||||||
import { STORE_USAGE, storeCommand } from '../cli/store.mjs';
|
import { STORE_USAGE, storeCommand } from '../cli/store.mjs';
|
||||||
|
|
@ -22,10 +23,14 @@ try {
|
||||||
process.exitCode = privacyCommand(rest);
|
process.exitCode = privacyCommand(rest);
|
||||||
} else if (area === 'build-env') {
|
} else if (area === 'build-env') {
|
||||||
process.exitCode = buildEnvCommand(rest);
|
process.exitCode = buildEnvCommand(rest);
|
||||||
|
} else if (area === 'dev') {
|
||||||
|
process.exitCode = await devCommand(rest);
|
||||||
} else if (area === '--version' || area === '-v') {
|
} else if (area === '--version' || area === '-v') {
|
||||||
console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
|
console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
|
||||||
} else {
|
} else {
|
||||||
console.log(`${STORE_USAGE}\n\n${RELEASE_USAGE}\n\n${I18N_USAGE}\n\n${PRIVACY_USAGE}\n\n${BUILD_ENV_USAGE}`);
|
console.log(`${STORE_USAGE}\n\n${RELEASE_USAGE}\n\n${I18N_USAGE}\n\n${PRIVACY_USAGE}\n\n${BUILD_ENV_USAGE}
|
||||||
|
|
||||||
|
${DEV_USAGE}`);
|
||||||
if (area && area !== '--help' && area !== '-h') process.exitCode = 1;
|
if (area && area !== '--help' && area !== '-h') process.exitCode = 1;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,8 @@
|
||||||
// jsx: 'automatic', // any other esbuild option passes through
|
// jsx: 'automatic', // any other esbuild option passes through
|
||||||
// });
|
// });
|
||||||
//
|
//
|
||||||
|
// `watch: true` (an app's build script passes `watchRequested()`) keeps esbuild watching and
|
||||||
|
// rebuilding `outfile`; a failed rebuild leaves the last good file in place.
|
||||||
// - `?inline` CSS imports become strings (Vite semantics); other CSS side-effect imports are
|
// - `?inline` CSS imports become strings (Vite semantics); other CSS side-effect imports are
|
||||||
// dropped, because injected UI adopts its stylesheet into a shadow root explicitly
|
// dropped, because injected UI adopts its stylesheet into a shadow root explicitly
|
||||||
// (`inlineCss: false` turns this off).
|
// (`inlineCss: false` turns this off).
|
||||||
|
|
@ -52,15 +54,15 @@ export function catalogPlugin(catalog, prefixes) {
|
||||||
/**
|
/**
|
||||||
* Builds `entry` into `outfile` (paths relative to `cwd`). Defaults: bundled IIFE, es2022,
|
* Builds `entry` into `outfile` (paths relative to `cwd`). Defaults: bundled IIFE, es2022,
|
||||||
* minified, no source map, no legal comments. Returns esbuild's result.
|
* minified, no source map, no legal comments. Returns esbuild's result.
|
||||||
* @param {{ entry: string, outfile: string, catalog?: string, prefixes?: string[], cwd?: string,
|
* @param {{ entry: string, outfile: string, watch?: boolean, catalog?: string, prefixes?: string[], cwd?: string,
|
||||||
* inlineCss?: boolean, esbuild?: { build: Function }, plugins?: object[], [option: string]: unknown }} options
|
* inlineCss?: boolean, esbuild?: { build: Function }, plugins?: object[], [option: string]: unknown }} options
|
||||||
*/
|
*/
|
||||||
export async function buildRuntime(options) {
|
export async function buildRuntime(options) {
|
||||||
const { entry, outfile, catalog, prefixes = [], cwd = process.cwd(), inlineCss = true, esbuild, plugins = [], ...rest } = options;
|
const { entry, outfile, catalog, prefixes = [], cwd = process.cwd(), inlineCss = true, esbuild, plugins = [], watch = false, ...rest } = options;
|
||||||
if (!entry || !outfile) throw new Error('buildRuntime: entry and outfile are required');
|
if (!entry || !outfile) throw new Error('buildRuntime: entry and outfile are required');
|
||||||
if (catalog && !prefixes.length) throw new Error('buildRuntime: a catalog needs the key prefixes the runtime ships');
|
if (catalog && !prefixes.length) throw new Error('buildRuntime: a catalog needs the key prefixes the runtime ships');
|
||||||
const bundler = esbuild ?? createRequire(path.join(path.resolve(cwd), 'package.json'))('esbuild');
|
const bundler = esbuild ?? createRequire(path.join(path.resolve(cwd), 'package.json'))('esbuild');
|
||||||
return bundler.build({
|
const config = {
|
||||||
absWorkingDir: path.resolve(cwd),
|
absWorkingDir: path.resolve(cwd),
|
||||||
entryPoints: [entry],
|
entryPoints: [entry],
|
||||||
outfile,
|
outfile,
|
||||||
|
|
@ -76,5 +78,28 @@ export async function buildRuntime(options) {
|
||||||
...(catalog ? [catalogPlugin(path.resolve(cwd, catalog), prefixes)] : []),
|
...(catalog ? [catalogPlugin(path.resolve(cwd, catalog), prefixes)] : []),
|
||||||
...plugins,
|
...plugins,
|
||||||
],
|
],
|
||||||
|
};
|
||||||
|
if (!watch) return bundler.build(config);
|
||||||
|
// Dev loop: rebuild `outfile` whenever a source changes (a debug host reloads its tabs when the
|
||||||
|
// file changes). The first build is done when this resolves; the returned context keeps watching.
|
||||||
|
const context = await bundler.context({
|
||||||
|
...config,
|
||||||
|
plugins: [
|
||||||
|
...config.plugins,
|
||||||
|
{
|
||||||
|
name: 'waybetter-watch-log',
|
||||||
|
setup(api) {
|
||||||
|
api.onEnd(result => {
|
||||||
|
const stamp = new Date().toTimeString().slice(0, 8);
|
||||||
|
console.log(result.errors.length ? `[${stamp}] ${outfile}: build failed, keeping the last good file` : `[${stamp}] rebuilt ${outfile}`);
|
||||||
});
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
await context.watch();
|
||||||
|
return context;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** True when the calling script was started with `--watch`. */
|
||||||
|
export const watchRequested = (argv = process.argv) => argv.includes('--watch');
|
||||||
|
|
|
||||||
97
packages/waybetter/cli/dev.mjs
Normal file
97
packages/waybetter/cli/dev.mjs
Normal file
|
|
@ -0,0 +1,97 @@
|
||||||
|
// `waybetter dev`: the dev loop in one command. Starts the app's build watchers, waits until each
|
||||||
|
// has built once, then runs `tauri dev`. In a debug build the host reads the page scripts from disk
|
||||||
|
// and rebuilds its tabs when a watcher rewrites one (`waybetter_host::page_script!`), and the
|
||||||
|
// shell hot-reloads through the frontend dev server (`beforeDevCommand`, e.g. vite).
|
||||||
|
//
|
||||||
|
// waybetter dev [--stable] [--watch "<command>"]... [-- <tauri dev args>]
|
||||||
|
//
|
||||||
|
// `--stable` adds `--no-watch`: Rust changes do not restart the app (restart it yourself); page
|
||||||
|
// script and shell changes still reload live. Every `--watch` command must keep running and print
|
||||||
|
// a line containing "watching" once its first build is done (`buildRuntime({ watch: true })`
|
||||||
|
// scripts print one); it is stopped with the app.
|
||||||
|
import { spawn, spawnSync } from 'node:child_process';
|
||||||
|
import { delimiter, join, resolve } from 'node:path';
|
||||||
|
|
||||||
|
export const DEV_USAGE = `Usage:
|
||||||
|
waybetter dev [--stable] [--watch "<command>"]... [-- <tauri dev args>]
|
||||||
|
Starts each --watch command (esbuild watchers), waits for its first build ("watching" on a
|
||||||
|
line of its output, at most 120 s), then runs \`tauri dev\`. --stable passes --no-watch so a
|
||||||
|
Rust file saved by someone else does not restart the app; Rust changes then need a manual
|
||||||
|
restart, page-script and shell changes reload live either way.`;
|
||||||
|
|
||||||
|
const READY = /watching/i;
|
||||||
|
const READY_TIMEOUT_MS = 120_000;
|
||||||
|
|
||||||
|
/** `waybetter dev` arguments: `{ stable, watch: string[], tauriArgs: string[] }`. */
|
||||||
|
export function parseDevArgs(args) {
|
||||||
|
const out = { stable: false, watch: [], tauriArgs: [] };
|
||||||
|
for (let index = 0; index < args.length; index += 1) {
|
||||||
|
const arg = args[index];
|
||||||
|
if (arg === '--') {
|
||||||
|
out.tauriArgs = args.slice(index + 1);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (arg === '--stable') out.stable = true;
|
||||||
|
else if (arg === '--watch') {
|
||||||
|
const command = args[(index += 1)];
|
||||||
|
if (!command) throw new Error('--watch needs a command');
|
||||||
|
out.watch.push(command);
|
||||||
|
} else throw new Error(`unknown argument: ${arg}`);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `tauri dev` arguments. */
|
||||||
|
export function tauriDevArgs({ stable, tauriArgs }) {
|
||||||
|
return ['dev', ...(stable && !tauriArgs.includes('--no-watch') ? ['--no-watch'] : []), ...tauriArgs];
|
||||||
|
}
|
||||||
|
|
||||||
|
function stop(child) {
|
||||||
|
if (!child.pid || child.exitCode !== null) return;
|
||||||
|
if (process.platform === 'win32') spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
|
||||||
|
else child.kill('SIGTERM');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function devCommand(args, cwd = process.cwd()) {
|
||||||
|
const options = parseDevArgs(args);
|
||||||
|
// Local tools (tauri, esbuild) the way an npm script finds them.
|
||||||
|
const env = { ...process.env, PATH: [join(cwd, 'node_modules', '.bin'), resolve(cwd, '..', 'node_modules', '.bin'), resolve(cwd, '..', '..', 'node_modules', '.bin'), process.env.PATH].join(delimiter) };
|
||||||
|
const children = [];
|
||||||
|
const stopAll = () => children.forEach(stop);
|
||||||
|
process.on('exit', stopAll);
|
||||||
|
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => process.exit(130));
|
||||||
|
|
||||||
|
for (const command of options.watch) {
|
||||||
|
const child = spawn(command, { cwd, env, shell: true, stdio: ['ignore', 'pipe', 'inherit'] });
|
||||||
|
children.push(child);
|
||||||
|
await new Promise((done, fail) => {
|
||||||
|
const timer = setTimeout(() => fail(new Error(`watcher did not report "watching" in time: ${command}`)), READY_TIMEOUT_MS);
|
||||||
|
let ready = false;
|
||||||
|
child.stdout.on('data', chunk => {
|
||||||
|
process.stdout.write(chunk);
|
||||||
|
if (!ready && READY.test(String(chunk))) {
|
||||||
|
ready = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
done();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
child.on('exit', code => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
if (!ready) fail(new Error(`watcher exited (${code}) before its first build: ${command}`));
|
||||||
|
else console.error(`waybetter dev: a watcher stopped (${code}): ${command}`);
|
||||||
|
});
|
||||||
|
}).catch(error => {
|
||||||
|
stopAll();
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const tauri = spawn('tauri', tauriDevArgs(options), { cwd, env, shell: true, stdio: 'inherit' });
|
||||||
|
children.push(tauri);
|
||||||
|
return new Promise(done =>
|
||||||
|
tauri.on('exit', code => {
|
||||||
|
stopAll();
|
||||||
|
done(code ?? 0);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -53,3 +53,27 @@ test('css plugin: ?inline imports are text, other CSS imports are dropped', asyn
|
||||||
const drop = load.find(hook => hook.options.namespace === 'css-drop');
|
const drop = load.find(hook => hook.options.namespace === 'css-drop');
|
||||||
assert.deepEqual(drop.fn({}), { contents: '', loader: 'js' });
|
assert.deepEqual(drop.fn({}), { contents: '', loader: 'js' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('buildRuntime: watch mode keeps an esbuild context watching and logs each rebuild', async () => {
|
||||||
|
let seen;
|
||||||
|
let watching = false;
|
||||||
|
const esbuild = { context: async options => { seen = options; return { watch: async () => { watching = true; } } } };
|
||||||
|
const context = await buildRuntime({ entry: 'src/a.ts', outfile: 'out.js', cwd: tmpdir(), esbuild, watch: true });
|
||||||
|
assert.equal(watching, true);
|
||||||
|
assert.equal(typeof context.watch, 'function');
|
||||||
|
assert.equal('watch' in seen, false, 'the flag is not an esbuild option');
|
||||||
|
const log = seen.plugins.find(plugin => plugin.name === 'waybetter-watch-log');
|
||||||
|
let onEnd;
|
||||||
|
log.setup({ onEnd: fn => { onEnd = fn; } });
|
||||||
|
const lines = [];
|
||||||
|
const original = console.log;
|
||||||
|
console.log = line => lines.push(line);
|
||||||
|
try {
|
||||||
|
onEnd({ errors: [] });
|
||||||
|
onEnd({ errors: [{}] });
|
||||||
|
} finally {
|
||||||
|
console.log = original;
|
||||||
|
}
|
||||||
|
assert.match(lines[0], /rebuilt out\.js/);
|
||||||
|
assert.match(lines[1], /build failed, keeping the last good file/);
|
||||||
|
});
|
||||||
|
|
|
||||||
17
packages/waybetter/tests/dev-cli.test.mjs
Normal file
17
packages/waybetter/tests/dev-cli.test.mjs
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
// `waybetter dev`: argument parsing and the `tauri dev` arguments (the processes themselves are not started).
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { parseDevArgs, tauriDevArgs } from '../cli/dev.mjs';
|
||||||
|
|
||||||
|
test('dev: watchers, --stable and the tauri arguments after --', () => {
|
||||||
|
const options = parseDevArgs(['--watch', 'node a.mjs --watch', '--stable', '--watch', 'node b.mjs --watch', '--', '--release']);
|
||||||
|
assert.deepEqual(options, { stable: true, watch: ['node a.mjs --watch', 'node b.mjs --watch'], tauriArgs: ['--release'] });
|
||||||
|
assert.deepEqual(tauriDevArgs(options), ['dev', '--no-watch', '--release']);
|
||||||
|
assert.deepEqual(tauriDevArgs(parseDevArgs([])), ['dev']);
|
||||||
|
assert.deepEqual(tauriDevArgs(parseDevArgs(['--stable', '--', '--no-watch'])), ['dev', '--no-watch']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dev: unknown arguments and a --watch without a command are refused', () => {
|
||||||
|
assert.throws(() => parseDevArgs(['--fast']), /unknown argument/);
|
||||||
|
assert.throws(() => parseDevArgs(['--watch']), /needs a command/);
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue