tthr 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,653 @@
1
+ // src/commands/generate.ts
2
+ import chalk2 from "chalk";
3
+ import ora from "ora";
4
+ import fs3 from "fs-extra";
5
+ import path3 from "path";
6
+
7
+ // src/utils/auth.ts
8
+ import chalk from "chalk";
9
+ import fs from "fs-extra";
10
+ import path from "path";
11
+ var CONFIG_DIR = path.join(process.env.HOME || process.env.USERPROFILE || "", ".tether");
12
+ var CREDENTIALS_FILE = path.join(CONFIG_DIR, "credentials.json");
13
+ var isDev = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
14
+ var API_URL = isDev ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
15
+ var REFRESH_THRESHOLD_DAYS = 7;
16
+ async function getCredentials() {
17
+ try {
18
+ if (await fs.pathExists(CREDENTIALS_FILE)) {
19
+ return await fs.readJSON(CREDENTIALS_FILE);
20
+ }
21
+ } catch {
22
+ }
23
+ return null;
24
+ }
25
+ async function refreshSession(credentials) {
26
+ try {
27
+ const response = await fetch(`${API_URL}/auth/session/refresh`, {
28
+ method: "POST",
29
+ headers: {
30
+ "Content-Type": "application/json",
31
+ "Authorization": `Bearer ${credentials.accessToken}`
32
+ }
33
+ });
34
+ if (!response.ok) {
35
+ return null;
36
+ }
37
+ const data = await response.json();
38
+ const updated = {
39
+ ...credentials,
40
+ expiresAt: data.expiresAt
41
+ };
42
+ await saveCredentials(updated);
43
+ return updated;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+ async function requireAuth() {
49
+ const credentials = await getCredentials();
50
+ if (!credentials) {
51
+ console.error(chalk.red("\n\u2717 Not logged in\n"));
52
+ console.log(chalk.dim("Run `tthr login` to authenticate\n"));
53
+ process.exit(1);
54
+ }
55
+ if (credentials.expiresAt) {
56
+ const expiresAt = new Date(credentials.expiresAt);
57
+ const now = /* @__PURE__ */ new Date();
58
+ if (now > expiresAt) {
59
+ await clearCredentials();
60
+ console.error(chalk.red("\n\u2717 Session expired \u2014 you have been signed out\n"));
61
+ console.log(chalk.dim("Run `tthr login` to authenticate\n"));
62
+ process.exit(1);
63
+ }
64
+ const daysUntilExpiry = (expiresAt.getTime() - now.getTime()) / (1e3 * 60 * 60 * 24);
65
+ if (daysUntilExpiry <= REFRESH_THRESHOLD_DAYS) {
66
+ const refreshed = await refreshSession(credentials);
67
+ if (refreshed) {
68
+ return refreshed;
69
+ }
70
+ }
71
+ }
72
+ return credentials;
73
+ }
74
+ async function saveCredentials(credentials) {
75
+ await fs.ensureDir(CONFIG_DIR);
76
+ await fs.writeJSON(CREDENTIALS_FILE, credentials, { spaces: 2, mode: 384 });
77
+ }
78
+ async function clearCredentials() {
79
+ try {
80
+ await fs.remove(CREDENTIALS_FILE);
81
+ } catch {
82
+ }
83
+ }
84
+
85
+ // src/utils/config.ts
86
+ import fs2 from "fs-extra";
87
+ import path2 from "path";
88
+ var DEFAULT_CONFIG = {
89
+ schema: "./tether/schema.ts",
90
+ functions: "./tether/functions",
91
+ output: "./tether/_generated",
92
+ dev: {
93
+ port: 3001,
94
+ host: "localhost"
95
+ },
96
+ database: {
97
+ walMode: true
98
+ }
99
+ };
100
+ async function loadConfig(cwd = process.cwd()) {
101
+ const configPath = path2.resolve(cwd, "tether.config.ts");
102
+ if (!await fs2.pathExists(configPath)) {
103
+ return DEFAULT_CONFIG;
104
+ }
105
+ const configSource = await fs2.readFile(configPath, "utf-8");
106
+ const config = {};
107
+ const schemaMatch = configSource.match(/schema\s*:\s*['"]([^'"]+)['"]/);
108
+ if (schemaMatch) {
109
+ config.schema = schemaMatch[1];
110
+ }
111
+ const functionsMatch = configSource.match(/functions\s*:\s*['"]([^'"]+)['"]/);
112
+ if (functionsMatch) {
113
+ config.functions = functionsMatch[1];
114
+ }
115
+ const outputMatch = configSource.match(/output\s*:\s*['"]([^'"]+)['"]/);
116
+ if (outputMatch) {
117
+ config.output = outputMatch[1];
118
+ }
119
+ const envMatch = configSource.match(/environment\s*:\s*['"]([^'"]+)['"]/);
120
+ if (envMatch) {
121
+ config.environment = envMatch[1];
122
+ }
123
+ const portMatch = configSource.match(/port\s*:\s*(\d+)/);
124
+ if (portMatch) {
125
+ config.dev = { ...config.dev, port: parseInt(portMatch[1], 10) };
126
+ }
127
+ const hostMatch = configSource.match(/host\s*:\s*['"]([^'"]+)['"]/);
128
+ if (hostMatch) {
129
+ config.dev = { ...config.dev, host: hostMatch[1] };
130
+ }
131
+ return {
132
+ ...DEFAULT_CONFIG,
133
+ ...config,
134
+ dev: { ...DEFAULT_CONFIG.dev, ...config.dev },
135
+ database: { ...DEFAULT_CONFIG.database, ...config.database }
136
+ };
137
+ }
138
+ function resolvePath(configPath, cwd = process.cwd()) {
139
+ const normalised = configPath.replace(/^\.\//, "");
140
+ return path2.resolve(cwd, normalised);
141
+ }
142
+ async function detectFramework(cwd = process.cwd()) {
143
+ const packageJsonPath = path2.resolve(cwd, "package.json");
144
+ if (!await fs2.pathExists(packageJsonPath)) {
145
+ return "unknown";
146
+ }
147
+ try {
148
+ const packageJson = await fs2.readJson(packageJsonPath);
149
+ const deps = {
150
+ ...packageJson.dependencies,
151
+ ...packageJson.devDependencies
152
+ };
153
+ if (deps.nuxt || deps["@nuxt/kit"]) {
154
+ return "nuxt";
155
+ }
156
+ if (deps.next) {
157
+ return "next";
158
+ }
159
+ if (deps["@sveltejs/kit"]) {
160
+ return "sveltekit";
161
+ }
162
+ if (deps.vite && !deps.nuxt && !deps.next && !deps["@sveltejs/kit"]) {
163
+ return "vite";
164
+ }
165
+ return "vanilla";
166
+ } catch {
167
+ return "unknown";
168
+ }
169
+ }
170
+ function getFrameworkDevCommand(framework) {
171
+ switch (framework) {
172
+ case "nuxt":
173
+ return "nuxt dev";
174
+ case "next":
175
+ return "next dev";
176
+ case "sveltekit":
177
+ return "vite dev";
178
+ case "vite":
179
+ return "vite dev";
180
+ case "vanilla":
181
+ return null;
182
+ // No default dev server for vanilla
183
+ default:
184
+ return null;
185
+ }
186
+ }
187
+
188
+ // src/commands/generate.ts
189
+ var isDev2 = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
190
+ var API_URL2 = isDev2 ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
191
+ function parseSchemaFile(source) {
192
+ const tables = [];
193
+ const schemaMatch = source.match(/defineSchema\s*\(\s*\{([\s\S]*)\}\s*\)/);
194
+ if (!schemaMatch) return tables;
195
+ const schemaContent = schemaMatch[1];
196
+ const tableStartRegex = /(\w+)\s*:\s*\{/g;
197
+ let match;
198
+ while ((match = tableStartRegex.exec(schemaContent)) !== null) {
199
+ const tableName = match[1];
200
+ const startOffset = match.index + match[0].length;
201
+ let braceCount = 1;
202
+ let endOffset = startOffset;
203
+ for (let i = startOffset; i < schemaContent.length && braceCount > 0; i++) {
204
+ const char = schemaContent[i];
205
+ if (char === "{") braceCount++;
206
+ else if (char === "}") braceCount--;
207
+ endOffset = i;
208
+ }
209
+ const columnsContent = schemaContent.slice(startOffset, endOffset);
210
+ const columns = parseColumns(columnsContent);
211
+ tables.push({ name: tableName, columns });
212
+ }
213
+ return tables;
214
+ }
215
+ function parseColumns(content) {
216
+ const columns = [];
217
+ const columnRegex = /(\w+)\s*:\s*(\w+)(?:<([^>]+)>)?\s*\(\s*\)((?:\[.*?\]|[^,\n}])*)/g;
218
+ let match;
219
+ while ((match = columnRegex.exec(content)) !== null) {
220
+ const name = match[1];
221
+ const schemaType = match[2];
222
+ const genericType = match[3];
223
+ const modifiers = match[4] || "";
224
+ const nullable = !modifiers.includes(".notNull()");
225
+ const oneOfMatch = modifiers.match(/\.oneOf\s*\(\s*\[(.*?)\]\s*\)/);
226
+ let oneOf;
227
+ if (oneOfMatch) {
228
+ oneOf = [...oneOfMatch[1].matchAll(/['"]([^'"]+)['"]/g)].map((m) => m[1]);
229
+ }
230
+ columns.push({
231
+ name,
232
+ type: schemaTypeToTS(schemaType),
233
+ nullable,
234
+ jsonType: genericType,
235
+ // Store the generic type for json columns
236
+ oneOf
237
+ });
238
+ }
239
+ return columns;
240
+ }
241
+ function schemaTypeToTS(schemaType) {
242
+ switch (schemaType) {
243
+ case "text":
244
+ return "string";
245
+ case "integer":
246
+ return "number";
247
+ case "real":
248
+ return "number";
249
+ case "boolean":
250
+ return "boolean";
251
+ case "timestamp":
252
+ return "string";
253
+ case "json":
254
+ return "unknown";
255
+ case "blob":
256
+ return "Uint8Array";
257
+ case "asset":
258
+ return "TetherAsset";
259
+ // Asset object returned by API
260
+ default:
261
+ return "unknown";
262
+ }
263
+ }
264
+ function extractTypeDefinitions(source, typeNames) {
265
+ if (typeNames.size === 0) return [];
266
+ const blocks = [];
267
+ for (const typeName of typeNames) {
268
+ const interfaceStart = new RegExp(`export\\s+interface\\s+${typeName}\\s*\\{`);
269
+ const interfaceMatch = interfaceStart.exec(source);
270
+ if (interfaceMatch) {
271
+ const startIdx = interfaceMatch.index;
272
+ const braceStart = startIdx + interfaceMatch[0].length;
273
+ let braceCount = 1;
274
+ let endIdx = braceStart;
275
+ for (let i = braceStart; i < source.length && braceCount > 0; i++) {
276
+ if (source[i] === "{") braceCount++;
277
+ else if (source[i] === "}") braceCount--;
278
+ endIdx = i;
279
+ }
280
+ blocks.push(source.slice(startIdx, endIdx + 1));
281
+ continue;
282
+ }
283
+ const typeStart = new RegExp(`export\\s+type\\s+${typeName}\\s*=`);
284
+ const typeMatch = typeStart.exec(source);
285
+ if (typeMatch) {
286
+ const startIdx = typeMatch.index;
287
+ const semiIdx = source.indexOf(";", startIdx);
288
+ if (semiIdx !== -1) {
289
+ blocks.push(source.slice(startIdx, semiIdx + 1));
290
+ }
291
+ }
292
+ }
293
+ return blocks;
294
+ }
295
+ function tableNameToInterface(tableName) {
296
+ let name = tableName;
297
+ if (name.endsWith("ies")) {
298
+ name = name.slice(0, -3) + "y";
299
+ } else if (name.endsWith("s") && !name.endsWith("ss")) {
300
+ name = name.slice(0, -1);
301
+ }
302
+ return name.charAt(0).toUpperCase() + name.slice(1);
303
+ }
304
+ function generateDbFile(tables, schemaSource) {
305
+ const TS_PRIMITIVES = /* @__PURE__ */ new Set(["number", "string", "boolean", "unknown", "any", "void", "never", "undefined", "null", "object"]);
306
+ const jsonTypes = /* @__PURE__ */ new Set();
307
+ for (const table of tables) {
308
+ for (const col of table.columns) {
309
+ if (col.jsonType) {
310
+ const baseType = col.jsonType.replace(/\[\]$/, "").replace(/\s*\|\s*null$/, "").trim();
311
+ if (!TS_PRIMITIVES.has(baseType)) {
312
+ jsonTypes.add(baseType);
313
+ }
314
+ }
315
+ }
316
+ }
317
+ const lines = [
318
+ "// Auto-generated by Tether CLI - do not edit manually",
319
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
320
+ "",
321
+ "import { createDatabaseProxy, type TetherDatabase } from '@tthr/client';",
322
+ "import {",
323
+ " type QueryDefinition,",
324
+ " type MutationDefinition,",
325
+ " z,",
326
+ "} from '@tthr/server';",
327
+ "import type { TetherEnv } from './env';"
328
+ ];
329
+ if (jsonTypes.size > 0) {
330
+ const typeBlocks = extractTypeDefinitions(schemaSource, jsonTypes);
331
+ if (typeBlocks.length > 0) {
332
+ lines.push("");
333
+ lines.push("// Schema types (inlined from schema.ts)");
334
+ for (const block of typeBlocks) {
335
+ lines.push(block);
336
+ lines.push("");
337
+ }
338
+ }
339
+ }
340
+ lines.push("");
341
+ lines.push("// Asset type returned by the API for asset columns");
342
+ lines.push("export interface TetherAsset {");
343
+ lines.push(" id: string;");
344
+ lines.push(" filename: string;");
345
+ lines.push(" contentType: string;");
346
+ lines.push(" size: number;");
347
+ lines.push(" url: string;");
348
+ lines.push(" createdAt: string;");
349
+ lines.push("}");
350
+ lines.push("");
351
+ for (const table of tables) {
352
+ const interfaceName = tableNameToInterface(table.name);
353
+ lines.push(`export interface ${interfaceName} {`);
354
+ lines.push(" _id: string;");
355
+ for (const col of table.columns) {
356
+ let colType;
357
+ if (col.oneOf && col.oneOf.length > 0) {
358
+ colType = col.oneOf.map((v) => `'${v}'`).join(" | ");
359
+ } else {
360
+ colType = col.jsonType || col.type;
361
+ }
362
+ const typeStr = col.nullable ? `${colType} | null` : colType;
363
+ const optional = col.nullable ? "?" : "";
364
+ lines.push(` ${col.name}${optional}: ${typeStr};`);
365
+ }
366
+ lines.push(" _createdAt: string;");
367
+ lines.push(" _updatedAt?: string | null;");
368
+ lines.push(" _deletedAt?: string | null;");
369
+ lines.push("}");
370
+ lines.push("");
371
+ }
372
+ lines.push("export interface Schema {");
373
+ for (const table of tables) {
374
+ const interfaceName = tableNameToInterface(table.name);
375
+ lines.push(` ${table.name}: ${interfaceName};`);
376
+ }
377
+ lines.push("}");
378
+ lines.push("");
379
+ lines.push("// Database client with typed tables");
380
+ lines.push("// This is a proxy that will be populated by the Tether runtime");
381
+ lines.push("export const db: TetherDatabase<Schema> = createDatabaseProxy<Schema>();");
382
+ lines.push("");
383
+ lines.push("// ============================================================================");
384
+ lines.push("// Typed function wrappers - use these instead of importing from @tthr/server");
385
+ lines.push("// This ensures the `db` and `env` parameters in handlers are properly typed");
386
+ lines.push("// ============================================================================");
387
+ lines.push("");
388
+ lines.push("/**");
389
+ lines.push(" * Define a query function with typed database and environment variable access.");
390
+ lines.push(" * The `db` and `env` parameters in the handler will have full type safety.");
391
+ lines.push(" */");
392
+ lines.push("export function query<TArgs = void, TResult = unknown>(");
393
+ lines.push(" definition: QueryDefinition<TArgs, TResult, Schema, TetherEnv>");
394
+ lines.push("): QueryDefinition<TArgs, TResult, Schema, TetherEnv> {");
395
+ lines.push(" return definition;");
396
+ lines.push("}");
397
+ lines.push("");
398
+ lines.push("/**");
399
+ lines.push(" * Define a mutation function with typed database and environment variable access.");
400
+ lines.push(" * The `db` and `env` parameters in the handler will have full type safety.");
401
+ lines.push(" */");
402
+ lines.push("export function mutation<TArgs = void, TResult = unknown>(");
403
+ lines.push(" definition: MutationDefinition<TArgs, TResult, Schema, TetherEnv>");
404
+ lines.push("): MutationDefinition<TArgs, TResult, Schema, TetherEnv> {");
405
+ lines.push(" return definition;");
406
+ lines.push("}");
407
+ lines.push("");
408
+ lines.push("// Re-export z for convenience");
409
+ lines.push("export { z };");
410
+ if (jsonTypes.size > 0) {
411
+ lines.push("");
412
+ lines.push("// Re-export JSON schema types");
413
+ const typeExports = Array.from(jsonTypes).sort().join(", ");
414
+ lines.push(`export type { ${typeExports} };`);
415
+ }
416
+ lines.push("");
417
+ return lines.join("\n");
418
+ }
419
+ async function parseFunctionsDir(functionsDir) {
420
+ const functions = [];
421
+ if (!await fs3.pathExists(functionsDir)) {
422
+ return functions;
423
+ }
424
+ const files = await fs3.readdir(functionsDir);
425
+ for (const file of files) {
426
+ if (!file.endsWith(".ts") && !file.endsWith(".js")) continue;
427
+ const filePath = path3.join(functionsDir, file);
428
+ const stat = await fs3.stat(filePath);
429
+ if (!stat.isFile()) continue;
430
+ const moduleName = file.replace(/\.(ts|js)$/, "");
431
+ const source = await fs3.readFile(filePath, "utf-8");
432
+ const exportRegex = /export\s+const\s+(\w+)\s*=\s*(query|mutation)\s*\(/g;
433
+ let match;
434
+ while ((match = exportRegex.exec(source)) !== null) {
435
+ functions.push({
436
+ name: match[1],
437
+ moduleName
438
+ });
439
+ }
440
+ }
441
+ return functions;
442
+ }
443
+ async function generateApiFile(functionsDir) {
444
+ const functions = await parseFunctionsDir(functionsDir);
445
+ const moduleMap = /* @__PURE__ */ new Map();
446
+ for (const fn of functions) {
447
+ if (!moduleMap.has(fn.moduleName)) {
448
+ moduleMap.set(fn.moduleName, []);
449
+ }
450
+ moduleMap.get(fn.moduleName).push(fn.name);
451
+ }
452
+ const lines = [
453
+ "// Auto-generated by Tether CLI - do not edit manually",
454
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
455
+ "",
456
+ "import { createApiProxy } from '@tthr/client';",
457
+ "",
458
+ "/**",
459
+ " * API function reference type for useQuery/useMutation.",
460
+ ' * The _name property contains the function path (e.g., "users.list").',
461
+ " */",
462
+ "export interface ApiFunction<TArgs = unknown, TResult = unknown> {",
463
+ " _name: string;",
464
+ " _args?: TArgs;",
465
+ " _result?: TResult;",
466
+ "}",
467
+ ""
468
+ ];
469
+ if (moduleMap.size > 0) {
470
+ for (const [moduleName, fnNames] of moduleMap) {
471
+ const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
472
+ lines.push(`export interface ${interfaceName} {`);
473
+ for (const fnName of fnNames) {
474
+ lines.push(` ${fnName}: ApiFunction;`);
475
+ }
476
+ lines.push("}");
477
+ lines.push("");
478
+ }
479
+ lines.push("export interface Api {");
480
+ for (const moduleName of moduleMap.keys()) {
481
+ const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
482
+ lines.push(` ${moduleName}: ${interfaceName};`);
483
+ }
484
+ lines.push("}");
485
+ } else {
486
+ lines.push("/**");
487
+ lines.push(" * Flexible API type that allows access to any function path.");
488
+ lines.push(" * Functions are accessed as api.moduleName.functionName");
489
+ lines.push(" * The actual types depend on your function definitions.");
490
+ lines.push(" */");
491
+ lines.push("export type Api = {");
492
+ lines.push(" [module: string]: {");
493
+ lines.push(" [fn: string]: ApiFunction;");
494
+ lines.push(" };");
495
+ lines.push("};");
496
+ }
497
+ lines.push("");
498
+ lines.push("// API client proxy - provides typed access to your functions");
499
+ lines.push("// On the client: returns { _name } references for useQuery/useMutation");
500
+ lines.push("// In Tether functions: calls the actual function implementation");
501
+ lines.push("export const api = createApiProxy<Api>();");
502
+ lines.push("");
503
+ return lines.join("\n");
504
+ }
505
+ async function fetchEnvVarKeys(projectId, environment) {
506
+ const credentials = await getCredentials();
507
+ if (!credentials) return [];
508
+ const envPath = environment !== "production" ? `/projects/${projectId}/env/${environment}/env-vars` : `/projects/${projectId}/env-vars`;
509
+ try {
510
+ const response = await fetch(`${API_URL2}${envPath}`, {
511
+ headers: {
512
+ "Authorization": `Bearer ${credentials.accessToken}`
513
+ }
514
+ });
515
+ if (!response.ok) return [];
516
+ const data = await response.json();
517
+ return (data.envVars || []).map((v) => v.key).sort();
518
+ } catch {
519
+ return [];
520
+ }
521
+ }
522
+ function generateEnvFile(keys) {
523
+ const lines = [
524
+ "// Auto-generated by Tether CLI - do not edit manually",
525
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
526
+ "",
527
+ "/**",
528
+ " * Typed environment variables for this project.",
529
+ " * Keys are fetched from the Tether API \u2014 values are never exposed.",
530
+ ' * Use `env.get("KEY")` in your functions to access them.',
531
+ " */",
532
+ ""
533
+ ];
534
+ if (keys.length > 0) {
535
+ lines.push("export type EnvVarKey =");
536
+ for (let i = 0; i < keys.length; i++) {
537
+ const sep = i === keys.length - 1 ? ";" : "";
538
+ lines.push(` | '${keys[i]}'${sep}`);
539
+ }
540
+ lines.push("");
541
+ lines.push("export interface TetherEnv {");
542
+ for (const key of keys) {
543
+ lines.push(` ${key}: string;`);
544
+ }
545
+ lines.push("}");
546
+ } else {
547
+ lines.push("export type EnvVarKey = string;");
548
+ lines.push("");
549
+ lines.push("export interface TetherEnv {");
550
+ lines.push(" [key: string]: string;");
551
+ lines.push("}");
552
+ }
553
+ lines.push("");
554
+ return lines.join("\n");
555
+ }
556
+ async function generateTypes(options = {}) {
557
+ const config = await loadConfig();
558
+ const schemaPath = resolvePath(config.schema);
559
+ const outputDir = resolvePath(config.output);
560
+ const functionsDir = resolvePath(config.functions);
561
+ if (!await fs3.pathExists(schemaPath)) {
562
+ throw new Error(`Schema file not found: ${schemaPath}`);
563
+ }
564
+ const schemaSource = await fs3.readFile(schemaPath, "utf-8");
565
+ const tables = parseSchemaFile(schemaSource);
566
+ const environment = config.environment || "development";
567
+ let projectId;
568
+ const envFilePath = path3.resolve(process.cwd(), ".env");
569
+ if (await fs3.pathExists(envFilePath)) {
570
+ const envContent = await fs3.readFile(envFilePath, "utf-8");
571
+ const match = envContent.match(/TETHER_PROJECT_ID=(.+)/);
572
+ projectId = match?.[1]?.trim();
573
+ }
574
+ const envVarKeys = projectId ? await fetchEnvVarKeys(projectId, environment) : [];
575
+ await fs3.ensureDir(outputDir);
576
+ await fs3.writeFile(
577
+ path3.join(outputDir, "db.ts"),
578
+ generateDbFile(tables, schemaSource)
579
+ );
580
+ await fs3.writeFile(
581
+ path3.join(outputDir, "api.ts"),
582
+ await generateApiFile(functionsDir)
583
+ );
584
+ await fs3.writeFile(
585
+ path3.join(outputDir, "env.ts"),
586
+ generateEnvFile(envVarKeys)
587
+ );
588
+ await fs3.writeFile(
589
+ path3.join(outputDir, "index.ts"),
590
+ `// Auto-generated by Tether CLI - do not edit manually
591
+ export * from './db';
592
+ export * from './api';
593
+ export * from './env';
594
+ `
595
+ );
596
+ return { tables, envVarKeys, outputDir };
597
+ }
598
+ async function generateCommand() {
599
+ await requireAuth();
600
+ const configPath = path3.resolve(process.cwd(), "tether.config.ts");
601
+ if (!await fs3.pathExists(configPath)) {
602
+ console.log(chalk2.red("\nError: Not a Tether project"));
603
+ console.log(chalk2.dim("Run `tthr init` to create a new project\n"));
604
+ process.exit(1);
605
+ }
606
+ console.log(chalk2.bold("\n\u26A1 Generating types from schema\n"));
607
+ const spinner = ora("Reading schema...").start();
608
+ try {
609
+ spinner.text = "Generating types...";
610
+ const { tables, envVarKeys, outputDir } = await generateTypes();
611
+ if (tables.length === 0) {
612
+ spinner.warn("No tables found in schema");
613
+ console.log(chalk2.dim(" Make sure your schema uses defineSchema({ ... })\n"));
614
+ return;
615
+ }
616
+ spinner.succeed(`Types generated for ${tables.length} table(s)`);
617
+ console.log("\n" + chalk2.green("\u2713") + " Tables:");
618
+ for (const table of tables) {
619
+ console.log(chalk2.dim(` - ${table.name} (${table.columns.length} columns)`));
620
+ }
621
+ if (envVarKeys.length > 0) {
622
+ console.log("\n" + chalk2.green("\u2713") + ` Environment variables: ${envVarKeys.length} key(s)`);
623
+ for (const key of envVarKeys) {
624
+ console.log(chalk2.dim(` - ${key}`));
625
+ }
626
+ }
627
+ const relativeOutput = path3.relative(process.cwd(), outputDir);
628
+ console.log("\n" + chalk2.green("\u2713") + " Generated files:");
629
+ console.log(chalk2.dim(` ${relativeOutput}/db.ts`));
630
+ console.log(chalk2.dim(` ${relativeOutput}/api.ts`));
631
+ console.log(chalk2.dim(` ${relativeOutput}/env.ts`));
632
+ console.log(chalk2.dim(` ${relativeOutput}/index.ts
633
+ `));
634
+ } catch (error) {
635
+ spinner.fail("Failed to generate types");
636
+ console.error(chalk2.red(error instanceof Error ? error.message : "Unknown error"));
637
+ process.exit(1);
638
+ }
639
+ }
640
+
641
+ export {
642
+ API_URL,
643
+ getCredentials,
644
+ requireAuth,
645
+ saveCredentials,
646
+ clearCredentials,
647
+ loadConfig,
648
+ resolvePath,
649
+ detectFramework,
650
+ getFrameworkDevCommand,
651
+ generateTypes,
652
+ generateCommand
653
+ };
@@ -0,0 +1,649 @@
1
+ // src/commands/generate.ts
2
+ import chalk2 from "chalk";
3
+ import ora from "ora";
4
+ import fs3 from "fs-extra";
5
+ import path3 from "path";
6
+
7
+ // src/utils/auth.ts
8
+ import chalk from "chalk";
9
+ import fs from "fs-extra";
10
+ import path from "path";
11
+ var CONFIG_DIR = path.join(process.env.HOME || process.env.USERPROFILE || "", ".tether");
12
+ var CREDENTIALS_FILE = path.join(CONFIG_DIR, "credentials.json");
13
+ var isDev = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
14
+ var API_URL = isDev ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
15
+ var REFRESH_THRESHOLD_DAYS = 7;
16
+ async function getCredentials() {
17
+ try {
18
+ if (await fs.pathExists(CREDENTIALS_FILE)) {
19
+ return await fs.readJSON(CREDENTIALS_FILE);
20
+ }
21
+ } catch {
22
+ }
23
+ return null;
24
+ }
25
+ async function refreshSession(credentials) {
26
+ try {
27
+ const response = await fetch(`${API_URL}/auth/session/refresh`, {
28
+ method: "POST",
29
+ headers: {
30
+ "Content-Type": "application/json",
31
+ "Authorization": `Bearer ${credentials.accessToken}`
32
+ }
33
+ });
34
+ if (!response.ok) {
35
+ return null;
36
+ }
37
+ const data = await response.json();
38
+ const updated = {
39
+ ...credentials,
40
+ expiresAt: data.expiresAt
41
+ };
42
+ await saveCredentials(updated);
43
+ return updated;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+ async function requireAuth() {
49
+ const credentials = await getCredentials();
50
+ if (!credentials) {
51
+ console.error(chalk.red("\n\u2717 Not logged in\n"));
52
+ console.log(chalk.dim("Run `tthr login` to authenticate\n"));
53
+ process.exit(1);
54
+ }
55
+ if (credentials.expiresAt) {
56
+ const expiresAt = new Date(credentials.expiresAt);
57
+ const now = /* @__PURE__ */ new Date();
58
+ if (now > expiresAt) {
59
+ await clearCredentials();
60
+ console.error(chalk.red("\n\u2717 Session expired \u2014 you have been signed out\n"));
61
+ console.log(chalk.dim("Run `tthr login` to authenticate\n"));
62
+ process.exit(1);
63
+ }
64
+ const daysUntilExpiry = (expiresAt.getTime() - now.getTime()) / (1e3 * 60 * 60 * 24);
65
+ if (daysUntilExpiry <= REFRESH_THRESHOLD_DAYS) {
66
+ const refreshed = await refreshSession(credentials);
67
+ if (refreshed) {
68
+ return refreshed;
69
+ }
70
+ }
71
+ }
72
+ return credentials;
73
+ }
74
+ async function saveCredentials(credentials) {
75
+ await fs.ensureDir(CONFIG_DIR);
76
+ await fs.writeJSON(CREDENTIALS_FILE, credentials, { spaces: 2, mode: 384 });
77
+ }
78
+ async function clearCredentials() {
79
+ try {
80
+ await fs.remove(CREDENTIALS_FILE);
81
+ } catch {
82
+ }
83
+ }
84
+
85
+ // src/utils/config.ts
86
+ import fs2 from "fs-extra";
87
+ import path2 from "path";
88
+ var DEFAULT_CONFIG = {
89
+ schema: "./tether/schema.ts",
90
+ functions: "./tether/functions",
91
+ output: "./tether/_generated",
92
+ dev: {
93
+ port: 3001,
94
+ host: "localhost"
95
+ },
96
+ database: {
97
+ walMode: true
98
+ }
99
+ };
100
+ async function loadConfig(cwd = process.cwd()) {
101
+ const configPath = path2.resolve(cwd, "tether.config.ts");
102
+ if (!await fs2.pathExists(configPath)) {
103
+ return DEFAULT_CONFIG;
104
+ }
105
+ const configSource = await fs2.readFile(configPath, "utf-8");
106
+ const config = {};
107
+ const schemaMatch = configSource.match(/schema\s*:\s*['"]([^'"]+)['"]/);
108
+ if (schemaMatch) {
109
+ config.schema = schemaMatch[1];
110
+ }
111
+ const functionsMatch = configSource.match(/functions\s*:\s*['"]([^'"]+)['"]/);
112
+ if (functionsMatch) {
113
+ config.functions = functionsMatch[1];
114
+ }
115
+ const outputMatch = configSource.match(/output\s*:\s*['"]([^'"]+)['"]/);
116
+ if (outputMatch) {
117
+ config.output = outputMatch[1];
118
+ }
119
+ const envMatch = configSource.match(/environment\s*:\s*['"]([^'"]+)['"]/);
120
+ if (envMatch) {
121
+ config.environment = envMatch[1];
122
+ }
123
+ const portMatch = configSource.match(/port\s*:\s*(\d+)/);
124
+ if (portMatch) {
125
+ config.dev = { ...config.dev, port: parseInt(portMatch[1], 10) };
126
+ }
127
+ const hostMatch = configSource.match(/host\s*:\s*['"]([^'"]+)['"]/);
128
+ if (hostMatch) {
129
+ config.dev = { ...config.dev, host: hostMatch[1] };
130
+ }
131
+ return {
132
+ ...DEFAULT_CONFIG,
133
+ ...config,
134
+ dev: { ...DEFAULT_CONFIG.dev, ...config.dev },
135
+ database: { ...DEFAULT_CONFIG.database, ...config.database }
136
+ };
137
+ }
138
+ function resolvePath(configPath, cwd = process.cwd()) {
139
+ const normalised = configPath.replace(/^\.\//, "");
140
+ return path2.resolve(cwd, normalised);
141
+ }
142
+ async function detectFramework(cwd = process.cwd()) {
143
+ const packageJsonPath = path2.resolve(cwd, "package.json");
144
+ if (!await fs2.pathExists(packageJsonPath)) {
145
+ return "unknown";
146
+ }
147
+ try {
148
+ const packageJson = await fs2.readJson(packageJsonPath);
149
+ const deps = {
150
+ ...packageJson.dependencies,
151
+ ...packageJson.devDependencies
152
+ };
153
+ if (deps.nuxt || deps["@nuxt/kit"]) {
154
+ return "nuxt";
155
+ }
156
+ if (deps.next) {
157
+ return "next";
158
+ }
159
+ if (deps["@sveltejs/kit"]) {
160
+ return "sveltekit";
161
+ }
162
+ if (deps.vite && !deps.nuxt && !deps.next && !deps["@sveltejs/kit"]) {
163
+ return "vite";
164
+ }
165
+ return "vanilla";
166
+ } catch {
167
+ return "unknown";
168
+ }
169
+ }
170
+ function getFrameworkDevCommand(framework) {
171
+ switch (framework) {
172
+ case "nuxt":
173
+ return "nuxt dev";
174
+ case "next":
175
+ return "next dev";
176
+ case "sveltekit":
177
+ return "vite dev";
178
+ case "vite":
179
+ return "vite dev";
180
+ case "vanilla":
181
+ return null;
182
+ // No default dev server for vanilla
183
+ default:
184
+ return null;
185
+ }
186
+ }
187
+
188
+ // src/commands/generate.ts
189
+ var isDev2 = process.env.NODE_ENV === "development" || process.env.TETHER_DEV === "true";
190
+ var API_URL2 = isDev2 ? "http://localhost:3001/api/v1" : "https://tether-api.strands.gg/api/v1";
191
+ function parseSchemaFile(source) {
192
+ const tables = [];
193
+ const schemaMatch = source.match(/defineSchema\s*\(\s*\{([\s\S]*)\}\s*\)/);
194
+ if (!schemaMatch) return tables;
195
+ const schemaContent = schemaMatch[1];
196
+ const tableStartRegex = /(\w+)\s*:\s*\{/g;
197
+ let match;
198
+ while ((match = tableStartRegex.exec(schemaContent)) !== null) {
199
+ const tableName = match[1];
200
+ const startOffset = match.index + match[0].length;
201
+ let braceCount = 1;
202
+ let endOffset = startOffset;
203
+ for (let i = startOffset; i < schemaContent.length && braceCount > 0; i++) {
204
+ const char = schemaContent[i];
205
+ if (char === "{") braceCount++;
206
+ else if (char === "}") braceCount--;
207
+ endOffset = i;
208
+ }
209
+ const columnsContent = schemaContent.slice(startOffset, endOffset);
210
+ const columns = parseColumns(columnsContent);
211
+ tables.push({ name: tableName, columns });
212
+ }
213
+ return tables;
214
+ }
215
+ function parseColumns(content) {
216
+ const columns = [];
217
+ const columnRegex = /(\w+)\s*:\s*(\w+)(?:<([^>]+)>)?\s*\(\s*\)((?:\[.*?\]|[^,\n}])*)/g;
218
+ let match;
219
+ while ((match = columnRegex.exec(content)) !== null) {
220
+ const name = match[1];
221
+ const schemaType = match[2];
222
+ const genericType = match[3];
223
+ const modifiers = match[4] || "";
224
+ const nullable = !modifiers.includes(".notNull()");
225
+ const oneOfMatch = modifiers.match(/\.oneOf\s*\(\s*\[(.*?)\]\s*\)/);
226
+ let oneOf;
227
+ if (oneOfMatch) {
228
+ oneOf = [...oneOfMatch[1].matchAll(/['"]([^'"]+)['"]/g)].map((m) => m[1]);
229
+ }
230
+ columns.push({
231
+ name,
232
+ type: schemaTypeToTS(schemaType),
233
+ nullable,
234
+ jsonType: genericType,
235
+ // Store the generic type for json columns
236
+ oneOf
237
+ });
238
+ }
239
+ return columns;
240
+ }
241
+ function schemaTypeToTS(schemaType) {
242
+ switch (schemaType) {
243
+ case "text":
244
+ return "string";
245
+ case "integer":
246
+ return "number";
247
+ case "real":
248
+ return "number";
249
+ case "boolean":
250
+ return "boolean";
251
+ case "timestamp":
252
+ return "string";
253
+ case "json":
254
+ return "unknown";
255
+ case "blob":
256
+ return "Uint8Array";
257
+ case "asset":
258
+ return "TetherAsset";
259
+ // Asset object returned by API
260
+ default:
261
+ return "unknown";
262
+ }
263
+ }
264
+ function extractTypeDefinitions(source, typeNames) {
265
+ if (typeNames.size === 0) return [];
266
+ const blocks = [];
267
+ for (const typeName of typeNames) {
268
+ const interfaceStart = new RegExp(`(?:export\\s+)?interface\\s+${typeName}\\s*\\{`);
269
+ const interfaceMatch = interfaceStart.exec(source);
270
+ if (interfaceMatch) {
271
+ const braceStart = interfaceMatch.index + interfaceMatch[0].length;
272
+ let braceCount = 1;
273
+ let endIdx = braceStart;
274
+ for (let i = braceStart; i < source.length && braceCount > 0; i++) {
275
+ if (source[i] === "{") braceCount++;
276
+ else if (source[i] === "}") braceCount--;
277
+ endIdx = i;
278
+ }
279
+ let block = source.slice(interfaceMatch.index, endIdx + 1);
280
+ block = block.replace(/^export\s+/, "");
281
+ blocks.push(block);
282
+ continue;
283
+ }
284
+ const typeStart = new RegExp(`(?:export\\s+)?type\\s+${typeName}\\s*=`);
285
+ const typeMatch = typeStart.exec(source);
286
+ if (typeMatch) {
287
+ const semiIdx = source.indexOf(";", typeMatch.index);
288
+ if (semiIdx !== -1) {
289
+ let block = source.slice(typeMatch.index, semiIdx + 1);
290
+ block = block.replace(/^export\s+/, "");
291
+ blocks.push(block);
292
+ }
293
+ }
294
+ }
295
+ return blocks;
296
+ }
297
+ function tableNameToInterface(tableName) {
298
+ let name = tableName;
299
+ if (name.endsWith("ies")) {
300
+ name = name.slice(0, -3) + "y";
301
+ } else if (name.endsWith("s") && !name.endsWith("ss")) {
302
+ name = name.slice(0, -1);
303
+ }
304
+ return name.charAt(0).toUpperCase() + name.slice(1);
305
+ }
306
+ function generateDbFile(tables, schemaSource) {
307
+ const TS_PRIMITIVES = /* @__PURE__ */ new Set(["number", "string", "boolean", "unknown", "any", "void", "never", "undefined", "null", "object"]);
308
+ const jsonTypes = /* @__PURE__ */ new Set();
309
+ for (const table of tables) {
310
+ for (const col of table.columns) {
311
+ if (col.jsonType) {
312
+ const baseType = col.jsonType.replace(/\[\]$/, "").replace(/\s*\|\s*null$/, "").trim();
313
+ if (!TS_PRIMITIVES.has(baseType)) {
314
+ jsonTypes.add(baseType);
315
+ }
316
+ }
317
+ }
318
+ }
319
+ const lines = [
320
+ "// Auto-generated by Tether CLI - do not edit manually",
321
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
322
+ "",
323
+ "import { createDatabaseProxy, type TetherDatabase } from '@tthr/client';",
324
+ "import {",
325
+ " type QueryDefinition,",
326
+ " type MutationDefinition,",
327
+ " z,",
328
+ "} from '@tthr/server';",
329
+ "import type { TetherEnv } from './env';"
330
+ ];
331
+ if (jsonTypes.size > 0) {
332
+ const typeBlocks = extractTypeDefinitions(schemaSource, jsonTypes);
333
+ if (typeBlocks.length > 0) {
334
+ lines.push("");
335
+ lines.push("// Schema types (inlined from schema.ts)");
336
+ for (const block of typeBlocks) {
337
+ lines.push(block);
338
+ lines.push("");
339
+ }
340
+ }
341
+ }
342
+ lines.push("");
343
+ lines.push("// Asset type returned by the API for asset columns");
344
+ lines.push("export interface TetherAsset {");
345
+ lines.push(" id: string;");
346
+ lines.push(" filename: string;");
347
+ lines.push(" contentType: string;");
348
+ lines.push(" size: number;");
349
+ lines.push(" url: string;");
350
+ lines.push(" createdAt: string;");
351
+ lines.push("}");
352
+ lines.push("");
353
+ for (const table of tables) {
354
+ const interfaceName = tableNameToInterface(table.name);
355
+ lines.push(`export interface ${interfaceName} {`);
356
+ lines.push(" _id: string;");
357
+ for (const col of table.columns) {
358
+ let colType;
359
+ if (col.oneOf && col.oneOf.length > 0) {
360
+ colType = col.oneOf.map((v) => `'${v}'`).join(" | ");
361
+ } else {
362
+ colType = col.jsonType || col.type;
363
+ }
364
+ const typeStr = col.nullable ? `${colType} | null` : colType;
365
+ const optional = col.nullable ? "?" : "";
366
+ lines.push(` ${col.name}${optional}: ${typeStr};`);
367
+ }
368
+ lines.push(" _createdAt: string;");
369
+ lines.push(" _updatedAt?: string | null;");
370
+ lines.push(" _deletedAt?: string | null;");
371
+ lines.push("}");
372
+ lines.push("");
373
+ }
374
+ lines.push("export interface Schema {");
375
+ for (const table of tables) {
376
+ const interfaceName = tableNameToInterface(table.name);
377
+ lines.push(` ${table.name}: ${interfaceName};`);
378
+ }
379
+ lines.push("}");
380
+ lines.push("");
381
+ lines.push("// Database client with typed tables");
382
+ lines.push("// This is a proxy that will be populated by the Tether runtime");
383
+ lines.push("export const db: TetherDatabase<Schema> = createDatabaseProxy<Schema>();");
384
+ lines.push("");
385
+ lines.push("// ============================================================================");
386
+ lines.push("// Typed function wrappers - use these instead of importing from @tthr/server");
387
+ lines.push("// This ensures the `db` and `env` parameters in handlers are properly typed");
388
+ lines.push("// ============================================================================");
389
+ lines.push("");
390
+ lines.push("/**");
391
+ lines.push(" * Define a query function with typed database and environment variable access.");
392
+ lines.push(" * The `db` and `env` parameters in the handler will have full type safety.");
393
+ lines.push(" */");
394
+ lines.push("export function query<TArgs = void, TResult = unknown>(");
395
+ lines.push(" definition: QueryDefinition<TArgs, TResult, Schema, TetherEnv>");
396
+ lines.push("): QueryDefinition<TArgs, TResult, Schema, TetherEnv> {");
397
+ lines.push(" return definition;");
398
+ lines.push("}");
399
+ lines.push("");
400
+ lines.push("/**");
401
+ lines.push(" * Define a mutation function with typed database and environment variable access.");
402
+ lines.push(" * The `db` and `env` parameters in the handler will have full type safety.");
403
+ lines.push(" */");
404
+ lines.push("export function mutation<TArgs = void, TResult = unknown>(");
405
+ lines.push(" definition: MutationDefinition<TArgs, TResult, Schema, TetherEnv>");
406
+ lines.push("): MutationDefinition<TArgs, TResult, Schema, TetherEnv> {");
407
+ lines.push(" return definition;");
408
+ lines.push("}");
409
+ lines.push("");
410
+ lines.push("// Re-export z for convenience");
411
+ lines.push("export { z };");
412
+ lines.push("");
413
+ return lines.join("\n");
414
+ }
415
+ async function parseFunctionsDir(functionsDir) {
416
+ const functions = [];
417
+ if (!await fs3.pathExists(functionsDir)) {
418
+ return functions;
419
+ }
420
+ const files = await fs3.readdir(functionsDir);
421
+ for (const file of files) {
422
+ if (!file.endsWith(".ts") && !file.endsWith(".js")) continue;
423
+ const filePath = path3.join(functionsDir, file);
424
+ const stat = await fs3.stat(filePath);
425
+ if (!stat.isFile()) continue;
426
+ const moduleName = file.replace(/\.(ts|js)$/, "");
427
+ const source = await fs3.readFile(filePath, "utf-8");
428
+ const exportRegex = /export\s+const\s+(\w+)\s*=\s*(query|mutation)\s*\(/g;
429
+ let match;
430
+ while ((match = exportRegex.exec(source)) !== null) {
431
+ functions.push({
432
+ name: match[1],
433
+ moduleName
434
+ });
435
+ }
436
+ }
437
+ return functions;
438
+ }
439
+ async function generateApiFile(functionsDir) {
440
+ const functions = await parseFunctionsDir(functionsDir);
441
+ const moduleMap = /* @__PURE__ */ new Map();
442
+ for (const fn of functions) {
443
+ if (!moduleMap.has(fn.moduleName)) {
444
+ moduleMap.set(fn.moduleName, []);
445
+ }
446
+ moduleMap.get(fn.moduleName).push(fn.name);
447
+ }
448
+ const lines = [
449
+ "// Auto-generated by Tether CLI - do not edit manually",
450
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
451
+ "",
452
+ "import { createApiProxy } from '@tthr/client';",
453
+ "",
454
+ "/**",
455
+ " * API function reference type for useQuery/useMutation.",
456
+ ' * The _name property contains the function path (e.g., "users.list").',
457
+ " */",
458
+ "export interface ApiFunction<TArgs = unknown, TResult = unknown> {",
459
+ " _name: string;",
460
+ " _args?: TArgs;",
461
+ " _result?: TResult;",
462
+ "}",
463
+ ""
464
+ ];
465
+ if (moduleMap.size > 0) {
466
+ for (const [moduleName, fnNames] of moduleMap) {
467
+ const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
468
+ lines.push(`export interface ${interfaceName} {`);
469
+ for (const fnName of fnNames) {
470
+ lines.push(` ${fnName}: ApiFunction;`);
471
+ }
472
+ lines.push("}");
473
+ lines.push("");
474
+ }
475
+ lines.push("export interface Api {");
476
+ for (const moduleName of moduleMap.keys()) {
477
+ const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
478
+ lines.push(` ${moduleName}: ${interfaceName};`);
479
+ }
480
+ lines.push("}");
481
+ } else {
482
+ lines.push("/**");
483
+ lines.push(" * Flexible API type that allows access to any function path.");
484
+ lines.push(" * Functions are accessed as api.moduleName.functionName");
485
+ lines.push(" * The actual types depend on your function definitions.");
486
+ lines.push(" */");
487
+ lines.push("export type Api = {");
488
+ lines.push(" [module: string]: {");
489
+ lines.push(" [fn: string]: ApiFunction;");
490
+ lines.push(" };");
491
+ lines.push("};");
492
+ }
493
+ lines.push("");
494
+ lines.push("// API client proxy - provides typed access to your functions");
495
+ lines.push("// On the client: returns { _name } references for useQuery/useMutation");
496
+ lines.push("// In Tether functions: calls the actual function implementation");
497
+ lines.push("export const api = createApiProxy<Api>();");
498
+ lines.push("");
499
+ return lines.join("\n");
500
+ }
501
+ async function fetchEnvVarKeys(projectId, environment) {
502
+ const credentials = await getCredentials();
503
+ if (!credentials) return [];
504
+ const envPath = environment !== "production" ? `/projects/${projectId}/env/${environment}/env-vars` : `/projects/${projectId}/env-vars`;
505
+ try {
506
+ const response = await fetch(`${API_URL2}${envPath}`, {
507
+ headers: {
508
+ "Authorization": `Bearer ${credentials.accessToken}`
509
+ }
510
+ });
511
+ if (!response.ok) return [];
512
+ const data = await response.json();
513
+ return (data.envVars || []).map((v) => v.key).sort();
514
+ } catch {
515
+ return [];
516
+ }
517
+ }
518
+ function generateEnvFile(keys) {
519
+ const lines = [
520
+ "// Auto-generated by Tether CLI - do not edit manually",
521
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
522
+ "",
523
+ "/**",
524
+ " * Typed environment variables for this project.",
525
+ " * Keys are fetched from the Tether API \u2014 values are never exposed.",
526
+ ' * Use `env.get("KEY")` in your functions to access them.',
527
+ " */",
528
+ ""
529
+ ];
530
+ if (keys.length > 0) {
531
+ lines.push("export type EnvVarKey =");
532
+ for (let i = 0; i < keys.length; i++) {
533
+ const sep = i === keys.length - 1 ? ";" : "";
534
+ lines.push(` | '${keys[i]}'${sep}`);
535
+ }
536
+ lines.push("");
537
+ lines.push("export interface TetherEnv {");
538
+ for (const key of keys) {
539
+ lines.push(` ${key}: string;`);
540
+ }
541
+ lines.push("}");
542
+ } else {
543
+ lines.push("export type EnvVarKey = string;");
544
+ lines.push("");
545
+ lines.push("export interface TetherEnv {");
546
+ lines.push(" [key: string]: string;");
547
+ lines.push("}");
548
+ }
549
+ lines.push("");
550
+ return lines.join("\n");
551
+ }
552
+ async function generateTypes(options = {}) {
553
+ const config = await loadConfig();
554
+ const schemaPath = resolvePath(config.schema);
555
+ const outputDir = resolvePath(config.output);
556
+ const functionsDir = resolvePath(config.functions);
557
+ if (!await fs3.pathExists(schemaPath)) {
558
+ throw new Error(`Schema file not found: ${schemaPath}`);
559
+ }
560
+ const schemaSource = await fs3.readFile(schemaPath, "utf-8");
561
+ const tables = parseSchemaFile(schemaSource);
562
+ const environment = config.environment || "development";
563
+ let projectId;
564
+ const envFilePath = path3.resolve(process.cwd(), ".env");
565
+ if (await fs3.pathExists(envFilePath)) {
566
+ const envContent = await fs3.readFile(envFilePath, "utf-8");
567
+ const match = envContent.match(/TETHER_PROJECT_ID=(.+)/);
568
+ projectId = match?.[1]?.trim();
569
+ }
570
+ const envVarKeys = projectId ? await fetchEnvVarKeys(projectId, environment) : [];
571
+ await fs3.ensureDir(outputDir);
572
+ await fs3.writeFile(
573
+ path3.join(outputDir, "db.ts"),
574
+ generateDbFile(tables, schemaSource)
575
+ );
576
+ await fs3.writeFile(
577
+ path3.join(outputDir, "api.ts"),
578
+ await generateApiFile(functionsDir)
579
+ );
580
+ await fs3.writeFile(
581
+ path3.join(outputDir, "env.ts"),
582
+ generateEnvFile(envVarKeys)
583
+ );
584
+ await fs3.writeFile(
585
+ path3.join(outputDir, "index.ts"),
586
+ `// Auto-generated by Tether CLI - do not edit manually
587
+ export * from './db';
588
+ export * from './api';
589
+ export * from './env';
590
+ `
591
+ );
592
+ return { tables, envVarKeys, outputDir };
593
+ }
594
+ async function generateCommand() {
595
+ await requireAuth();
596
+ const configPath = path3.resolve(process.cwd(), "tether.config.ts");
597
+ if (!await fs3.pathExists(configPath)) {
598
+ console.log(chalk2.red("\nError: Not a Tether project"));
599
+ console.log(chalk2.dim("Run `tthr init` to create a new project\n"));
600
+ process.exit(1);
601
+ }
602
+ console.log(chalk2.bold("\n\u26A1 Generating types from schema\n"));
603
+ const spinner = ora("Reading schema...").start();
604
+ try {
605
+ spinner.text = "Generating types...";
606
+ const { tables, envVarKeys, outputDir } = await generateTypes();
607
+ if (tables.length === 0) {
608
+ spinner.warn("No tables found in schema");
609
+ console.log(chalk2.dim(" Make sure your schema uses defineSchema({ ... })\n"));
610
+ return;
611
+ }
612
+ spinner.succeed(`Types generated for ${tables.length} table(s)`);
613
+ console.log("\n" + chalk2.green("\u2713") + " Tables:");
614
+ for (const table of tables) {
615
+ console.log(chalk2.dim(` - ${table.name} (${table.columns.length} columns)`));
616
+ }
617
+ if (envVarKeys.length > 0) {
618
+ console.log("\n" + chalk2.green("\u2713") + ` Environment variables: ${envVarKeys.length} key(s)`);
619
+ for (const key of envVarKeys) {
620
+ console.log(chalk2.dim(` - ${key}`));
621
+ }
622
+ }
623
+ const relativeOutput = path3.relative(process.cwd(), outputDir);
624
+ console.log("\n" + chalk2.green("\u2713") + " Generated files:");
625
+ console.log(chalk2.dim(` ${relativeOutput}/db.ts`));
626
+ console.log(chalk2.dim(` ${relativeOutput}/api.ts`));
627
+ console.log(chalk2.dim(` ${relativeOutput}/env.ts`));
628
+ console.log(chalk2.dim(` ${relativeOutput}/index.ts
629
+ `));
630
+ } catch (error) {
631
+ spinner.fail("Failed to generate types");
632
+ console.error(chalk2.red(error instanceof Error ? error.message : "Unknown error"));
633
+ process.exit(1);
634
+ }
635
+ }
636
+
637
+ export {
638
+ API_URL,
639
+ getCredentials,
640
+ requireAuth,
641
+ saveCredentials,
642
+ clearCredentials,
643
+ loadConfig,
644
+ resolvePath,
645
+ detectFramework,
646
+ getFrameworkDevCommand,
647
+ generateTypes,
648
+ generateCommand
649
+ };
@@ -0,0 +1,8 @@
1
+ import {
2
+ generateCommand,
3
+ generateTypes
4
+ } from "./chunk-QUS263RB.js";
5
+ export {
6
+ generateCommand,
7
+ generateTypes
8
+ };
@@ -0,0 +1,8 @@
1
+ import {
2
+ generateCommand,
3
+ generateTypes
4
+ } from "./chunk-WVCYYQ3X.js";
5
+ export {
6
+ generateCommand,
7
+ generateTypes
8
+ };
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  requireAuth,
12
12
  resolvePath,
13
13
  saveCredentials
14
- } from "./chunk-GYMF5VG7.js";
14
+ } from "./chunk-WVCYYQ3X.js";
15
15
 
16
16
  // src/index.ts
17
17
  import { Command } from "commander";
@@ -1684,7 +1684,7 @@ async function runGenerate(spinner) {
1684
1684
  }
1685
1685
  isGenerating = true;
1686
1686
  try {
1687
- const { generateTypes: generateTypes2 } = await import("./generate-ZY23LDYI.js");
1687
+ const { generateTypes: generateTypes2 } = await import("./generate-OAXWQ64W.js");
1688
1688
  spinner.text = "Regenerating types...";
1689
1689
  await generateTypes2({ silent: true });
1690
1690
  spinner.succeed("Types regenerated");
@@ -1904,7 +1904,7 @@ async function devCommand(options) {
1904
1904
  }
1905
1905
  }
1906
1906
  spinner.text = "Generating types...";
1907
- const { generateTypes: generateTypes2 } = await import("./generate-ZY23LDYI.js");
1907
+ const { generateTypes: generateTypes2 } = await import("./generate-OAXWQ64W.js");
1908
1908
  await generateTypes2({ silent: true });
1909
1909
  spinner.succeed("Types generated");
1910
1910
  if (config.projectId) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tthr",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "Tether CLI - project scaffolding and deployment",
5
5
  "type": "module",
6
6
  "bin": {