pub mod package_json;
pub mod project_detect;
pub mod project_wiring;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use offline_registry::{Registry, RegistryError};
use serde::Serialize;
#[derive(Debug, thiserror::Error)]
pub enum GeneratorError {
#[error(transparent)]
Registry(#[from] RegistryError),
#[error("target directory `{0}` already exists and is not empty")]
TargetNotEmpty(String),
#[error("missing required variable `{0}`")]
MissingVariable(String),
#[error("template render failed for `{0}`: {1}")]
Render(String, String),
#[error("io error at {0}: {1}")]
Io(String, #[source] std::io::Error),
}
#[derive(Debug, Serialize)]
pub struct GeneratedProject {
pub template: String,
pub target_dir: PathBuf,
pub files_written: Vec<String>,
pub post_generate: Vec<String>,
pub notes: Vec<String>,
}
pub fn generate(
registry: &Registry,
template_name: &str,
target_dir: &Path,
project_name: &str,
vars: &BTreeMap<String, String>,
) -> Result<GeneratedProject, GeneratorError> {
let meta = registry
.template(template_name)
.ok_or_else(|| RegistryError::NotFound(format!("template `{template_name}`")))?
.clone();
if target_dir.exists() {
let non_empty = std::fs::read_dir(target_dir)
.map_err(|e| GeneratorError::Io(target_dir.display().to_string(), e))?
.next()
.is_some();
if non_empty {
return Err(GeneratorError::TargetNotEmpty(
target_dir.display().to_string(),
));
}
}
let mut context = tera::Context::new();
let mut declared: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
declared.insert("project_name");
context.insert("project_name", project_name);
for v in &meta.variables {
declared.insert(v.name.as_str());
match vars.get(&v.name).or(v.default.as_ref()) {
Some(value) => context.insert(&v.name, value),
None if v.required => return Err(GeneratorError::MissingVariable(v.name.clone())),
None => context.insert(&v.name, ""),
}
}
for (k, v) in vars {
if !declared.contains(k.as_str()) {
context.insert(k, v);
}
}
if meta.platform == "react-native" && !context.contains_key("rn_module_name") {
let module = rn_module_name(project_name);
context.insert("rn_module_name", &module);
}
let versions: BTreeMap<String, String> = registry
.packages()
.map(|p| (p.name.clone(), p.version.clone()))
.collect();
context.insert("versions", &versions);
context.insert("offline_cli_version", offline_registry::CLI_VERSION);
context.insert(
"offline_mcp_command",
&offline_registry::mcp_serve_command_line(),
);
if let Some(wf) = &meta.workflow {
if let Ok(res) = registry.resolve_workflow(wf, &meta.platform) {
context.insert("packages", &res.packages);
}
}
let mesh_enabled = vars
.get("enable_mesh")
.map(|s| s == "true")
.unwrap_or(false);
if !context.contains_key("enable_mesh") {
context.insert("enable_mesh", if mesh_enabled { "true" } else { "false" });
}
let pol_enabled = vars.get("enable_pol").map(|s| s == "true").unwrap_or(false);
if !context.contains_key("enable_pol") {
context.insert("enable_pol", if pol_enabled { "true" } else { "false" });
}
let offline_id_default =
template_name == "react-native-social" || template_name == "react-native-id-only";
let offline_id_enabled = vars
.get("enable_offline_id")
.map(|s| s == "true")
.unwrap_or(offline_id_default);
if !context.contains_key("enable_offline_id") {
context.insert(
"enable_offline_id",
if offline_id_enabled { "true" } else { "false" },
);
}
let files = registry.template_files(template_name)?;
let mut tera = tera::Tera::default();
tera.autoescape_on(vec![]);
let mut planned: Vec<PlannedFile> = Vec::new();
for (rel, data) in files {
if is_mesh_only_path(&rel) && !mesh_enabled {
continue;
}
if is_pol_only_path(&rel) && !pol_enabled {
continue;
}
let rel = strip_optional_prefixes(&rel);
let planned_file = plan_file(&rel, &data, &mut tera)
.map_err(|e| GeneratorError::Render(rel.display().to_string(), e))?;
planned.push(planned_file);
}
let mut rendered: Vec<(PathBuf, Vec<u8>)> = Vec::with_capacity(planned.len());
for file in &planned {
let content = match &file.kind {
PlannedKind::Copy(bytes) => bytes.clone(),
PlannedKind::Template(name) => tera
.render(name, &context)
.map_err(|e| GeneratorError::Render(name.clone(), format!("{e:#}")))?
.into_bytes(),
};
rendered.push((file.out_rel.clone(), content));
}
let target_preexisted = target_dir.exists();
let cleanup_on_error = !target_preexisted
|| std::fs::read_dir(target_dir)
.map(|mut d| d.next().is_none())
.unwrap_or(false);
let write_all = || -> Result<Vec<String>, GeneratorError> {
let mut written = Vec::new();
for (out_rel, content) in &rendered {
let out_path = target_dir.join(out_rel);
if let Some(parent) = out_path.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| GeneratorError::Io(parent.display().to_string(), e))?;
}
std::fs::write(&out_path, content)
.map_err(|e| GeneratorError::Io(out_path.display().to_string(), e))?;
written.push(out_rel.to_string_lossy().replace('\\', "/"));
}
written.sort();
Ok(written)
};
let written = match write_all() {
Ok(written) => written,
Err(err) if cleanup_on_error => {
let _ = std::fs::remove_dir_all(target_dir);
return Err(err);
}
Err(err) => return Err(err),
};
Ok(GeneratedProject {
template: template_name.to_string(),
target_dir: target_dir.to_path_buf(),
files_written: written,
post_generate: meta.post_generate.clone(),
notes: meta.notes.clone(),
})
}
enum PlannedKind {
Copy(Vec<u8>),
Template(String),
}
struct PlannedFile {
out_rel: PathBuf,
kind: PlannedKind,
}
fn plan_file(rel: &Path, data: &[u8], tera: &mut tera::Tera) -> Result<PlannedFile, String> {
let mut out_rel = rel.to_path_buf();
rename_template_dotfile(&mut out_rel);
let is_template = out_rel
.extension()
.and_then(|e| e.to_str())
.map(|e| e == "tera")
.unwrap_or(false);
if !is_template {
return Ok(PlannedFile {
out_rel,
kind: PlannedKind::Copy(data.to_vec()),
});
}
out_rel.set_extension(""); let source = std::str::from_utf8(data).map_err(|e| e.to_string())?;
let name = out_rel.to_string_lossy().replace('\\', "/");
tera.add_raw_template(&name, source)
.map_err(|e| format!("{e:#}"))?;
Ok(PlannedFile {
out_rel,
kind: PlannedKind::Template(name),
})
}
fn rename_template_dotfile(out_rel: &mut PathBuf) {
let Some(name) = out_rel.file_name().and_then(|f| f.to_str()) else {
return;
};
let (base, tera_suffix) = match name.strip_suffix(".tera") {
Some(stripped) => (stripped, true),
None => (name, false),
};
let renamed = match base {
"_gitignore" => ".gitignore",
"_env" => ".env",
"_env.example" => ".env.example",
_ => return,
};
if tera_suffix {
out_rel.set_file_name(format!("{renamed}.tera"));
} else {
out_rel.set_file_name(renamed);
}
}
fn is_mesh_only_path(rel: &Path) -> bool {
rel.components().any(|c| c.as_os_str() == ".mesh")
}
fn is_pol_only_path(rel: &Path) -> bool {
rel.components().any(|c| c.as_os_str() == ".pol")
}
fn strip_optional_prefixes(rel: &Path) -> PathBuf {
rel.components()
.filter(|c| c.as_os_str() != ".mesh" && c.as_os_str() != ".pol")
.collect()
}
fn rn_module_name(slug: &str) -> String {
slug.split('-')
.filter(|part| !part.is_empty())
.map(|part| {
let mut chars = part.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generates_react_native_id_only_template() {
let registry = Registry::load_embedded().unwrap();
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("my-id-app");
let mut vars = BTreeMap::new();
vars.insert("app_id".to_string(), "app_id_only".to_string());
let out = generate(
®istry,
"react-native-id-only",
&target,
"my-id-app",
&vars,
)
.expect("generation succeeds");
assert!(out.files_written.contains(&"package.json".to_string()));
assert!(out
.files_written
.contains(&"src/screens/HomeScreen.tsx".to_string()));
assert!(!out
.files_written
.iter()
.any(|f| f.contains("ProtocolContext")));
let pkg = std::fs::read_to_string(target.join("package.json")).unwrap();
assert!(pkg.contains("@offline-protocol/id-react-native"));
assert!(!pkg.contains("@offline-protocol/mesh-sdk"));
let app = std::fs::read_to_string(target.join("App.tsx")).unwrap();
assert!(!app.contains("ProtocolProvider"));
assert!(app.contains("HomeScreen"));
let cfg = std::fs::read_to_string(target.join("offline.config.json")).unwrap();
assert!(cfg.contains("react-native-id-only"));
assert_ships_attestation(&target, &pkg);
}
fn assert_ships_attestation(target: &std::path::Path, pkg: &str) {
let registry = Registry::load_embedded().unwrap();
let rn = registry
.package("@offline-protocol/id-react-native")
.unwrap();
assert!(
pkg.contains(&format!(
"\"@offline-protocol/id-react-native\": \"^{}\"",
rn.version
)),
"{pkg}"
);
let minor: u64 = rn.version.split('.').nth(1).unwrap().parse().unwrap();
assert!(
rn.version.starts_with("0.") && minor >= 4,
"id-react-native {} does not attest code requests",
rn.version
);
let provider =
std::fs::read_to_string(target.join("src/providers/IdentityProvider.tsx")).unwrap();
assert!(provider.contains("attestation={attestation}"));
let attestation = std::fs::read_to_string(target.join("src/attestation.ts")).unwrap();
assert!(attestation.contains("NativeModules.OfflineIdAttestation"));
for file in [
"react-native.config.js",
"modules/offline-id-attestation/OfflineIdAttestation.podspec",
"modules/offline-id-attestation/ios/OfflineIdAttestation.m",
"modules/offline-id-attestation/android/build.gradle",
"modules/offline-id-attestation/android/src/main/java/com/offlineprotocol/idattestation/OfflineIdAttestationModule.kt",
"modules/offline-id-attestation/android/src/main/java/com/offlineprotocol/idattestation/OfflineIdAttestationPackage.kt",
] {
assert!(target.join(file).is_file(), "{file} missing");
}
}
#[test]
fn generates_react_native_social_template() {
let registry = Registry::load_embedded().unwrap();
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("my-social-app");
let mut vars = BTreeMap::new();
vars.insert("app_id".to_string(), "app_rn".to_string());
let out = generate(
®istry,
"react-native-social",
&target,
"my-social-app",
&vars,
)
.expect("generation succeeds");
assert!(out.files_written.contains(&"package.json".to_string()));
assert!(out
.files_written
.contains(&"src/screens/HomeScreen.tsx".to_string()));
let pkg = std::fs::read_to_string(target.join("package.json")).unwrap();
assert!(pkg.contains("@offline-protocol/id-react-native"));
assert!(!pkg.contains("@offline-protocol/mesh-sdk"));
let cfg = std::fs::read_to_string(target.join("offline.config.json")).unwrap();
assert!(cfg.contains("react-native-social"));
assert_ships_attestation(&target, &pkg);
}
#[test]
fn generates_react_native_id_only_with_pol() {
let registry = Registry::load_embedded().unwrap();
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("my-pol-app");
let mut vars = BTreeMap::new();
vars.insert("app_id".to_string(), "app_test123".to_string());
vars.insert("enable_pol".to_string(), "true".to_string());
let out = generate(
®istry,
"react-native-id-only",
&target,
"my-pol-app",
&vars,
)
.expect("generation succeeds");
let pkg = std::fs::read_to_string(target.join("package.json")).unwrap();
assert!(pkg.contains("@offline-protocol/pol"));
assert!(out
.files_written
.contains(&"src/providers/PolProvider.tsx".to_string()));
let app = std::fs::read_to_string(target.join("App.tsx")).unwrap();
assert!(app.contains("PolProvider"));
let home = std::fs::read_to_string(target.join("src/screens/HomeScreen.tsx")).unwrap();
assert!(home.contains("PolCommitPanel"));
let cfg = std::fs::read_to_string(target.join("src/config.ts")).unwrap();
assert!(cfg.contains("export const APP_ID"));
}
#[test]
fn generates_react_native_social_with_mesh() {
let registry = Registry::load_embedded().unwrap();
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("my-mesh-social");
let mut vars = BTreeMap::new();
vars.insert("app_id".to_string(), "app_rn".to_string());
vars.insert("enable_mesh".to_string(), "true".to_string());
vars.insert("mesh_app_id".to_string(), "my-mesh-social".to_string());
vars.insert(
"relay_server_url".to_string(),
"wss://relay.offlineprotocol.com".to_string(),
);
let out = generate(
®istry,
"react-native-social",
&target,
"my-mesh-social",
&vars,
)
.expect("generation succeeds");
assert!(out
.files_written
.contains(&"src/context/ProtocolContext.tsx".to_string()));
assert!(out
.files_written
.contains(&"src/screens/PeopleScreen.tsx".to_string()));
assert!(out
.files_written
.contains(&"src/providers/MeshSessionBridge.tsx".to_string()));
let pkg = std::fs::read_to_string(target.join("package.json")).unwrap();
assert!(pkg.contains("@offline-protocol/mesh-sdk"));
assert!(out
.files_written
.contains(&"src/screens/GroupsScreen.tsx".to_string()));
let app = std::fs::read_to_string(target.join("App.tsx")).unwrap();
assert!(app.contains("ProtocolProvider"));
assert!(app.contains("MeshSessionBridge"));
assert!(app.contains("PeopleScreen"));
assert!(app.contains("GroupsScreen"));
let protocol_ctx =
std::fs::read_to_string(target.join("src/context/ProtocolContext.tsx")).unwrap();
assert!(protocol_ctx.contains("mlsGetOrCreateKeyPackage"));
assert!(protocol_ctx.contains("BLE_DESTROY_SETTLE_MS"));
assert!(protocol_ctx.contains("localAddressRef"));
let env = std::fs::read_to_string(target.join(".env")).unwrap();
assert!(env.contains("APP_ID=app_rn"));
assert!(env.contains("MESH_APP_ID=my-mesh-social"));
assert!(env.contains("OFFLINE_RELAY_SERVER_URL=wss://relay.offlineprotocol.com"));
let config = std::fs::read_to_string(target.join("src/config.ts")).unwrap();
assert!(config.contains("MESH_APP_ID"));
assert!(config.contains("from '@env'"));
}
#[test]
fn generates_react_native_template() {
let registry = Registry::load_embedded().unwrap();
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("my-app");
let mut vars = BTreeMap::new();
vars.insert("app_id".to_string(), "my-app".to_string());
let out = generate(®istry, "react-native-mesh-app", &target, "my-app", &vars)
.expect("generation succeeds");
assert!(out.files_written.contains(&"package.json".to_string()));
assert!(out.files_written.contains(&".gitignore".to_string()));
assert!(out.files_written.contains(&"AGENTS.md".to_string()));
assert!(out
.files_written
.contains(&"src/context/ProtocolContext.tsx".to_string()));
assert!(out.files_written.contains(&"src/constants.ts".to_string()));
assert!(out
.files_written
.contains(&"src/screens/OnboardingScreen.tsx".to_string()));
let pkg = std::fs::read_to_string(target.join("package.json")).unwrap();
assert!(pkg.contains("\"name\": \"my-app\""));
assert!(pkg.contains("@offline-protocol/mesh-sdk"));
assert!(!pkg.contains("@offline-protocol/id-react-native"));
let mesh = registry.package("@offline-protocol/mesh-sdk").unwrap();
assert!(pkg.contains(&mesh.version));
let app = std::fs::read_to_string(target.join("App.tsx")).unwrap();
assert!(app.contains("ProtocolProvider"));
assert!(app.contains("OnboardingScreen"));
assert!(app.contains("GroupsScreen"));
let constants = std::fs::read_to_string(target.join("src/constants.ts")).unwrap();
assert!(constants.contains("appId: 'my-app'"));
assert!(constants.contains("requireEncryption: false"));
assert!(constants.contains("BLE_DESTROY_SETTLE_MS"));
let protocol_ctx =
std::fs::read_to_string(target.join("src/context/ProtocolContext.tsx")).unwrap();
assert!(protocol_ctx.contains("mlsGetOrCreateKeyPackage"));
assert!(protocol_ctx.contains("connection_request_undeliverable"));
assert!(protocol_ctx.contains("mlsImportKeyPackage"));
assert!(protocol_ctx.contains("BLE_DESTROY_SETTLE_MS"));
assert!(protocol_ctx.contains("identity not ready"));
assert!(target.join(".gitignore").exists());
let cfg = std::fs::read_to_string(target.join("offline.config.json")).unwrap();
assert!(cfg.contains("@offline-protocol/mesh-sdk"));
}
#[test]
fn generates_nextjs_template() {
let registry = Registry::load_embedded().unwrap();
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("web");
let mut vars = BTreeMap::new();
vars.insert("app_id".to_string(), "app_web".to_string());
let out = generate(®istry, "nextjs-social", &target, "web", &vars)
.expect("generation succeeds");
assert!(out.files_written.contains(&"package.json".to_string()));
assert!(out.files_written.contains(&".env".to_string()));
assert!(out.files_written.contains(&".env.example".to_string()));
assert!(out.files_written.contains(&".gitignore".to_string()));
let providers = std::fs::read_to_string(target.join("src/app/providers.tsx")).unwrap();
assert!(providers.contains("OfflineAppProvider"));
let config = std::fs::read_to_string(target.join("src/lib/config.ts")).unwrap();
assert!(config.contains("NEXT_PUBLIC_APP_ID"));
assert!(!config.contains("app_web"));
let env = std::fs::read_to_string(target.join(".env")).unwrap();
assert!(env.contains("NEXT_PUBLIC_APP_ID=app_web"));
}
#[test]
fn refuses_non_empty_target() {
let registry = Registry::load_embedded().unwrap();
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("existing.txt"), "x").unwrap();
let err = generate(
®istry,
"nextjs-social",
tmp.path(),
"web",
&BTreeMap::new(),
)
.unwrap_err();
assert!(matches!(err, GeneratorError::TargetNotEmpty(_)));
}
#[test]
fn missing_required_variable_errors() {
let registry = Registry::load_embedded().unwrap();
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("app");
let err = generate(
®istry,
"react-native-mesh-app",
&target,
"app",
&BTreeMap::new(),
)
.unwrap_err();
assert!(matches!(err, GeneratorError::MissingVariable(_)));
}
#[test]
fn all_templates_render_without_errors() {
let registry = Registry::load_embedded().unwrap();
for t in registry.templates() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("proj");
let mut vars = BTreeMap::new();
for v in &t.variables {
vars.insert(v.name.clone(), format!("test-{}", v.name));
}
generate(®istry, &t.name, &target, "proj", &vars)
.unwrap_or_else(|e| panic!("template `{}` failed: {e}", t.name));
}
}
const WORKFLOW_TEMPLATES: &[(&str, &str, &[&str])] = &[
(
"react-native-mesh-handoff",
"local-handoff",
&[
"src/handoff/ledger.ts",
"src/handoff/protocol.ts",
"__tests__/handoff.test.ts",
"backend/src/server.mjs",
"backend/test/server.test.mjs",
"src/backend/client.ts",
],
),
(
"react-native-mesh-event-delivery",
"backend-delivery",
&[
"src/delivery/outbox.ts",
"src/delivery/protocol.ts",
"__tests__/delivery.test.ts",
"backend/src/server.mjs",
"backend/test/server.test.mjs",
"src/backend/client.ts",
],
),
(
"react-native-mesh-service",
"nearby-service",
&[
"src/service/provider.ts",
"src/service/client.ts",
"src/service/contract.ts",
"src/platform/existingApp.ts",
"__tests__/service.test.ts",
],
),
];
#[test]
fn generates_workflow_templates() {
let registry = Registry::load_embedded().unwrap();
for (template, workflow, expected) in WORKFLOW_TEMPLATES {
let meta = registry.template(template).expect("template registered");
assert!(meta.requires_mesh, "{template} must require mesh");
assert!(!meta.requires_login, "{template} is a local starter");
assert_eq!(meta.workflow.as_deref(), Some(*workflow));
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("field-app");
let mut vars = BTreeMap::new();
vars.insert("mesh_app_id".to_string(), "field-app".to_string());
vars.insert("enable_mesh".to_string(), "true".to_string());
let out = generate(®istry, template, &target, "field-app", &vars)
.unwrap_or_else(|e| panic!("{template}: {e}"));
for file in expected.iter().chain(&[
"package.json",
"App.tsx",
"src/config.ts",
"src/platform/mesh.ts",
"src/core/storage.ts",
"AGENTS.md",
"CLAUDE.md",
".mcp.json",
"offline.config.json",
"README.md",
".gitignore",
]) {
assert!(
out.files_written.contains(&file.to_string()),
"{template}: missing {file}"
);
}
assert!(
!out.files_written.iter().any(|f| f.ends_with(".tera")),
"{template}: unrendered template file"
);
let pkg: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(target.join("package.json")).unwrap(),
)
.expect("package.json is valid JSON");
let mesh = registry.package("@offline-protocol/mesh-sdk").unwrap();
assert_eq!(
pkg["dependencies"]["@offline-protocol/mesh-sdk"],
format!("^{}", mesh.version)
);
assert_eq!(
pkg["scripts"]["backend:test"].is_string(),
expected.contains(&"backend/src/server.mjs"),
"{template}: backend scripts"
);
let config = std::fs::read_to_string(target.join("src/config.ts")).unwrap();
assert!(config.contains("export const APP_ID = 'field-app';"));
let offline_config =
std::fs::read_to_string(target.join("offline.config.json")).unwrap();
assert!(offline_config.contains(&format!("\"workflow\": \"{workflow}\"")));
for (rel, _) in registry.template_files(template).unwrap() {
let rel = rel.to_string_lossy().replace('\\', "/");
if rel.starts_with("src/platform/") || !rel.contains(".ts") {
continue;
}
let text = std::fs::read_to_string(target.join(rel.trim_end_matches(".tera")))
.unwrap_or_default();
assert!(
!text.contains("@offline-protocol/mesh-sdk'"),
"{template}: {rel} imports the SDK outside src/platform/"
);
}
}
}
#[test]
fn generates_example_app_templates() {
let registry = Registry::load_embedded().unwrap();
for (template, mesh_app_id) in [
("orderup", "orderup"),
("stocksync", "stocksync"),
("cowrite", "cowrite"),
] {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("example-out");
let mut vars = BTreeMap::new();
vars.insert("app_id".to_string(), mesh_app_id.to_string());
vars.insert("enable_mesh".to_string(), "true".to_string());
let out = generate(®istry, template, &target, "my-example", &vars)
.unwrap_or_else(|e| panic!("{template}: {e}"));
assert!(
out.files_written
.iter()
.any(|f| f.starts_with("packages/mesh/")),
"{template}: missing packages/mesh"
);
assert!(
out.files_written
.iter()
.any(|f| f.starts_with("packages/ui/")),
"{template}: missing packages/ui"
);
assert!(
out.files_written
.iter()
.any(|f| f == "android/app/build.gradle"),
"{template}: missing android/"
);
assert!(
!out.files_written
.iter()
.any(|f| f.contains("offline-app-examples")),
"{template}: leaked monorepo path"
);
assert!(!target.join("ios/Podfile.lock").exists());
let app = std::fs::read_to_string(target.join("App.tsx")).unwrap();
assert!(app.contains(&format!("const APP_ID = '{mesh_app_id}'")));
let pkg: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(target.join("package.json")).unwrap(),
)
.expect("package.json");
assert_eq!(pkg["name"], "my-example");
assert_eq!(
pkg["dependencies"]["@offline-app-examples/mesh"],
"file:./packages/mesh"
);
let meta = registry.template(template).unwrap();
assert!(meta.example_app);
}
}
#[test]
fn workflow_templates_share_identical_core_files() {
let shared = [
"src/core/backoff.ts",
"src/core/ids.ts",
"src/core/mutex.ts",
"src/core/ports.ts",
"src/core/storage.ts",
"src/platform/mesh.ts",
"src/platform/permissions.ts",
"src/platform/deviceStore.ts",
"__tests__/core.test.ts",
"tsconfig.json",
];
let with_backend = [
"src/backend/client.ts",
"__tests__/backendClient.test.ts",
"__tests__/fakes.ts",
"backend/src/server.mjs",
"backend/src/store.mjs",
"backend/test/server.test.mjs",
"backend/package.json",
"backend/README.md",
"package.json.tera",
];
let registry = Registry::load_embedded().unwrap();
let files = |t: &str| -> BTreeMap<String, Vec<u8>> {
registry
.template_files(t)
.unwrap()
.into_iter()
.map(|(p, d)| (p.to_string_lossy().replace('\\', "/"), d))
.collect()
};
let handoff = files("react-native-mesh-handoff");
let delivery = files("react-native-mesh-event-delivery");
let service = files("react-native-mesh-service");
for f in shared {
assert_eq!(
handoff.get(f),
delivery.get(f),
"{f} differs (handoff, delivery)"
);
assert_eq!(
handoff.get(f),
service.get(f),
"{f} differs (handoff, service)"
);
assert!(handoff.contains_key(f), "{f} missing");
}
for f in with_backend {
assert!(handoff.contains_key(f), "{f} missing");
assert_eq!(
handoff.get(f),
delivery.get(f),
"{f} differs (handoff, delivery)"
);
assert!(!service.contains_key(f) || f == "package.json.tera");
}
}
}