use std::collections::{BTreeMap, BTreeSet};
use std::sync::OnceLock;
use serde_json::{Map, Value};
use crate::model::{InvocationRecord, InvocationStatus, RecordingParam, RecordingStep};
const RUN_KEY_INPUT: &str = "runKey";
#[derive(Debug)]
pub(crate) struct EmittedRecipe {
pub(crate) code: String,
pub(crate) input_schema: Value,
pub(crate) description: String,
}
pub(crate) fn transcribe(
records: &[InvocationRecord],
take: u32,
skipped: &BTreeSet<String>,
) -> Vec<RecordingStep> {
let captured = records
.iter()
.map(|record| record.id.as_str())
.collect::<BTreeSet<_>>();
records
.iter()
.filter(|record| !skipped.contains(&record.id))
.filter(|record| !is_recording_command(&record.command_path))
.filter(|record| record.status != InvocationStatus::Incomplete)
.filter(|record| {
record
.parent_id
.as_deref()
.is_none_or(|parent| !captured.contains(parent))
})
.filter_map(|record| {
let input = merged_input(record, host_method(&record.command_path).as_str())?;
Some(RecordingStep {
invocation_id: record.id.clone(),
take,
command_path: record.command_path.clone(),
method: host_method(&record.command_path),
input,
pattern_signature: record.pattern_signature.clone(),
variable_paths: step_variable_paths(&record.variable_paths),
})
})
.collect()
}
pub(crate) fn emit(
takes: &[Vec<RecordingStep>],
params: &[RecordingParam],
literal_paths: &[String],
name: &str,
) -> Result<EmittedRecipe, String> {
let Some(primary) = takes.first() else {
return Err("RECORDING_EMPTY: A recording needs at least one take".to_string());
};
if primary.is_empty() {
return Err(format!(
"RECORDING_EMPTY: Recording \"{name}\" captured no emittable apoc calls"
));
}
align(takes)?;
let literal_paths = literal_paths.iter().cloned().collect::<BTreeSet<_>>();
let mut inputs = InputRegistry::default();
for param in params {
inputs.declare_explicit(¶m.name);
}
let mut body = String::new();
let mut locals = Vec::new();
for (index, step) in primary.iter().enumerate() {
let mut binder = Binder {
step_index: index,
takes,
params,
literal_paths: &literal_paths,
variable_paths: &step.variable_paths.iter().cloned().collect::<BTreeSet<_>>(),
inputs: &mut inputs,
};
let rendered = binder.render(&step.input, "$", Origin::Node, 1);
let local = local_name(&step.method, index + 1);
body.push_str(&format!(
"const {local} = await {}({rendered});\n",
step.method
));
locals.push(local);
}
let last = locals
.last()
.expect("a non-empty take emits at least one local");
body.push_str(&format!("return {last};\n"));
let secrets = inputs.secret_names();
let mut description = format!(
"Recorded from {} apoc {} across {} {}.",
primary.len(),
plural(primary.len(), "call", "calls"),
takes.len(),
plural(takes.len(), "take", "takes"),
);
if inputs.uses_run_key {
description.push_str(&format!(
" Supply a fresh `{RUN_KEY_INPUT}` per run so recorded idempotency keys do not replay."
));
}
if !secrets.is_empty() {
description.push_str(&format!(
" Recorded secret references were redacted; supply {} as PROVIDER:REFERENCE.",
secrets.join(", ")
));
}
Ok(EmittedRecipe {
code: body,
input_schema: inputs.schema(),
description,
})
}
fn align(takes: &[Vec<RecordingStep>]) -> Result<(), String> {
let Some(primary) = takes.first() else {
return Ok(());
};
for (index, take) in takes.iter().enumerate().skip(1) {
if take.len() != primary.len() {
return Err(format!(
"RECORDING_TAKES_DIVERGED: take 1 captured {} calls and take {} captured {}",
primary.len(),
index + 1,
take.len()
));
}
for (position, (first, other)) in primary.iter().zip(take).enumerate() {
if first.command_path != other.command_path
|| first.pattern_signature != other.pattern_signature
{
return Err(format!(
"RECORDING_TAKES_DIVERGED: call {} is \"{}\" in take 1 and \"{}\" in take {}",
position + 1,
first.command_path,
other.command_path,
index + 1
));
}
}
}
Ok(())
}
#[derive(Default)]
struct InputRegistry {
properties: BTreeMap<String, InputSpec>,
order: Vec<String>,
uses_run_key: bool,
}
struct InputSpec {
json_type: &'static str,
required: bool,
description: Option<String>,
}
impl InputRegistry {
fn declare_explicit(&mut self, name: &str) {
self.insert(name.to_string(), "string", true, None);
}
fn declare(
&mut self,
preferred: &str,
value: &Value,
required: bool,
description: Option<String>,
) -> String {
let mut name = preferred.to_string();
let mut suffix = 2;
while self.properties.contains_key(&name) {
name = format!("{preferred}{suffix}");
suffix += 1;
}
self.insert(name.clone(), json_type(value), required, description);
name
}
fn insert(
&mut self,
name: String,
json_type: &'static str,
required: bool,
description: Option<String>,
) {
if !self.properties.contains_key(&name) {
self.order.push(name.clone());
}
self.properties.insert(
name,
InputSpec {
json_type,
required,
description,
},
);
}
fn declare_run_key(&mut self) {
if !self.uses_run_key {
self.uses_run_key = true;
self.insert(
RUN_KEY_INPUT.to_string(),
"string",
true,
Some(
"Fresh caller key per run. Each recorded idempotency key is derived from it."
.to_string(),
),
);
}
}
fn declare_secret(&mut self, destination: &str) -> String {
let name = format!("secret{}", pascal_case(destination));
self.insert(
name.clone(),
"string",
true,
Some(format!(
"PROVIDER:REFERENCE for the redacted secret \"{destination}\"."
)),
);
name
}
fn secret_names(&self) -> Vec<String> {
self.order
.iter()
.filter(|name| name.starts_with("secret"))
.cloned()
.collect()
}
fn schema(&self) -> Value {
let mut properties = Map::new();
let mut required = Vec::new();
for name in &self.order {
let spec = &self.properties[name];
let mut property = Map::new();
property.insert(
"type".to_string(),
Value::String(spec.json_type.to_string()),
);
if let Some(description) = &spec.description {
property.insert(
"description".to_string(),
Value::String(description.clone()),
);
}
properties.insert(name.clone(), Value::Object(property));
if spec.required {
required.push(Value::String(name.clone()));
}
}
serde_json::json!({
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": Value::Object(properties),
"required": Value::Array(required),
"additionalProperties": false,
})
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Origin {
Node,
ArrayElement,
}
struct Binder<'a> {
step_index: usize,
takes: &'a [Vec<RecordingStep>],
params: &'a [RecordingParam],
literal_paths: &'a BTreeSet<String>,
variable_paths: &'a BTreeSet<String>,
inputs: &'a mut InputRegistry,
}
impl Binder<'_> {
fn render(&mut self, value: &Value, path: &str, origin: Origin, depth: usize) -> String {
if self.is_literal(path) {
return literal(value);
}
if let Some(name) = self.explicit_binding(value) {
return format!("input.{name}");
}
if let Some(rendered) = self.secret_binding(value, path) {
return rendered;
}
if self.is_idempotency_key(path) {
self.inputs.declare_run_key();
return format!("`${{input.{RUN_KEY_INPUT}}}:{}`", self.step_index + 1);
}
if origin == Origin::Node && !self.has_forced_descendant(value, path) {
if self.differs_across_takes(path) {
let name = self.inputs.declare(&derived_name(path), value, true, None);
return format!("input.{name}");
}
if self.is_variable(value, path) {
let name = self.inputs.declare(&derived_name(path), value, false, None);
return format!("(input.{name} ?? {})", literal(value));
}
}
match value {
Value::Object(object) => {
if object.is_empty() {
return "{}".to_string();
}
let pad = " ".repeat(depth);
let close = " ".repeat(depth.saturating_sub(1));
let entries = object
.iter()
.map(|(key, value)| {
let path = format!("{path}.{key}");
let rendered = self.render(value, &path, Origin::Node, depth + 1);
format!("{pad}{}: {rendered}", property_key(key))
})
.collect::<Vec<_>>()
.join(",\n");
format!("{{\n{entries}\n{close}}}")
}
Value::Array(values) => {
if values.is_empty() {
return "[]".to_string();
}
let entries = values
.iter()
.map(|value| {
self.render(value, &format!("{path}[]"), Origin::ArrayElement, depth)
})
.collect::<Vec<_>>()
.join(", ");
format!("[{entries}]")
}
value => literal(value),
}
}
fn explicit_binding(&self, value: &Value) -> Option<String> {
self.params
.iter()
.find(|param| ¶m.value == value)
.map(|param| param.name.clone())
}
fn secret_binding(&mut self, value: &Value, path: &str) -> Option<String> {
let destination = redacted_destination(value)?;
let name = self.inputs.declare_secret(&destination);
let reference = format!("`{destination}=${{input.{name}}}`");
Some(if path.ends_with("[]") {
reference
} else {
format!("[{reference}]")
})
}
fn is_idempotency_key(&self, path: &str) -> bool {
path.rsplit('.')
.next()
.is_some_and(|segment| segment == "idempotency_key")
}
fn is_literal(&self, path: &str) -> bool {
path == "$.purpose" || self.literal_paths.contains(path)
}
fn is_variable(&self, value: &Value, path: &str) -> bool {
if path == "$" || matches!(value, Value::Object(_)) {
return false;
}
self.variable_paths.contains(path)
}
fn differs_across_takes(&self, path: &str) -> bool {
if self.takes.len() < 2 || path == "$" {
return false;
}
let baseline = self.value_at(0, path);
(1..self.takes.len()).any(|take| self.value_at(take, path) != baseline)
}
fn value_at(&self, take: usize, path: &str) -> Option<Value> {
let step = self.takes.get(take)?.get(self.step_index)?;
resolve(&step.input, path)
}
fn has_forced_descendant(&self, value: &Value, path: &str) -> bool {
match value {
Value::Object(object) => object.iter().any(|(key, value)| {
let path = format!("{path}.{key}");
self.is_forced(value, &path) || self.has_forced_descendant(value, &path)
}),
Value::Array(values) => values.iter().any(|value| {
let path = format!("{path}[]");
self.is_forced(value, &path) || self.has_forced_descendant(value, &path)
}),
_ => false,
}
}
fn is_forced(&self, value: &Value, path: &str) -> bool {
self.is_literal(path)
|| self.explicit_binding(value).is_some()
|| redacted_destination(value).is_some()
|| self.is_idempotency_key(path)
|| self.differs_across_takes(path)
}
}
fn resolve(value: &Value, path: &str) -> Option<Value> {
let mut current = value;
for segment in path.trim_start_matches('$').split('.') {
if segment.is_empty() {
continue;
}
let segment = segment.strip_suffix("[]").unwrap_or(segment);
current = current.get(segment)?;
}
Some(current.clone())
}
fn merged_input(record: &InvocationRecord, method: &str) -> Option<Value> {
let input = record.normalized_input.as_object()?;
let declared = call_schemas().get(method);
let mut merged = Map::new();
for section in ["args", "options"] {
if let Some(Value::Object(values)) = input.get(section) {
for (key, value) in values {
if value.is_null() {
continue;
}
if declared.is_some_and(|schema| schema.is_default(key, value)) {
continue;
}
merged.insert(key.clone(), value.clone());
}
}
}
if let Some(idempotency_key) = input.get("idempotency_key") {
merged.insert("idempotency_key".to_string(), idempotency_key.clone());
}
if merged.is_empty() && !input.contains_key("purpose") {
return None;
}
if let Some(purpose) = input.get("purpose") {
merged.insert("purpose".to_string(), purpose.clone());
}
Some(Value::Object(merged))
}
struct CallSchema {
defaults: BTreeMap<String, Value>,
required: BTreeSet<String>,
}
impl CallSchema {
fn is_default(&self, key: &str, value: &Value) -> bool {
if self.required.contains(key) {
return false;
}
match self.defaults.get(key) {
Some(default) => default == value,
None => match value {
Value::Bool(value) => !value,
Value::Number(value) => value.as_f64() == Some(0.0),
Value::Array(values) => values.is_empty(),
_ => false,
},
}
}
}
fn call_schemas() -> &'static BTreeMap<String, CallSchema> {
static SCHEMAS: OnceLock<BTreeMap<String, CallSchema>> = OnceLock::new();
SCHEMAS.get_or_init(|| {
crate::cli::build_agent_cli_with_store(None)
.tool_catalog()
.definitions()
.into_iter()
.map(|definition| {
let required = definition
.input_schema
.get("required")
.and_then(Value::as_array)
.map(|values| {
values
.iter()
.filter_map(Value::as_str)
.map(ToString::to_string)
.collect()
})
.unwrap_or_default();
let defaults = definition
.input_schema
.get("properties")
.and_then(Value::as_object)
.map(|properties| {
properties
.iter()
.filter_map(|(key, property)| {
Some((key.clone(), property.get("default")?.clone()))
})
.collect()
})
.unwrap_or_default();
(
format!("apoc.{}", definition.name),
CallSchema { defaults, required },
)
})
.collect()
})
}
fn step_variable_paths(paths: &[String]) -> Vec<String> {
paths
.iter()
.map(|path| {
path.strip_prefix("$.args.")
.or_else(|| path.strip_prefix("$.options."))
.map_or_else(|| path.clone(), |rest| format!("$.{rest}"))
})
.collect()
}
fn redacted_destination(value: &Value) -> Option<String> {
let entries = value.as_array()?;
let [entry] = entries.as_slice() else {
return None;
};
let entry = entry.as_object()?;
if entry.get("redacted") != Some(&Value::Bool(true)) {
return None;
}
entry
.get("name")
.and_then(Value::as_str)
.map(ToString::to_string)
}
fn is_recording_command(command_path: &str) -> bool {
command_path == "recording" || command_path.starts_with("recording ")
}
fn host_method(command_path: &str) -> String {
format!("apoc.{}", command_path.replace(' ', "_"))
}
fn local_name(method: &str, position: usize) -> String {
let base = method.strip_prefix("apoc.").unwrap_or(method);
format!("{}{position}", camel_case(base))
}
fn derived_name(path: &str) -> String {
let segment = path
.trim_end_matches("[]")
.rsplit('.')
.find(|segment| !segment.is_empty() && *segment != "$")
.unwrap_or("value");
let name = camel_case(segment);
if name.is_empty() {
"value".to_string()
} else {
name
}
}
fn camel_case(value: &str) -> String {
let mut out = String::new();
let mut upper = false;
for character in value.chars() {
if character == '_' || character == '-' || character == ' ' {
upper = !out.is_empty();
continue;
}
if upper {
out.extend(character.to_uppercase());
upper = false;
} else {
out.push(character);
}
}
out
}
fn pascal_case(value: &str) -> String {
let camel = camel_case(&value.to_ascii_lowercase());
let mut characters = camel.chars();
match characters.next() {
Some(first) => first.to_uppercase().chain(characters).collect(),
None => String::new(),
}
}
fn property_key(key: &str) -> String {
let bare = !key.is_empty()
&& !key.starts_with(|character: char| character.is_ascii_digit())
&& key
.chars()
.all(|character| character.is_ascii_alphanumeric() || character == '_');
if bare {
key.to_string()
} else {
literal(&Value::String(key.to_string()))
}
}
fn literal(value: &Value) -> String {
value.to_string()
}
fn json_type(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
fn plural<'a>(count: usize, one: &'a str, many: &'a str) -> &'a str {
if count == 1 { one } else { many }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{InvocationScopeKind, InvocationSource, InvocationSurface};
fn record(id: &str, command_path: &str, input: Value) -> InvocationRecord {
let pattern = crate::pattern::invocation_pattern_signature(command_path, &input);
InvocationRecord {
id: id.to_string(),
parent_id: None,
execution_id: None,
source: InvocationSource::Native,
source_id: None,
source_order: None,
source_path: None,
accepted_sequence: 0,
surface: InvocationSurface::Cli,
actor: None,
agent: true,
command_path: command_path.to_string(),
purpose: Some("Recorded step.".to_string()),
normalized_input: input,
search_text: String::new(),
pattern_signature: pattern.signature,
variable_paths: pattern.variable_paths,
cwd: None,
scope_kind: InvocationScopeKind::Cwd,
scope_key: Some("/tmp/scope".to_string()),
recording_id: Some("rec".to_string()),
recording_take: Some(1),
started_at: 1,
completed_at: Some(2),
updated_at: 2,
status: InvocationStatus::Succeeded,
exit_code: Some(0),
error_code: None,
error: None,
}
}
fn command(id: &str, args: Value, options: Value) -> InvocationRecord {
record(
id,
"execution command",
serde_json::json!({ "purpose": "Verify the build.", "args": args, "options": options }),
)
}
fn take(records: &[InvocationRecord]) -> Vec<RecordingStep> {
transcribe(records, 1, &BTreeSet::new())
}
#[test]
fn transcription_drops_recording_commands_and_nested_host_calls() {
let mut nested = command("child", serde_json::json!({}), serde_json::json!({}));
nested.parent_id = Some("outer".to_string());
let records = vec![
record("start", "recording start", serde_json::json!({})),
command("outer", serde_json::json!({}), serde_json::json!({})),
nested,
];
let steps = take(&records);
assert_eq!(steps.len(), 1);
assert_eq!(steps[0].invocation_id, "outer");
assert_eq!(steps[0].method, "apoc.execution_command");
}
#[test]
fn an_explicit_holder_replaces_its_value_at_every_path() {
let records = vec![command(
"one",
serde_json::json!({ "executable": "./deploy.sh" }),
serde_json::json!({ "arg": ["--sha", "abc123"], "name": "abc123" }),
)];
let params = vec![RecordingParam {
name: "sha".to_string(),
value: Value::String("abc123".to_string()),
}];
let emitted = emit(&[take(&records)], ¶ms, &[], "deploy.verify").unwrap();
assert_eq!(emitted.code.matches("input.sha").count(), 2);
assert!(!emitted.code.contains("abc123"));
assert!(emitted.code.contains("\"./deploy.sh\""));
}
#[test]
fn a_differing_literal_across_takes_becomes_a_required_input() {
let first = vec![command(
"one",
serde_json::json!({ "executable": "cargo" }),
serde_json::json!({ "arg": ["test"], "timeout_ms": 1000 }),
)];
let second = vec![command(
"two",
serde_json::json!({ "executable": "cargo" }),
serde_json::json!({ "arg": ["test"], "timeout_ms": 2000 }),
)];
let emitted = emit(&[take(&first), take(&second)], &[], &[], "verify").unwrap();
assert!(emitted.code.contains("timeout_ms: input.timeoutMs"));
assert!(emitted.code.contains("executable: \"cargo\""));
let required = emitted.input_schema["required"].as_array().unwrap();
assert!(required.contains(&Value::String("timeoutMs".to_string())));
}
#[test]
fn diverging_takes_are_rejected_instead_of_guessed() {
let first = vec![command(
"one",
serde_json::json!({ "executable": "cargo" }),
serde_json::json!({}),
)];
let second = vec![
command(
"two",
serde_json::json!({ "executable": "cargo" }),
serde_json::json!({}),
),
command(
"three",
serde_json::json!({ "executable": "git" }),
serde_json::json!({}),
),
];
let error = emit(&[take(&first), take(&second)], &[], &[], "verify").unwrap_err();
assert!(error.starts_with("RECORDING_TAKES_DIVERGED"), "{error}");
}
#[test]
fn a_redacted_secret_becomes_a_required_reference_input() {
let records = vec![command(
"one",
serde_json::json!({ "executable": "./publish.sh" }),
serde_json::json!({ "secret_env": [{ "name": "TOKEN", "redacted": true }] }),
)];
let emitted = emit(&[take(&records)], &[], &[], "publish").unwrap();
assert!(
emitted.code.contains("[`TOKEN=${input.secretToken}`]"),
"{}",
emitted.code
);
assert!(!emitted.code.contains("redacted"));
let required = emitted.input_schema["required"].as_array().unwrap();
assert!(required.contains(&Value::String("secretToken".to_string())));
}
#[test]
fn recorded_idempotency_keys_are_derived_from_one_fresh_run_key() {
let records = vec![
command(
"one",
serde_json::json!({ "executable": "cargo" }),
serde_json::json!({ "idempotency_key": "build-1" }),
),
command(
"two",
serde_json::json!({ "executable": "cargo" }),
serde_json::json!({ "idempotency_key": "test-1" }),
),
];
let emitted = emit(&[take(&records)], &[], &[], "verify").unwrap();
assert!(
emitted
.code
.contains("idempotency_key: `${input.runKey}:1`")
);
assert!(
emitted
.code
.contains("idempotency_key: `${input.runKey}:2`")
);
assert!(!emitted.code.contains("build-1"));
let required = emitted.input_schema["required"].as_array().unwrap();
assert!(required.contains(&Value::String(RUN_KEY_INPUT.to_string())));
}
#[test]
fn a_literal_override_keeps_a_variable_path_hardcoded() {
let records = vec![command(
"one",
serde_json::json!({ "executable": "cargo" }),
serde_json::json!({ "timeout_ms": 1000 }),
)];
let open = emit(&[take(&records)], &[], &[], "verify").unwrap();
assert!(open.code.contains("input.timeoutMs ?? 1000"));
let pinned = emit(
&[take(&records)],
&[],
&["$.timeout_ms".to_string()],
"verify",
)
.unwrap();
assert!(pinned.code.contains("timeout_ms: 1000"));
assert!(!pinned.code.contains("input.timeoutMs"));
}
#[test]
fn an_explicit_holder_inside_an_array_keeps_its_siblings_literal() {
let records = vec![command(
"one",
serde_json::json!({ "executable": "cargo" }),
serde_json::json!({ "arg": ["test", "--filter", "abc123"] }),
)];
let params = vec![RecordingParam {
name: "filter".to_string(),
value: Value::String("abc123".to_string()),
}];
let emitted = emit(&[take(&records)], ¶ms, &[], "verify").unwrap();
assert!(
emitted
.code
.contains(r#"arg: ["test", "--filter", input.filter]"#),
"{}",
emitted.code
);
}
#[test]
fn the_last_recorded_call_is_the_recipe_result() {
let records = vec![
command(
"one",
serde_json::json!({ "executable": "cargo" }),
serde_json::json!({}),
),
record(
"two",
"process list",
serde_json::json!({ "purpose": "List processes.", "args": {}, "options": { "limit": 20 } }),
),
];
let emitted = emit(&[take(&records)], &[], &[], "verify").unwrap();
assert!(
emitted
.code
.contains("const executionCommand1 = await apoc.execution_command(")
);
assert!(
emitted
.code
.contains("const processList2 = await apoc.process_list(")
);
assert!(emitted.code.trim_end().ends_with("return processList2;"));
}
#[test]
fn an_empty_recording_refuses_to_emit() {
let error = emit(&[], &[], &[], "verify").unwrap_err();
assert!(error.starts_with("RECORDING_EMPTY"), "{error}");
let error = emit(&[Vec::new()], &[], &[], "verify").unwrap_err();
assert!(error.starts_with("RECORDING_EMPTY"), "{error}");
}
#[test]
fn transcription_drops_skipped_incomplete_and_unusable_records() {
let mut skipped = BTreeSet::new();
skipped.insert("skip".to_string());
let mut incomplete = command("incomplete", serde_json::json!({}), serde_json::json!({}));
incomplete.status = InvocationStatus::Incomplete;
let records = vec![
command("skip", serde_json::json!({}), serde_json::json!({})),
incomplete,
record(
"scalar",
"process list",
Value::String("invalid".to_string()),
),
record(
"empty",
"process list",
serde_json::json!({ "args": {}, "options": {} }),
),
];
assert!(transcribe(&records, 1, &skipped).is_empty());
assert!(is_recording_command("recording"));
}
#[test]
fn alignment_rejects_mismatched_commands_and_accepts_no_takes() {
assert!(align(&[]).is_ok());
let first = vec![command(
"one",
serde_json::json!({ "executable": "cargo" }),
serde_json::json!({}),
)];
let second = vec![record(
"two",
"process list",
serde_json::json!({ "purpose": "List.", "args": {}, "options": {} }),
)];
let error = align(&[take(&first), take(&second)]).unwrap_err();
assert!(error.contains("call 1"), "{error}");
}
#[test]
fn renders_empty_structures_quoted_keys_and_missing_paths() {
let takes = vec![take(&[command(
"one",
serde_json::json!({ "executable": "cargo" }),
serde_json::json!({}),
)])];
let literal_paths = BTreeSet::new();
let variable_paths = BTreeSet::new();
let mut inputs = InputRegistry::default();
let mut binder = Binder {
step_index: 0,
takes: &takes,
params: &[],
literal_paths: &literal_paths,
variable_paths: &variable_paths,
inputs: &mut inputs,
};
assert_eq!(
binder.render(&serde_json::json!({}), "$.object", Origin::Node, 1),
"{}"
);
assert_eq!(
binder.render(&serde_json::json!([]), "$.array", Origin::Node, 1),
"[]"
);
assert_eq!(property_key("needs-quote"), r#""needs-quote""#);
assert_eq!(local_name("custom_method", 2), "customMethod2");
assert_eq!(derived_name("$.--"), "value");
assert_eq!(pascal_case(""), "");
assert!(resolve(&serde_json::json!({}), "$.missing").is_none());
assert!(redacted_destination(&serde_json::json!([{ "redacted": false }])).is_none());
assert_eq!(
binder.secret_binding(
&serde_json::json!([{ "name": "TOKEN", "redacted": true }]),
"$.secret_env[]",
),
Some("`TOKEN=${input.secretToken}`".to_string())
);
assert!(!binder.differs_across_takes("$.executable"));
assert!(binder.value_at(1, "$.executable").is_none());
let mut missing_step_inputs = InputRegistry::default();
let missing_step = Binder {
step_index: 1,
takes: &takes,
params: &[],
literal_paths: &literal_paths,
variable_paths: &variable_paths,
inputs: &mut missing_step_inputs,
};
assert!(missing_step.value_at(0, "$.executable").is_none());
let two_takes = vec![takes[0].clone(), takes[0].clone()];
let mut root_inputs = InputRegistry::default();
let root = Binder {
step_index: 0,
takes: &two_takes,
params: &[],
literal_paths: &literal_paths,
variable_paths: &variable_paths,
inputs: &mut root_inputs,
};
assert!(!root.differs_across_takes("$"));
let purpose_only = record(
"purpose",
"process list",
serde_json::json!({ "purpose": "List processes." }),
);
assert_eq!(
merged_input(&purpose_only, "apoc.process_list"),
Some(serde_json::json!({ "purpose": "List processes." }))
);
}
#[test]
fn input_registry_handles_collisions_replacement_and_every_json_type() {
let mut inputs = InputRegistry::default();
assert_eq!(inputs.declare("value", &Value::Null, false, None), "value");
assert_eq!(
inputs.declare("value", &Value::Bool(true), false, None),
"value2"
);
inputs.insert("value".to_string(), "string", true, None);
inputs.declare_run_key();
inputs.declare_run_key();
for (name, value) in [
("number", serde_json::json!(1)),
("string", serde_json::json!("text")),
("array", serde_json::json!([])),
("object", serde_json::json!({})),
] {
inputs.declare(name, &value, false, None);
}
let schema = inputs.schema();
assert_eq!(schema["properties"]["value"]["type"], "string");
assert!(
schema["required"]
.as_array()
.unwrap()
.contains(&serde_json::json!("value"))
);
assert!(
schema["required"]
.as_array()
.unwrap()
.contains(&serde_json::json!(RUN_KEY_INPUT))
);
}
#[test]
fn merged_input_drops_nulls_declared_defaults_and_empty_flags() {
let null = record(
"null",
"process list",
serde_json::json!({ "args": { "selector": null }, "options": {} }),
);
assert!(merged_input(&null, "apoc.process_list").is_none());
let schemas = call_schemas();
let (method, schema) = schemas
.iter()
.find(|(_, schema)| !schema.defaults.is_empty())
.expect("the public command graph declares at least one default");
let (key, value) = schema.defaults.iter().next().unwrap();
let mut options = Map::new();
options.insert(key.clone(), value.clone());
let defaulted = record(
"default",
"discovery",
serde_json::json!({ "args": {}, "options": Value::Object(options) }),
);
assert!(merged_input(&defaulted, method).is_none());
let implicit = CallSchema {
defaults: BTreeMap::new(),
required: BTreeSet::new(),
};
assert!(implicit.is_default("flag", &Value::Bool(false)));
let no_purpose = record(
"no-purpose",
"process list",
serde_json::json!({ "args": { "limit": 1 }, "options": {} }),
);
assert_eq!(
merged_input(&no_purpose, "apoc.process_list"),
Some(serde_json::json!({ "limit": 1 }))
);
}
}