appstruct-codegen 0.2.0

Deterministic Rust, SQL, OpenAPI, TypeScript, and React generation for AppStruct
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
mod activity;
mod auth;
mod billing;
mod bulk;
mod collections;
mod entity;
mod modules;
mod realtime;
mod report;
mod saved_views;
use crate::{Artifact, ArtifactKind, generated_header};
use appstruct_ir::{
    AppIr, EntityIr, FieldIr, FieldTypeIr, GeneratedValueIr, OperationTypeIr, ValueObjectIr,
};
use modules::{audit_source, tenant_source, tenant_storage_source};
pub(crate) fn plan(ir: &AppIr) -> Vec<Artifact> {
    vec![Artifact::text(
        "web/src/generated/client.ts",
        client_source(ir),
        ArtifactKind::TypeScript,
    )]
}
fn client_source(ir: &AppIr) -> String {
    let mut sections = vec![
        generated_header("//"),
        format!("{}{}", runtime_source(), collections::types()),
        tenant_storage_source(ir.auth.enabled),
        saved_views::source(ir),
    ];
    if ir.auth.enabled {
        sections.push(auth::source(ir));
    }
    if ir.billing.enabled {
        sections.push(billing::source(ir));
    }
    if ir.tenant.enabled {
        sections.push(tenant_source());
    }
    if ir.audit.enabled {
        sections.push(audit_source());
    }
    if ir.realtime.enabled {
        sections.push(realtime::source().to_owned());
    }
    if ir.report.enabled {
        sections.push(report::source(ir));
    }
    if ir.activity.enabled {
        sections.push(activity::source(ir));
    }
    sections.extend(ir.value_objects.iter().map(value_object_type));
    for entity in &ir.entities {
        sections.push(entity_types(entity));
        sections.push(entity::client(ir, entity));
    }
    sections.extend(operation_clients(ir));
    format!("{}\n", sections.join("\n"))
}
fn value_object_type(value: &ValueObjectIr) -> String {
    let fields = value
        .fields
        .iter()
        .map(|field| {
            let optional = if field.required { "" } else { "?" };
            let nullable = if field.required { "" } else { " | null" };
            format!(
                "  {}{optional}: {}{nullable};",
                field.rust_name,
                base_type(&field.ty)
            )
        })
        .collect::<Vec<_>>()
        .join("\n");
    format!("export interface {} {{\n{fields}\n}}\n", value.rust_name)
}
fn operation_clients(ir: &AppIr) -> Vec<String> {
    let mut clients = Vec::new();
    for command in &ir.commands {
        let variable = format!("{}Command", lower_camel(&command.rust_name));
        let input = operation_type_name(ir, &command.input);
        let output = operation_type_name(ir, &command.output);
        let path = format!("/api/commands/{}", kebab_name(&command.rust_name));
        clients.push(format!(
            "export const {variable} = (input: {input}) => request<{output}>(\"{path}\", {{ method: \"POST\", body: JSON.stringify(input) }});\n"
        ));
    }
    for query in &ir.queries {
        let variable = format!("{}Query", lower_camel(&query.rust_name));
        let output = operation_type_name(ir, &query.output);
        let path = format!("/api/queries/{}", kebab_name(&query.rust_name));
        clients.push(query.input.as_ref().map_or_else(
            || format!("export const {variable} = () => request<{output}>(\"{path}\");\n"),
            |input| {
                let input = operation_type_name(ir, input);
                format!(
                    "export const {variable} = (input: {input}) => request<{output}>(\"{path}\", {{ method: \"POST\", body: JSON.stringify(input) }});\n"
                )
            },
        ));
    }
    clients
}
fn operation_type_name<'ir>(ir: &'ir AppIr, operation_type: &OperationTypeIr) -> &'ir str {
    match operation_type {
        OperationTypeIr::Entity { entity } => ir
            .entities
            .iter()
            .find(|candidate| candidate.id == *entity)
            .map(|entity| entity.rust_name.as_str())
            .expect("compiler resolved operation entity"),
        OperationTypeIr::ValueObject { value_object } => ir
            .value_objects
            .iter()
            .find(|candidate| candidate.id == *value_object)
            .map(|value| value.rust_name.as_str())
            .expect("compiler resolved operation value object"),
    }
}
fn runtime_source() -> String {
    format!(
        "{}\n{}\n{}",
        request_runtime_source(),
        bulk::runtime_source(),
        list_runtime_source()
    )
}
fn request_runtime_source() -> &'static str {
    r#"const API_BASE = (import.meta.env.PUBLIC_API_URL as string | undefined) ?? (import.meta.env.VITE_API_URL as string | undefined) ?? (import.meta.env.PROD ? "" : "http://127.0.0.1:3000");

export interface RequestOptions { signal?: AbortSignal; }
export const sessionSyncKey = "appstruct_session_sync";

export interface WorkflowTransitionCapability { name: string; to: string; input: string | null; }
export interface WorkflowCapabilities { state: string; revision: number; allowed_transitions: WorkflowTransitionCapability[]; }

export interface FieldViolation {
  field: string;
  message: string;
}

interface ErrorEnvelope {
  error: {
    code: string;
    message: string;
    fields: FieldViolation[];
  };
}

export class ApiError extends Error {
  constructor(
    public readonly status: number,
    public readonly code: string,
    message: string,
    public readonly fields: FieldViolation[] = [],
  ) {
    super(message);
  }
}

const resourceEtags = new Map<string, string>();

export function requestHeaders(init?: RequestInit, revisionKey?: string, requireRevision = false): Headers {
  const headers = new Headers(init?.headers);
  const method = init?.method ?? "GET";
  if (init?.body != null && !headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }
  const tenant = currentTenant();
  if (tenant) headers.set("X-AppStruct-Tenant", tenant);
  if (method !== "GET" && method !== "HEAD") {
    const csrf = cookieValue("appstruct_csrf");
    if (csrf) headers.set("X-CSRF-Token", csrf);
  }
  if (init?.method === "PATCH" || init?.method === "DELETE" || requireRevision) {
    const etag = revisionKey ? resourceEtags.get(revisionKey) : undefined;
    if (etag && !headers.has("If-Match")) headers.set("If-Match", etag);
  }
  return headers;
}

async function request<T>(path: string, init?: RequestInit, revisionKey?: string, requireRevision = false): Promise<T> {
  const headers = requestHeaders(init, revisionKey ?? path, requireRevision);
  const response = await fetch(`${API_BASE}${path}`, {
    ...init,
    headers,
    credentials: "include",
  });
  if (!response.ok) {
    const body = (await response.json().catch(() => null)) as ErrorEnvelope | null;
    if (response.status === 401 && typeof window !== "undefined") {
      window.dispatchEvent(new Event("appstruct:unauthorized"));
    }
    throw new ApiError(
      response.status,
      body?.error.code ?? "HTTP_ERROR",
      body?.error.message ?? `Request failed with status ${response.status}`,
      body?.error.fields,
    );
  }
  const etag = response.headers.get("ETag");
  if (etag && revisionKey) resourceEtags.set(revisionKey, etag);
  if (init?.method === "DELETE") resourceEtags.delete(path);
  if (response.status === 204) return undefined as T;
  return (await response.json()) as T;
}

function cookieValue(name: string): string | undefined {
  return document.cookie
    .split(";")
    .map((part) => part.trim().split("="))
    .find(([candidate]) => candidate === name)?.[1];
}
"#
}

fn list_runtime_source() -> &'static str {
    r#"export type FilterOperator = "eq" | "ne" | "gt" | "gte" | "lt" | "lte" | "in" | "not_in" | "is_null" | "not_null" | "contains" | "starts_with" | "ends_with" | "json_contains" | "json_contained_by" | "json_key";
export type FilterExpression = { all: FilterExpression[] } | { any: FilterExpression[] } | { field: string; op: FilterOperator; values?: string[] };

export interface FilterQuery {
  q?: string;
  filters?: Record<string, string>;
  range_filters?: Record<string, { gte?: string; lte?: string }>;
  where?: FilterExpression;
}

export interface ListQuery extends FilterQuery {
  page?: number;
  page_size?: number;
  sort?: string;
  fields?: string[];
}

export interface CursorListQuery extends FilterQuery {
  cursor?: string;
  limit?: number;
  direction?: "next" | "previous";
  sort?: string;
  fields?: string[];
}

export interface AggregateQuery extends FilterQuery {
  metrics?: string[];
  group_by?: string[];
  limit?: number;
  order?: "asc" | "desc";
  order_by?: "metric" | "group";
  time_bucket?: "day" | "week" | "month";
}

export interface ListResponse<T> {
  data: T[];
  meta: { page: number; page_size: number; total: number };
}

export interface CursorListResponse<T> {
  data: T[];
  meta: { limit: number; next_cursor: string | null; previous_cursor: string | null; has_more: boolean };
}

export interface AggregateRow { [key: string]: unknown; }

export interface AggregateResponse {
  data: AggregateRow[];
  meta: { metrics: string[]; group_by: string[]; limit: number; order: "asc" | "desc"; order_by?: "metric" | "group"; time_bucket?: "day" | "week" | "month" | null };
}

export interface FacetResponse { data: Record<string, { buckets: { value: unknown; count: number }[]; other_count: number }>; }
export interface FacetQuery extends FilterQuery { facet: string[]; limit?: number; }

function facetPath(path: string, query: FacetQuery): string {
  const params = new URLSearchParams();
  params.set("facet", query.facet.join(","));
  if (query.limit) params.set("limit", String(query.limit));
  appendFilterParams(params, query);
  return `${path}?${params}`;
}

function listPath(path: string, query: ListQuery | CursorListQuery): string {
  const params = new URLSearchParams();
  if ("page" in query && query.page) params.set("page", String(query.page));
  if ("page_size" in query && query.page_size) params.set("page_size", String(query.page_size));
  if ("sort" in query && query.sort) params.set("sort", query.sort);
  if ("cursor" in query && query.cursor) params.set("cursor", query.cursor);
  if ("limit" in query && query.limit) params.set("limit", String(query.limit));
  if ("direction" in query && query.direction) params.set("direction", query.direction);
  if (query.fields?.length) params.set("fields", query.fields.join(","));
  appendFilterParams(params, query);
  const search = params.toString();
  return search ? `${path}?${search}` : path;
}

function aggregatePath(path: string, query: AggregateQuery): string {
  const params = new URLSearchParams();
  if (query.metrics?.length) params.set("metrics", query.metrics.join(","));
  if (query.group_by?.length) params.set("group_by", query.group_by.join(","));
  if (query.limit) params.set("limit", String(query.limit));
  if (query.order) params.set("order", query.order);
  if (query.order_by) params.set("order_by", query.order_by);
  if (query.time_bucket) params.set("time_bucket", query.time_bucket);
  appendFilterParams(params, query);
  const search = params.toString();
  return search ? `${path}?${search}` : path;
}

function appendFilterParams(params: URLSearchParams, query: FilterQuery): void {
  if (query.q) params.set("q", query.q);
  if (query.where) params.set("where", JSON.stringify(query.where));
  for (const [key, value] of Object.entries(query.filters ?? {})) {
    if (value !== "") params.set(`filter[${key}]`, value);
  }
  for (const [key, range] of Object.entries(query.range_filters ?? {})) {
    if (range.gte) params.set(`filter[${key}][gte]`, range.gte);
    if (range.lte) params.set(`filter[${key}][lte]`, range.lte);
  }
}
"#
}

fn entity_types(entity: &EntityIr) -> String {
    let model_fields = entity
        .fields
        .iter()
        .map(|field| {
            let marker = if field.read_access.is_some() { "?" } else { "" };
            format!("  {}{marker}: {};", field.rust_name, model_type(field))
        })
        .collect::<Vec<_>>()
        .join("\n");
    let create_fields = entity
        .fields
        .iter()
        .filter(|field| field.generated.is_none() && !entity.is_workflow_field(field))
        .map(|field| input_property(field, false))
        .collect::<Vec<_>>()
        .join("\n");
    let update_fields = entity
        .fields
        .iter()
        .filter(|field| {
            !field.primary_key && field.generated.is_none() && !entity.is_workflow_field(field)
        })
        .map(|field| input_property(field, true))
        .collect::<Vec<_>>()
        .join("\n");
    let workflow = entity
        .workflow
        .as_ref()
        .map_or_else(String::new, |workflow| {
            let names = workflow
                .transitions
                .iter()
                .map(|transition| format!("{:?}", transition.name))
                .collect::<Vec<_>>()
                .join(" | ");
            format!(
                "\nexport type {}WorkflowTransition = {names};\n",
                entity.rust_name,
            )
        });
    format!(
        "export interface {} {{\n{model_fields}\n}}\n\nexport interface Create{}Input {{\n{create_fields}\n}}\n\nexport interface Update{}Input {{\n{update_fields}\n}}\n{workflow}",
        entity.rust_name, entity.rust_name, entity.rust_name
    )
}

fn input_property(field: &FieldIr, update: bool) -> String {
    let optional =
        update || field.nullable || field.default.is_some() || field.write_access.is_some();
    let marker = if optional { "?" } else { "" };
    let nullable = if field.nullable { " | null" } else { "" };
    format!(
        "  {}{marker}: {}{nullable};",
        field.rust_name,
        base_type(&field.ty)
    )
}

fn model_type(field: &FieldIr) -> String {
    if matches!(field.generated, Some(GeneratedValueIr::Revision)) {
        return "number".to_owned();
    }
    let nullable = if field.nullable { " | null" } else { "" };
    format!("{}{nullable}", base_type(&field.ty))
}

fn base_type(field_type: &FieldTypeIr) -> &'static str {
    match field_type {
        FieldTypeIr::Integer => "number",
        FieldTypeIr::Boolean => "boolean",
        FieldTypeIr::Json => "unknown",
        FieldTypeIr::Uuid
        | FieldTypeIr::Bigint
        | FieldTypeIr::String
        | FieldTypeIr::Text
        | FieldTypeIr::Decimal
        | FieldTypeIr::Date
        | FieldTypeIr::Datetime
        | FieldTypeIr::Enum { .. }
        | FieldTypeIr::Relation { .. } => "string",
    }
}

fn lower_camel(value: &str) -> String {
    let mut characters = value.chars();
    characters.next().map_or_else(String::new, |first| {
        first.to_lowercase().chain(characters).collect()
    })
}

fn kebab_name(value: &str) -> String {
    let mut output = String::new();
    for (index, character) in value.chars().enumerate() {
        if character.is_ascii_uppercase() {
            if index > 0 {
                output.push('-');
            }
            output.push(character.to_ascii_lowercase());
        } else {
            output.push(character);
        }
    }
    output
}