mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
feat(cli-rs): generate the Rust API client from ClientApi
script/gen/api.ts compiles ClientApi with the Promise client's options and emits types and one method per endpoint (166) into crates/api/src/generated. The request core, errors, query encoding, and the reqwest transport are written by hand. Tagged unions decode through a generated Deserialize that keeps unknown members and routes rpc.* events.
This commit is contained in:
parent
6954ec9bf2
commit
cc409d1fcf
15 changed files with 18912 additions and 5 deletions
14
packages/cli-rs/Cargo.lock
generated
14
packages/cli-rs/Cargo.lock
generated
|
|
@ -862,13 +862,16 @@ dependencies = [
|
|||
name = "opencode-api"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
"futures-util",
|
||||
"log",
|
||||
"percent-encoding",
|
||||
"rand",
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_path_to_error",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tokio-tungstenite",
|
||||
|
|
@ -1428,6 +1431,17 @@ dependencies = [
|
|||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_path_to_error"
|
||||
version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.11.0"
|
||||
|
|
|
|||
|
|
@ -51,6 +51,7 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls", "j
|
|||
rustix = { version = "1", features = ["fs", "process"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = { version = "1", features = ["preserve_order"] }
|
||||
serde_path_to_error = "0.1"
|
||||
sha1 = "0.11"
|
||||
similar = "3"
|
||||
tempfile = "3"
|
||||
|
|
|
|||
|
|
@ -10,12 +10,16 @@ publish.workspace = true
|
|||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
bytes.workspace = true
|
||||
futures-util.workspace = true
|
||||
log.workspace = true
|
||||
percent-encoding.workspace = true
|
||||
rand.workspace = true
|
||||
reqwest.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_path_to_error.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio.workspace = true
|
||||
tokio-tungstenite.workspace = true
|
||||
|
|
@ -23,5 +27,4 @@ tokio-util.workspace = true
|
|||
url.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
reqwest.workspace = true
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
|
|
|||
|
|
@ -1 +1,423 @@
|
|||
//! Request core: base URL, authentication, per-call headers, and declared errors (F.2).
|
||||
//! Request core: base URL, authentication, per-call headers, and declared errors. It follows the
|
||||
//! `make` function of the TypeScript Promise client (`packages/client/src/promise/generated/client.ts:354-473`).
|
||||
//! The generated methods (`generated/methods.rs`) build a [`Call`] and send it here.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use base64::Engine;
|
||||
use bytes::Bytes;
|
||||
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::error::{DeclaredError, Error};
|
||||
use crate::query;
|
||||
use crate::transport::{Request, Reqwest, Response, SseResponse, Transport};
|
||||
|
||||
/// The query parameter the server reads credentials from when a request cannot carry headers.
|
||||
pub const AUTH_TOKEN_QUERY: &str = "auth_token";
|
||||
|
||||
/// How the client authenticates. The server accepts `Basic` credentials in the `authorization` header or,
|
||||
/// base64-encoded the same way, in the `auth_token` query parameter
|
||||
/// (`packages/server/src/middleware/authorization.ts:33-40`).
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub enum Auth {
|
||||
/// `authorization: Basic base64(username:password)`.
|
||||
Basic { username: String, password: String },
|
||||
/// `?auth_token=base64(username:password)`.
|
||||
Query { username: String, password: String },
|
||||
}
|
||||
|
||||
impl Auth {
|
||||
/// Basic credentials with the user name the CLI uses for its local service.
|
||||
pub fn password(password: impl Into<String>) -> Self {
|
||||
Self::Basic {
|
||||
username: "opencode".to_owned(),
|
||||
password: password.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `base64(username:password)`, the value of the header after `Basic ` and of `auth_token`.
|
||||
pub fn token(&self) -> String {
|
||||
let (Self::Basic { username, password } | Self::Query { username, password }) = self;
|
||||
base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Auth {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let (kind, username) = match self {
|
||||
Self::Basic { username, .. } => ("Basic", username),
|
||||
Self::Query { username, .. } => ("Query", username),
|
||||
};
|
||||
write!(
|
||||
f,
|
||||
"Auth::{kind} {{ username: {username:?}, password: <redacted> }}"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-call options. Headers here replace client and input headers of the same name.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct RequestOptions {
|
||||
pub headers: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl RequestOptions {
|
||||
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
self.headers.push((name.into(), value.into()));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The API client. Cheap to clone.
|
||||
#[derive(Clone)]
|
||||
pub struct Client {
|
||||
base_url: url::Url,
|
||||
auth: Option<Auth>,
|
||||
headers: Vec<(String, String)>,
|
||||
transport: Arc<dyn Transport>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Client {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Client")
|
||||
.field("base_url", &self.base_url.as_str())
|
||||
.field("auth", &self.auth)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Client {
|
||||
/// A client on the `reqwest` transport.
|
||||
pub fn new(base_url: &str) -> Result<Self, Error> {
|
||||
Self::with_transport(base_url, Arc::new(Reqwest::default()))
|
||||
}
|
||||
|
||||
pub fn with_transport(base_url: &str, transport: Arc<dyn Transport>) -> Result<Self, Error> {
|
||||
let mut base_url = url::Url::parse(base_url)
|
||||
.map_err(|error| Error::Transport(format!("{base_url}: {error}")))?;
|
||||
// A leading slash would replace any path prefix on the base URL, so paths join relative to it.
|
||||
if !base_url.path().ends_with('/') {
|
||||
let path = format!("{}/", base_url.path());
|
||||
base_url.set_path(&path);
|
||||
}
|
||||
Ok(Self {
|
||||
base_url,
|
||||
auth: None,
|
||||
headers: Vec::new(),
|
||||
transport,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn auth(mut self, auth: Auth) -> Self {
|
||||
self.auth = Some(auth);
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a header to every request.
|
||||
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
set_header(&mut self.headers, name.into(), value.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn base_url(&self) -> &url::Url {
|
||||
&self.base_url
|
||||
}
|
||||
|
||||
pub fn credentials(&self) -> Option<&Auth> {
|
||||
self.auth.as_ref()
|
||||
}
|
||||
|
||||
pub fn transport(&self) -> &Arc<dyn Transport> {
|
||||
&self.transport
|
||||
}
|
||||
|
||||
/// The URL of `path` (which starts with `/`) on this server, with `query` and no credentials.
|
||||
pub fn url(&self, path: &str, query: &[(String, String)]) -> Result<url::Url, Error> {
|
||||
let mut url = self
|
||||
.base_url
|
||||
.join(path.trim_start_matches('/'))
|
||||
.map_err(|error| Error::Transport(format!("{path}: {error}")))?;
|
||||
if !query.is_empty() {
|
||||
url.set_query(Some(&query::encode(query)));
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
/// Builds the request for `call`, as `prepare` does in TypeScript.
|
||||
pub fn prepare(&self, call: Call, options: &RequestOptions) -> Result<Request, Error> {
|
||||
let mut query = call.query;
|
||||
if let Some(auth @ Auth::Query { .. }) = &self.auth {
|
||||
query.push((AUTH_TOKEN_QUERY.to_owned(), auth.token()));
|
||||
}
|
||||
let url = self.url(&call.path, &query)?;
|
||||
let mut headers = Vec::new();
|
||||
if let Some(auth @ Auth::Basic { .. }) = &self.auth {
|
||||
headers.push((
|
||||
"authorization".to_owned(),
|
||||
format!("Basic {}", auth.token()),
|
||||
));
|
||||
}
|
||||
for (name, value) in self
|
||||
.headers
|
||||
.iter()
|
||||
.chain(&call.headers)
|
||||
.chain(&options.headers)
|
||||
{
|
||||
set_header(&mut headers, name.clone(), value.clone());
|
||||
}
|
||||
let body = match call.body {
|
||||
None => None,
|
||||
Some(Body::Bytes(bytes)) => {
|
||||
default_header(&mut headers, "content-type", "application/octet-stream");
|
||||
Some(bytes)
|
||||
}
|
||||
Some(Body::Json(value)) => {
|
||||
default_header(&mut headers, "content-type", "application/json");
|
||||
Some(Bytes::from(
|
||||
serde_json::to_vec(&value).map_err(encode_error)?,
|
||||
))
|
||||
}
|
||||
};
|
||||
Ok(Request {
|
||||
method: call.method,
|
||||
url,
|
||||
headers,
|
||||
body,
|
||||
})
|
||||
}
|
||||
|
||||
async fn execute(&self, call: Call, options: &RequestOptions) -> Result<Response, Error> {
|
||||
let success = call.success_status;
|
||||
let declared = call.declared_statuses;
|
||||
let request = self.prepare(call, options)?;
|
||||
let response = self
|
||||
.transport
|
||||
.send(request)
|
||||
.await
|
||||
.map_err(Error::Transport)?;
|
||||
if response.status != success {
|
||||
return Err(response_error(response, declared).await);
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub(crate) async fn json<T: DeserializeOwned>(
|
||||
&self,
|
||||
call: Call,
|
||||
options: &RequestOptions,
|
||||
) -> Result<T, Error> {
|
||||
let bytes = json_body(self.execute(call, options).await?).await?;
|
||||
let mut deserializer = serde_json::Deserializer::from_slice(&bytes);
|
||||
// The JSON path of the first failure goes in the message, so a schema mismatch names its field.
|
||||
serde_path_to_error::deserialize(&mut deserializer)
|
||||
.map_err(|error| Error::MalformedResponse(error.to_string()))
|
||||
}
|
||||
|
||||
pub(crate) async fn data<T: DeserializeOwned>(
|
||||
&self,
|
||||
call: Call,
|
||||
options: &RequestOptions,
|
||||
) -> Result<T, Error> {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Data<T> {
|
||||
data: T,
|
||||
}
|
||||
self.json::<Data<T>>(call, options)
|
||||
.await
|
||||
.map(|value| value.data)
|
||||
}
|
||||
|
||||
pub(crate) async fn empty(&self, call: Call, options: &RequestOptions) -> Result<(), Error> {
|
||||
self.execute(call, options).await.map(|_| ())
|
||||
}
|
||||
|
||||
pub(crate) async fn binary(
|
||||
&self,
|
||||
call: Call,
|
||||
options: &RequestOptions,
|
||||
) -> Result<Bytes, Error> {
|
||||
let response = self.execute(call, options).await?;
|
||||
response.bytes().await.map_err(Error::Transport)
|
||||
}
|
||||
|
||||
pub(crate) async fn sse<T>(
|
||||
&self,
|
||||
call: Call,
|
||||
options: &RequestOptions,
|
||||
) -> Result<SseResponse<T>, Error> {
|
||||
let response = self.execute(call, options).await?;
|
||||
if !is_content_type(&response, "text/event-stream") {
|
||||
return Err(Error::UnsupportedContentType(
|
||||
response.header("content-type").map(str::to_owned),
|
||||
));
|
||||
}
|
||||
Ok(SseResponse::new(response))
|
||||
}
|
||||
}
|
||||
|
||||
/// One request a generated method describes.
|
||||
#[derive(Debug)]
|
||||
pub struct Call {
|
||||
pub method: &'static str,
|
||||
pub path: String,
|
||||
pub query: Vec<(String, String)>,
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: Option<Body>,
|
||||
pub success_status: u16,
|
||||
pub declared_statuses: &'static [u16],
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Body {
|
||||
Json(Value),
|
||||
Bytes(Bytes),
|
||||
}
|
||||
|
||||
impl Call {
|
||||
pub fn new(
|
||||
method: &'static str,
|
||||
path: String,
|
||||
success_status: u16,
|
||||
declared_statuses: &'static [u16],
|
||||
) -> Self {
|
||||
Self {
|
||||
method,
|
||||
path,
|
||||
query: Vec::new(),
|
||||
headers: Vec::new(),
|
||||
body: None,
|
||||
success_status,
|
||||
declared_statuses,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a query value, bracket-encoded like `appendQuery`.
|
||||
pub fn query<T: Serialize + ?Sized>(&mut self, key: &str, value: &T) -> Result<(), Error> {
|
||||
query::append(
|
||||
&mut self.query,
|
||||
key,
|
||||
&serde_json::to_value(value).map_err(encode_error)?,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sets a header from an input field; `null` is skipped.
|
||||
pub fn header<T: Serialize + ?Sized>(&mut self, name: &str, value: &T) -> Result<(), Error> {
|
||||
let value = serde_json::to_value(value).map_err(encode_error)?;
|
||||
if !value.is_null() {
|
||||
set_header(&mut self.headers, name.to_owned(), query::js_string(&value));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Starts a JSON object body; [`Call::field`] fills it.
|
||||
pub fn object(&mut self) {
|
||||
self.body = Some(Body::Json(Value::Object(serde_json::Map::new())));
|
||||
}
|
||||
|
||||
pub fn field<T: Serialize + ?Sized>(&mut self, key: &str, value: &T) -> Result<(), Error> {
|
||||
let value = serde_json::to_value(value).map_err(encode_error)?;
|
||||
if let Some(Body::Json(Value::Object(map))) = &mut self.body {
|
||||
map.insert(key.to_owned(), value);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sets the whole JSON body, for payloads that are not flattened into fields.
|
||||
pub fn json<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
|
||||
self.body = Some(Body::Json(
|
||||
serde_json::to_value(value).map_err(encode_error)?,
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn bytes(&mut self, value: Bytes) {
|
||||
self.body = Some(Body::Bytes(value));
|
||||
}
|
||||
}
|
||||
|
||||
/// A path parameter: `String(value)` encoded like `encodeURIComponent`.
|
||||
pub fn path_param<T: Serialize + ?Sized>(value: &T) -> Result<String, Error> {
|
||||
let value = serde_json::to_value(value).map_err(encode_error)?;
|
||||
Ok(utf8_percent_encode(&query::js_string(&value), COMPONENT).to_string())
|
||||
}
|
||||
|
||||
/// A trailing wildcard path, each segment encoded like `encodeURIComponent`.
|
||||
pub fn path_wildcard(value: &str) -> String {
|
||||
value
|
||||
.split('/')
|
||||
.map(|segment| utf8_percent_encode(segment, COMPONENT).to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("/")
|
||||
}
|
||||
|
||||
/// The characters `encodeURIComponent` escapes: everything except `A-Z a-z 0-9 - _ . ! ~ * ' ( )`.
|
||||
const COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
|
||||
.remove(b'-')
|
||||
.remove(b'_')
|
||||
.remove(b'.')
|
||||
.remove(b'!')
|
||||
.remove(b'~')
|
||||
.remove(b'*')
|
||||
.remove(b'\'')
|
||||
.remove(b'(')
|
||||
.remove(b')');
|
||||
|
||||
fn set_header(headers: &mut Vec<(String, String)>, name: String, value: String) {
|
||||
let name = name.to_ascii_lowercase();
|
||||
headers.retain(|(key, _)| *key != name);
|
||||
headers.push((name, value));
|
||||
}
|
||||
|
||||
fn default_header(headers: &mut Vec<(String, String)>, name: &str, value: &str) {
|
||||
if !headers.iter().any(|(key, _)| key == name) {
|
||||
headers.push((name.to_owned(), value.to_owned()));
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_error(error: serde_json::Error) -> Error {
|
||||
Error::Transport(format!("encode request: {error}"))
|
||||
}
|
||||
|
||||
async fn response_error(response: Response, declared: &[u16]) -> Error {
|
||||
let status = response.status;
|
||||
if !declared.contains(&status) {
|
||||
return Error::UnexpectedStatus { status };
|
||||
}
|
||||
let body = match json_body(response).await {
|
||||
Ok(body) => body,
|
||||
Err(error) => return error,
|
||||
};
|
||||
match serde_json::from_slice(&body) {
|
||||
Ok(body) => Error::Declared(Box::new(DeclaredError::new(status, body))),
|
||||
Err(error) => Error::MalformedResponse(error.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of a JSON response: checks the content type and rejects an empty body, as `json` does in
|
||||
/// TypeScript.
|
||||
async fn json_body(response: Response) -> Result<Bytes, Error> {
|
||||
let content_type = response.header("content-type").map(str::to_owned);
|
||||
if !is_content_type(&response, "application/json")
|
||||
&& !content_type
|
||||
.as_deref()
|
||||
.is_some_and(|value| value.contains("+json"))
|
||||
{
|
||||
return Err(Error::UnsupportedContentType(content_type));
|
||||
}
|
||||
let bytes = response.bytes().await.map_err(Error::Transport)?;
|
||||
if bytes.is_empty() {
|
||||
return Err(Error::MalformedResponse("empty body".to_owned()));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn is_content_type(response: &Response, expected: &str) -> bool {
|
||||
response
|
||||
.header("content-type")
|
||||
.and_then(|value| value.split(';').next())
|
||||
.is_some_and(|value| value.trim().eq_ignore_ascii_case(expected))
|
||||
}
|
||||
|
|
|
|||
17
packages/cli-rs/crates/api/src/de.rs
Normal file
17
packages/cli-rs/crates/api/src/de.rs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
//! Serde helpers the generated types use.
|
||||
|
||||
use serde::de::{DeserializeOwned, Error};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
/// For an optional and nullable field: absent is `None` (through `#[serde(default)]`), `null` is
|
||||
/// `Some(None)`, and a value is `Some(Some(value))`.
|
||||
pub fn double_option<'de, T: Deserialize<'de>, D: Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<Option<Option<T>>, D::Error> {
|
||||
Option::<T>::deserialize(deserializer).map(Some)
|
||||
}
|
||||
|
||||
/// Decodes the member of a tagged union once its tag is known.
|
||||
pub fn variant<T: DeserializeOwned, E: Error>(value: serde_json::Value) -> Result<T, E> {
|
||||
serde_json::from_value(value).map_err(E::custom)
|
||||
}
|
||||
|
|
@ -1 +1,88 @@
|
|||
//! Client errors, mirroring the reasons of the TypeScript `ClientError` (F.2).
|
||||
//! Client errors, mirroring the reasons of the TypeScript `ClientError`
|
||||
//! (`packages/client/src/promise/generated/client-error.ts`), plus declared error bodies.
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// The request could not be sent or the response could not be read.
|
||||
#[error("Transport: {0}")]
|
||||
Transport(String),
|
||||
/// A status that is neither the success status nor a declared error status.
|
||||
#[error("UnexpectedStatus: {status}")]
|
||||
UnexpectedStatus { status: u16 },
|
||||
/// The response has the wrong content type.
|
||||
#[error("UnsupportedContentType: {}", .0.as_deref().unwrap_or("none"))]
|
||||
UnsupportedContentType(Option<String>),
|
||||
/// The response body is empty or not valid for its type.
|
||||
#[error("MalformedResponse: {0}")]
|
||||
MalformedResponse(String),
|
||||
/// One server-sent event exceeds the size limit.
|
||||
#[error("SseEventTooLarge")]
|
||||
SseEventTooLarge,
|
||||
/// A declared error the server returned, such as `SessionNotFoundError`.
|
||||
#[error("{0}")]
|
||||
Declared(Box<DeclaredError>),
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// The `ClientError` reason, or the declared error's tag.
|
||||
pub fn reason(&self) -> &str {
|
||||
match self {
|
||||
Self::Transport(_) => "Transport",
|
||||
Self::UnexpectedStatus { .. } => "UnexpectedStatus",
|
||||
Self::UnsupportedContentType(_) => "UnsupportedContentType",
|
||||
Self::MalformedResponse(_) => "MalformedResponse",
|
||||
Self::SseEventTooLarge => "SseEventTooLarge",
|
||||
Self::Declared(error) => error.tag.as_deref().unwrap_or("DeclaredError"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The declared error, if the server returned one.
|
||||
pub fn declared(&self) -> Option<&DeclaredError> {
|
||||
match self {
|
||||
Self::Declared(error) => Some(error),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A declared error body. The tag is `_tag`, else `name`; the message is `message`, else `data.message`,
|
||||
/// as `declared` in the TypeScript client.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DeclaredError {
|
||||
pub status: u16,
|
||||
pub tag: Option<String>,
|
||||
pub message: Option<String>,
|
||||
pub body: Value,
|
||||
}
|
||||
|
||||
impl DeclaredError {
|
||||
pub fn new(status: u16, body: Value) -> Self {
|
||||
let text = |value: Option<&Value>| value.and_then(Value::as_str).map(str::to_owned);
|
||||
Self {
|
||||
status,
|
||||
tag: text(body.get("_tag")).or_else(|| text(body.get("name"))),
|
||||
message: text(body.get("message"))
|
||||
.or_else(|| text(body.get("data").and_then(|data| data.get("message")))),
|
||||
body,
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes the body into a generated error type, such as `SessionNotFoundError`.
|
||||
pub fn decode<T: DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
|
||||
serde_json::from_value(self.body.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for DeclaredError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match (&self.tag, &self.message) {
|
||||
(Some(tag), Some(message)) => write!(f, "{tag}: {message}"),
|
||||
(Some(tag), None) => f.write_str(tag),
|
||||
(None, Some(message)) => f.write_str(message),
|
||||
(None, None) => write!(f, "declared error {}", self.status),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
3398
packages/cli-rs/crates/api/src/generated/methods.rs
Normal file
3398
packages/cli-rs/crates/api/src/generated/methods.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1 +1,10 @@
|
|||
// Generated by script/gen/api.ts from ClientApi. Do not edit.
|
||||
//! Types and methods generated from `ClientApi` by `script/gen/api.ts` (F.2).
|
||||
|
||||
mod methods;
|
||||
pub mod types;
|
||||
|
||||
pub use types::*;
|
||||
|
||||
/// Endpoints in the generated client.
|
||||
pub const ENDPOINTS: usize = 166;
|
||||
|
|
|
|||
14016
packages/cli-rs/crates/api/src/generated/types.rs
Normal file
14016
packages/cli-rs/crates/api/src/generated/types.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
pub mod client;
|
||||
pub mod client_mcp;
|
||||
pub mod de;
|
||||
pub mod error;
|
||||
pub mod events;
|
||||
pub mod generated;
|
||||
|
|
|
|||
|
|
@ -1 +1,106 @@
|
|||
//! Query string encoding, bracket-encoded like `appendQuery` (F.2).
|
||||
//! Query string encoding, bracket-encoded like `appendQuery`
|
||||
//! (`packages/client/src/promise/generated/client.ts:2795-2810`).
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// Appends `value` under `key`: `null` as `"null"`, arrays as repeated keys, objects as `key[child]`,
|
||||
/// and scalars as JavaScript's `String(value)` would write them.
|
||||
pub fn append(pairs: &mut Vec<(String, String)>, key: &str, value: &Value) {
|
||||
match value {
|
||||
Value::Array(items) => items.iter().for_each(|item| append(pairs, key, item)),
|
||||
Value::Object(map) => map
|
||||
.iter()
|
||||
.for_each(|(child, item)| append(pairs, &format!("{key}[{child}]"), item)),
|
||||
_ => pairs.push((key.to_owned(), js_string(value))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `String(value)` for a JSON value. Objects and arrays never reach here from [`append`].
|
||||
pub fn js_string(value: &Value) -> String {
|
||||
match value {
|
||||
Value::Null => "null".to_owned(),
|
||||
Value::Bool(value) => value.to_string(),
|
||||
Value::String(value) => value.clone(),
|
||||
Value::Number(number) => match (number.as_i64(), number.as_u64(), number.as_f64()) {
|
||||
(Some(value), _, _) => value.to_string(),
|
||||
(_, Some(value), _) => value.to_string(),
|
||||
(_, _, Some(value)) => js_number(value),
|
||||
_ => number.to_string(),
|
||||
},
|
||||
Value::Array(items) => items.iter().map(js_string).collect::<Vec<_>>().join(","),
|
||||
Value::Object(_) => "[object Object]".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// JavaScript's `Number.prototype.toString()`: shortest round-trip digits, with exponent notation
|
||||
/// outside `[1e-6, 1e21)`.
|
||||
fn js_number(value: f64) -> String {
|
||||
if value == 0.0 {
|
||||
return "0".to_owned();
|
||||
}
|
||||
let magnitude = value.abs();
|
||||
if (1e-6..1e21).contains(&magnitude) {
|
||||
return format!("{value}");
|
||||
}
|
||||
// Rust writes `1e21` and `1e-7`; JavaScript writes `1e+21` and `1e-7`.
|
||||
let text = format!("{value:e}");
|
||||
match text.split_once('e') {
|
||||
Some((mantissa, exponent)) if !exponent.starts_with('-') => {
|
||||
format!("{mantissa}e+{exponent}")
|
||||
}
|
||||
_ => text,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `application/x-www-form-urlencoded` form of `pairs`, as `URLSearchParams` serializes it.
|
||||
pub fn encode(pairs: &[(String, String)]) -> String {
|
||||
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
|
||||
for (key, value) in pairs {
|
||||
serializer.append_pair(key, value);
|
||||
}
|
||||
serializer.finish()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn query(key: &str, value: Value) -> String {
|
||||
let mut pairs = Vec::new();
|
||||
append(&mut pairs, key, &value);
|
||||
encode(&pairs)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_objects_use_brackets() {
|
||||
assert_eq!(
|
||||
query(
|
||||
"location",
|
||||
json!({ "directory": "/a b", "workspace": { "id": "w" } })
|
||||
),
|
||||
"location%5Bdirectory%5D=%2Fa+b&location%5Bworkspace%5D%5Bid%5D=w"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrays_repeat_and_null_is_written() {
|
||||
assert_eq!(query("types", json!(["a", "b"])), "types=a&types=b");
|
||||
assert_eq!(query("cursor", Value::Null), "cursor=null");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_match_javascript() {
|
||||
let cases = [
|
||||
(1.0, "1"),
|
||||
(1.5, "1.5"),
|
||||
(1e21, "1e+21"),
|
||||
(1e-7, "1e-7"),
|
||||
(0.000001, "0.000001"),
|
||||
(-0.0, "0"),
|
||||
];
|
||||
for (value, text) in cases {
|
||||
assert_eq!(js_string(&json!(value)), text, "{value}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1 +1,132 @@
|
|||
//! The transport trait and its `reqwest` implementation (F.2).
|
||||
//! The transport trait and its `reqwest` implementation.
|
||||
|
||||
use std::future::Future;
|
||||
use std::marker::PhantomData;
|
||||
use std::pin::Pin;
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures_util::{Stream, StreamExt};
|
||||
|
||||
/// A future a transport returns.
|
||||
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
|
||||
/// A response body as a stream of chunks.
|
||||
pub type BodyStream = Pin<Box<dyn Stream<Item = Result<Bytes, String>> + Send>>;
|
||||
|
||||
/// One HTTP request, fully prepared by the client.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Request {
|
||||
pub method: &'static str,
|
||||
pub url: url::Url,
|
||||
/// Header names are lowercase; each name appears once.
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: Option<Bytes>,
|
||||
}
|
||||
|
||||
/// One HTTP response. The body is read lazily, so server-sent events can stream.
|
||||
pub struct Response {
|
||||
pub status: u16,
|
||||
/// Header names are lowercase.
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: BodyStream,
|
||||
}
|
||||
|
||||
impl Response {
|
||||
pub fn header(&self, name: &str) -> Option<&str> {
|
||||
self.headers
|
||||
.iter()
|
||||
.find(|(key, _)| key.eq_ignore_ascii_case(name))
|
||||
.map(|(_, value)| value.as_str())
|
||||
}
|
||||
|
||||
/// Reads the whole body.
|
||||
pub async fn bytes(mut self) -> Result<Bytes, String> {
|
||||
let mut buffer = Vec::new();
|
||||
while let Some(chunk) = self.body.next().await {
|
||||
buffer.extend_from_slice(&chunk?);
|
||||
}
|
||||
Ok(Bytes::from(buffer))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Response {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Response")
|
||||
.field("status", &self.status)
|
||||
.field("headers", &self.headers)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends requests. The `reqwest` implementation talks to a server; tests and P-APP use in-memory ones.
|
||||
pub trait Transport: Send + Sync {
|
||||
/// Sends `request`. An error is a transport failure (no response), described as text.
|
||||
fn send(&self, request: Request) -> BoxFuture<'_, Result<Response, String>>;
|
||||
}
|
||||
|
||||
/// The checked response of a server-sent events endpoint: status and content type are verified, and
|
||||
/// the body has not been read. F.3 parses it into events of type `T`.
|
||||
pub struct SseResponse<T> {
|
||||
pub response: Response,
|
||||
event: PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<T> SseResponse<T> {
|
||||
pub fn new(response: Response) -> Self {
|
||||
Self {
|
||||
response,
|
||||
event: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::fmt::Debug for SseResponse<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("SseResponse").field(&self.response).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// The `reqwest` transport, with rustls.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Reqwest {
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
||||
impl Reqwest {
|
||||
pub fn new(client: reqwest::Client) -> Self {
|
||||
Self { client }
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for Reqwest {
|
||||
fn send(&self, request: Request) -> BoxFuture<'_, Result<Response, String>> {
|
||||
Box::pin(async move {
|
||||
let method = reqwest::Method::from_bytes(request.method.as_bytes())
|
||||
.map_err(|error| error.to_string())?;
|
||||
let mut builder = self.client.request(method, request.url);
|
||||
for (name, value) in &request.headers {
|
||||
builder = builder.header(name, value);
|
||||
}
|
||||
if let Some(body) = request.body {
|
||||
builder = builder.body(body);
|
||||
}
|
||||
let response = builder.send().await.map_err(|error| error.to_string())?;
|
||||
let headers = response
|
||||
.headers()
|
||||
.iter()
|
||||
.filter_map(|(name, value)| {
|
||||
Some((name.as_str().to_owned(), value.to_str().ok()?.to_owned()))
|
||||
})
|
||||
.collect();
|
||||
Ok(Response {
|
||||
status: response.status().as_u16(),
|
||||
headers,
|
||||
body: Box::pin(
|
||||
response
|
||||
.bytes_stream()
|
||||
.map(|chunk| chunk.map_err(|error| error.to_string())),
|
||||
),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
177
packages/cli-rs/script/gen/api.ts
Normal file
177
packages/cli-rs/script/gen/api.ts
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
// Generates crates/api/src/generated from ClientApi, with the options of the Promise client
|
||||
// (packages/client/script/generate.ts). The type mapping is in docs/F.2.md.
|
||||
import { compile, type Endpoint } from "@opencode/httpapi-codegen"
|
||||
import { ClientApi, clientNamespace, groupNames, promiseOmitEndpoints } from "@opencode/protocol/client"
|
||||
import { Schema, SchemaAST, SchemaRepresentation } from "effect"
|
||||
import { HttpApiSchema } from "effect/http-api"
|
||||
import { emitMethod, type Field, type Method } from "../rust/methods.ts"
|
||||
import { pascal, Types } from "../rust/types.ts"
|
||||
|
||||
const root = new URL("..", import.meta.url).pathname.replace(/script\/$/, "")
|
||||
const directory = `${root}crates/api/src/generated`
|
||||
const resolveEncoding = SchemaAST.resolveAt<{ readonly _tag: string }>("~httpApiEncoding")
|
||||
const resolveStatus = SchemaAST.resolveAt<number>("httpApiStatus")
|
||||
|
||||
const contract = compile(ClientApi, { groupNames, omitEndpoints: promiseOmitEndpoints, namespace: clientNamespace })
|
||||
|
||||
type Root = { readonly ast: SchemaAST.AST }
|
||||
const roots: Array<Root> = []
|
||||
const add = (ast: SchemaAST.AST) => {
|
||||
const item = { ast }
|
||||
roots.push(item)
|
||||
return item
|
||||
}
|
||||
|
||||
const plans = contract.groups.flatMap((group) =>
|
||||
group.endpoints.map((endpoint) => {
|
||||
const opaque = endpoint.payloads[0] !== undefined && !flattenable(endpoint.payloads[0])
|
||||
const binaryBody = endpoint.payloads[0] !== undefined && resolveEncoding(endpoint.payloads[0].ast)?._tag === "Uint8Array"
|
||||
const sources = { params: endpoint.params, query: endpoint.query, headers: endpoint.headers, payload: endpoint.payloads[0] }
|
||||
const fields = endpoint.input.map((field) => {
|
||||
const schema = sources[field.source]!
|
||||
if (opaque && field.source === "payload") return { ...field, root: binaryBody ? undefined : add(Schema.toEncoded(schema).ast) }
|
||||
const ast = (field.source === "query" ? Schema.toType(schema) : Schema.toEncoded(schema)).ast
|
||||
if (!SchemaAST.isObjects(ast)) throw new Error(`Input schema must be a struct: ${endpoint.operation.name}`)
|
||||
const property = ast.propertySignatures.find((item) => item.name === field.name)!
|
||||
return { ...field, root: add(property.type) }
|
||||
})
|
||||
const wildcard = endpoint.endpoint.path.endsWith("*")
|
||||
? [{ name: endpoint.input.some((field) => field.name === "path") ? "wildcard" : "path", source: "wildcard" as const, optional: false, root: undefined }]
|
||||
: []
|
||||
const success = endpoint.successes[0]
|
||||
const kind = streamKind(success)
|
||||
const output = (() => {
|
||||
if (kind === "sse") return add(sseData(success))
|
||||
if (HttpApiSchema.isNoContent(success.ast) || resolveEncoding(success.ast)?._tag === "Uint8Array") return undefined
|
||||
const ast = Schema.toEncoded(success).ast
|
||||
if (!endpoint.unwrapData) return add(ast)
|
||||
if (!SchemaAST.isObjects(ast)) throw new Error(`Invalid data envelope: ${endpoint.operation.name}`)
|
||||
return add(ast.propertySignatures.find((item) => item.name === "data")!.type)
|
||||
})()
|
||||
for (const error of endpoint.errors) add(Schema.toEncoded(error.schema).ast)
|
||||
const successKind: Method["success"] =
|
||||
kind === "sse"
|
||||
? "sse"
|
||||
: HttpApiSchema.isNoContent(success.ast)
|
||||
? "empty"
|
||||
: resolveEncoding(success.ast)?._tag === "Uint8Array"
|
||||
? "binary"
|
||||
: endpoint.unwrapData
|
||||
? "data"
|
||||
: "json"
|
||||
return { group, endpoint, opaque, binaryBody, fields: [...fields, ...wildcard], output, success: successKind }
|
||||
}),
|
||||
)
|
||||
|
||||
const document = SchemaRepresentation.toRepresentations(
|
||||
normalize(roots.map((item) => item.ast)) as [SchemaAST.AST, ...Array<SchemaAST.AST>],
|
||||
)
|
||||
const representation = new Map(roots.map((item, index) => [item, document.representations[index]]))
|
||||
const types = new Types(document.references)
|
||||
for (const name of ["Client", "Call", "Error", "RequestOptions", "SseResponse"]) types.name(name)
|
||||
|
||||
const methods = plans.map((plan) =>
|
||||
emitMethod(types, {
|
||||
group: plan.group,
|
||||
endpoint: plan.endpoint,
|
||||
prefix: `${pascal(plan.group.identifier)}${plan.endpoint.clientPath.map(pascal).join("")}`,
|
||||
opaque: plan.opaque,
|
||||
binaryBody: plan.binaryBody,
|
||||
fields: plan.fields.map(
|
||||
(field): Field => ({
|
||||
name: field.name,
|
||||
source: field.source,
|
||||
optional: field.optional,
|
||||
representation: field.root === undefined ? undefined : representation.get(field.root),
|
||||
}),
|
||||
),
|
||||
success: plan.success,
|
||||
output: plan.output === undefined ? undefined : representation.get(plan.output),
|
||||
successStatus: resolveStatus(plan.endpoint.successes[0].ast) ?? 200,
|
||||
}),
|
||||
)
|
||||
// Declared error bodies get types too, for `DeclaredError::decode`.
|
||||
for (const ref of Object.keys(document.references)) {
|
||||
if (/Error$/.test(ref)) types.type({ _tag: "Reference", $ref: ref }, ref)
|
||||
}
|
||||
|
||||
const header = "// Generated by script/gen/api.ts from ClientApi. Do not edit.\n"
|
||||
await Bun.write(
|
||||
`${directory}/types.rs`,
|
||||
`${header}#![allow(clippy::all, clippy::pedantic, non_camel_case_types)]\n\nuse std::collections::BTreeMap;\n\nuse serde::{Deserialize, Serialize};\n\n${types.items.join("\n\n")}\n`,
|
||||
)
|
||||
await Bun.write(
|
||||
`${directory}/methods.rs`,
|
||||
`${header}#![allow(clippy::all, clippy::pedantic)]\n\nuse super::types::*;\nuse crate::client::{Call, Client, RequestOptions};\nuse crate::error::Error;\nuse crate::transport::SseResponse;\n\nimpl Client {\n${methods.join("\n\n")}\n}\n`,
|
||||
)
|
||||
await Bun.write(
|
||||
`${directory}/mod.rs`,
|
||||
`${header}//! Types and methods generated from \`ClientApi\` by \`script/gen/api.ts\` (F.2).\n\nmod methods;\npub mod types;\n\npub use types::*;\n\n/// Endpoints in the generated client.\npub const ENDPOINTS: usize = ${plans.length};\n`,
|
||||
)
|
||||
const format = Bun.spawnSync(["rustfmt", "--edition", "2024", `${directory}/mod.rs`], { stdout: "inherit", stderr: "inherit" })
|
||||
if (format.exitCode !== 0) process.exit(format.exitCode ?? 1)
|
||||
console.log(`api: ${plans.length} endpoints, ${types.items.length} items`)
|
||||
|
||||
function flattenable(schema: Schema.Top) {
|
||||
const ast = Schema.toType(schema).ast
|
||||
return SchemaAST.isObjects(ast) && ast.indexSignatures.length === 0
|
||||
}
|
||||
|
||||
function streamKind(schema: Schema.Top) {
|
||||
if (!("_tag" in schema)) return undefined
|
||||
if (schema._tag === "StreamSse") return "sse"
|
||||
if (schema._tag === "StreamUint8Array") throw new Error("Byte streams are not supported")
|
||||
return undefined
|
||||
}
|
||||
|
||||
// The encoded data schema of an SSE endpoint, as `streamEncodedDataSchema` in httpapi-codegen.
|
||||
function sseData(schema: Endpoint["successes"][number]) {
|
||||
const events = (schema as unknown as { readonly events: Schema.Top }).events.ast
|
||||
if (!SchemaAST.isObjects(events)) throw new Error("Invalid SSE data schema")
|
||||
const data = events.propertySignatures.find((field) => field.name === "data")!.type
|
||||
// oxlint-disable-next-line no-restricted-globals -- Effect exposes this runtime helper without a public type.
|
||||
const replaceEncoding = Reflect.get(SchemaAST, "replaceEncoding") as (ast: SchemaAST.AST, encoding: undefined) => SchemaAST.AST
|
||||
return Schema.toEncoded(Schema.make<Schema.Top>(replaceEncoding(data, undefined))).ast
|
||||
}
|
||||
|
||||
// Declarations become their fields or JSON, as `codegenAsts` in httpapi-codegen, and equal named
|
||||
// schemas share one reference.
|
||||
function normalize(input: ReadonlyArray<SchemaAST.AST>) {
|
||||
const cache = new WeakMap<SchemaAST.AST, SchemaAST.AST>()
|
||||
const references = new Map<string, SchemaAST.AST>()
|
||||
const recur = (ast: SchemaAST.AST): SchemaAST.AST => {
|
||||
const cached = cache.get(ast)
|
||||
if (cached !== undefined) return cached
|
||||
const identifier = SchemaAST.resolveIdentifier(ast)
|
||||
const output = step(ast)
|
||||
const key =
|
||||
identifier === undefined
|
||||
? undefined
|
||||
: `${identifier}\0${ast.context?.isOptional === true}\0${JSON.stringify(SchemaRepresentation.toJson(SchemaRepresentation.toRepresentation(output)))}`
|
||||
const reference = key === undefined ? undefined : references.get(key)
|
||||
if (reference !== undefined) {
|
||||
cache.set(ast, reference)
|
||||
return reference
|
||||
}
|
||||
cache.set(ast, output)
|
||||
if (key !== undefined) references.set(key, output)
|
||||
return output
|
||||
}
|
||||
const step = (ast: SchemaAST.AST): SchemaAST.AST => {
|
||||
if (SchemaAST.isDeclaration(ast) && ast.annotations?.toCode === undefined) {
|
||||
const representation = ast.annotations?.representation
|
||||
if (typeof representation === "object" && representation !== null && "id" in representation && representation.id === "effect/schema/Json") {
|
||||
return Schema.Json.ast
|
||||
}
|
||||
if (ast.annotations?.["~constructor"] !== undefined && ast.typeParameters[0] !== undefined) {
|
||||
const identifier = SchemaAST.resolveIdentifier(ast)
|
||||
const fields = recur(ast.typeParameters[0])
|
||||
if (identifier === undefined) return fields
|
||||
return Schema.make<Schema.Top>(fields).annotate({ identifier }).ast
|
||||
}
|
||||
}
|
||||
if (!("recur" in ast) || typeof ast.recur !== "function") return ast
|
||||
return ast.recur(recur)
|
||||
}
|
||||
return input.map(recur)
|
||||
}
|
||||
125
packages/cli-rs/script/rust/methods.ts
Normal file
125
packages/cli-rs/script/rust/methods.ts
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
// Emits one `Client` method per endpoint, following docs/F.2.md.
|
||||
import type { Endpoint, Group } from "@opencode/httpapi-codegen"
|
||||
import type { SchemaRepresentation } from "effect"
|
||||
import { pascal, snake, type Types } from "./types.ts"
|
||||
|
||||
export type Field = {
|
||||
readonly name: string
|
||||
readonly source: "params" | "query" | "headers" | "payload" | "wildcard"
|
||||
readonly optional: boolean
|
||||
/** Undefined for the wildcard, which is always a string. */
|
||||
readonly representation: SchemaRepresentation.Representation | undefined
|
||||
}
|
||||
|
||||
export type Method = {
|
||||
readonly group: Group
|
||||
readonly endpoint: Endpoint
|
||||
readonly prefix: string
|
||||
readonly fields: ReadonlyArray<Field>
|
||||
readonly opaque: boolean
|
||||
readonly binaryBody: boolean
|
||||
readonly success: "json" | "data" | "empty" | "binary" | "sse"
|
||||
readonly output: SchemaRepresentation.Representation | undefined
|
||||
readonly successStatus: number
|
||||
}
|
||||
|
||||
export function emitMethod(types: Types, method: Method) {
|
||||
const name = snake([...method.group.path, ...method.endpoint.clientPath].map((part) => snake(part).replace(/^r#/, "")).join("_"))
|
||||
const idents = new Map<Field, string>()
|
||||
for (const field of method.fields) {
|
||||
let ident = snake(field.name)
|
||||
for (let i = 2; [...idents.values()].includes(ident); i++) ident = `${snake(field.name)}_${i}`
|
||||
idents.set(field, ident)
|
||||
}
|
||||
const input = method.fields.length === 0 ? undefined : types.name(`${method.prefix}Input`)
|
||||
if (input !== undefined) {
|
||||
const lines = method.fields.map((field) => {
|
||||
const hint = `${method.prefix}Input${pascal(field.name)}`
|
||||
const type =
|
||||
method.binaryBody && field.source === "payload"
|
||||
? "bytes::Bytes"
|
||||
: field.representation === undefined
|
||||
? "String"
|
||||
: (types.field(field.representation, field.optional, hint)?.type ?? "()")
|
||||
return { line: ` pub ${idents.get(field)}: ${type},`, type }
|
||||
})
|
||||
const defaults = lines.every((line) => types.isDefault(line.type) || line.type === "bytes::Bytes")
|
||||
types.items.push(
|
||||
`/// Input of [\`Client::${name.replace(/^r#/, "")}\`].\n#[derive(Debug, Clone, PartialEq${defaults ? ", Default" : ""})]\npub struct ${input} {\n${lines.map((line) => line.line).join("\n")}\n}`,
|
||||
)
|
||||
}
|
||||
const outputName = types.name(`${method.prefix}Output`)
|
||||
const output = (() => {
|
||||
if (method.success === "empty") return "()"
|
||||
if (method.success === "binary") return "bytes::Bytes"
|
||||
const representation = method.output!
|
||||
if (representation._tag === "Objects" && representation.propertySignatures.length > 0) {
|
||||
return types.objects(representation, outputName, outputName)
|
||||
}
|
||||
const type = types.type(representation, outputName)
|
||||
types.items.push(`/// Output of [\`Client::${name.replace(/^r#/, "")}\`].\npub type ${outputName} = ${type};`)
|
||||
return outputName
|
||||
})()
|
||||
|
||||
const path = pathTemplate(method, idents)
|
||||
const access = (field: Field) => `input.${idents.get(field)}`
|
||||
const statements = method.fields.flatMap((field) => {
|
||||
const call =
|
||||
field.source === "query"
|
||||
? `call.query(${JSON.stringify(field.name)}, VALUE)?;`
|
||||
: field.source === "headers"
|
||||
? `call.header(${JSON.stringify(field.name)}, VALUE)?;`
|
||||
: field.source === "payload"
|
||||
? method.binaryBody
|
||||
? `call.bytes(${access(field)}.clone());`
|
||||
: method.opaque
|
||||
? "call.json(VALUE)?;"
|
||||
: `call.field(${JSON.stringify(field.name)}, VALUE)?;`
|
||||
: undefined
|
||||
if (call === undefined) return []
|
||||
if (field.optional) return [`if let Some(value) = &${access(field)} {\n ${call.replace("VALUE", "value")}\n }`]
|
||||
return [call.replace("VALUE", `&${access(field)}`)]
|
||||
})
|
||||
if (method.endpoint.payloads.length > 0 && !method.binaryBody && !method.opaque) statements.unshift("call.object();")
|
||||
const declared = [...new Set(method.endpoint.errors.map((error) => error.status))]
|
||||
const send =
|
||||
method.success === "sse"
|
||||
? "self.sse(call, options).await"
|
||||
: method.success === "data"
|
||||
? "self.data(call, options).await"
|
||||
: method.success === "empty"
|
||||
? "self.empty(call, options).await"
|
||||
: method.success === "binary"
|
||||
? "self.binary(call, options).await"
|
||||
: "self.json(call, options).await"
|
||||
const returns = method.success === "sse" ? `SseResponse<${output}>` : output
|
||||
const argument = input === undefined ? "" : `input: &${input}, `
|
||||
const mutable = statements.length === 0 ? "" : "mut "
|
||||
return ` /// \`${method.endpoint.endpoint.method} ${method.endpoint.endpoint.path}\` (\`${method.endpoint.operation.name}\`)
|
||||
pub async fn ${name}(&self, ${argument}options: &RequestOptions) -> Result<${returns}, Error> {
|
||||
let ${mutable}call = Call::new(${JSON.stringify(method.endpoint.endpoint.method)}, ${path}, ${method.successStatus}, &[${declared.join(", ")}]);
|
||||
${statements.map((statement) => ` ${statement}`).join("\n")}
|
||||
${send}
|
||||
}`
|
||||
}
|
||||
|
||||
function pathTemplate(method: Method, idents: Map<Field, string>) {
|
||||
const params = new Map(method.fields.filter((field) => field.source === "params").map((field) => [field.name, field]))
|
||||
const wildcard = method.fields.find((field) => field.source === "wildcard")
|
||||
const source = wildcard === undefined ? method.endpoint.endpoint.path : method.endpoint.endpoint.path.slice(0, -1)
|
||||
const args: Array<string> = []
|
||||
const template = source
|
||||
.split(/(:[A-Za-z_][A-Za-z0-9_]*)/g)
|
||||
.filter(Boolean)
|
||||
.map((segment) => {
|
||||
if (!segment.startsWith(":")) return segment.replaceAll("{", "{{").replaceAll("}", "}}")
|
||||
const field = params.get(segment.slice(1))
|
||||
if (field === undefined) throw new Error(`Missing path parameter: ${segment}`)
|
||||
args.push(`crate::client::path_param(&input.${idents.get(field)})?`)
|
||||
return "{}"
|
||||
})
|
||||
.join("")
|
||||
if (wildcard !== undefined) args.push(`crate::client::path_wildcard(&input.${idents.get(wildcard)})`)
|
||||
if (args.length === 0) return `${JSON.stringify(template)}.to_owned()`
|
||||
return `format!(${JSON.stringify(template + (wildcard === undefined ? "" : "{}"))}, ${args.join(", ")})`
|
||||
}
|
||||
401
packages/cli-rs/script/rust/types.ts
Normal file
401
packages/cli-rs/script/rust/types.ts
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
// Emits Rust types from Effect schema representations, following docs/F.2.md.
|
||||
import type { SchemaRepresentation } from "effect"
|
||||
|
||||
type R = SchemaRepresentation.Representation
|
||||
type Objects = SchemaRepresentation.Objects
|
||||
|
||||
const keywords = new Set(
|
||||
"as async await break const continue crate dyn else enum extern false fn for gen if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while abstract become box do final macro override priv try typeof unsized virtual yield".split(
|
||||
" ",
|
||||
),
|
||||
)
|
||||
|
||||
export function pascal(value: string) {
|
||||
const name = value
|
||||
.split(/[^A-Za-z0-9]+/)
|
||||
.filter(Boolean)
|
||||
.map((part) => `${part[0].toUpperCase()}${part.slice(1)}`)
|
||||
.join("")
|
||||
return /^[A-Za-z]/.test(name) ? name : `V${name}`
|
||||
}
|
||||
|
||||
export function snake(value: string) {
|
||||
const name = value
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
|
||||
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
|
||||
.split(/[^A-Za-z0-9]+/)
|
||||
.filter(Boolean)
|
||||
.join("_")
|
||||
.toLowerCase()
|
||||
const safe = /^[a-z_]/.test(name) ? name : `v${name}`
|
||||
if (safe === "self" || safe === "super" || safe === "crate" || safe === "_") return `${safe}_`
|
||||
return keywords.has(safe) ? `r#${safe}` : safe
|
||||
}
|
||||
|
||||
/** Turns representations into Rust items. `type(r, hint)` returns a Rust type expression and emits what it names. */
|
||||
export class Types {
|
||||
readonly items: Array<string> = []
|
||||
private readonly names = new Set<string>()
|
||||
private readonly referenced = new Map<string, string>()
|
||||
private readonly defaultable = new Set<string>()
|
||||
private readonly visiting = new Set<string>()
|
||||
|
||||
constructor(private readonly references: SchemaRepresentation.References) {}
|
||||
|
||||
/** Reserves a unique type name based on `seed`. */
|
||||
name(seed: string) {
|
||||
const base = pascal(seed)
|
||||
let name = base
|
||||
for (let index = 2; this.names.has(name); index++) name = `${base}${index}`
|
||||
this.names.add(name)
|
||||
return name
|
||||
}
|
||||
|
||||
deref(r: R): R {
|
||||
if (r._tag === "Reference") return this.deref(this.references[r.$ref])
|
||||
if (r._tag === "Suspend") return this.deref(r.thunk)
|
||||
return r
|
||||
}
|
||||
|
||||
isDefault(type: string) {
|
||||
return (
|
||||
/^(Option|Vec|BTreeMap)</.test(type) ||
|
||||
["String", "bool", "i64", "f64", "serde_json::Value", "()"].includes(type) ||
|
||||
this.defaultable.has(type)
|
||||
)
|
||||
}
|
||||
|
||||
type(r: R, hint: string): string {
|
||||
switch (r._tag) {
|
||||
case "Reference":
|
||||
return this.reference(r.$ref)
|
||||
case "Suspend":
|
||||
return this.type(r.thunk, hint)
|
||||
case "String":
|
||||
case "TemplateLiteral":
|
||||
case "Enum":
|
||||
return "String"
|
||||
case "Number":
|
||||
return integer(r) ? "i64" : "f64"
|
||||
case "Boolean":
|
||||
return "bool"
|
||||
case "Literal":
|
||||
return literalType(r.literal)
|
||||
case "Null":
|
||||
case "Undefined":
|
||||
case "Void":
|
||||
case "Never":
|
||||
return "()"
|
||||
case "Objects":
|
||||
return this.objects(r, this.name(hint), hint)
|
||||
case "Arrays":
|
||||
return this.arrays(r, hint)
|
||||
case "Union":
|
||||
return this.union(r, hint, undefined)
|
||||
default:
|
||||
return "serde_json::Value"
|
||||
}
|
||||
}
|
||||
|
||||
private reference(ref: string): string {
|
||||
const existing = this.referenced.get(ref)
|
||||
if (existing !== undefined) return existing
|
||||
if (this.visiting.has(ref)) throw new Error(`Recursive schema reference is not supported: ${ref}`)
|
||||
this.visiting.add(ref)
|
||||
const target = this.references[ref]
|
||||
const resolved = this.deref(target)
|
||||
const result = (() => {
|
||||
if (resolved._tag === "Objects" && resolved.propertySignatures.length > 0) {
|
||||
const name = this.name(ref)
|
||||
this.referenced.set(ref, name)
|
||||
return this.objects(resolved, name, name)
|
||||
}
|
||||
if (resolved._tag === "Union") {
|
||||
const shape = this.union(resolved, ref, ref)
|
||||
return shape
|
||||
}
|
||||
if (resolved._tag === "String" || resolved._tag === "TemplateLiteral") {
|
||||
const name = this.name(ref)
|
||||
this.defaultable.add(name)
|
||||
this.items.push(newtype(name, ref))
|
||||
return name
|
||||
}
|
||||
const type = this.type(target, ref)
|
||||
if (/^[A-Z][A-Za-z0-9]*$/.test(type) && !["String"].includes(type)) return type
|
||||
const name = this.name(ref)
|
||||
if (this.isDefault(type)) this.defaultable.add(name)
|
||||
this.items.push(`/// \`${ref}\`\npub type ${name} = ${type};`)
|
||||
return name
|
||||
})()
|
||||
this.visiting.delete(ref)
|
||||
this.referenced.set(ref, result)
|
||||
return result
|
||||
}
|
||||
|
||||
private arrays(r: SchemaRepresentation.Arrays, hint: string): string {
|
||||
if (r.elements.length === 0 && r.rest.length === 1) return `Vec<${this.type(r.rest[0], `${hint}Item`)}>`
|
||||
if (r.rest.length === 0 && r.elements.every((element) => !element.isOptional)) {
|
||||
return `(${r.elements.map((element, index) => `${this.type(element.type, `${hint}${index}`)},`).join(" ")})`
|
||||
}
|
||||
return "Vec<serde_json::Value>"
|
||||
}
|
||||
|
||||
/** A struct, or a map for an object with only index signatures. */
|
||||
objects(r: Objects, name: string, hint: string): string {
|
||||
const index = r.indexSignatures[0]
|
||||
const value = index === undefined ? undefined : this.type(index.type, `${hint}Value`)
|
||||
if (r.propertySignatures.length === 0 && value !== undefined) {
|
||||
this.names.delete(name)
|
||||
return `BTreeMap<String, ${value}>`
|
||||
}
|
||||
const used = new Set<string>()
|
||||
const fields = r.propertySignatures.flatMap((property) => {
|
||||
const key = String(property.name)
|
||||
const field = this.field(property.type, property.isOptional, `${hint}${pascal(key)}`)
|
||||
if (field === undefined) return []
|
||||
let ident = snake(key)
|
||||
for (let i = 2; used.has(ident); i++) ident = `${snake(key)}_${i}`
|
||||
used.add(ident)
|
||||
const plain = ident.replace(/^r#/, "")
|
||||
const attrs = [plain === key ? undefined : `rename = ${JSON.stringify(key)}`, ...field.attrs].filter(Boolean)
|
||||
const doc = docOf(property.annotations)
|
||||
return [
|
||||
`${doc}${attrs.length ? ` #[serde(${attrs.join(", ")})]\n` : ""} pub ${ident}: ${field.type},`,
|
||||
field.type,
|
||||
]
|
||||
})
|
||||
const lines = fields.filter((_, i) => i % 2 === 0)
|
||||
const types = fields.filter((_, i) => i % 2 === 1)
|
||||
if (value !== undefined) {
|
||||
lines.push(` #[serde(flatten)]\n pub extra: BTreeMap<String, ${value}>,`)
|
||||
types.push("BTreeMap")
|
||||
}
|
||||
const defaults = types.every((type) => this.isDefault(type) || type === "BTreeMap")
|
||||
if (defaults) this.defaultable.add(name)
|
||||
this.items.push(
|
||||
`#[derive(Debug, Clone, PartialEq, Serialize, Deserialize${defaults ? ", Default" : ""})]\npub struct ${name} {\n${lines.join("\n")}\n}`,
|
||||
)
|
||||
return name
|
||||
}
|
||||
|
||||
/** A field type with its serde attributes, or undefined for a field that can only be absent. */
|
||||
field(r: R, optional: boolean, hint: string) {
|
||||
const members = r._tag === "Union" ? flatten(r.types) : [r]
|
||||
const present = members.filter((member) => !["Undefined", "Never", "Void"].includes(this.deref(member)._tag))
|
||||
if (present.length === 0) return undefined
|
||||
const nullable = present.some((member) => this.deref(member)._tag === "Null")
|
||||
const rest = present.filter((member) => this.deref(member)._tag !== "Null")
|
||||
const inner =
|
||||
rest.length === 0
|
||||
? "()"
|
||||
: rest.length === 1
|
||||
? this.type(rest[0], hint)
|
||||
: this.union({ ...(r as SchemaRepresentation.Union), types: rest }, hint, undefined)
|
||||
if (optional && nullable) {
|
||||
return {
|
||||
type: `Option<Option<${inner}>>`,
|
||||
attrs: ['default', 'deserialize_with = "crate::de::double_option"', 'skip_serializing_if = "Option::is_none"'],
|
||||
}
|
||||
}
|
||||
if (optional) return { type: `Option<${inner}>`, attrs: ["default", 'skip_serializing_if = "Option::is_none"'] }
|
||||
if (nullable) return { type: `Option<${inner}>`, attrs: ["default"] }
|
||||
return { type: inner, attrs: [] as Array<string> }
|
||||
}
|
||||
|
||||
/** A union. `ref` names the reference it defines, if any. */
|
||||
union(r: SchemaRepresentation.Union, hint: string, ref: string | undefined): string {
|
||||
const members = flatten(r.types).filter((member) => !["Undefined", "Never", "Void"].includes(this.deref(member)._tag))
|
||||
const nullable = members.some((member) => this.deref(member)._tag === "Null")
|
||||
const rest = members.filter((member) => this.deref(member)._tag !== "Null")
|
||||
const wrap = (type: string) => (nullable ? `Option<${type}>` : type)
|
||||
if (rest.length === 0) return "()"
|
||||
if (rest.length === 1) return wrap(this.type(rest[0], hint))
|
||||
const resolved = rest.map((member) => this.deref(member))
|
||||
if (resolved.every((member) => member._tag === "Literal")) {
|
||||
const values = resolved.map((member) => (member as SchemaRepresentation.Literal).literal)
|
||||
if (values.every((value) => typeof value === "string")) {
|
||||
return wrap(this.literals(values as Array<string>, ref ?? hint, ref))
|
||||
}
|
||||
if (values.every((value) => typeof value === "boolean")) return wrap("bool")
|
||||
if (values.every((value) => typeof value === "number"))
|
||||
return wrap(values.every(Number.isInteger) ? "i64" : "f64")
|
||||
return wrap("serde_json::Value")
|
||||
}
|
||||
if (resolved.every((member) => member._tag === "Literal" || member._tag === "String")) return wrap("String")
|
||||
if (resolved.every((member) => member._tag === "Objects")) {
|
||||
const tagged = this.discriminator(resolved as Array<Objects>)
|
||||
if (tagged !== undefined) return wrap(this.tagged(rest, tagged, ref ?? hint, ref))
|
||||
}
|
||||
return wrap(this.untagged(rest, ref ?? hint, ref))
|
||||
}
|
||||
|
||||
private literals(values: Array<string>, seed: string, ref: string | undefined) {
|
||||
const name = this.name(seed)
|
||||
const variants = uniqueVariants(values.map((value) => pascal(value)))
|
||||
const doc = ref === undefined ? "" : `/// \`${ref}\`\n`
|
||||
this.items.push(
|
||||
`${doc}#[derive(Debug, Clone, PartialEq, Eq, Hash)]\npub enum ${name} {\n${variants.map((variant) => ` ${variant},`).join("\n")}\n Unknown(String),\n}\n\nimpl ${name} {\n pub fn as_str(&self) -> &str {\n match self {\n${variants.map((variant, i) => ` Self::${variant} => ${JSON.stringify(values[i])},`).join("\n")}\n Self::Unknown(value) => value,\n }\n }\n}\n\nimpl From<&str> for ${name} {\n fn from(value: &str) -> Self {\n match value {\n${variants.map((variant, i) => ` ${JSON.stringify(values[i])} => Self::${variant},`).join("\n")}\n _ => Self::Unknown(value.to_owned()),\n }\n }\n}\n\nimpl Serialize for ${name} {\n fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {\n serializer.serialize_str(self.as_str())\n }\n}\n\nimpl<'de> Deserialize<'de> for ${name} {\n fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {\n let value = String::deserialize(deserializer)?;\n Ok(Self::from(value.as_str()))\n }\n}`,
|
||||
)
|
||||
return name
|
||||
}
|
||||
|
||||
/** The discriminator of an object union: a required field whose literal values tell every member apart. */
|
||||
private discriminator(members: Array<Objects>) {
|
||||
const tags = (member: Objects, key: string) => {
|
||||
const property = member.propertySignatures.find((p) => p.name === key)
|
||||
if (property === undefined || property.isOptional) return undefined
|
||||
return this.tagValues(property.type)
|
||||
}
|
||||
const keys = members[0].propertySignatures.map((p) => String(p.name))
|
||||
const ordered = [...keys.filter((key) => key === "type" || key === "_tag"), ...keys.filter((key) => key !== "type" && key !== "_tag")]
|
||||
for (const key of ordered) {
|
||||
const values = members.map((member) => tags(member, key))
|
||||
if (values.some((value) => value === undefined)) continue
|
||||
const exact = values.flatMap((value) => value!.exact.map((item) => JSON.stringify(item)))
|
||||
if (new Set(exact).size !== exact.length) continue
|
||||
const kinds = new Set(values.flatMap((value) => value!.exact.map((item) => typeof item)))
|
||||
if (kinds.size > 1 || (kinds.size === 1 && !kinds.has("string") && !kinds.has("boolean"))) continue
|
||||
if (kinds.has("boolean") && values.some((value) => value!.prefixes.length > 0)) continue
|
||||
return { key, values: values as Array<{ exact: Array<string | boolean>; prefixes: Array<string> }> }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
private tagValues(r: R): { exact: Array<string | boolean>; prefixes: Array<string> } | undefined {
|
||||
const resolved = this.deref(r)
|
||||
if (resolved._tag === "Literal") {
|
||||
if (typeof resolved.literal !== "string" && typeof resolved.literal !== "boolean") return undefined
|
||||
return { exact: [resolved.literal], prefixes: [] }
|
||||
}
|
||||
if (resolved._tag === "TemplateLiteral") {
|
||||
const [head, ...tail] = resolved.parts
|
||||
if (head?._tag !== "Literal" || typeof head.literal !== "string") return undefined
|
||||
if (tail.length !== 1 || this.deref(tail[0])._tag !== "String") return undefined
|
||||
return { exact: [], prefixes: [head.literal] }
|
||||
}
|
||||
if (resolved._tag === "Union") {
|
||||
const parts = flatten(resolved.types).map((member) => this.tagValues(member))
|
||||
if (parts.some((part) => part === undefined)) return undefined
|
||||
return { exact: parts.flatMap((part) => part!.exact), prefixes: parts.flatMap((part) => part!.prefixes) }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
private tagged(
|
||||
members: Array<R>,
|
||||
tag: { key: string; values: Array<{ exact: Array<string | boolean>; prefixes: Array<string> }> },
|
||||
seed: string,
|
||||
ref: string | undefined,
|
||||
) {
|
||||
const name = this.name(seed)
|
||||
const variants = uniqueVariants(
|
||||
tag.values.map((value, index) => {
|
||||
if (value.exact.length === 1) return pascal(String(value.exact[0]))
|
||||
if (value.prefixes.length > 0 && value.exact.length === 0) return pascal(value.prefixes[0])
|
||||
const member = members[index]
|
||||
return member._tag === "Reference" ? pascal(member.$ref.split(".").at(-1)!) : `Variant${index + 1}`
|
||||
}),
|
||||
)
|
||||
const types = members.map((member, index) => {
|
||||
const resolved = this.deref(member)
|
||||
if (member._tag === "Reference") return this.type(member, `${name}${variants[index]}`)
|
||||
return this.objects(resolved as Objects, this.name(`${name}${variants[index]}`), `${name}${variants[index]}`)
|
||||
})
|
||||
const kind = typeof tag.values.find((value) => value.exact.length > 0)?.exact[0]
|
||||
const access = kind === "boolean" ? "as_bool" : "as_str"
|
||||
const arms = tag.values.flatMap((value, index) => [
|
||||
...(value.exact.length === 0
|
||||
? []
|
||||
: [` ${value.exact.map((item) => `Some(${JSON.stringify(item)})`).join(" | ")} => crate::de::variant(value).map(Self::${variants[index]}),`]),
|
||||
...value.prefixes.map(
|
||||
(prefix) =>
|
||||
` Some(tag) if tag.starts_with(${JSON.stringify(prefix)}) => crate::de::variant(value).map(Self::${variants[index]}),`,
|
||||
),
|
||||
])
|
||||
const ordered = [...arms.filter((arm) => !arm.includes("starts_with")), ...arms.filter((arm) => arm.includes("starts_with"))]
|
||||
const doc = ref === undefined ? "" : `/// \`${ref}\`, tagged by \`${tag.key}\`.\n`
|
||||
this.items.push(
|
||||
`${doc}#[derive(Debug, Clone, PartialEq, Serialize)]\n#[serde(untagged)]\npub enum ${name} {\n${variants.map((variant, index) => ` ${variant}(${types[index]}),`).join("\n")}\n /// A member this client does not know, kept as it arrived.\n Unknown(serde_json::Value),\n}\n\nimpl<'de> Deserialize<'de> for ${name} {\n fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {\n let value = serde_json::Value::deserialize(deserializer)?;\n match value.get(${JSON.stringify(tag.key)}).and_then(serde_json::Value::${access}) {\n${ordered.join("\n")}\n _ => Ok(Self::Unknown(value)),\n }\n }\n}`,
|
||||
)
|
||||
return name
|
||||
}
|
||||
|
||||
private untagged(members: Array<R>, seed: string, ref: string | undefined) {
|
||||
const name = this.name(seed)
|
||||
const seen = new Map<string, string>()
|
||||
for (const member of members) {
|
||||
const resolved = this.deref(member)
|
||||
const variant =
|
||||
member._tag === "Reference" && resolved._tag !== "String"
|
||||
? pascal(member.$ref.split(".").at(-1)!)
|
||||
: resolved._tag === "Literal"
|
||||
? typeof resolved.literal === "string"
|
||||
? "String"
|
||||
: typeof resolved.literal === "boolean"
|
||||
? "Bool"
|
||||
: "Number"
|
||||
: ({ String: "String", TemplateLiteral: "String", Boolean: "Bool", Number: "Number", Arrays: "Array", Objects: "Object" } as Record<string, string>)[
|
||||
resolved._tag
|
||||
] ?? "Value"
|
||||
const type =
|
||||
resolved._tag === "Literal"
|
||||
? typeof resolved.literal === "string"
|
||||
? "String"
|
||||
: typeof resolved.literal === "boolean"
|
||||
? "bool"
|
||||
: "f64"
|
||||
: this.type(member, `${name}${variant}`)
|
||||
if ([...seen.values()].includes(type)) continue
|
||||
let unique = variant
|
||||
for (let index = 2; seen.has(unique); index++) unique = `${variant}${index}`
|
||||
seen.set(unique, type)
|
||||
}
|
||||
const doc = ref === undefined ? "" : `/// \`${ref}\`\n`
|
||||
this.items.push(
|
||||
`${doc}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n#[serde(untagged)]\npub enum ${name} {\n${[...seen].map(([variant, type]) => ` ${variant}(${type}),`).join("\n")}\n /// A shape this client does not know, kept as it arrived.\n Unknown(serde_json::Value),\n}`,
|
||||
)
|
||||
return name
|
||||
}
|
||||
}
|
||||
|
||||
function flatten(types: ReadonlyArray<R>): Array<R> {
|
||||
return types.flatMap((type) => (type._tag === "Union" ? flatten(type.types) : [type]))
|
||||
}
|
||||
|
||||
function integer(r: SchemaRepresentation.Number) {
|
||||
const visit = (checks: ReadonlyArray<SchemaRepresentation.Check>): boolean =>
|
||||
checks.some((check) =>
|
||||
check._tag === "Filter" ? check.representation?.id === "effect/schema/isInt" : visit(check.checks),
|
||||
)
|
||||
return visit(r.checks)
|
||||
}
|
||||
|
||||
function literalType(literal: unknown) {
|
||||
if (typeof literal === "string") return "String"
|
||||
if (typeof literal === "boolean") return "bool"
|
||||
if (typeof literal === "number") return Number.isInteger(literal) ? "i64" : "f64"
|
||||
return "serde_json::Value"
|
||||
}
|
||||
|
||||
function newtype(name: string, ref: string) {
|
||||
return `/// \`${ref}\`\n#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize)]\n#[serde(transparent)]\npub struct ${name}(pub String);\n\nimpl ${name} {\n pub fn as_str(&self) -> &str {\n &self.0\n }\n}\n\nimpl std::fmt::Display for ${name} {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.write_str(&self.0)\n }\n}\n\nimpl From<String> for ${name} {\n fn from(value: String) -> Self {\n Self(value)\n }\n}\n\nimpl From<&str> for ${name} {\n fn from(value: &str) -> Self {\n Self(value.to_owned())\n }\n}`
|
||||
}
|
||||
|
||||
function uniqueVariants(names: Array<string>) {
|
||||
const seen = new Set<string>(["Unknown"])
|
||||
return names.map((name) => {
|
||||
let unique = name
|
||||
for (let index = 2; seen.has(unique); index++) unique = `${name}${index}`
|
||||
seen.add(unique)
|
||||
return unique
|
||||
})
|
||||
}
|
||||
|
||||
function docOf(annotations: { readonly [key: string]: unknown } | undefined) {
|
||||
const description = annotations?.description
|
||||
if (typeof description !== "string" || description === "") return ""
|
||||
return description
|
||||
.split("\n")
|
||||
.map((line) => ` /// ${line}`.trimEnd() + "\n")
|
||||
.join("")
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue