cufflink-cli 0.14.2

CLI for the Cufflink CRUD microservice platform — deploy, init, and manage services
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
use crate::config::CliConfig;
use std::process::Command;

/// Parse the local manifest by running `cargo run -- --emit-manifest`.
fn load_local_manifest() -> eyre::Result<cufflink_types::ServiceManifest> {
    let output = Command::new("cargo")
        .args(["run", "--", "--emit-manifest"])
        .output()?;

    if !output.status.success() {
        eyre::bail!("Failed to build service. Run from a cufflink service directory.");
    }

    let stdout = String::from_utf8(output.stdout)?;
    let manifest: cufflink_types::ServiceManifest = serde_json::from_str(stdout.trim())?;
    Ok(manifest)
}

/// Generate the OpenAPI spec locally from the manifest (no deployment required).
fn generate_local_spec(tenant_slug: Option<&str>) -> eyre::Result<serde_json::Value> {
    let manifest = load_local_manifest()?;
    let slug = tenant_slug.unwrap_or("local");
    Ok(cufflink_types::openapi::generate_openapi(&manifest, slug))
}

/// Fetch the OpenAPI spec from the deployed platform.
async fn fetch_remote_spec(env: Option<&str>) -> eyre::Result<serde_json::Value> {
    let config = CliConfig::load_with_env(env)?;
    let manifest = load_local_manifest()?;

    let client = config.http_client();
    let resp = config
        .auth_request(
            &client,
            reqwest::Method::GET,
            &format!("{}/api/services", config.api_url),
        )
        .send()
        .await?;

    let body: serde_json::Value = resp.json().await?;
    let services = body["services"]
        .as_array()
        .ok_or_else(|| eyre::eyre!("No services found"))?;

    let service = services
        .iter()
        .find(|s| s["name"].as_str() == Some(&manifest.name))
        .ok_or_else(|| {
            eyre::eyre!(
                "Service '{}' not found. Deploy it first, or use --local.",
                manifest.name
            )
        })?;

    let service_id = service["id"]
        .as_str()
        .ok_or_else(|| eyre::eyre!("Service has no ID"))?;

    let spec_resp = config
        .auth_request(
            &client,
            reqwest::Method::GET,
            &format!(
                "{}/api/services/{}/openapi.json",
                config.api_url, service_id
            ),
        )
        .send()
        .await?;

    if !spec_resp.status().is_success() {
        let status = spec_resp.status();
        let body = spec_resp.text().await.unwrap_or_default();
        eyre::bail!("Failed to fetch OpenAPI spec ({}): {}", status, body);
    }

    Ok(spec_resp.json().await?)
}

/// Fetch and display the OpenAPI spec for the current service
pub async fn run(local: bool, tenant_slug: Option<&str>, env: Option<&str>) -> eyre::Result<()> {
    let spec = if local {
        generate_local_spec(tenant_slug)?
    } else {
        fetch_remote_spec(env).await?
    };

    println!("{}", serde_json::to_string_pretty(&spec)?);
    Ok(())
}

/// Fetch OpenAPI spec and write to a file
pub async fn save(
    output_path: &str,
    local: bool,
    tenant_slug: Option<&str>,
    env: Option<&str>,
) -> eyre::Result<()> {
    let spec = if local {
        generate_local_spec(tenant_slug)?
    } else {
        fetch_remote_spec(env).await?
    };

    std::fs::write(output_path, serde_json::to_string_pretty(&spec)?)?;
    println!("OpenAPI spec written to {}", output_path);
    Ok(())
}

/// Generate a TypeScript client from the OpenAPI spec
pub async fn generate_client(
    output_dir: &str,
    local: bool,
    tenant_slug: Option<&str>,
    env: Option<&str>,
) -> eyre::Result<()> {
    let manifest = load_local_manifest()?;
    let service_name = &manifest.name;

    let spec = if local {
        let slug = tenant_slug.unwrap_or("local");
        cufflink_types::openapi::generate_openapi(&manifest, slug)
    } else {
        fetch_remote_spec(env).await?
    };

    // Write the spec to a file
    let spec_path = format!("{}/openapi.json", output_dir);
    std::fs::create_dir_all(output_dir)?;
    std::fs::write(&spec_path, serde_json::to_string_pretty(&spec)?)?;

    // Generate TypeScript client directly (no external dependency needed)
    let ts_client = generate_typescript_client(&spec, service_name);
    let client_path = format!("{}/client.ts", output_dir);
    std::fs::write(&client_path, ts_client)?;

    // Emit the package entrypoint too, so the ESM re-export isn't hand-maintained
    // (a stale `export *` wrapper is what broke named imports for non-bundler
    // consumers). The `.js` specifier is required for NodeNext/ESM resolution of
    // the compiled output.
    let index_path = format!("{}/index.ts", output_dir);
    std::fs::write(&index_path, generate_index_ts())?;

    println!("Generated TypeScript client:");
    println!("  {}", spec_path);
    println!("  {}", client_path);
    println!("  {}", index_path);

    Ok(())
}

/// Package entrypoint that re-exports the generated client class and types.
fn generate_index_ts() -> &'static str {
    "// Auto-generated by cufflink CLI\nexport * from \"./client.js\";\n"
}

fn generate_typescript_client(spec: &serde_json::Value, service_name: &str) -> String {
    let mut out = String::new();

    // Header
    out.push_str(&format!(
        "// Auto-generated TypeScript client for {}\n",
        service_name
    ));
    out.push_str("// Generated by cufflink CLI\n\n");

    // Types from schemas
    if let Some(schemas) = spec["components"]["schemas"].as_object() {
        for (name, schema) in schemas {
            if name == "Pagination" {
                continue;
            }
            out.push_str(&format!("export interface {} {{\n", name));
            if let Some(props) = schema["properties"].as_object() {
                for (prop_name, prop_def) in props {
                    let ts_type = openapi_type_to_ts(prop_def);
                    let nullable = prop_def["nullable"].as_bool().unwrap_or(false);
                    if nullable {
                        out.push_str(&format!("  {}: {} | null;\n", prop_name, ts_type));
                    } else {
                        out.push_str(&format!("  {}: {};\n", prop_name, ts_type));
                    }
                }
            }
            out.push_str("}\n\n");
        }

        // Pagination type
        out.push_str("export interface Pagination {\n");
        out.push_str("  current_page: number;\n");
        out.push_str("  per_page: number;\n");
        out.push_str("  total_records: number;\n");
        out.push_str("  total_pages: number;\n");
        out.push_str("}\n\n");
    }

    // Client class
    out.push_str("export class CufflinkClient {\n");
    out.push_str("  private baseUrl: string;\n");
    out.push_str("  private headers: Record<string, string>;\n\n");
    out.push_str("  constructor(baseUrl: string, headers: Record<string, string> = {}) {\n");
    out.push_str("    this.baseUrl = baseUrl.replace(/\\/$/, '');\n");
    out.push_str("    this.headers = { 'Content-Type': 'application/json', ...headers };\n");
    out.push_str("  }\n\n");

    out.push_str(
        "  private async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n",
    );
    out.push_str("    const resp = await fetch(`${this.baseUrl}${path}`, {\n");
    out.push_str("      method,\n");
    out.push_str("      headers: this.headers,\n");
    out.push_str("      body: body ? JSON.stringify(body) : undefined,\n");
    out.push_str("    });\n");
    out.push_str(
        "    if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);\n",
    );
    // Cast: under Node's fetch types `resp.json()` is `Promise<unknown>` (it's
    // only `any` under DOM/Next), which fails strict tsc when assigned to `T`.
    out.push_str("    return resp.json() as Promise<T>;\n");
    out.push_str("  }\n\n");

    // Generate methods from paths
    if let Some(paths) = spec["paths"].as_object() {
        for (path, operations) in paths {
            if let Some(ops) = operations.as_object() {
                for (method, op) in ops {
                    let operation_id = op["operationId"].as_str().unwrap_or("unknown");
                    let fn_name = to_camel_case(operation_id);

                    // Check if this is a custom route (tagged with "custom")
                    let is_custom = op["tags"]
                        .as_array()
                        .map(|tags| tags.iter().any(|t| t.as_str() == Some("custom")))
                        .unwrap_or(false);

                    if is_custom {
                        // Custom WASM handler route
                        let has_body = op.get("requestBody").is_some();

                        if has_body {
                            out.push_str(&format!(
                                "  async {}(data?: Record<string, unknown>): Promise<Record<string, unknown>> {{\n",
                                fn_name
                            ));
                            out.push_str(&format!(
                                "    return this.request('{}', '{}', data);\n",
                                method.to_uppercase(),
                                path
                            ));
                        } else {
                            out.push_str(&format!(
                                "  async {}(params?: Record<string, string>): Promise<Record<string, unknown>> {{\n",
                                fn_name
                            ));
                            out.push_str(
                                "    const query = params ? '?' + new URLSearchParams(params).toString() : '';\n"
                            );
                            out.push_str(&format!(
                                "    return this.request('GET', `{}${{query}}`);\n",
                                path
                            ));
                        }
                        out.push_str("  }\n\n");
                    } else {
                        match method.as_str() {
                            "get" if !path.contains(":id") => {
                                // List endpoint
                                let schema_ref = op["responses"]["200"]["content"]
                                    ["application/json"]["schema"]["properties"]["results"]
                                    ["items"]["$ref"]
                                    .as_str()
                                    .and_then(|r| r.split('/').next_back());
                                let return_type = schema_ref.unwrap_or("unknown");

                                out.push_str(&format!(
                                "  async {}(params?: Record<string, string>): Promise<{{ results: {}[]; pagination: Pagination }}> {{\n",
                                fn_name, return_type
                            ));
                                out.push_str(
                                "    const query = params ? '?' + new URLSearchParams(params).toString() : '';\n"
                            );
                                out.push_str(&format!(
                                    "    return this.request('GET', `{}${{query}}`);\n",
                                    path
                                ));
                                out.push_str("  }\n\n");
                            }
                            "post" => {
                                // Create endpoint
                                let create_ref = op["requestBody"]["content"]["application/json"]
                                    ["schema"]["$ref"]
                                    .as_str()
                                    .and_then(|r| r.split('/').next_back());
                                let body_type = create_ref.unwrap_or("unknown");

                                let response_ref = op["responses"]["200"]["content"]
                                    ["application/json"]["schema"]["$ref"]
                                    .as_str()
                                    .and_then(|r| r.split('/').next_back());
                                let return_type = response_ref.unwrap_or("unknown");

                                out.push_str(&format!(
                                    "  async {}(data: {}): Promise<{}> {{\n",
                                    fn_name, body_type, return_type
                                ));
                                out.push_str(&format!(
                                    "    return this.request('POST', '{}', data);\n",
                                    path
                                ));
                                out.push_str("  }\n\n");
                            }
                            "get" if path.contains(":id") => {
                                // Get by ID
                                let response_ref = op["responses"]["200"]["content"]
                                    ["application/json"]["schema"]["$ref"]
                                    .as_str()
                                    .and_then(|r| r.split('/').next_back());
                                let return_type = response_ref.unwrap_or("unknown");
                                let base_path = path.replace("/:id", "");

                                out.push_str(&format!(
                                    "  async {}(id: string): Promise<{}> {{\n",
                                    fn_name, return_type
                                ));
                                out.push_str(&format!(
                                    "    return this.request('GET', `{}/${{id}}`);\n",
                                    base_path
                                ));
                                out.push_str("  }\n\n");
                            }
                            "put" => {
                                // Update
                                let body_ref = op["requestBody"]["content"]["application/json"]
                                    ["schema"]["$ref"]
                                    .as_str()
                                    .and_then(|r| r.split('/').next_back());
                                let body_type = body_ref.unwrap_or("unknown");

                                let response_ref = op["responses"]["200"]["content"]
                                    ["application/json"]["schema"]["$ref"]
                                    .as_str()
                                    .and_then(|r| r.split('/').next_back());
                                let return_type = response_ref.unwrap_or("unknown");
                                let base_path = path.replace("/:id", "");

                                out.push_str(&format!(
                                    "  async {}(id: string, data: {}): Promise<{}> {{\n",
                                    fn_name, body_type, return_type
                                ));
                                out.push_str(&format!(
                                    "    return this.request('PUT', `{}/${{id}}`, data);\n",
                                    base_path
                                ));
                                out.push_str("  }\n\n");
                            }
                            "delete" => {
                                // Delete
                                let base_path = path.replace("/:id", "");

                                out.push_str(&format!(
                                    "  async {}(id: string): Promise<void> {{\n",
                                    fn_name
                                ));
                                out.push_str(&format!(
                                    "    await this.request('DELETE', `{}/${{id}}`);\n",
                                    base_path
                                ));
                                out.push_str("  }\n\n");
                            }
                            _ => {}
                        }
                    } // end else (non-custom)
                }
            }
        }
    }

    out.push_str("}\n");
    out
}

fn openapi_type_to_ts(prop: &serde_json::Value) -> &str {
    match prop["type"].as_str() {
        Some("string") => match prop["format"].as_str() {
            Some("uuid") => "string",
            Some("date-time") => "string",
            Some("date") => "string",
            _ => "string",
        },
        Some("integer") => "number",
        Some("number") => "number",
        Some("boolean") => "boolean",
        Some("object") => "Record<string, unknown>",
        Some("array") => "unknown[]",
        _ => "unknown",
    }
}

fn to_camel_case(s: &str) -> String {
    let mut result = String::new();
    let mut capitalize_next = false;
    for (i, c) in s.chars().enumerate() {
        if c == '_' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(c.to_ascii_uppercase());
            capitalize_next = false;
        } else if i == 0 {
            result.push(c.to_ascii_lowercase());
        } else {
            result.push(c);
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// A spec exercising every emit branch: a list, a create, a get-by-id, an
    /// update, a delete, plus custom GET and custom POST (`_fn`) handlers.
    fn sample_spec() -> serde_json::Value {
        let item_ref = json!({ "$ref": "#/components/schemas/Item" });
        let json_body = json!({ "content": { "application/json": { "schema": item_ref } } });
        json!({
            "components": { "schemas": {
                "Item": { "properties": {
                    "id": { "type": "string", "format": "uuid" },
                    "name": { "type": "string" },
                    "count": { "type": "integer" },
                    "note": { "type": "string", "nullable": true }
                }}
            }},
            "paths": {
                "/svc/t/s/items": {
                    "get": {
                        "operationId": "list_items",
                        "responses": { "200": { "content": { "application/json": {
                            "schema": { "properties": { "results": { "items": item_ref } } }
                        }}}}
                    },
                    "post": { "operationId": "create_item", "requestBody": json_body, "responses": { "200": json_body } }
                },
                "/svc/t/s/items/:id": {
                    "get": { "operationId": "get_item", "responses": { "200": json_body } },
                    "put": { "operationId": "update_item", "requestBody": json_body, "responses": { "200": json_body } },
                    "delete": { "operationId": "delete_item", "responses": {} }
                },
                "/svc/t/s/_fn/handle_search": { "get": { "operationId": "handle_search", "tags": ["custom"] } },
                "/svc/t/s/_fn/handle_do": {
                    "post": { "operationId": "handle_do", "tags": ["custom"], "requestBody": json_body }
                }
            }
        })
    }

    /// Regression guard for the missing-`}` bug seen in stale generated clients:
    /// a dropped method-closing brace makes the counts diverge.
    #[test]
    fn generated_client_is_brace_balanced() {
        let out = generate_typescript_client(&sample_spec(), "test-service");
        assert_eq!(
            out.matches('{').count(),
            out.matches('}').count(),
            "unbalanced braces in generated client:\n{out}"
        );
    }

    /// `resp.json()` is `Promise<unknown>` under Node's fetch types; the cast
    /// keeps the generated client strict-tsc clean for non-DOM consumers.
    #[test]
    fn request_helper_casts_json_to_generic() {
        let out = generate_typescript_client(&sample_spec(), "test-service");
        assert!(
            out.contains("return resp.json() as Promise<T>;"),
            "request<T> helper is missing the Promise<T> cast:\n{out}"
        );
    }

    #[test]
    fn index_reexports_client_with_js_specifier() {
        let index = generate_index_ts();
        // `.js` specifier is required for NodeNext/ESM resolution of the dist.
        assert!(index.contains("export * from \"./client.js\";"), "{index}");
    }

    #[test]
    fn emits_each_method_kind_and_closes_class() {
        let out = generate_typescript_client(&sample_spec(), "test-service");
        for needle in [
            "async listItems(",
            "async createItem(",
            "async getItem(",
            "async updateItem(",
            "async deleteItem(",
            "async handleSearch(",
            "async handleDo(",
        ] {
            assert!(out.contains(needle), "missing method `{needle}`:\n{out}");
        }
        assert!(out.contains("export class CufflinkClient {"));
        assert!(out.trim_end().ends_with('}'));
    }
}