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