Skip to main content

offline_generator/
lib.rs

1//! # offline-generator
2//!
3//! Renders a registry template into a new project directory.
4//!
5//! Template contract (`registry/templates/<name>/files/`):
6//! - `*.tera` is rendered (suffix stripped); other files are copied as-is.
7//! - Underscore-prefixed names map to dotfiles: `_gitignore` -> `.gitignore`,
8//!   `_env` -> `.env`, `_env.example` -> `.env.example` (also with `.tera`).
9//! - Context always includes `project_name`, `versions`, and optionally `packages`.
10
11pub mod package_json;
12pub mod project_detect;
13pub mod project_wiring;
14
15use std::collections::BTreeMap;
16use std::path::{Path, PathBuf};
17
18use offline_registry::{Registry, RegistryError};
19use serde::Serialize;
20
21#[derive(Debug, thiserror::Error)]
22pub enum GeneratorError {
23    #[error(transparent)]
24    Registry(#[from] RegistryError),
25    #[error("target directory `{0}` already exists and is not empty")]
26    TargetNotEmpty(String),
27    #[error("missing required variable `{0}`")]
28    MissingVariable(String),
29    #[error("template render failed for `{0}`: {1}")]
30    Render(String, String),
31    #[error("io error at {0}: {1}")]
32    Io(String, #[source] std::io::Error),
33}
34
35#[derive(Debug, Serialize)]
36pub struct GeneratedProject {
37    pub template: String,
38    pub target_dir: PathBuf,
39    pub files_written: Vec<String>,
40    pub post_generate: Vec<String>,
41    pub notes: Vec<String>,
42}
43
44/// Generate `template_name` into `target_dir` with the given variables.
45///
46/// `vars` must satisfy the template's declared required variables; defaults
47/// are applied for the rest. `project_name` is always injected.
48pub fn generate(
49    registry: &Registry,
50    template_name: &str,
51    target_dir: &Path,
52    project_name: &str,
53    vars: &BTreeMap<String, String>,
54) -> Result<GeneratedProject, GeneratorError> {
55    let meta = registry
56        .template(template_name)
57        .ok_or_else(|| RegistryError::NotFound(format!("template `{template_name}`")))?
58        .clone();
59
60    if target_dir.exists() {
61        let non_empty = std::fs::read_dir(target_dir)
62            .map_err(|e| GeneratorError::Io(target_dir.display().to_string(), e))?
63            .next()
64            .is_some();
65        if non_empty {
66            return Err(GeneratorError::TargetNotEmpty(
67                target_dir.display().to_string(),
68            ));
69        }
70    }
71
72    let mut context = tera::Context::new();
73    let mut declared: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
74    declared.insert("project_name");
75    context.insert("project_name", project_name);
76    for v in &meta.variables {
77        declared.insert(v.name.as_str());
78        match vars.get(&v.name).or(v.default.as_ref()) {
79            Some(value) => context.insert(&v.name, value),
80            None if v.required => return Err(GeneratorError::MissingVariable(v.name.clone())),
81            None => context.insert(&v.name, ""),
82        }
83    }
84    for (k, v) in vars {
85        if !declared.contains(k.as_str()) {
86            context.insert(k, v);
87        }
88    }
89
90    if meta.platform == "react-native" && !context.contains_key("rn_module_name") {
91        let module = rn_module_name(project_name);
92        context.insert("rn_module_name", &module);
93    }
94
95    let versions: BTreeMap<String, String> = registry
96        .packages()
97        .map(|p| (p.name.clone(), p.version.clone()))
98        .collect();
99    context.insert("versions", &versions);
100    // Generated `.mcp.json` / agent guidance start this release's MCP server
101    // through npx, so they work without a global `offline` install.
102    context.insert("offline_cli_version", offline_registry::CLI_VERSION);
103    context.insert(
104        "offline_mcp_command",
105        &offline_registry::mcp_serve_command_line(),
106    );
107
108    if let Some(wf) = &meta.workflow {
109        if let Ok(res) = registry.resolve_workflow(wf, &meta.platform) {
110            context.insert("packages", &res.packages);
111        }
112    }
113
114    let mesh_enabled = vars
115        .get("enable_mesh")
116        .map(|s| s == "true")
117        .unwrap_or(false);
118    if !context.contains_key("enable_mesh") {
119        context.insert("enable_mesh", if mesh_enabled { "true" } else { "false" });
120    }
121
122    let pol_enabled = vars.get("enable_pol").map(|s| s == "true").unwrap_or(false);
123    if !context.contains_key("enable_pol") {
124        context.insert("enable_pol", if pol_enabled { "true" } else { "false" });
125    }
126
127    let offline_id_default =
128        template_name == "react-native-social" || template_name == "react-native-id-only";
129    let offline_id_enabled = vars
130        .get("enable_offline_id")
131        .map(|s| s == "true")
132        .unwrap_or(offline_id_default);
133    if !context.contains_key("enable_offline_id") {
134        context.insert(
135            "enable_offline_id",
136            if offline_id_enabled { "true" } else { "false" },
137        );
138    }
139
140    let files = registry.template_files(template_name)?;
141
142    let mut tera = tera::Tera::default();
143    tera.autoescape_on(vec![]);
144    let mut planned: Vec<PlannedFile> = Vec::new();
145
146    for (rel, data) in files {
147        if is_mesh_only_path(&rel) && !mesh_enabled {
148            continue;
149        }
150        if is_pol_only_path(&rel) && !pol_enabled {
151            continue;
152        }
153        let rel = strip_optional_prefixes(&rel);
154        let planned_file = plan_file(&rel, &data, &mut tera)
155            .map_err(|e| GeneratorError::Render(rel.display().to_string(), e))?;
156        planned.push(planned_file);
157    }
158
159    // Render fully before writing to avoid partial trees on failure.
160    let mut rendered: Vec<(PathBuf, Vec<u8>)> = Vec::with_capacity(planned.len());
161    for file in &planned {
162        let content = match &file.kind {
163            PlannedKind::Copy(bytes) => bytes.clone(),
164            PlannedKind::Template(name) => tera
165                .render(name, &context)
166                .map_err(|e| GeneratorError::Render(name.clone(), format!("{e:#}")))?
167                .into_bytes(),
168        };
169        rendered.push((file.out_rel.clone(), content));
170    }
171
172    let target_preexisted = target_dir.exists();
173    let cleanup_on_error = !target_preexisted
174        || std::fs::read_dir(target_dir)
175            .map(|mut d| d.next().is_none())
176            .unwrap_or(false);
177
178    let write_all = || -> Result<Vec<String>, GeneratorError> {
179        let mut written = Vec::new();
180        for (out_rel, content) in &rendered {
181            let out_path = target_dir.join(out_rel);
182            if let Some(parent) = out_path.parent() {
183                std::fs::create_dir_all(parent)
184                    .map_err(|e| GeneratorError::Io(parent.display().to_string(), e))?;
185            }
186            std::fs::write(&out_path, content)
187                .map_err(|e| GeneratorError::Io(out_path.display().to_string(), e))?;
188            written.push(out_rel.to_string_lossy().replace('\\', "/"));
189        }
190        written.sort();
191        Ok(written)
192    };
193
194    let written = match write_all() {
195        Ok(written) => written,
196        Err(err) if cleanup_on_error => {
197            let _ = std::fs::remove_dir_all(target_dir);
198            return Err(err);
199        }
200        Err(err) => return Err(err),
201    };
202
203    Ok(GeneratedProject {
204        template: template_name.to_string(),
205        target_dir: target_dir.to_path_buf(),
206        files_written: written,
207        post_generate: meta.post_generate.clone(),
208        notes: meta.notes.clone(),
209    })
210}
211
212enum PlannedKind {
213    Copy(Vec<u8>),
214    Template(String),
215}
216
217struct PlannedFile {
218    out_rel: PathBuf,
219    kind: PlannedKind,
220}
221
222fn plan_file(rel: &Path, data: &[u8], tera: &mut tera::Tera) -> Result<PlannedFile, String> {
223    let mut out_rel = rel.to_path_buf();
224    rename_template_dotfile(&mut out_rel);
225
226    let is_template = out_rel
227        .extension()
228        .and_then(|e| e.to_str())
229        .map(|e| e == "tera")
230        .unwrap_or(false);
231
232    if !is_template {
233        return Ok(PlannedFile {
234            out_rel,
235            kind: PlannedKind::Copy(data.to_vec()),
236        });
237    }
238
239    out_rel.set_extension(""); // strip `.tera`, keeping the real extension
240    let source = std::str::from_utf8(data).map_err(|e| e.to_string())?;
241    let name = out_rel.to_string_lossy().replace('\\', "/");
242    tera.add_raw_template(&name, source)
243        .map_err(|e| format!("{e:#}"))?;
244    Ok(PlannedFile {
245        out_rel,
246        kind: PlannedKind::Template(name),
247    })
248}
249
250/// Map underscore-prefixed template filenames to real leading-dot names.
251fn rename_template_dotfile(out_rel: &mut PathBuf) {
252    let Some(name) = out_rel.file_name().and_then(|f| f.to_str()) else {
253        return;
254    };
255    let (base, tera_suffix) = match name.strip_suffix(".tera") {
256        Some(stripped) => (stripped, true),
257        None => (name, false),
258    };
259    let renamed = match base {
260        "_gitignore" => ".gitignore",
261        "_env" => ".env",
262        "_env.example" => ".env.example",
263        _ => return,
264    };
265    if tera_suffix {
266        out_rel.set_file_name(format!("{renamed}.tera"));
267    } else {
268        out_rel.set_file_name(renamed);
269    }
270}
271
272/// Template files under a `.mesh/` directory are included only when `enable_mesh=true`.
273fn is_mesh_only_path(rel: &Path) -> bool {
274    rel.components().any(|c| c.as_os_str() == ".mesh")
275}
276
277/// Template files under `.pol/` are included only when `enable_pol=true`.
278fn is_pol_only_path(rel: &Path) -> bool {
279    rel.components().any(|c| c.as_os_str() == ".pol")
280}
281
282fn strip_optional_prefixes(rel: &Path) -> PathBuf {
283    rel.components()
284        .filter(|c| c.as_os_str() != ".mesh" && c.as_os_str() != ".pol")
285        .collect()
286}
287
288fn rn_module_name(slug: &str) -> String {
289    slug.split('-')
290        .filter(|part| !part.is_empty())
291        .map(|part| {
292            let mut chars = part.chars();
293            match chars.next() {
294                None => String::new(),
295                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
296            }
297        })
298        .collect()
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    #[test]
306    fn generates_react_native_id_only_template() {
307        let registry = Registry::load_embedded().unwrap();
308        let tmp = tempfile::tempdir().unwrap();
309        let target = tmp.path().join("my-id-app");
310        let mut vars = BTreeMap::new();
311        vars.insert("app_id".to_string(), "app_id_only".to_string());
312
313        let out = generate(
314            &registry,
315            "react-native-id-only",
316            &target,
317            "my-id-app",
318            &vars,
319        )
320        .expect("generation succeeds");
321        assert!(out.files_written.contains(&"package.json".to_string()));
322        assert!(out
323            .files_written
324            .contains(&"src/screens/HomeScreen.tsx".to_string()));
325        assert!(!out
326            .files_written
327            .iter()
328            .any(|f| f.contains("ProtocolContext")));
329
330        let pkg = std::fs::read_to_string(target.join("package.json")).unwrap();
331        assert!(pkg.contains("@offline-protocol/id-react-native"));
332        assert!(!pkg.contains("@offline-protocol/mesh-sdk"));
333
334        let app = std::fs::read_to_string(target.join("App.tsx")).unwrap();
335        assert!(!app.contains("ProtocolProvider"));
336        assert!(app.contains("HomeScreen"));
337
338        let cfg = std::fs::read_to_string(target.join("offline.config.json")).unwrap();
339        assert!(cfg.contains("react-native-id-only"));
340        assert_ships_attestation(&target, &pkg);
341    }
342
343    /// React Native Offline ID starters pin an SDK that attests code
344    /// requests and pass it the native attestation module.
345    fn assert_ships_attestation(target: &std::path::Path, pkg: &str) {
346        let registry = Registry::load_embedded().unwrap();
347        let rn = registry
348            .package("@offline-protocol/id-react-native")
349            .unwrap();
350        assert!(
351            pkg.contains(&format!(
352                "\"@offline-protocol/id-react-native\": \"^{}\"",
353                rn.version
354            )),
355            "{pkg}"
356        );
357        let minor: u64 = rn.version.split('.').nth(1).unwrap().parse().unwrap();
358        assert!(
359            rn.version.starts_with("0.") && minor >= 4,
360            "id-react-native {} does not attest code requests",
361            rn.version
362        );
363        let provider =
364            std::fs::read_to_string(target.join("src/providers/IdentityProvider.tsx")).unwrap();
365        assert!(provider.contains("attestation={attestation}"));
366        let attestation = std::fs::read_to_string(target.join("src/attestation.ts")).unwrap();
367        assert!(attestation.contains("NativeModules.OfflineIdAttestation"));
368        for file in [
369            "react-native.config.js",
370            "modules/offline-id-attestation/OfflineIdAttestation.podspec",
371            "modules/offline-id-attestation/ios/OfflineIdAttestation.m",
372            "modules/offline-id-attestation/android/build.gradle",
373            "modules/offline-id-attestation/android/src/main/java/com/offlineprotocol/idattestation/OfflineIdAttestationModule.kt",
374            "modules/offline-id-attestation/android/src/main/java/com/offlineprotocol/idattestation/OfflineIdAttestationPackage.kt",
375        ] {
376            assert!(target.join(file).is_file(), "{file} missing");
377        }
378    }
379
380    #[test]
381    fn generates_react_native_social_template() {
382        let registry = Registry::load_embedded().unwrap();
383        let tmp = tempfile::tempdir().unwrap();
384        let target = tmp.path().join("my-social-app");
385        let mut vars = BTreeMap::new();
386        vars.insert("app_id".to_string(), "app_rn".to_string());
387
388        let out = generate(
389            &registry,
390            "react-native-social",
391            &target,
392            "my-social-app",
393            &vars,
394        )
395        .expect("generation succeeds");
396        assert!(out.files_written.contains(&"package.json".to_string()));
397        assert!(out
398            .files_written
399            .contains(&"src/screens/HomeScreen.tsx".to_string()));
400
401        let pkg = std::fs::read_to_string(target.join("package.json")).unwrap();
402        assert!(pkg.contains("@offline-protocol/id-react-native"));
403        assert!(!pkg.contains("@offline-protocol/mesh-sdk"));
404
405        let cfg = std::fs::read_to_string(target.join("offline.config.json")).unwrap();
406        assert!(cfg.contains("react-native-social"));
407        assert_ships_attestation(&target, &pkg);
408    }
409
410    #[test]
411    fn generates_react_native_id_only_with_pol() {
412        let registry = Registry::load_embedded().unwrap();
413        let tmp = tempfile::tempdir().unwrap();
414        let target = tmp.path().join("my-pol-app");
415        let mut vars = BTreeMap::new();
416        vars.insert("app_id".to_string(), "app_test123".to_string());
417        vars.insert("enable_pol".to_string(), "true".to_string());
418
419        let out = generate(
420            &registry,
421            "react-native-id-only",
422            &target,
423            "my-pol-app",
424            &vars,
425        )
426        .expect("generation succeeds");
427
428        let pkg = std::fs::read_to_string(target.join("package.json")).unwrap();
429        assert!(pkg.contains("@offline-protocol/pol"));
430        assert!(out
431            .files_written
432            .contains(&"src/providers/PolProvider.tsx".to_string()));
433        let app = std::fs::read_to_string(target.join("App.tsx")).unwrap();
434        assert!(app.contains("PolProvider"));
435        let home = std::fs::read_to_string(target.join("src/screens/HomeScreen.tsx")).unwrap();
436        assert!(home.contains("PolCommitPanel"));
437        let cfg = std::fs::read_to_string(target.join("src/config.ts")).unwrap();
438        assert!(cfg.contains("export const APP_ID"));
439    }
440
441    #[test]
442    fn generates_react_native_social_with_mesh() {
443        let registry = Registry::load_embedded().unwrap();
444        let tmp = tempfile::tempdir().unwrap();
445        let target = tmp.path().join("my-mesh-social");
446        let mut vars = BTreeMap::new();
447        vars.insert("app_id".to_string(), "app_rn".to_string());
448        vars.insert("enable_mesh".to_string(), "true".to_string());
449        vars.insert("mesh_app_id".to_string(), "my-mesh-social".to_string());
450        vars.insert(
451            "relay_server_url".to_string(),
452            "wss://relay.offlineprotocol.com".to_string(),
453        );
454
455        let out = generate(
456            &registry,
457            "react-native-social",
458            &target,
459            "my-mesh-social",
460            &vars,
461        )
462        .expect("generation succeeds");
463        assert!(out
464            .files_written
465            .contains(&"src/context/ProtocolContext.tsx".to_string()));
466        assert!(out
467            .files_written
468            .contains(&"src/screens/PeopleScreen.tsx".to_string()));
469        assert!(out
470            .files_written
471            .contains(&"src/providers/MeshSessionBridge.tsx".to_string()));
472
473        let pkg = std::fs::read_to_string(target.join("package.json")).unwrap();
474        assert!(pkg.contains("@offline-protocol/mesh-sdk"));
475
476        assert!(out
477            .files_written
478            .contains(&"src/screens/GroupsScreen.tsx".to_string()));
479
480        let app = std::fs::read_to_string(target.join("App.tsx")).unwrap();
481        assert!(app.contains("ProtocolProvider"));
482        assert!(app.contains("MeshSessionBridge"));
483        assert!(app.contains("PeopleScreen"));
484        assert!(app.contains("GroupsScreen"));
485
486        let protocol_ctx =
487            std::fs::read_to_string(target.join("src/context/ProtocolContext.tsx")).unwrap();
488        assert!(protocol_ctx.contains("mlsGetOrCreateKeyPackage"));
489        assert!(protocol_ctx.contains("BLE_DESTROY_SETTLE_MS"));
490        assert!(protocol_ctx.contains("localAddressRef"));
491
492        let env = std::fs::read_to_string(target.join(".env")).unwrap();
493        assert!(env.contains("APP_ID=app_rn"));
494        assert!(env.contains("MESH_APP_ID=my-mesh-social"));
495        assert!(env.contains("OFFLINE_RELAY_SERVER_URL=wss://relay.offlineprotocol.com"));
496        let config = std::fs::read_to_string(target.join("src/config.ts")).unwrap();
497        assert!(config.contains("MESH_APP_ID"));
498        assert!(config.contains("from '@env'"));
499    }
500
501    #[test]
502    fn generates_react_native_template() {
503        let registry = Registry::load_embedded().unwrap();
504        let tmp = tempfile::tempdir().unwrap();
505        let target = tmp.path().join("my-app");
506        let mut vars = BTreeMap::new();
507        vars.insert("app_id".to_string(), "my-app".to_string());
508
509        let out = generate(&registry, "react-native-mesh-app", &target, "my-app", &vars)
510            .expect("generation succeeds");
511        assert!(out.files_written.contains(&"package.json".to_string()));
512        assert!(out.files_written.contains(&".gitignore".to_string()));
513        assert!(out.files_written.contains(&"AGENTS.md".to_string()));
514        assert!(out
515            .files_written
516            .contains(&"src/context/ProtocolContext.tsx".to_string()));
517        assert!(out.files_written.contains(&"src/constants.ts".to_string()));
518        assert!(out
519            .files_written
520            .contains(&"src/screens/OnboardingScreen.tsx".to_string()));
521
522        let pkg = std::fs::read_to_string(target.join("package.json")).unwrap();
523        assert!(pkg.contains("\"name\": \"my-app\""));
524        assert!(pkg.contains("@offline-protocol/mesh-sdk"));
525        assert!(!pkg.contains("@offline-protocol/id-react-native"));
526        // Version must be injected from the registry, not hard-coded.
527        let mesh = registry.package("@offline-protocol/mesh-sdk").unwrap();
528        assert!(pkg.contains(&mesh.version));
529
530        let app = std::fs::read_to_string(target.join("App.tsx")).unwrap();
531        assert!(app.contains("ProtocolProvider"));
532        assert!(app.contains("OnboardingScreen"));
533        assert!(app.contains("GroupsScreen"));
534
535        let constants = std::fs::read_to_string(target.join("src/constants.ts")).unwrap();
536        assert!(constants.contains("appId: 'my-app'"));
537        assert!(constants.contains("requireEncryption: false"));
538        assert!(constants.contains("BLE_DESTROY_SETTLE_MS"));
539
540        let protocol_ctx =
541            std::fs::read_to_string(target.join("src/context/ProtocolContext.tsx")).unwrap();
542        assert!(protocol_ctx.contains("mlsGetOrCreateKeyPackage"));
543        assert!(protocol_ctx.contains("connection_request_undeliverable"));
544        assert!(protocol_ctx.contains("mlsImportKeyPackage"));
545        assert!(protocol_ctx.contains("BLE_DESTROY_SETTLE_MS"));
546        assert!(protocol_ctx.contains("identity not ready"));
547
548        assert!(target.join(".gitignore").exists());
549        let cfg = std::fs::read_to_string(target.join("offline.config.json")).unwrap();
550        assert!(cfg.contains("@offline-protocol/mesh-sdk"));
551    }
552
553    #[test]
554    fn generates_nextjs_template() {
555        let registry = Registry::load_embedded().unwrap();
556        let tmp = tempfile::tempdir().unwrap();
557        let target = tmp.path().join("web");
558        let mut vars = BTreeMap::new();
559        vars.insert("app_id".to_string(), "app_web".to_string());
560
561        let out = generate(&registry, "nextjs-social", &target, "web", &vars)
562            .expect("generation succeeds");
563        assert!(out.files_written.contains(&"package.json".to_string()));
564        assert!(out.files_written.contains(&".env".to_string()));
565        assert!(out.files_written.contains(&".env.example".to_string()));
566        assert!(out.files_written.contains(&".gitignore".to_string()));
567        let providers = std::fs::read_to_string(target.join("src/app/providers.tsx")).unwrap();
568        assert!(providers.contains("OfflineAppProvider"));
569        let config = std::fs::read_to_string(target.join("src/lib/config.ts")).unwrap();
570        assert!(config.contains("NEXT_PUBLIC_APP_ID"));
571        assert!(!config.contains("app_web"));
572        let env = std::fs::read_to_string(target.join(".env")).unwrap();
573        assert!(env.contains("NEXT_PUBLIC_APP_ID=app_web"));
574    }
575
576    #[test]
577    fn refuses_non_empty_target() {
578        let registry = Registry::load_embedded().unwrap();
579        let tmp = tempfile::tempdir().unwrap();
580        std::fs::write(tmp.path().join("existing.txt"), "x").unwrap();
581        let err = generate(
582            &registry,
583            "nextjs-social",
584            tmp.path(),
585            "web",
586            &BTreeMap::new(),
587        )
588        .unwrap_err();
589        assert!(matches!(err, GeneratorError::TargetNotEmpty(_)));
590    }
591
592    #[test]
593    fn missing_required_variable_errors() {
594        let registry = Registry::load_embedded().unwrap();
595        let tmp = tempfile::tempdir().unwrap();
596        let target = tmp.path().join("app");
597        // Omit required `app_id`.
598        let err = generate(
599            &registry,
600            "react-native-mesh-app",
601            &target,
602            "app",
603            &BTreeMap::new(),
604        )
605        .unwrap_err();
606        assert!(matches!(err, GeneratorError::MissingVariable(_)));
607    }
608
609    #[test]
610    fn all_templates_render_without_errors() {
611        let registry = Registry::load_embedded().unwrap();
612        for t in registry.templates() {
613            let tmp = tempfile::tempdir().unwrap();
614            let target = tmp.path().join("proj");
615            let mut vars = BTreeMap::new();
616            for v in &t.variables {
617                vars.insert(v.name.clone(), format!("test-{}", v.name));
618            }
619            generate(&registry, &t.name, &target, "proj", &vars)
620                .unwrap_or_else(|e| panic!("template `{}` failed: {e}", t.name));
621        }
622    }
623
624    /// The three workflow entrances: handoff, retained event delivery, nearby service.
625    const WORKFLOW_TEMPLATES: &[(&str, &str, &[&str])] = &[
626        (
627            "react-native-mesh-handoff",
628            "local-handoff",
629            &[
630                "src/handoff/ledger.ts",
631                "src/handoff/protocol.ts",
632                "__tests__/handoff.test.ts",
633                "backend/src/server.mjs",
634                "backend/test/server.test.mjs",
635                "src/backend/client.ts",
636            ],
637        ),
638        (
639            "react-native-mesh-event-delivery",
640            "backend-delivery",
641            &[
642                "src/delivery/outbox.ts",
643                "src/delivery/protocol.ts",
644                "__tests__/delivery.test.ts",
645                "backend/src/server.mjs",
646                "backend/test/server.test.mjs",
647                "src/backend/client.ts",
648            ],
649        ),
650        (
651            "react-native-mesh-service",
652            "nearby-service",
653            &[
654                "src/service/provider.ts",
655                "src/service/client.ts",
656                "src/service/contract.ts",
657                "src/platform/existingApp.ts",
658                "__tests__/service.test.ts",
659            ],
660        ),
661    ];
662
663    #[test]
664    fn generates_workflow_templates() {
665        let registry = Registry::load_embedded().unwrap();
666        for (template, workflow, expected) in WORKFLOW_TEMPLATES {
667            let meta = registry.template(template).expect("template registered");
668            assert!(meta.requires_mesh, "{template} must require mesh");
669            assert!(!meta.requires_login, "{template} is a local starter");
670            assert_eq!(meta.workflow.as_deref(), Some(*workflow));
671
672            let tmp = tempfile::tempdir().unwrap();
673            let target = tmp.path().join("field-app");
674            let mut vars = BTreeMap::new();
675            vars.insert("mesh_app_id".to_string(), "field-app".to_string());
676            vars.insert("enable_mesh".to_string(), "true".to_string());
677            let out = generate(&registry, template, &target, "field-app", &vars)
678                .unwrap_or_else(|e| panic!("{template}: {e}"));
679
680            for file in expected.iter().chain(&[
681                "package.json",
682                "App.tsx",
683                "src/config.ts",
684                "src/platform/mesh.ts",
685                "src/core/storage.ts",
686                "AGENTS.md",
687                "CLAUDE.md",
688                ".mcp.json",
689                "offline.config.json",
690                "README.md",
691                ".gitignore",
692            ]) {
693                assert!(
694                    out.files_written.contains(&file.to_string()),
695                    "{template}: missing {file}"
696                );
697            }
698            assert!(
699                !out.files_written.iter().any(|f| f.ends_with(".tera")),
700                "{template}: unrendered template file"
701            );
702
703            let pkg: serde_json::Value = serde_json::from_str(
704                &std::fs::read_to_string(target.join("package.json")).unwrap(),
705            )
706            .expect("package.json is valid JSON");
707            let mesh = registry.package("@offline-protocol/mesh-sdk").unwrap();
708            assert_eq!(
709                pkg["dependencies"]["@offline-protocol/mesh-sdk"],
710                format!("^{}", mesh.version)
711            );
712            assert_eq!(
713                pkg["scripts"]["backend:test"].is_string(),
714                expected.contains(&"backend/src/server.mjs"),
715                "{template}: backend scripts"
716            );
717
718            let config = std::fs::read_to_string(target.join("src/config.ts")).unwrap();
719            assert!(config.contains("export const APP_ID = 'field-app';"));
720            let offline_config =
721                std::fs::read_to_string(target.join("offline.config.json")).unwrap();
722            assert!(offline_config.contains(&format!("\"workflow\": \"{workflow}\"")));
723
724            // Only src/platform/ may import the SDK.
725            for (rel, _) in registry.template_files(template).unwrap() {
726                let rel = rel.to_string_lossy().replace('\\', "/");
727                if rel.starts_with("src/platform/") || !rel.contains(".ts") {
728                    continue;
729                }
730                let text = std::fs::read_to_string(target.join(rel.trim_end_matches(".tera")))
731                    .unwrap_or_default();
732                assert!(
733                    !text.contains("@offline-protocol/mesh-sdk'"),
734                    "{template}: {rel} imports the SDK outside src/platform/"
735                );
736            }
737        }
738    }
739
740    #[test]
741    fn generates_example_app_templates() {
742        let registry = Registry::load_embedded().unwrap();
743        for (template, mesh_app_id) in [
744            ("orderup", "orderup"),
745            ("stocksync", "stocksync"),
746            ("cowrite", "cowrite"),
747        ] {
748            let tmp = tempfile::tempdir().unwrap();
749            let target = tmp.path().join("example-out");
750            let mut vars = BTreeMap::new();
751            vars.insert("app_id".to_string(), mesh_app_id.to_string());
752            vars.insert("enable_mesh".to_string(), "true".to_string());
753
754            let out = generate(&registry, template, &target, "my-example", &vars)
755                .unwrap_or_else(|e| panic!("{template}: {e}"));
756
757            assert!(
758                out.files_written
759                    .iter()
760                    .any(|f| f.starts_with("packages/mesh/")),
761                "{template}: missing packages/mesh"
762            );
763            assert!(
764                out.files_written
765                    .iter()
766                    .any(|f| f.starts_with("packages/ui/")),
767                "{template}: missing packages/ui"
768            );
769            assert!(
770                out.files_written
771                    .iter()
772                    .any(|f| f == "android/app/build.gradle"),
773                "{template}: missing android/"
774            );
775            assert!(
776                !out.files_written
777                    .iter()
778                    .any(|f| f.contains("offline-app-examples")),
779                "{template}: leaked monorepo path"
780            );
781            assert!(!target.join("ios/Podfile.lock").exists());
782
783            let app = std::fs::read_to_string(target.join("App.tsx")).unwrap();
784            assert!(app.contains(&format!("const APP_ID = '{mesh_app_id}'")));
785
786            let pkg: serde_json::Value = serde_json::from_str(
787                &std::fs::read_to_string(target.join("package.json")).unwrap(),
788            )
789            .expect("package.json");
790            assert_eq!(pkg["name"], "my-example");
791            assert_eq!(
792                pkg["dependencies"]["@offline-app-examples/mesh"],
793                "file:./packages/mesh"
794            );
795
796            let meta = registry.template(template).unwrap();
797            assert!(meta.example_app);
798        }
799    }
800
801    #[test]
802    fn workflow_templates_share_identical_core_files() {
803        // These files are copies of one source; drift would mean a fix landed in
804        // one template only.
805        let shared = [
806            "src/core/backoff.ts",
807            "src/core/ids.ts",
808            "src/core/mutex.ts",
809            "src/core/ports.ts",
810            "src/core/storage.ts",
811            "src/platform/mesh.ts",
812            "src/platform/permissions.ts",
813            "src/platform/deviceStore.ts",
814            "__tests__/core.test.ts",
815            "tsconfig.json",
816        ];
817        let with_backend = [
818            "src/backend/client.ts",
819            "__tests__/backendClient.test.ts",
820            "__tests__/fakes.ts",
821            "backend/src/server.mjs",
822            "backend/src/store.mjs",
823            "backend/test/server.test.mjs",
824            "backend/package.json",
825            "backend/README.md",
826            "package.json.tera",
827        ];
828        let registry = Registry::load_embedded().unwrap();
829        let files = |t: &str| -> BTreeMap<String, Vec<u8>> {
830            registry
831                .template_files(t)
832                .unwrap()
833                .into_iter()
834                .map(|(p, d)| (p.to_string_lossy().replace('\\', "/"), d))
835                .collect()
836        };
837        let handoff = files("react-native-mesh-handoff");
838        let delivery = files("react-native-mesh-event-delivery");
839        let service = files("react-native-mesh-service");
840        for f in shared {
841            assert_eq!(
842                handoff.get(f),
843                delivery.get(f),
844                "{f} differs (handoff, delivery)"
845            );
846            assert_eq!(
847                handoff.get(f),
848                service.get(f),
849                "{f} differs (handoff, service)"
850            );
851            assert!(handoff.contains_key(f), "{f} missing");
852        }
853        for f in with_backend {
854            assert!(handoff.contains_key(f), "{f} missing");
855            assert_eq!(
856                handoff.get(f),
857                delivery.get(f),
858                "{f} differs (handoff, delivery)"
859            );
860            assert!(!service.contains_key(f) || f == "package.json.tera");
861        }
862    }
863}