tthr 0.0.48 → 0.0.49

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,481 @@
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
+ async function getCredentials() {
14
+ try {
15
+ if (await fs.pathExists(CREDENTIALS_FILE)) {
16
+ return await fs.readJSON(CREDENTIALS_FILE);
17
+ }
18
+ } catch {
19
+ }
20
+ return null;
21
+ }
22
+ async function requireAuth() {
23
+ const credentials = await getCredentials();
24
+ if (!credentials) {
25
+ console.error(chalk.red("\n\u2717 Not logged in\n"));
26
+ console.log(chalk.dim("Run `tthr login` to authenticate\n"));
27
+ process.exit(1);
28
+ }
29
+ if (credentials.expiresAt) {
30
+ const expiresAt = new Date(credentials.expiresAt);
31
+ if (/* @__PURE__ */ new Date() > expiresAt) {
32
+ console.error(chalk.red("\n\u2717 Session expired\n"));
33
+ console.log(chalk.dim("Run `tthr login` to authenticate\n"));
34
+ process.exit(1);
35
+ }
36
+ }
37
+ return credentials;
38
+ }
39
+ async function saveCredentials(credentials) {
40
+ await fs.ensureDir(CONFIG_DIR);
41
+ await fs.writeJSON(CREDENTIALS_FILE, credentials, { spaces: 2, mode: 384 });
42
+ }
43
+ async function clearCredentials() {
44
+ try {
45
+ await fs.remove(CREDENTIALS_FILE);
46
+ } catch {
47
+ }
48
+ }
49
+
50
+ // src/utils/config.ts
51
+ import fs2 from "fs-extra";
52
+ import path2 from "path";
53
+ var DEFAULT_CONFIG = {
54
+ schema: "./tether/schema.ts",
55
+ functions: "./tether/functions",
56
+ output: "./tether/_generated",
57
+ dev: {
58
+ port: 3001,
59
+ host: "localhost"
60
+ },
61
+ database: {
62
+ walMode: true
63
+ }
64
+ };
65
+ async function loadConfig(cwd = process.cwd()) {
66
+ const configPath = path2.resolve(cwd, "tether.config.ts");
67
+ if (!await fs2.pathExists(configPath)) {
68
+ return DEFAULT_CONFIG;
69
+ }
70
+ const configSource = await fs2.readFile(configPath, "utf-8");
71
+ const config = {};
72
+ const schemaMatch = configSource.match(/schema\s*:\s*['"]([^'"]+)['"]/);
73
+ if (schemaMatch) {
74
+ config.schema = schemaMatch[1];
75
+ }
76
+ const functionsMatch = configSource.match(/functions\s*:\s*['"]([^'"]+)['"]/);
77
+ if (functionsMatch) {
78
+ config.functions = functionsMatch[1];
79
+ }
80
+ const outputMatch = configSource.match(/output\s*:\s*['"]([^'"]+)['"]/);
81
+ if (outputMatch) {
82
+ config.output = outputMatch[1];
83
+ }
84
+ const envMatch = configSource.match(/environment\s*:\s*['"]([^'"]+)['"]/);
85
+ if (envMatch) {
86
+ config.environment = envMatch[1];
87
+ }
88
+ const portMatch = configSource.match(/port\s*:\s*(\d+)/);
89
+ if (portMatch) {
90
+ config.dev = { ...config.dev, port: parseInt(portMatch[1], 10) };
91
+ }
92
+ const hostMatch = configSource.match(/host\s*:\s*['"]([^'"]+)['"]/);
93
+ if (hostMatch) {
94
+ config.dev = { ...config.dev, host: hostMatch[1] };
95
+ }
96
+ return {
97
+ ...DEFAULT_CONFIG,
98
+ ...config,
99
+ dev: { ...DEFAULT_CONFIG.dev, ...config.dev },
100
+ database: { ...DEFAULT_CONFIG.database, ...config.database }
101
+ };
102
+ }
103
+ function resolvePath(configPath, cwd = process.cwd()) {
104
+ const normalised = configPath.replace(/^\.\//, "");
105
+ return path2.resolve(cwd, normalised);
106
+ }
107
+ async function detectFramework(cwd = process.cwd()) {
108
+ const packageJsonPath = path2.resolve(cwd, "package.json");
109
+ if (!await fs2.pathExists(packageJsonPath)) {
110
+ return "unknown";
111
+ }
112
+ try {
113
+ const packageJson = await fs2.readJson(packageJsonPath);
114
+ const deps = {
115
+ ...packageJson.dependencies,
116
+ ...packageJson.devDependencies
117
+ };
118
+ if (deps.nuxt || deps["@nuxt/kit"]) {
119
+ return "nuxt";
120
+ }
121
+ if (deps.next) {
122
+ return "next";
123
+ }
124
+ if (deps["@sveltejs/kit"]) {
125
+ return "sveltekit";
126
+ }
127
+ if (deps.vite && !deps.nuxt && !deps.next && !deps["@sveltejs/kit"]) {
128
+ return "vite";
129
+ }
130
+ return "vanilla";
131
+ } catch {
132
+ return "unknown";
133
+ }
134
+ }
135
+ function getFrameworkDevCommand(framework) {
136
+ switch (framework) {
137
+ case "nuxt":
138
+ return "nuxt dev";
139
+ case "next":
140
+ return "next dev";
141
+ case "sveltekit":
142
+ return "vite dev";
143
+ case "vite":
144
+ return "vite dev";
145
+ case "vanilla":
146
+ return null;
147
+ // No default dev server for vanilla
148
+ default:
149
+ return null;
150
+ }
151
+ }
152
+
153
+ // src/commands/generate.ts
154
+ function parseSchemaFile(source) {
155
+ const tables = [];
156
+ const schemaMatch = source.match(/defineSchema\s*\(\s*\{([\s\S]*)\}\s*\)/);
157
+ if (!schemaMatch) return tables;
158
+ const schemaContent = schemaMatch[1];
159
+ const tableStartRegex = /(\w+)\s*:\s*\{/g;
160
+ let match;
161
+ while ((match = tableStartRegex.exec(schemaContent)) !== null) {
162
+ const tableName = match[1];
163
+ const startOffset = match.index + match[0].length;
164
+ let braceCount = 1;
165
+ let endOffset = startOffset;
166
+ for (let i = startOffset; i < schemaContent.length && braceCount > 0; i++) {
167
+ const char = schemaContent[i];
168
+ if (char === "{") braceCount++;
169
+ else if (char === "}") braceCount--;
170
+ endOffset = i;
171
+ }
172
+ const columnsContent = schemaContent.slice(startOffset, endOffset);
173
+ const columns = parseColumns(columnsContent);
174
+ tables.push({ name: tableName, columns });
175
+ }
176
+ return tables;
177
+ }
178
+ function parseColumns(content) {
179
+ const columns = [];
180
+ const columnRegex = /(\w+)\s*:\s*(\w+)\s*\(\s*\)([^,\n}]*)/g;
181
+ let match;
182
+ while ((match = columnRegex.exec(content)) !== null) {
183
+ const name = match[1];
184
+ const schemaType = match[2];
185
+ const modifiers = match[3] || "";
186
+ const nullable = !modifiers.includes(".notNull()");
187
+ columns.push({
188
+ name,
189
+ type: schemaTypeToTS(schemaType),
190
+ nullable
191
+ });
192
+ }
193
+ return columns;
194
+ }
195
+ function schemaTypeToTS(schemaType) {
196
+ switch (schemaType) {
197
+ case "text":
198
+ return "string";
199
+ case "integer":
200
+ return "number";
201
+ case "real":
202
+ return "number";
203
+ case "boolean":
204
+ return "boolean";
205
+ case "timestamp":
206
+ return "string";
207
+ case "json":
208
+ return "unknown";
209
+ case "blob":
210
+ return "Uint8Array";
211
+ case "asset":
212
+ return "TetherAsset";
213
+ // Asset object returned by API
214
+ default:
215
+ return "unknown";
216
+ }
217
+ }
218
+ function tableNameToInterface(tableName) {
219
+ let name = tableName;
220
+ if (name.endsWith("ies")) {
221
+ name = name.slice(0, -3) + "y";
222
+ } else if (name.endsWith("s") && !name.endsWith("ss")) {
223
+ name = name.slice(0, -1);
224
+ }
225
+ return name.charAt(0).toUpperCase() + name.slice(1);
226
+ }
227
+ function generateDbFile(tables) {
228
+ const lines = [
229
+ "// Auto-generated by Tether CLI - do not edit manually",
230
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
231
+ "",
232
+ "import { createDatabaseProxy, type TetherDatabase } from '@tthr/client';",
233
+ "import {",
234
+ " query as baseQuery,",
235
+ " mutation as baseMutation,",
236
+ " action as baseAction,",
237
+ " type QueryDefinition,",
238
+ " type MutationDefinition,",
239
+ " type ActionDefinition,",
240
+ " z,",
241
+ "} from '@tthr/server';",
242
+ "",
243
+ "// Asset type returned by the API for asset columns",
244
+ "export interface TetherAsset {",
245
+ " id: string;",
246
+ " filename: string;",
247
+ " contentType: string;",
248
+ " size: number;",
249
+ " url: string;",
250
+ " createdAt: string;",
251
+ "}",
252
+ ""
253
+ ];
254
+ for (const table of tables) {
255
+ const interfaceName = tableNameToInterface(table.name);
256
+ lines.push(`export interface ${interfaceName} {`);
257
+ lines.push(" _id: string;");
258
+ for (const col of table.columns) {
259
+ const typeStr = col.nullable ? `${col.type} | null` : col.type;
260
+ const optional = col.nullable ? "?" : "";
261
+ lines.push(` ${col.name}${optional}: ${typeStr};`);
262
+ }
263
+ lines.push(" _createdAt: string;");
264
+ lines.push(" _updatedAt?: string | null;");
265
+ lines.push(" _deletedAt?: string | null;");
266
+ lines.push("}");
267
+ lines.push("");
268
+ }
269
+ lines.push("export interface Schema {");
270
+ for (const table of tables) {
271
+ const interfaceName = tableNameToInterface(table.name);
272
+ lines.push(` ${table.name}: ${interfaceName};`);
273
+ }
274
+ lines.push("}");
275
+ lines.push("");
276
+ lines.push("// Database client with typed tables");
277
+ lines.push("// This is a proxy that will be populated by the Tether runtime");
278
+ lines.push("export const db: TetherDatabase<Schema> = createDatabaseProxy<Schema>();");
279
+ lines.push("");
280
+ lines.push("// ============================================================================");
281
+ lines.push("// Typed function wrappers - use these instead of importing from @tthr/server");
282
+ lines.push("// This ensures the `db` parameter in handlers is properly typed with Schema");
283
+ lines.push("// ============================================================================");
284
+ lines.push("");
285
+ lines.push("/**");
286
+ lines.push(" * Define a query function with typed database access.");
287
+ lines.push(" * The `db` parameter in the handler will have full type safety for your schema.");
288
+ lines.push(" */");
289
+ lines.push("export function query<TArgs = void, TResult = unknown>(");
290
+ lines.push(" definition: QueryDefinition<TArgs, TResult, Schema>");
291
+ lines.push("): QueryDefinition<TArgs, TResult, Schema> {");
292
+ lines.push(" return baseQuery(definition);");
293
+ lines.push("}");
294
+ lines.push("");
295
+ lines.push("/**");
296
+ lines.push(" * Define a mutation function with typed database access.");
297
+ lines.push(" * The `db` parameter in the handler will have full type safety for your schema.");
298
+ lines.push(" */");
299
+ lines.push("export function mutation<TArgs = void, TResult = unknown>(");
300
+ lines.push(" definition: MutationDefinition<TArgs, TResult, Schema>");
301
+ lines.push("): MutationDefinition<TArgs, TResult, Schema> {");
302
+ lines.push(" return baseMutation(definition);");
303
+ lines.push("}");
304
+ lines.push("");
305
+ lines.push("/**");
306
+ lines.push(" * Define an action function with typed database access.");
307
+ lines.push(" * The `db` parameter in the handler will have full type safety for your schema.");
308
+ lines.push(" */");
309
+ lines.push("export function action<TArgs = void, TResult = unknown>(");
310
+ lines.push(" definition: ActionDefinition<TArgs, TResult, Schema>");
311
+ lines.push("): ActionDefinition<TArgs, TResult, Schema> {");
312
+ lines.push(" return baseAction(definition);");
313
+ lines.push("}");
314
+ lines.push("");
315
+ lines.push("// Re-export z for convenience");
316
+ lines.push("export { z };");
317
+ lines.push("");
318
+ return lines.join("\n");
319
+ }
320
+ async function parseFunctionsDir(functionsDir) {
321
+ const functions = [];
322
+ if (!await fs3.pathExists(functionsDir)) {
323
+ return functions;
324
+ }
325
+ const files = await fs3.readdir(functionsDir);
326
+ for (const file of files) {
327
+ if (!file.endsWith(".ts") && !file.endsWith(".js")) continue;
328
+ const filePath = path3.join(functionsDir, file);
329
+ const stat = await fs3.stat(filePath);
330
+ if (!stat.isFile()) continue;
331
+ const moduleName = file.replace(/\.(ts|js)$/, "");
332
+ const source = await fs3.readFile(filePath, "utf-8");
333
+ const exportRegex = /export\s+const\s+(\w+)\s*=\s*(query|mutation|action)\s*\(/g;
334
+ let match;
335
+ while ((match = exportRegex.exec(source)) !== null) {
336
+ functions.push({
337
+ name: match[1],
338
+ moduleName
339
+ });
340
+ }
341
+ }
342
+ return functions;
343
+ }
344
+ async function generateApiFile(functionsDir) {
345
+ const functions = await parseFunctionsDir(functionsDir);
346
+ const moduleMap = /* @__PURE__ */ new Map();
347
+ for (const fn of functions) {
348
+ if (!moduleMap.has(fn.moduleName)) {
349
+ moduleMap.set(fn.moduleName, []);
350
+ }
351
+ moduleMap.get(fn.moduleName).push(fn.name);
352
+ }
353
+ const lines = [
354
+ "// Auto-generated by Tether CLI - do not edit manually",
355
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
356
+ "",
357
+ "import { createApiProxy } from '@tthr/client';",
358
+ "",
359
+ "/**",
360
+ " * API function reference type for useQuery/useMutation.",
361
+ ' * The _name property contains the function path (e.g., "users.list").',
362
+ " */",
363
+ "export interface ApiFunction<TArgs = unknown, TResult = unknown> {",
364
+ " _name: string;",
365
+ " _args?: TArgs;",
366
+ " _result?: TResult;",
367
+ "}",
368
+ ""
369
+ ];
370
+ if (moduleMap.size > 0) {
371
+ for (const [moduleName, fnNames] of moduleMap) {
372
+ const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
373
+ lines.push(`export interface ${interfaceName} {`);
374
+ for (const fnName of fnNames) {
375
+ lines.push(` ${fnName}: ApiFunction;`);
376
+ }
377
+ lines.push("}");
378
+ lines.push("");
379
+ }
380
+ lines.push("export interface Api {");
381
+ for (const moduleName of moduleMap.keys()) {
382
+ const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
383
+ lines.push(` ${moduleName}: ${interfaceName};`);
384
+ }
385
+ lines.push("}");
386
+ } else {
387
+ lines.push("/**");
388
+ lines.push(" * Flexible API type that allows access to any function path.");
389
+ lines.push(" * Functions are accessed as api.moduleName.functionName");
390
+ lines.push(" * The actual types depend on your function definitions.");
391
+ lines.push(" */");
392
+ lines.push("export type Api = {");
393
+ lines.push(" [module: string]: {");
394
+ lines.push(" [fn: string]: ApiFunction;");
395
+ lines.push(" };");
396
+ lines.push("};");
397
+ }
398
+ lines.push("");
399
+ lines.push("// API client proxy - provides typed access to your functions");
400
+ lines.push("// On the client: returns { _name } references for useQuery/useMutation");
401
+ lines.push("// In Tether functions: calls the actual function implementation");
402
+ lines.push("export const api = createApiProxy<Api>();");
403
+ lines.push("");
404
+ return lines.join("\n");
405
+ }
406
+ async function generateTypes(options = {}) {
407
+ const config = await loadConfig();
408
+ const schemaPath = resolvePath(config.schema);
409
+ const outputDir = resolvePath(config.output);
410
+ const functionsDir = resolvePath(config.functions);
411
+ if (!await fs3.pathExists(schemaPath)) {
412
+ throw new Error(`Schema file not found: ${schemaPath}`);
413
+ }
414
+ const schemaSource = await fs3.readFile(schemaPath, "utf-8");
415
+ const tables = parseSchemaFile(schemaSource);
416
+ await fs3.ensureDir(outputDir);
417
+ await fs3.writeFile(
418
+ path3.join(outputDir, "db.ts"),
419
+ generateDbFile(tables)
420
+ );
421
+ await fs3.writeFile(
422
+ path3.join(outputDir, "api.ts"),
423
+ await generateApiFile(functionsDir)
424
+ );
425
+ await fs3.writeFile(
426
+ path3.join(outputDir, "index.ts"),
427
+ `// Auto-generated by Tether CLI - do not edit manually
428
+ export * from './db';
429
+ export * from './api';
430
+ `
431
+ );
432
+ return { tables, outputDir };
433
+ }
434
+ async function generateCommand() {
435
+ await requireAuth();
436
+ const configPath = path3.resolve(process.cwd(), "tether.config.ts");
437
+ if (!await fs3.pathExists(configPath)) {
438
+ console.log(chalk2.red("\nError: Not a Tether project"));
439
+ console.log(chalk2.dim("Run `tthr init` to create a new project\n"));
440
+ process.exit(1);
441
+ }
442
+ console.log(chalk2.bold("\n\u26A1 Generating types from schema\n"));
443
+ const spinner = ora("Reading schema...").start();
444
+ try {
445
+ spinner.text = "Generating types...";
446
+ const { tables, outputDir } = await generateTypes();
447
+ if (tables.length === 0) {
448
+ spinner.warn("No tables found in schema");
449
+ console.log(chalk2.dim(" Make sure your schema uses defineSchema({ ... })\n"));
450
+ return;
451
+ }
452
+ spinner.succeed(`Types generated for ${tables.length} table(s)`);
453
+ console.log("\n" + chalk2.green("\u2713") + " Tables:");
454
+ for (const table of tables) {
455
+ console.log(chalk2.dim(` - ${table.name} (${table.columns.length} columns)`));
456
+ }
457
+ const relativeOutput = path3.relative(process.cwd(), outputDir);
458
+ console.log("\n" + chalk2.green("\u2713") + " Generated files:");
459
+ console.log(chalk2.dim(` ${relativeOutput}/db.ts`));
460
+ console.log(chalk2.dim(` ${relativeOutput}/api.ts`));
461
+ console.log(chalk2.dim(` ${relativeOutput}/index.ts
462
+ `));
463
+ } catch (error) {
464
+ spinner.fail("Failed to generate types");
465
+ console.error(chalk2.red(error instanceof Error ? error.message : "Unknown error"));
466
+ process.exit(1);
467
+ }
468
+ }
469
+
470
+ export {
471
+ getCredentials,
472
+ requireAuth,
473
+ saveCredentials,
474
+ clearCredentials,
475
+ loadConfig,
476
+ resolvePath,
477
+ detectFramework,
478
+ getFrameworkDevCommand,
479
+ generateTypes,
480
+ generateCommand
481
+ };
@@ -0,0 +1,471 @@
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
+ async function getCredentials() {
14
+ try {
15
+ if (await fs.pathExists(CREDENTIALS_FILE)) {
16
+ return await fs.readJSON(CREDENTIALS_FILE);
17
+ }
18
+ } catch {
19
+ }
20
+ return null;
21
+ }
22
+ async function requireAuth() {
23
+ const credentials = await getCredentials();
24
+ if (!credentials) {
25
+ console.error(chalk.red("\n\u2717 Not logged in\n"));
26
+ console.log(chalk.dim("Run `tthr login` to authenticate\n"));
27
+ process.exit(1);
28
+ }
29
+ if (credentials.expiresAt) {
30
+ const expiresAt = new Date(credentials.expiresAt);
31
+ if (/* @__PURE__ */ new Date() > expiresAt) {
32
+ console.error(chalk.red("\n\u2717 Session expired\n"));
33
+ console.log(chalk.dim("Run `tthr login` to authenticate\n"));
34
+ process.exit(1);
35
+ }
36
+ }
37
+ return credentials;
38
+ }
39
+ async function saveCredentials(credentials) {
40
+ await fs.ensureDir(CONFIG_DIR);
41
+ await fs.writeJSON(CREDENTIALS_FILE, credentials, { spaces: 2, mode: 384 });
42
+ }
43
+ async function clearCredentials() {
44
+ try {
45
+ await fs.remove(CREDENTIALS_FILE);
46
+ } catch {
47
+ }
48
+ }
49
+
50
+ // src/utils/config.ts
51
+ import fs2 from "fs-extra";
52
+ import path2 from "path";
53
+ var DEFAULT_CONFIG = {
54
+ schema: "./tether/schema.ts",
55
+ functions: "./tether/functions",
56
+ output: "./tether/_generated",
57
+ dev: {
58
+ port: 3001,
59
+ host: "localhost"
60
+ },
61
+ database: {
62
+ walMode: true
63
+ }
64
+ };
65
+ async function loadConfig(cwd = process.cwd()) {
66
+ const configPath = path2.resolve(cwd, "tether.config.ts");
67
+ if (!await fs2.pathExists(configPath)) {
68
+ return DEFAULT_CONFIG;
69
+ }
70
+ const configSource = await fs2.readFile(configPath, "utf-8");
71
+ const config = {};
72
+ const schemaMatch = configSource.match(/schema\s*:\s*['"]([^'"]+)['"]/);
73
+ if (schemaMatch) {
74
+ config.schema = schemaMatch[1];
75
+ }
76
+ const functionsMatch = configSource.match(/functions\s*:\s*['"]([^'"]+)['"]/);
77
+ if (functionsMatch) {
78
+ config.functions = functionsMatch[1];
79
+ }
80
+ const outputMatch = configSource.match(/output\s*:\s*['"]([^'"]+)['"]/);
81
+ if (outputMatch) {
82
+ config.output = outputMatch[1];
83
+ }
84
+ const envMatch = configSource.match(/environment\s*:\s*['"]([^'"]+)['"]/);
85
+ if (envMatch) {
86
+ config.environment = envMatch[1];
87
+ }
88
+ const portMatch = configSource.match(/port\s*:\s*(\d+)/);
89
+ if (portMatch) {
90
+ config.dev = { ...config.dev, port: parseInt(portMatch[1], 10) };
91
+ }
92
+ const hostMatch = configSource.match(/host\s*:\s*['"]([^'"]+)['"]/);
93
+ if (hostMatch) {
94
+ config.dev = { ...config.dev, host: hostMatch[1] };
95
+ }
96
+ return {
97
+ ...DEFAULT_CONFIG,
98
+ ...config,
99
+ dev: { ...DEFAULT_CONFIG.dev, ...config.dev },
100
+ database: { ...DEFAULT_CONFIG.database, ...config.database }
101
+ };
102
+ }
103
+ function resolvePath(configPath, cwd = process.cwd()) {
104
+ const normalised = configPath.replace(/^\.\//, "");
105
+ return path2.resolve(cwd, normalised);
106
+ }
107
+ async function detectFramework(cwd = process.cwd()) {
108
+ const packageJsonPath = path2.resolve(cwd, "package.json");
109
+ if (!await fs2.pathExists(packageJsonPath)) {
110
+ return "unknown";
111
+ }
112
+ try {
113
+ const packageJson = await fs2.readJson(packageJsonPath);
114
+ const deps = {
115
+ ...packageJson.dependencies,
116
+ ...packageJson.devDependencies
117
+ };
118
+ if (deps.nuxt || deps["@nuxt/kit"]) {
119
+ return "nuxt";
120
+ }
121
+ if (deps.next) {
122
+ return "next";
123
+ }
124
+ if (deps["@sveltejs/kit"]) {
125
+ return "sveltekit";
126
+ }
127
+ if (deps.vite && !deps.nuxt && !deps.next && !deps["@sveltejs/kit"]) {
128
+ return "vite";
129
+ }
130
+ return "vanilla";
131
+ } catch {
132
+ return "unknown";
133
+ }
134
+ }
135
+ function getFrameworkDevCommand(framework) {
136
+ switch (framework) {
137
+ case "nuxt":
138
+ return "nuxt dev";
139
+ case "next":
140
+ return "next dev";
141
+ case "sveltekit":
142
+ return "vite dev";
143
+ case "vite":
144
+ return "vite dev";
145
+ case "vanilla":
146
+ return null;
147
+ // No default dev server for vanilla
148
+ default:
149
+ return null;
150
+ }
151
+ }
152
+
153
+ // src/commands/generate.ts
154
+ function parseSchemaFile(source) {
155
+ const tables = [];
156
+ const schemaMatch = source.match(/defineSchema\s*\(\s*\{([\s\S]*)\}\s*\)/);
157
+ if (!schemaMatch) return tables;
158
+ const schemaContent = schemaMatch[1];
159
+ const tableStartRegex = /(\w+)\s*:\s*\{/g;
160
+ let match;
161
+ while ((match = tableStartRegex.exec(schemaContent)) !== null) {
162
+ const tableName = match[1];
163
+ const startOffset = match.index + match[0].length;
164
+ let braceCount = 1;
165
+ let endOffset = startOffset;
166
+ for (let i = startOffset; i < schemaContent.length && braceCount > 0; i++) {
167
+ const char = schemaContent[i];
168
+ if (char === "{") braceCount++;
169
+ else if (char === "}") braceCount--;
170
+ endOffset = i;
171
+ }
172
+ const columnsContent = schemaContent.slice(startOffset, endOffset);
173
+ const columns = parseColumns(columnsContent);
174
+ tables.push({ name: tableName, columns });
175
+ }
176
+ return tables;
177
+ }
178
+ function parseColumns(content) {
179
+ const columns = [];
180
+ const columnRegex = /(\w+)\s*:\s*(\w+)\s*\(\s*\)([^,\n}]*)/g;
181
+ let match;
182
+ while ((match = columnRegex.exec(content)) !== null) {
183
+ const name = match[1];
184
+ const schemaType = match[2];
185
+ const modifiers = match[3] || "";
186
+ const nullable = !modifiers.includes(".notNull()");
187
+ columns.push({
188
+ name,
189
+ type: schemaTypeToTS(schemaType),
190
+ nullable
191
+ });
192
+ }
193
+ return columns;
194
+ }
195
+ function schemaTypeToTS(schemaType) {
196
+ switch (schemaType) {
197
+ case "text":
198
+ return "string";
199
+ case "integer":
200
+ return "number";
201
+ case "real":
202
+ return "number";
203
+ case "boolean":
204
+ return "boolean";
205
+ case "timestamp":
206
+ return "string";
207
+ case "json":
208
+ return "unknown";
209
+ case "blob":
210
+ return "Uint8Array";
211
+ case "asset":
212
+ return "string";
213
+ // Asset ID (UUID) referencing _tether_assets
214
+ default:
215
+ return "unknown";
216
+ }
217
+ }
218
+ function tableNameToInterface(tableName) {
219
+ let name = tableName;
220
+ if (name.endsWith("ies")) {
221
+ name = name.slice(0, -3) + "y";
222
+ } else if (name.endsWith("s") && !name.endsWith("ss")) {
223
+ name = name.slice(0, -1);
224
+ }
225
+ return name.charAt(0).toUpperCase() + name.slice(1);
226
+ }
227
+ function generateDbFile(tables) {
228
+ const lines = [
229
+ "// Auto-generated by Tether CLI - do not edit manually",
230
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
231
+ "",
232
+ "import { createDatabaseProxy, type TetherDatabase } from '@tthr/client';",
233
+ "import {",
234
+ " query as baseQuery,",
235
+ " mutation as baseMutation,",
236
+ " action as baseAction,",
237
+ " type QueryDefinition,",
238
+ " type MutationDefinition,",
239
+ " type ActionDefinition,",
240
+ " z,",
241
+ "} from '@tthr/server';",
242
+ ""
243
+ ];
244
+ for (const table of tables) {
245
+ const interfaceName = tableNameToInterface(table.name);
246
+ lines.push(`export interface ${interfaceName} {`);
247
+ lines.push(" _id: string;");
248
+ for (const col of table.columns) {
249
+ const typeStr = col.nullable ? `${col.type} | null` : col.type;
250
+ const optional = col.nullable ? "?" : "";
251
+ lines.push(` ${col.name}${optional}: ${typeStr};`);
252
+ }
253
+ lines.push(" _createdAt: string;");
254
+ lines.push(" _updatedAt?: string | null;");
255
+ lines.push(" _deletedAt?: string | null;");
256
+ lines.push("}");
257
+ lines.push("");
258
+ }
259
+ lines.push("export interface Schema {");
260
+ for (const table of tables) {
261
+ const interfaceName = tableNameToInterface(table.name);
262
+ lines.push(` ${table.name}: ${interfaceName};`);
263
+ }
264
+ lines.push("}");
265
+ lines.push("");
266
+ lines.push("// Database client with typed tables");
267
+ lines.push("// This is a proxy that will be populated by the Tether runtime");
268
+ lines.push("export const db: TetherDatabase<Schema> = createDatabaseProxy<Schema>();");
269
+ lines.push("");
270
+ lines.push("// ============================================================================");
271
+ lines.push("// Typed function wrappers - use these instead of importing from @tthr/server");
272
+ lines.push("// This ensures the `db` parameter in handlers is properly typed with Schema");
273
+ lines.push("// ============================================================================");
274
+ lines.push("");
275
+ lines.push("/**");
276
+ lines.push(" * Define a query function with typed database access.");
277
+ lines.push(" * The `db` parameter in the handler will have full type safety for your schema.");
278
+ lines.push(" */");
279
+ lines.push("export function query<TArgs = void, TResult = unknown>(");
280
+ lines.push(" definition: QueryDefinition<TArgs, TResult, Schema>");
281
+ lines.push("): QueryDefinition<TArgs, TResult, Schema> {");
282
+ lines.push(" return baseQuery(definition);");
283
+ lines.push("}");
284
+ lines.push("");
285
+ lines.push("/**");
286
+ lines.push(" * Define a mutation function with typed database access.");
287
+ lines.push(" * The `db` parameter in the handler will have full type safety for your schema.");
288
+ lines.push(" */");
289
+ lines.push("export function mutation<TArgs = void, TResult = unknown>(");
290
+ lines.push(" definition: MutationDefinition<TArgs, TResult, Schema>");
291
+ lines.push("): MutationDefinition<TArgs, TResult, Schema> {");
292
+ lines.push(" return baseMutation(definition);");
293
+ lines.push("}");
294
+ lines.push("");
295
+ lines.push("/**");
296
+ lines.push(" * Define an action function with typed database access.");
297
+ lines.push(" * The `db` parameter in the handler will have full type safety for your schema.");
298
+ lines.push(" */");
299
+ lines.push("export function action<TArgs = void, TResult = unknown>(");
300
+ lines.push(" definition: ActionDefinition<TArgs, TResult, Schema>");
301
+ lines.push("): ActionDefinition<TArgs, TResult, Schema> {");
302
+ lines.push(" return baseAction(definition);");
303
+ lines.push("}");
304
+ lines.push("");
305
+ lines.push("// Re-export z for convenience");
306
+ lines.push("export { z };");
307
+ lines.push("");
308
+ return lines.join("\n");
309
+ }
310
+ async function parseFunctionsDir(functionsDir) {
311
+ const functions = [];
312
+ if (!await fs3.pathExists(functionsDir)) {
313
+ return functions;
314
+ }
315
+ const files = await fs3.readdir(functionsDir);
316
+ for (const file of files) {
317
+ if (!file.endsWith(".ts") && !file.endsWith(".js")) continue;
318
+ const filePath = path3.join(functionsDir, file);
319
+ const stat = await fs3.stat(filePath);
320
+ if (!stat.isFile()) continue;
321
+ const moduleName = file.replace(/\.(ts|js)$/, "");
322
+ const source = await fs3.readFile(filePath, "utf-8");
323
+ const exportRegex = /export\s+const\s+(\w+)\s*=\s*(query|mutation|action)\s*\(/g;
324
+ let match;
325
+ while ((match = exportRegex.exec(source)) !== null) {
326
+ functions.push({
327
+ name: match[1],
328
+ moduleName
329
+ });
330
+ }
331
+ }
332
+ return functions;
333
+ }
334
+ async function generateApiFile(functionsDir) {
335
+ const functions = await parseFunctionsDir(functionsDir);
336
+ const moduleMap = /* @__PURE__ */ new Map();
337
+ for (const fn of functions) {
338
+ if (!moduleMap.has(fn.moduleName)) {
339
+ moduleMap.set(fn.moduleName, []);
340
+ }
341
+ moduleMap.get(fn.moduleName).push(fn.name);
342
+ }
343
+ const lines = [
344
+ "// Auto-generated by Tether CLI - do not edit manually",
345
+ `// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
346
+ "",
347
+ "import { createApiProxy } from '@tthr/client';",
348
+ "",
349
+ "/**",
350
+ " * API function reference type for useQuery/useMutation.",
351
+ ' * The _name property contains the function path (e.g., "users.list").',
352
+ " */",
353
+ "export interface ApiFunction<TArgs = unknown, TResult = unknown> {",
354
+ " _name: string;",
355
+ " _args?: TArgs;",
356
+ " _result?: TResult;",
357
+ "}",
358
+ ""
359
+ ];
360
+ if (moduleMap.size > 0) {
361
+ for (const [moduleName, fnNames] of moduleMap) {
362
+ const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
363
+ lines.push(`export interface ${interfaceName} {`);
364
+ for (const fnName of fnNames) {
365
+ lines.push(` ${fnName}: ApiFunction;`);
366
+ }
367
+ lines.push("}");
368
+ lines.push("");
369
+ }
370
+ lines.push("export interface Api {");
371
+ for (const moduleName of moduleMap.keys()) {
372
+ const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
373
+ lines.push(` ${moduleName}: ${interfaceName};`);
374
+ }
375
+ lines.push("}");
376
+ } else {
377
+ lines.push("/**");
378
+ lines.push(" * Flexible API type that allows access to any function path.");
379
+ lines.push(" * Functions are accessed as api.moduleName.functionName");
380
+ lines.push(" * The actual types depend on your function definitions.");
381
+ lines.push(" */");
382
+ lines.push("export type Api = {");
383
+ lines.push(" [module: string]: {");
384
+ lines.push(" [fn: string]: ApiFunction;");
385
+ lines.push(" };");
386
+ lines.push("};");
387
+ }
388
+ lines.push("");
389
+ lines.push("// API client proxy - provides typed access to your functions");
390
+ lines.push("// On the client: returns { _name } references for useQuery/useMutation");
391
+ lines.push("// In Tether functions: calls the actual function implementation");
392
+ lines.push("export const api = createApiProxy<Api>();");
393
+ lines.push("");
394
+ return lines.join("\n");
395
+ }
396
+ async function generateTypes(options = {}) {
397
+ const config = await loadConfig();
398
+ const schemaPath = resolvePath(config.schema);
399
+ const outputDir = resolvePath(config.output);
400
+ const functionsDir = resolvePath(config.functions);
401
+ if (!await fs3.pathExists(schemaPath)) {
402
+ throw new Error(`Schema file not found: ${schemaPath}`);
403
+ }
404
+ const schemaSource = await fs3.readFile(schemaPath, "utf-8");
405
+ const tables = parseSchemaFile(schemaSource);
406
+ await fs3.ensureDir(outputDir);
407
+ await fs3.writeFile(
408
+ path3.join(outputDir, "db.ts"),
409
+ generateDbFile(tables)
410
+ );
411
+ await fs3.writeFile(
412
+ path3.join(outputDir, "api.ts"),
413
+ await generateApiFile(functionsDir)
414
+ );
415
+ await fs3.writeFile(
416
+ path3.join(outputDir, "index.ts"),
417
+ `// Auto-generated by Tether CLI - do not edit manually
418
+ export * from './db';
419
+ export * from './api';
420
+ `
421
+ );
422
+ return { tables, outputDir };
423
+ }
424
+ async function generateCommand() {
425
+ await requireAuth();
426
+ const configPath = path3.resolve(process.cwd(), "tether.config.ts");
427
+ if (!await fs3.pathExists(configPath)) {
428
+ console.log(chalk2.red("\nError: Not a Tether project"));
429
+ console.log(chalk2.dim("Run `tthr init` to create a new project\n"));
430
+ process.exit(1);
431
+ }
432
+ console.log(chalk2.bold("\n\u26A1 Generating types from schema\n"));
433
+ const spinner = ora("Reading schema...").start();
434
+ try {
435
+ spinner.text = "Generating types...";
436
+ const { tables, outputDir } = await generateTypes();
437
+ if (tables.length === 0) {
438
+ spinner.warn("No tables found in schema");
439
+ console.log(chalk2.dim(" Make sure your schema uses defineSchema({ ... })\n"));
440
+ return;
441
+ }
442
+ spinner.succeed(`Types generated for ${tables.length} table(s)`);
443
+ console.log("\n" + chalk2.green("\u2713") + " Tables:");
444
+ for (const table of tables) {
445
+ console.log(chalk2.dim(` - ${table.name} (${table.columns.length} columns)`));
446
+ }
447
+ const relativeOutput = path3.relative(process.cwd(), outputDir);
448
+ console.log("\n" + chalk2.green("\u2713") + " Generated files:");
449
+ console.log(chalk2.dim(` ${relativeOutput}/db.ts`));
450
+ console.log(chalk2.dim(` ${relativeOutput}/api.ts`));
451
+ console.log(chalk2.dim(` ${relativeOutput}/index.ts
452
+ `));
453
+ } catch (error) {
454
+ spinner.fail("Failed to generate types");
455
+ console.error(chalk2.red(error instanceof Error ? error.message : "Unknown error"));
456
+ process.exit(1);
457
+ }
458
+ }
459
+
460
+ export {
461
+ getCredentials,
462
+ requireAuth,
463
+ saveCredentials,
464
+ clearCredentials,
465
+ loadConfig,
466
+ resolvePath,
467
+ detectFramework,
468
+ getFrameworkDevCommand,
469
+ generateTypes,
470
+ generateCommand
471
+ };
@@ -0,0 +1,8 @@
1
+ import {
2
+ generateCommand,
3
+ generateTypes
4
+ } from "./chunk-QOJ5HQFG.js";
5
+ export {
6
+ generateCommand,
7
+ generateTypes
8
+ };
@@ -0,0 +1,8 @@
1
+ import {
2
+ generateCommand,
3
+ generateTypes
4
+ } from "./chunk-T4NH3NQS.js";
5
+ export {
6
+ generateCommand,
7
+ generateTypes
8
+ };
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  requireAuth,
10
10
  resolvePath,
11
11
  saveCredentials
12
- } from "./chunk-EIJEC3SG.js";
12
+ } from "./chunk-QOJ5HQFG.js";
13
13
 
14
14
  // src/index.ts
15
15
  import { Command } from "commander";
@@ -1510,7 +1510,7 @@ async function runGenerate(spinner) {
1510
1510
  }
1511
1511
  isGenerating = true;
1512
1512
  try {
1513
- const { generateTypes } = await import("./generate-56PV7NJX.js");
1513
+ const { generateTypes } = await import("./generate-C3VMXUXE.js");
1514
1514
  spinner.text = "Regenerating types...";
1515
1515
  await generateTypes({ silent: true });
1516
1516
  spinner.succeed("Types regenerated");
@@ -1695,7 +1695,7 @@ async function devCommand(options) {
1695
1695
  }
1696
1696
  }
1697
1697
  spinner.text = "Generating types...";
1698
- const { generateTypes } = await import("./generate-56PV7NJX.js");
1698
+ const { generateTypes } = await import("./generate-C3VMXUXE.js");
1699
1699
  await generateTypes({ silent: true });
1700
1700
  spinner.succeed("Types generated");
1701
1701
  spinner.start("Setting up file watchers...");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tthr",
3
- "version": "0.0.48",
3
+ "version": "0.0.49",
4
4
  "description": "Tether CLI - project scaffolding and deployment",
5
5
  "type": "module",
6
6
  "bin": {