Skip to main content

crucible_codegen_cdk/
lib.rs

1//! One jsii-compatible construct library from a resolved provisioning plan.
2
3mod source;
4
5use crucible_codegen_infra::Plan;
6use crucible_ir::{Diagnostics, ir::Service};
7use serde::{Deserialize, Serialize};
8use serde_json::json;
9
10/// Publishing metadata is explicit: generation does not choose package ownership.
11#[derive(Debug, Clone, Deserialize, Serialize)]
12#[serde(deny_unknown_fields)]
13pub struct Options {
14    pub package_name: String,
15    pub package_version: String,
16    pub author: String,
17    pub repository_url: String,
18    pub license: String,
19    #[serde(default)]
20    pub targets: Targets,
21}
22
23#[derive(Debug, Clone, Default, Deserialize, Serialize)]
24#[serde(deny_unknown_fields)]
25pub struct Targets {
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub python: Option<Python>,
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub java: Option<Java>,
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub dotnet: Option<DotNet>,
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub go: Option<Go>,
34}
35
36#[derive(Debug, Clone, Deserialize, Serialize)]
37#[serde(rename_all = "camelCase", deny_unknown_fields)]
38pub struct Python {
39    pub dist_name: String,
40    pub module: String,
41}
42
43#[derive(Debug, Clone, Deserialize, Serialize)]
44#[serde(deny_unknown_fields)]
45pub struct Java {
46    pub package: String,
47    pub maven: Maven,
48}
49
50#[derive(Debug, Clone, Deserialize, Serialize)]
51#[serde(rename_all = "camelCase", deny_unknown_fields)]
52pub struct Maven {
53    pub group_id: String,
54    pub artifact_id: String,
55}
56
57#[derive(Debug, Clone, Deserialize, Serialize)]
58#[serde(rename_all = "camelCase", deny_unknown_fields)]
59pub struct DotNet {
60    pub namespace: String,
61    pub package_id: String,
62}
63
64#[derive(Debug, Clone, Deserialize, Serialize)]
65#[serde(rename_all = "camelCase", deny_unknown_fields)]
66pub struct Go {
67    pub module_name: String,
68    pub package_name: String,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct File {
73    pub path: String,
74    pub contents: String,
75}
76
77pub fn emit(service: &Service, plan: &Plan, options: &Options) -> Result<Vec<File>, Diagnostics> {
78    let mut diagnostics = Diagnostics::default();
79    for (field, value) in [
80        ("package_name", &options.package_name),
81        ("package_version", &options.package_version),
82        ("author", &options.author),
83        ("repository_url", &options.repository_url),
84        ("license", &options.license),
85    ] {
86        if value.trim().is_empty() || value.chars().any(char::is_control) {
87            diagnostics.push(
88                &service.id,
89                format!("CDK {field} must be nonempty and contain no control characters"),
90            );
91        }
92    }
93    let targets = serde_json::to_value(&options.targets).expect("metadata serializes");
94    validate_metadata(&targets, "targets", service, &mut diagnostics);
95    let source = source::emit(service, plan, &mut diagnostics);
96    if !diagnostics.is_empty() {
97        return Err(diagnostics);
98    }
99    let package = json!({
100        "name": options.package_name,
101        "version": options.package_version,
102        "description": format!("CDK resources for {}", service.id),
103        "author": { "name": options.author },
104        "repository": { "type": "git", "url": options.repository_url },
105        "license": options.license,
106        "main": "lib/index.js", "types": "lib/index.d.ts",
107        "files": ["lib", ".jsii"],
108        "scripts": { "build": "jsii --strict", "package": "jsii-pacmak" },
109        "peerDependencies": { "aws-cdk-lib": "^2.272.0", "constructs": "^10.8.1" },
110        "devDependencies": { "aws-cdk-lib": "2.272.0", "constructs": "10.8.1", "jsii": "~5.9.0", "jsii-pacmak": "^1.0.0", "@types/node": "^22.0.0" },
111        "jsii": { "outdir": "dist", "targets": targets, "tsc": { "rootDir": "src", "outDir": "lib" } },
112    });
113    Ok(vec![
114        File {
115            path: "src/index.ts".into(),
116            contents: source,
117        },
118        File {
119            path: "src/validation.ts".into(),
120            contents: include_str!("../runtime/validation.ts").replace("\r\n", "\n"),
121        },
122        File {
123            path: "package.json".into(),
124            contents: format!("{}\n", serde_json::to_string_pretty(&package).unwrap()),
125        },
126        File {
127            path: "README.md".into(),
128            contents: format!(
129                "# {}\n\nGenerated CDK constructs for `{}`. Supply the service token of an existing provider that implements the configured resource contract. This package does not create a provider or implement resource lifecycle operations.\n\nRun `npm install` and `npm run build` to compile the jsii assembly. Run `npm run package` to package configured language targets. Node.js is required by jsii consumers.\n\nModel constraints are checked for concrete values. Deployment-time tokens are checked by the provider. Replacement and deletion behavior belong to that provider; immutable documentation does not enforce replacement.\n",
130                options.package_name, service.id
131            ),
132        },
133    ])
134}
135
136fn validate_metadata(
137    value: &serde_json::Value,
138    path: &str,
139    service: &Service,
140    diagnostics: &mut Diagnostics,
141) {
142    match value {
143        serde_json::Value::String(value)
144            if value.trim().is_empty() || value.chars().any(char::is_control) =>
145        {
146            diagnostics.push(
147                &service.id,
148                format!("CDK {path} must be nonempty and contain no control characters"),
149            )
150        }
151        serde_json::Value::Object(object) => {
152            for (name, value) in object {
153                validate_metadata(value, &format!("{path}.{name}"), service, diagnostics);
154            }
155        }
156        _ => {}
157    }
158}