rspyts-cli 3.0.3

Compiler and build orchestrator for rspyts
Documentation
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! Rendering of TypeScript callables, resources, constants, and Wasm runtime.
//!
//! Public wrappers preserve strict host types while the runtime recursively
//! prepares Serde-shaped values and restores immutable results. Typed arrays
//! remain on wasm-bindgen's direct vector ABI.

use super::*;
use crate::documentation::{CallableDocumentation, CallableReturn};

/// Render errors, functions, resources, and constants for one namespace.
pub(super) fn typescript_api(
    items: &NamespaceItems<'_>,
    context: &TypeScriptContext<'_>,
) -> Result<String> {
    let runtime_imports = typescript_runtime_imports(items);
    let mut source = String::new();
    let local_types = typescript_local_type_names(items);
    if !local_types.is_empty() {
        writeln!(
            source,
            "import type {{ {} }} from \"./models.js\";",
            local_types.join(", ")
        )?;
    }
    for import in typescript_type_imports(items, context)? {
        writeln!(
            source,
            "import type * as {} from {};",
            namespace_alias(&import),
            ts_string(&typescript_namespace_path(
                context.namespace,
                &import,
                "models.js"
            ))
        )?;
    }
    if !runtime_imports.is_empty() {
        source.push_str("import {\n");
        for name in runtime_imports {
            writeln!(source, "  {name},")?;
        }
        writeln!(
            source,
            "}} from {};",
            ts_string(&typescript_runtime_path(context.namespace))
        )?;
    }
    for import in typescript_error_imports(items, context)? {
        writeln!(
            source,
            "import * as {} from {};",
            api_namespace_alias(&import),
            ts_string(&typescript_namespace_path(
                context.namespace,
                &import,
                "api.js"
            ))
        )?;
    }
    for error in &items.errors {
        source.push('\n');
        emit_ts_doc(
            &mut source,
            Some(
                error
                    .docs
                    .as_deref()
                    .unwrap_or("An error reported by the Rust implementation."),
            ),
            "",
        )?;
        writeln!(
            source,
            "export class {} extends globalThis.Error {{\n  /**\n   * Stable machine-readable error code.\n   */\n  readonly code: string;\n\n  constructor(code: string, message: string) {{\n    super(message);\n    this.name = {};\n    this.code = code;\n  }}\n}}",
            error.name,
            ts_string(&error.name)
        )?;
    }
    for function in &items.functions {
        emit_typescript_function(&mut source, function, context, None)?;
    }
    for resource in &items.resources {
        emit_typescript_resource(&mut source, resource, context)?;
    }
    for constant in &items.constants {
        source.push('\n');
        let docs = constant
            .docs
            .as_deref()
            .map(|docs| typescript_documentation_text(docs, context));
        emit_ts_doc(&mut source, docs.as_deref(), "")?;
        writeln!(
            source,
            "export const {}: {} = restoreHost({}, {});",
            constant.host_name,
            type_ref(&constant.ty, context)?,
            typescript_value(&constant.value, &constant.ty, context.manifest)?,
            typescript_spec(&constant.ty)?
        )?;
    }
    Ok(source)
}

/// Render the package-level Wasm loader and recursive host adapters.
pub(super) fn typescript_runtime(manifest: &Manifest) -> Result<String> {
    let mut source = String::from(
        "import initializeNative, * as native from \"./native/native.js\";\n\nconst wasmUrl = new URL(\"./native/native_bg.wasm\", import.meta.url);\nlet wasmInput: any = wasmUrl;\nconst process = (globalThis as { process?: { versions?: { node?: string } } }).process;\nif (process?.versions?.node) {\n  const nodeModule = \"node:fs/promises\";\n  const { readFile } = await import(/* @vite-ignore */ nodeModule);\n  if (wasmUrl.protocol === \"file:\") {\n    wasmInput = await readFile(wasmUrl);\n  } else if (wasmUrl.pathname.startsWith(\"/@fs/\")) {\n    wasmInput = await readFile(decodeURIComponent(wasmUrl.pathname.slice(4)));\n  }\n}\nawait initializeNative({ module_or_path: wasmInput });\n\nexport { native };\n",
    );
    source.push_str(TYPESCRIPT_ADAPTERS);
    source.push_str("\nconst nativeSchemas: Record<string, any> = {\n");
    for definition in &manifest.types {
        writeln!(
            source,
            "  {}: {},",
            ts_property(&definition_key(&definition.identity())),
            typescript_named_spec(definition)?
        )?;
    }
    source.push_str("};\n");
    Ok(source)
}

// Import planning ----------------------------------------------------------

/// Return model names declared locally and needed by the API module.
fn typescript_local_type_names(items: &NamespaceItems<'_>) -> Vec<String> {
    let mut names = items
        .types
        .iter()
        .map(|definition| definition.name.clone())
        .collect::<Vec<_>>();
    if namespace_refs(items)
        .iter()
        .any(|reference| reference_contains(reference, &|item| matches!(item, TypeRef::Json)))
    {
        names.push("JsonValue".to_owned());
    }
    names.sort();
    names.dedup();
    names
}

/// Compute the runtime helpers required by one generated API module.
fn typescript_runtime_imports(items: &NamespaceItems<'_>) -> Vec<&'static str> {
    let has_calls = !items.functions.is_empty() || !items.resources.is_empty();
    let has_params = items
        .functions
        .iter()
        .any(|function| !function.params.is_empty())
        || items.resources.iter().any(|resource| {
            resource
                .constructors
                .iter()
                .any(|constructor| !constructor.params.is_empty())
                || resource
                    .methods
                    .iter()
                    .any(|method| !method.params.is_empty())
        });
    let restores_values = !items.functions.is_empty()
        || items
            .resources
            .iter()
            .any(|resource| !resource.methods.is_empty())
        || !items.constants.is_empty();
    let translates_errors = items
        .functions
        .iter()
        .any(|function| function.error.is_some())
        || items.resources.iter().any(|resource| {
            resource
                .constructors
                .iter()
                .any(|constructor| constructor.error.is_some())
                || resource.methods.iter().any(|method| method.error.is_some())
        });
    let mut imports = Vec::new();
    if has_calls {
        imports.push("native");
    }
    if translates_errors {
        imports.push("nativeError");
    }
    if has_params {
        imports.push("prepareHost");
    }
    if restores_values {
        imports.push("restoreHost");
    }
    imports
}

const TYPESCRIPT_ADAPTERS: &str = r#"
function prepareJson(value: any): any {
  if (typeof value === "number") {
    if (!Number.isFinite(value)) throw new RangeError("JSON numbers must be finite");
    if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
      throw new RangeError("JSON integers outside JavaScript's safe range must be provided as bigint");
    }
    return value;
  }
  if (typeof value === "bigint" || value == null || typeof value !== "object") return value;
  if (Array.isArray(value)) return value.map(prepareJson);
  return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, prepareJson(item)]));
}

export function prepareHost(value: any, spec: any = null): any {
  if (value == null) return value;
  if (value instanceof Date) return value.toISOString();
  if (ArrayBuffer.isView(value)) return value;
  if (spec != null) {
    const [kind, detail, variants] = spec;
    if (kind === "json") return prepareJson(value);
    if (kind === "named") return prepareHost(value, nativeSchemas[detail]);
    if (kind === "alias") return prepareHost(value, detail);
    if (kind === "list") return Array.from(value, (item: any) => prepareHost(item, detail));
    if (kind === "map") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, prepareHost(item, detail)]));
    if (kind === "tuple") return value.map((item: any, index: number) => prepareHost(item, detail[index]));
    if (kind === "struct") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, prepareHost(item, detail[key])]));
    if (kind === "tagged") {
      const fields = variants[value[detail]] ?? {};
      return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, prepareHost(item, fields[key])]));
    }
  }
  if (Array.isArray(value)) return value.map((item: any) => prepareHost(item));
  if (value !== null && typeof value === "object") {
    return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, prepareHost(item)]));
  }
  return value;
}

const bufferConstructors: Record<string, any> = {
  u8: Uint8Array, i8: Int8Array, u16: Uint16Array, i16: Int16Array,
  u32: Uint32Array, i32: Int32Array, u64: BigUint64Array, i64: BigInt64Array,
  f32: Float32Array, f64: Float64Array,
};

function restoreJson(value: any): any {
  if (typeof value === "bigint") {
    const number = Number(value);
    return Number.isSafeInteger(number) && BigInt(number) === value ? number : value;
  }
  if (Array.isArray(value)) return Object.freeze(value.map(restoreJson));
  if (value !== null && typeof value === "object") {
    return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, restoreJson(item)])));
  }
  return value;
}

export function restoreHost(value: any, spec: any): any {
  if (value == null || spec == null) return value;
  const [kind, detail, variants] = spec;
  if (kind === "bytes") return value instanceof Uint8Array ? value : new Uint8Array(value);
  if (kind === "buffer") {
    const BufferType = bufferConstructors[detail];
    return value instanceof BufferType ? value : new BufferType(value);
  }
  if (kind === "json") return restoreJson(value);
  if (kind === "list") return Object.freeze(Array.from(value, (item: any) => restoreHost(item, detail)));
  if (kind === "map") return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, restoreHost(item, detail)])));
  if (kind === "tuple") return Object.freeze(value.map((item: any, index: number) => restoreHost(item, detail[index])));
  if (kind === "named") return restoreHost(value, nativeSchemas[detail]);
  if (kind === "alias") return restoreHost(value, detail);
  if (kind === "struct") return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, restoreHost(item, detail[key])])));
  if (kind === "tagged") {
    const fields = variants[value[detail]] ?? {};
    return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, restoreHost(item, fields[key])])));
  }
  return value;
}

export function nativeError(error: any, ErrorType: new (code: string, message: string) => Error): any {
  const text = String(error);
  const line = text.indexOf("\n");
  return line < 0 ? error : new ErrorType(text.slice(0, line), text.slice(line + 1));
}
"#;

// Callable and resource rendering -----------------------------------------

/// Render one free function or resource method wrapper.
fn emit_typescript_function(
    source: &mut String,
    function: &FunctionDef,
    context: &TypeScriptContext<'_>,
    receiver: Option<&str>,
) -> Result<()> {
    let params = typescript_params(&function.params, context)?;
    let calls = function
        .params
        .iter()
        .map(typescript_host_argument)
        .collect::<Result<Vec<_>>>()?
        .join(", ");
    let mut result_name = "nativeResult".to_owned();
    let parameter_names = function
        .params
        .iter()
        .map(|param| param.host_name.as_str())
        .collect::<BTreeSet<_>>();
    while parameter_names.contains(result_name.as_str()) {
        result_name.push_str("Value");
    }
    let native_name = &function.native_name;
    let (indent, signature, call) = if receiver.is_some() {
        (
            "  ",
            format!(
                "  {}({params}): {} {{",
                function.host_name,
                return_type_ref(&function.returns, context)?
            ),
            format!("this.nativeResource.{}({calls})", function.host_name),
        )
    } else {
        (
            "",
            format!(
                "export function {}({params}): {} {{",
                function.host_name,
                return_type_ref(&function.returns, context)?
            ),
            format!("native[{quoted}]({calls})", quoted = ts_string(native_name)),
        )
    };
    source.push('\n');
    emit_ts_callable_doc(
        source,
        &CallableDocumentation {
            docs: function.docs.as_deref(),
            fallback_summary: format!("Calls the Rust implementation of `{}`.", function.host_name),
            params: &function.params,
            returns: CallableReturn::Contract(&function.returns),
            error: function.error.as_ref(),
        },
        context,
        indent,
    )?;
    writeln!(source, "{signature}")?;
    if function.error.is_some() {
        writeln!(source, "{indent}  try {{")?;
        writeln!(source, "{indent}    const {result_name} = {call};")?;
        writeln!(
            source,
            "{indent}    return restoreHost({result_name}, {});",
            typescript_spec(&function.returns)?
        )?;
        writeln!(source, "{indent}  }} catch (error) {{")?;
        writeln!(
            source,
            "{indent}    throw nativeError(error, {});",
            typescript_error_ref(function.error.as_ref(), context)?
        )?;
        writeln!(source, "{indent}  }}")?;
    } else {
        writeln!(source, "{indent}  const {result_name} = {call};")?;
        writeln!(
            source,
            "{indent}  return restoreHost({result_name}, {});",
            typescript_spec(&function.returns)?
        )?;
    }
    writeln!(source, "{indent}}}")?;
    Ok(())
}

/// Render one resource class, its factories, methods, and disposal hooks.
fn emit_typescript_resource(
    source: &mut String,
    resource: &ResourceDef,
    context: &TypeScriptContext<'_>,
) -> Result<()> {
    let constructor = resource
        .constructors
        .iter()
        .find(|item| item.rust_name == "new")
        .or_else(|| resource.constructors.first())
        .context("resource has no constructor")?;
    let params = typescript_params(&constructor.params, context)?;
    let calls = constructor
        .params
        .iter()
        .map(typescript_host_argument)
        .collect::<Result<Vec<_>>>()?
        .join(", ");
    source.push('\n');
    emit_ts_doc(
        source,
        Some(
            resource
                .docs
                .as_deref()
                .unwrap_or("A stateful resource implemented in Rust."),
        ),
        "",
    )?;
    writeln!(source, "export class {} {{", resource.name)?;
    source.push_str("  private nativeResource!: any;\n\n");
    emit_ts_callable_doc(
        source,
        &CallableDocumentation {
            docs: constructor.docs.as_deref(),
            fallback_summary: format!("Creates a `{}` instance.", resource.name),
            params: &constructor.params,
            returns: CallableReturn::Omitted,
            error: constructor.error.as_ref(),
        },
        context,
        "  ",
    )?;
    writeln!(source, "  constructor({params}) {{")?;
    let native_call = format!(
        "new native[{quoted}]({calls})",
        quoted = ts_string(&resource.native_name)
    );
    if constructor.error.is_some() {
        source.push_str("    try {\n");
        writeln!(source, "      this.nativeResource = {native_call};")?;
        source.push_str("    } catch (error) {\n");
        writeln!(
            source,
            "      throw nativeError(error, {});",
            typescript_error_ref(constructor.error.as_ref(), context)?
        )?;
        source.push_str("    }\n");
    } else {
        writeln!(source, "    this.nativeResource = {native_call};")?;
    }
    source.push_str("  }\n");
    for factory in resource
        .constructors
        .iter()
        .filter(|item| !std::ptr::eq(*item, constructor))
    {
        let params = typescript_params(&factory.params, context)?;
        let calls = factory
            .params
            .iter()
            .map(typescript_host_argument)
            .collect::<Result<Vec<_>>>()?
            .join(", ");
        source.push('\n');
        emit_ts_callable_doc(
            source,
            &CallableDocumentation {
                docs: factory.docs.as_deref(),
                fallback_summary: format!("Creates a `{}` instance.", resource.name),
                params: &factory.params,
                returns: CallableReturn::Resource(&resource.name),
                error: factory.error.as_ref(),
            },
            context,
            "  ",
        )?;
        writeln!(
            source,
            "  static {}({params}): {} {{",
            factory.host_name, resource.name
        )?;
        writeln!(
            source,
            "    const value = Object.create({}.prototype);",
            resource.name
        )?;
        let native_call = format!(
            "native[{quoted}].{}({calls})",
            factory.host_name,
            quoted = ts_string(&resource.native_name)
        );
        if factory.error.is_some() {
            source.push_str("    try {\n");
            writeln!(source, "      value.nativeResource = {native_call};")?;
            source.push_str("    } catch (error) {\n");
            writeln!(
                source,
                "      throw nativeError(error, {});",
                typescript_error_ref(factory.error.as_ref(), context)?
            )?;
            source.push_str("    }\n");
        } else {
            writeln!(source, "    value.nativeResource = {native_call};")?;
        }
        source.push_str("    return value;\n  }\n");
    }
    for method in &resource.methods {
        let function = FunctionDef {
            owner: resource.owner.clone(),
            rust_module: resource.rust_module.clone(),
            rust_name: method.rust_name.clone(),
            host_name: method.host_name.clone(),
            native_name: resource.native_name.clone(),
            docs: method.docs.clone(),
            params: method.params.clone(),
            returns: method.returns.clone(),
            error: method.error.clone(),
        };
        emit_typescript_function(source, &function, context, Some(&resource.name))?;
    }
    source.push('\n');
    emit_ts_callable_doc(
        source,
        &CallableDocumentation {
            docs: None,
            fallback_summary: "Releases the native resources owned by this instance.".to_owned(),
            params: &[],
            returns: CallableReturn::Omitted,
            error: None,
        },
        context,
        "  ",
    )?;
    source.push_str("  close(): void {\n    this.nativeResource.close();\n  }\n}\n");
    Ok(())
}

/// Render one Wasm-call argument, bypassing adapters for direct buffers.
fn typescript_host_argument(param: &ParamDef) -> Result<String> {
    Ok(format!(
        "prepareHost({}, {})",
        param.host_name,
        typescript_spec(&param.ty)?
    ))
}

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

    fn resource_manifest() -> Manifest {
        let owner = rspyts::ir::CargoPackageId::new("test");
        let identity = rspyts::ir::DefinitionId::new("test", "test::Recorder");
        let constructor = |rust_name: &str, host_name: &str| FunctionDef {
            owner: owner.clone(),
            rust_module: "test".to_owned(),
            rust_name: rust_name.to_owned(),
            host_name: host_name.to_owned(),
            native_name: "native_recorder".to_owned(),
            docs: Some(format!("Create a recorder with `{rust_name}`.")),
            params: Vec::new(),
            returns: TypeRef::Named {
                identity: identity.clone(),
            },
            error: None,
        };
        Manifest {
            package_name: "test".to_owned(),
            package_version: "0.0.0".to_owned(),
            module_name: "native".to_owned(),
            types: Vec::new(),
            errors: Vec::new(),
            functions: Vec::new(),
            resources: vec![ResourceDef {
                owner: owner.clone(),
                rust_module: "test".to_owned(),
                name: "Recorder".to_owned(),
                native_name: "native_recorder".to_owned(),
                docs: Some("A stateful recorder.".to_owned()),
                constructors: vec![
                    constructor("new", "new"),
                    constructor("from_default", "fromDefault"),
                ],
                methods: Vec::new(),
            }],
            constants: Vec::new(),
        }
    }

    #[test]
    fn resource_factories_document_the_resource_without_model_resolution() {
        let manifest = resource_manifest();
        let namespace = Namespace::root();
        let context = TypeScriptContext {
            manifest: &manifest,
            namespace: &namespace,
        };
        let items = NamespaceItems {
            resources: vec![&manifest.resources[0]],
            ..NamespaceItems::default()
        };

        let source = typescript_api(&items, &context).expect("render resource factory");

        assert!(source.contains("static fromDefault(): Recorder"));
        assert!(source.contains("@returns A value typed as `Recorder`."));
    }
}