bynk_emit/emitter/workers_entry/
field_specs.rs1use crate::emitter::serialisation;
5use crate::ts_build::{bool_lit, str_lit};
6use bynk_check::symbols::UnitTable;
7use bynk_syntax::ast::{Handler, LimitsPolicy, TypeRef};
8use bynk_ts::TsExpr;
9
10pub(crate) type FieldSpec = (String, &'static str, bool, bool, Option<String>);
14
15fn field_spec_expr((name, kind, list, option, wire): &FieldSpec) -> TsExpr {
17 let mut props = vec![("name".to_string(), str_lit(name.clone()))];
18 if let Some(wire) = wire {
19 props.push(("wire".to_string(), str_lit(wire.clone())));
20 }
21 props.push(("kind".to_string(), str_lit(*kind)));
22 props.push(("list".to_string(), bool_lit(*list)));
23 props.push(("option".to_string(), bool_lit(*option)));
24 TsExpr::object(props)
25}
26
27pub fn field_spec_source((name, kind, list, option, wire): &FieldSpec) -> String {
30 let wire = wire
31 .as_ref()
32 .map(|w| format!(" wire: {w:?},"))
33 .unwrap_or_default();
34 format!("{{ name: {name:?},{wire} kind: {kind:?}, list: {list}, option: {option} }}")
35}
36
37pub fn renamed_specs_source(
41 type_ref: &TypeRef,
42 types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
43) -> Option<String> {
44 use bynk_syntax::ast::TypeBody;
45 let TypeRef::Named(id) = type_ref else {
46 return None;
47 };
48 let Some(TypeBody::Record(rec)) = types.get(&id.name).map(|t| &t.body) else {
49 return None;
50 };
51 let specs = record_field_specs(rec, types, false);
52 if specs.iter().all(|s| s.4.is_none()) {
53 return None;
54 }
55 let items: Vec<String> = specs.iter().map(field_spec_source).collect();
56 Some(format!("[{}] as const", items.join(", ")))
57}
58
59pub(super) fn field_specs_exprs(fields: &[FieldSpec]) -> Vec<TsExpr> {
60 fields.iter().map(field_spec_expr).collect()
61}
62
63#[derive(Debug, Clone)]
65pub(super) struct MultipartSpec {
66 pub(super) fields: Vec<FieldSpec>,
67 pub(super) max_file: Option<i64>,
69 pub(super) max_parts: i64,
71 pub(super) has_files: bool,
74}
75
76pub(crate) fn query_leaf_kind(
79 r: &TypeRef,
80 types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
81 allow_file: bool,
82) -> &'static str {
83 use bynk_syntax::ast::{BaseType, TypeBody};
84 let of_base = |b: &BaseType| match b {
85 BaseType::Int => "int",
86 BaseType::Bool => "bool",
87 BaseType::Decimal => "decimal",
90 BaseType::String
91 | BaseType::Float
92 | BaseType::Duration
93 | BaseType::Instant
94 | BaseType::Bytes => "string",
95 };
96 match r {
97 TypeRef::Base(b, _) => of_base(b),
98 TypeRef::Named(id) if allow_file && id.name == "File" => "file",
103 TypeRef::Named(id) => match types.get(&id.name).map(|t| &t.body) {
104 Some(TypeBody::Refined { base, .. }) | Some(TypeBody::Opaque { base, .. }) => {
105 of_base(base)
106 }
107 Some(TypeBody::Sum(_)) => "enum",
108 _ => "string",
109 },
110 TypeRef::Result(..)
111 | TypeRef::Option(..)
112 | TypeRef::Effect(..)
113 | TypeRef::HttpResult(..)
114 | TypeRef::QueueResult(_)
115 | TypeRef::Asset(_)
116 | TypeRef::RequestHeaders(_)
117 | TypeRef::RequestQuery(_)
118 | TypeRef::RequestCookies(_)
119 | TypeRef::TokenClaims(_)
120 | TypeRef::BoundaryRejection(_)
121 | TypeRef::List(..)
122 | TypeRef::Map(..)
123 | TypeRef::Set(..)
124 | TypeRef::Query(..)
125 | TypeRef::Stream(..)
126 | TypeRef::Connection(..)
127 | TypeRef::History(..)
128 | TypeRef::ValidationError(_)
129 | TypeRef::DecodeError(_)
130 | TypeRef::Unit(_)
131 | TypeRef::Fn(..)
132 | TypeRef::App { .. } => "string",
133 }
134}
135
136pub(super) fn query_field_specs(
140 h: &Handler,
141 path: &str,
142 types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
143) -> Option<Vec<FieldSpec>> {
144 use bynk_syntax::ast::TypeBody;
145 if path.split('/').any(|seg| seg == ":query") {
146 return None;
147 }
148 let p = h.params.iter().find(|p| p.name.name == "query")?;
149 let TypeRef::Named(id) = &p.type_ref else {
150 return None;
151 };
152 let Some(TypeBody::Record(rec)) = types.get(&id.name).map(|t| &t.body) else {
153 return None;
154 };
155 Some(record_field_specs(rec, types, false))
156}
157
158pub(super) fn form_field_specs(
161 h: &Handler,
162 types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
163) -> Option<Vec<FieldSpec>> {
164 use bynk_syntax::ast::TypeBody;
165 if !h.annotations.iter().any(|a| a.name.name == "form") {
166 return None;
167 }
168 let p = h.params.iter().find(|p| p.name.name == "body")?;
169 let TypeRef::Named(id) = &p.type_ref else {
170 return None;
171 };
172 let Some(TypeBody::Record(rec)) = types.get(&id.name).map(|t| &t.body) else {
173 return None;
174 };
175 Some(record_field_specs(rec, types, false))
176}
177
178pub(super) fn cookies_field_specs(
181 h: &Handler,
182 path: &str,
183 types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
184) -> Option<Vec<FieldSpec>> {
185 use bynk_syntax::ast::TypeBody;
186 if path.split('/').any(|seg| seg == ":cookies") {
187 return None;
188 }
189 let p = h.params.iter().find(|p| p.name.name == "cookies")?;
190 let TypeRef::Named(id) = &p.type_ref else {
191 return None;
192 };
193 let Some(TypeBody::Record(rec)) = types.get(&id.name).map(|t| &t.body) else {
194 return None;
195 };
196 Some(record_field_specs(rec, types, false))
197}
198
199pub fn form_body_specs(
202 h: &Handler,
203 types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
204) -> Option<Vec<FieldSpec>> {
205 form_field_specs(h, types).or_else(|| multipart_spec(None, h, types).map(|m| m.fields))
206}
207
208pub(super) fn multipart_spec(
210 service_limits: Option<&LimitsPolicy>,
211 h: &Handler,
212 types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
213) -> Option<MultipartSpec> {
214 use bynk_syntax::ast::TypeBody;
215 if !h.annotations.iter().any(|a| a.name.name == "multipart") {
216 return None;
217 }
218 let p = h.params.iter().find(|p| p.name.name == "body")?;
219 let TypeRef::Named(id) = &p.type_ref else {
220 return None;
221 };
222 let Some(TypeBody::Record(rec)) = types.get(&id.name).map(|t| &t.body) else {
223 return None;
224 };
225 let fields = record_field_specs(rec, types, true);
226 let has_files = fields.iter().any(|(_, kind, _, _, _)| *kind == "file");
227 Some(MultipartSpec {
228 fields,
229 max_file: h
230 .limit_max_file()
231 .or_else(|| service_limits.and_then(|p| p.max_file())),
232 max_parts: h
233 .limit_max_parts()
234 .or_else(|| service_limits.and_then(|p| p.max_parts()))
235 .unwrap_or(bynk_syntax::ast::DEFAULT_MAX_PARTS),
236 has_files,
237 })
238}
239
240pub(crate) fn record_field_specs(
243 rec: &bynk_syntax::ast::RecordBody,
244 types: &std::collections::HashMap<String, std::sync::Arc<bynk_syntax::ast::TypeDecl>>,
245 allow_file: bool,
246) -> Vec<FieldSpec> {
247 rec.fields
248 .iter()
249 .map(|f| {
250 let (inner, list, option) = serialisation::peel_list_option(&f.type_ref);
251 (
252 f.name.name.clone(),
253 query_leaf_kind(inner, types, allow_file),
254 list,
255 option,
256 f.wire_name(),
257 )
258 })
259 .collect()
260}
261
262pub fn table_has_plain_json(table: &UnitTable) -> bool {
265 table.services.values().any(|svc| {
266 svc.handlers.iter().any(|h| {
267 bynk_syntax::ast::effective_json_options(svc.json.as_ref(), h)
268 == bynk_syntax::ast::JsonOptions::Plain
269 })
270 })
271}
272
273pub(super) fn effective_max_body(
283 service_limits: Option<&LimitsPolicy>,
284 h: &Handler,
285) -> Option<i64> {
286 h.limit_max_body()
287 .or_else(|| service_limits.and_then(|p| p.max_body()))
288}