forge-codegen 0.10.0

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

mod api;
mod reactive;
mod stores;
mod types;

use std::path::PathBuf;

use forge_core::schema::{FunctionKind, SchemaRegistry};

use crate::binding::BindingSet;

/// Runes content shared between schema-aware and stub generation paths.
pub const RUNES_SVELTE_TS: &str = r#"// @generated by FORGE - DO NOT EDIT
import type { SubscriptionStore, ForgeError } from "@forge-rs/svelte";
import type { SubscriptionResult } from "@forge-rs/svelte";
import { ForgeClientError } from "@forge-rs/svelte";

export interface ReactiveQuery<T> extends SubscriptionResult<T> {
  unsubscribe: () => void;
}

export function toReactive<T>(store: SubscriptionStore<T>): ReactiveQuery<T> {
  const state: ReactiveQuery<T> = $state({
    loading: true,
    data: null,
    error: null,
    stale: false,
    unsubscribe: () => {},
  });

  $effect(() => {
    const unsubCallback = store.subscribe((s) => {
      state.loading = s.loading;
      state.data = s.data;
      state.error = s.error;
      state.stale = s.stale;
    });

    const cleanup = () => {
      unsubCallback();
      store.unsubscribe();
    };

    state.unsubscribe = cleanup;
    return cleanup;
  });

  return state;
}

export interface ReactiveMutation<TArgs, TResult> {
  mutate: (args: TArgs) => Promise<TResult>;
  pending: boolean;
  error: ForgeError | null;
}

export function toReactiveMutation<TArgs, TResult>(
  fn: (args: TArgs) => Promise<TResult>,
): ReactiveMutation<TArgs, TResult> {
  const state: ReactiveMutation<TArgs, TResult> = $state({
    mutate: async (args: TArgs) => {
      state.pending = true;
      state.error = null;
      try {
        return await fn(args);
      } catch (e) {
        const err =
          e instanceof ForgeClientError
            ? e
            : new ForgeClientError("UNKNOWN", String(e));
        state.error = err;
        throw e;
      } finally {
        state.pending = false;
      }
    },
    pending: false,
    error: null,
  });
  return state;
}
"#;

/// Options for TypeScript code generation.
#[derive(Debug, Clone, Default)]
pub struct GenerateOptions {
    pub generate_auth_store: bool,
}

pub struct TypeScriptGenerator {
    output_dir: PathBuf,
    options: GenerateOptions,
}

impl TypeScriptGenerator {
    pub fn new(output_dir: impl Into<PathBuf>) -> Self {
        Self {
            output_dir: output_dir.into(),
            options: GenerateOptions::default(),
        }
    }

    pub fn with_options(output_dir: impl Into<PathBuf>, options: GenerateOptions) -> Self {
        Self {
            output_dir: output_dir.into(),
            options,
        }
    }

    pub fn generate(&self, registry: &SchemaRegistry) -> Result<(), Error> {
        std::fs::create_dir_all(&self.output_dir)?;

        let bindings = BindingSet::from_registry(registry);

        // Collect referenced types so types.ts can emit built-ins not in the schema.
        let mut referenced_types = Vec::new();
        for binding in bindings.all() {
            for arg in &binding.args {
                crate::emit::collect_type_imports(&arg.rust_type, &mut referenced_types);
            }
            crate::emit::collect_type_imports(&binding.return_type, &mut referenced_types);
        }
        referenced_types.sort();
        referenced_types.dedup();

        std::fs::write(
            self.output_dir.join("types.ts"),
            types::generate(registry, &referenced_types)?,
        )?;
        std::fs::write(self.output_dir.join("api.ts"), api::generate(&bindings)?)?;
        std::fs::write(
            self.output_dir.join("runes.svelte.ts"),
            Self::runes_content(),
        )?;

        let reactive_content = reactive::generate(&bindings)?;
        if !reactive_content.is_empty() {
            std::fs::write(self.output_dir.join("reactive.svelte.ts"), reactive_content)?;
        }

        std::fs::write(self.output_dir.join("stores.ts"), stores::generate()?)?;

        if self.options.generate_auth_store {
            std::fs::write(self.output_dir.join("auth.svelte.ts"), Self::auth_content())?;
        }

        std::fs::write(
            self.output_dir.join("index.ts"),
            self.generate_index(registry),
        )?;

        Ok(())
    }

    fn runes_content() -> &'static str {
        RUNES_SVELTE_TS
    }

    fn auth_content() -> &'static str {
        r#"// @generated by FORGE - DO NOT EDIT
// Auth store for Svelte 5 with localStorage persistence and refresh token support
import { getForgeClient } from "@forge-rs/svelte";

interface User {
  id: string;
  email: string;
  name?: string;
}

interface AuthState {
  token: string | null;
  refreshToken: string | null;
  user: User | null;
}

const AUTH_KEY = "forge_auth";

function loadFromStorage(): AuthState {
  if (typeof localStorage === "undefined") {
    return { token: null, refreshToken: null, user: null };
  }
  const stored = localStorage.getItem(AUTH_KEY);
  if (!stored) {
    return { token: null, refreshToken: null, user: null };
  }
  try {
    return JSON.parse(stored);
  } catch {
    return { token: null, refreshToken: null, user: null };
  }
}

function saveToStorage(state: AuthState): void {
  if (typeof localStorage === "undefined") return;
  if (state.token) {
    localStorage.setItem(AUTH_KEY, JSON.stringify(state));
  } else {
    localStorage.removeItem(AUTH_KEY);
  }
}

class AuthStore {
  #state: AuthState = $state(loadFromStorage());
  #refreshInterval: ReturnType<typeof setInterval> | null = null;
  #apiUrl: string = "";

  get token(): string | null {
    return this.#state.token;
  }

  get refreshToken(): string | null {
    return this.#state.refreshToken;
  }

  get user(): User | null {
    return this.#state.user;
  }

  get isAuthenticated(): boolean {
    return this.#state.token !== null;
  }

  /** Initialize periodic refresh. Call once from your root layout. */
  startRefreshLoop(apiUrl: string, intervalMs = 40 * 60 * 1000): void {
    this.#apiUrl = apiUrl;
    this.stopRefreshLoop();
    this.#refreshInterval = setInterval(() => {
      if (this.isAuthenticated) {
        this.tryRefresh();
      }
    }, intervalMs);
  }

  stopRefreshLoop(): void {
    if (this.#refreshInterval) {
      clearInterval(this.#refreshInterval);
      this.#refreshInterval = null;
    }
  }

  setAuth(token: string, refreshToken: string, user: User): void {
    this.#state = { token, refreshToken, user };
    saveToStorage(this.#state);
    getForgeClient()?.reconnect();
  }

  updateTokens(token: string, refreshToken: string): void {
    this.#state = { ...this.#state, token, refreshToken };
    saveToStorage(this.#state);
  }

  updateUser(user: User): void {
    this.#state = { ...this.#state, user };
    saveToStorage(this.#state);
  }

  clearAuth(): void {
    this.#state = { token: null, refreshToken: null, user: null };
    saveToStorage(this.#state);
    this.stopRefreshLoop();
    getForgeClient()?.reconnect();
  }

  /** Attempt to refresh tokens using the backend refresh mutation.
   *  Only clears auth on definitive failures (401/403). Network errors
   *  are silently ignored so transient issues don't force logouts. */
  async tryRefresh(): Promise<boolean> {
    if (!this.#state.refreshToken || !this.#apiUrl) return false;
    try {
      const res = await fetch(`${this.#apiUrl}/_api/rpc/refresh`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ args: { refresh_token: this.#state.refreshToken } }),
      });
      if (!res.ok) {
        if (res.status === 401 || res.status === 403) {
          this.clearAuth();
        }
        return false;
      }
      const envelope = await res.json();
      if (envelope.success && envelope.data) {
        this.updateTokens(envelope.data.access_token, envelope.data.refresh_token);
        return true;
      }
      this.clearAuth();
      return false;
    } catch {
      // Network error - keep tokens and retry later
      return false;
    }
  }

  #refreshPromise: Promise<boolean> | null = null;

  /** Call from ForgeProvider's onAuthError callback.
   *  Coalesces concurrent calls so multiple 401s don't race. */
  async handleAuthError(): Promise<void> {
    if (!this.isAuthenticated) return;
    if (!this.#refreshPromise) {
      this.#refreshPromise = this.tryRefresh().finally(() => {
        this.#refreshPromise = null;
      });
    }
    const ok = await this.#refreshPromise;
    if (!ok) this.clearAuth();
  }
}

export const auth = new AuthStore();

export function getToken(): string | null {
  return auth.token;
}
"#
    }

    fn generate_index(&self, registry: &SchemaRegistry) -> String {
        let has_queries = registry
            .all_functions()
            .iter()
            .any(|f| matches!(f.kind, FunctionKind::Query));

        let mut output = String::from("// @generated by FORGE - DO NOT EDIT\n");
        output.push_str("export * from './types';\n");
        output.push_str("export * from './api';\n");
        output.push_str("export * from './stores';\n");
        output.push_str("export * from './runes.svelte';\n");
        if has_queries {
            output.push_str("export * from './reactive.svelte';\n");
        }
        if self.options.generate_auth_store {
            output.push_str("export * from './auth.svelte';\n");
        }
        output.push_str(
            "export { ForgeClient, ForgeClientError, createForgeClient, ForgeProvider } from '@forge-rs/svelte';\n",
        );
        output
    }

    pub fn output_dir(&self) -> &PathBuf {
        &self.output_dir
    }
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("Parse error in {file}: {message}")]
    Parse { file: String, message: String },

    #[error("Generation error: {0}")]
    Generation(String),
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
mod tests {
    use super::*;
    use forge_core::schema::{FunctionDef, RustType};

    #[test]
    fn with_options_stores_auth_flag() {
        let opts = GenerateOptions {
            generate_auth_store: true,
        };
        let g = TypeScriptGenerator::with_options("/tmp/forge", opts);
        assert!(g.options.generate_auth_store);
    }

    #[test]
    fn default_options_disables_auth_store() {
        let g = TypeScriptGenerator::new("/tmp/forge");
        assert!(!g.options.generate_auth_store);
    }

    #[test]
    fn test_generate_index() {
        let generator = TypeScriptGenerator::new("/tmp/forge");
        let registry = SchemaRegistry::new();
        let index = generator.generate_index(&registry);
        assert!(index.contains("'./types'"));
        assert!(index.contains("'./api'"));
        assert!(index.contains("'./stores'"));
        assert!(index.contains("'./runes.svelte'"));
        assert!(index.contains("ForgeClient"));
        assert!(index.contains("createForgeClient"));
        assert!(index.contains("ForgeProvider"));
    }

    #[test]
    fn generate_index_emits_reactive_only_when_a_query_exists() {
        let generator = TypeScriptGenerator::new("/tmp/forge");
        let registry = SchemaRegistry::new();
        registry.register_function(FunctionDef::query("list_users", RustType::String));
        let index = generator.generate_index(&registry);
        assert!(
            index.contains("'./reactive.svelte'"),
            "queries must trigger reactive export"
        );
    }

    #[test]
    fn generate_index_skips_reactive_when_only_mutations_present() {
        let generator = TypeScriptGenerator::new("/tmp/forge");
        let registry = SchemaRegistry::new();
        registry.register_function(FunctionDef::mutation("create_user", RustType::String));
        let index = generator.generate_index(&registry);
        assert!(
            !index.contains("'./reactive.svelte'"),
            "no queries => no reactive export"
        );
    }

    #[test]
    fn generate_index_emits_auth_only_when_flag_set() {
        let registry = SchemaRegistry::new();

        let off = TypeScriptGenerator::new("/tmp/forge");
        assert!(!off.generate_index(&registry).contains("'./auth.svelte'"));

        let on = TypeScriptGenerator::with_options(
            "/tmp/forge",
            GenerateOptions {
                generate_auth_store: true,
            },
        );
        assert!(on.generate_index(&registry).contains("'./auth.svelte'"));
    }

    #[test]
    fn runes_content_is_the_published_constant() {
        // The static method must return the same bytes as the public constant.
        assert_eq!(TypeScriptGenerator::runes_content(), RUNES_SVELTE_TS);
    }

    #[test]
    fn runes_constant_exports_expected_helpers() {
        assert!(RUNES_SVELTE_TS.contains("export function toReactive<"));
        assert!(RUNES_SVELTE_TS.contains("export function toReactiveMutation<"));
        assert!(RUNES_SVELTE_TS.contains("@generated by FORGE"));
    }

    #[test]
    fn auth_content_exports_singleton_and_helpers() {
        let body = TypeScriptGenerator::auth_content();
        assert!(body.contains("export const auth = new AuthStore();"));
        assert!(body.contains("export function getToken("));
        assert!(body.contains("@generated by FORGE"));
    }

    #[test]
    fn error_display_includes_underlying_message() {
        let io = Error::Io(std::io::Error::other("disk full"));
        assert!(io.to_string().contains("disk full"));

        let parse = Error::Parse {
            file: "users.rs".into(),
            message: "bad token".into(),
        };
        let s = parse.to_string();
        assert!(s.contains("users.rs"));
        assert!(s.contains("bad token"));

        let gen_err = Error::Generation("schema empty".into());
        assert!(gen_err.to_string().contains("schema empty"));
    }
}