tthr 0.3.4 → 0.3.6
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.
- package/dist/chunk-CPBP6GSK.js +684 -0
- package/dist/chunk-VBD4DOWS.js +649 -0
- package/dist/generate-FTLMBVLH.js +8 -0
- package/dist/generate-LVU4IEMB.js +8 -0
- package/dist/index.js +3 -3
- package/package.json +1 -1
|
@@ -0,0 +1,684 @@
|
|
|
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 extractSingleType(source, typeName) {
|
|
265
|
+
const interfaceStart = new RegExp(`(?:export\\s+)?interface\\s+${typeName}\\s*\\{`);
|
|
266
|
+
const interfaceMatch = interfaceStart.exec(source);
|
|
267
|
+
if (interfaceMatch) {
|
|
268
|
+
const braceStart = interfaceMatch.index + interfaceMatch[0].length;
|
|
269
|
+
let braceCount = 1;
|
|
270
|
+
let endIdx = braceStart;
|
|
271
|
+
for (let i = braceStart; i < source.length && braceCount > 0; i++) {
|
|
272
|
+
if (source[i] === "{") braceCount++;
|
|
273
|
+
else if (source[i] === "}") braceCount--;
|
|
274
|
+
endIdx = i;
|
|
275
|
+
}
|
|
276
|
+
return source.slice(interfaceMatch.index, endIdx + 1).replace(/^export\s+/, "");
|
|
277
|
+
}
|
|
278
|
+
const typeStart = new RegExp(`(?:export\\s+)?type\\s+${typeName}\\s*=`);
|
|
279
|
+
const typeMatch = typeStart.exec(source);
|
|
280
|
+
if (typeMatch) {
|
|
281
|
+
const semiIdx = source.indexOf(";", typeMatch.index);
|
|
282
|
+
if (semiIdx !== -1) {
|
|
283
|
+
return source.slice(typeMatch.index, semiIdx + 1).replace(/^export\s+/, "");
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
function extractTypeDefinitions(source, typeNames) {
|
|
289
|
+
if (typeNames.size === 0) return [];
|
|
290
|
+
const allDefinedTypes = /* @__PURE__ */ new Set();
|
|
291
|
+
const typeDefRegex = /(?:export\s+)?(?:interface|type)\s+(\w+)/g;
|
|
292
|
+
let m;
|
|
293
|
+
while ((m = typeDefRegex.exec(source)) !== null) {
|
|
294
|
+
allDefinedTypes.add(m[1]);
|
|
295
|
+
}
|
|
296
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
297
|
+
const queue = [...typeNames];
|
|
298
|
+
while (queue.length > 0) {
|
|
299
|
+
const name = queue.shift();
|
|
300
|
+
if (resolved.has(name)) continue;
|
|
301
|
+
const block = extractSingleType(source, name);
|
|
302
|
+
if (!block) continue;
|
|
303
|
+
resolved.set(name, block);
|
|
304
|
+
for (const definedType of allDefinedTypes) {
|
|
305
|
+
if (!resolved.has(definedType) && !queue.includes(definedType)) {
|
|
306
|
+
const refRegex = new RegExp(`\\b${definedType}\\b`);
|
|
307
|
+
if (refRegex.test(block)) {
|
|
308
|
+
queue.push(definedType);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
const ordered = [];
|
|
314
|
+
const visited = /* @__PURE__ */ new Set();
|
|
315
|
+
function visit(name) {
|
|
316
|
+
if (visited.has(name)) return;
|
|
317
|
+
visited.add(name);
|
|
318
|
+
const block = resolved.get(name);
|
|
319
|
+
if (!block) return;
|
|
320
|
+
for (const dep of resolved.keys()) {
|
|
321
|
+
if (dep !== name && new RegExp(`\\b${dep}\\b`).test(block)) {
|
|
322
|
+
visit(dep);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
ordered.push(name);
|
|
326
|
+
}
|
|
327
|
+
for (const name of resolved.keys()) {
|
|
328
|
+
visit(name);
|
|
329
|
+
}
|
|
330
|
+
return ordered.map((name) => resolved.get(name));
|
|
331
|
+
}
|
|
332
|
+
function tableNameToInterface(tableName) {
|
|
333
|
+
let name = tableName;
|
|
334
|
+
if (name.endsWith("ies")) {
|
|
335
|
+
name = name.slice(0, -3) + "y";
|
|
336
|
+
} else if (name.endsWith("s") && !name.endsWith("ss")) {
|
|
337
|
+
name = name.slice(0, -1);
|
|
338
|
+
}
|
|
339
|
+
return name.charAt(0).toUpperCase() + name.slice(1);
|
|
340
|
+
}
|
|
341
|
+
function generateDbFile(tables, schemaSource) {
|
|
342
|
+
const TS_PRIMITIVES = /* @__PURE__ */ new Set(["number", "string", "boolean", "unknown", "any", "void", "never", "undefined", "null", "object"]);
|
|
343
|
+
const jsonTypes = /* @__PURE__ */ new Set();
|
|
344
|
+
for (const table of tables) {
|
|
345
|
+
for (const col of table.columns) {
|
|
346
|
+
if (col.jsonType) {
|
|
347
|
+
const baseType = col.jsonType.replace(/\s*\|\s*null/g, "").replace(/\[\]/g, "").trim();
|
|
348
|
+
if (!TS_PRIMITIVES.has(baseType)) {
|
|
349
|
+
jsonTypes.add(baseType);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
const lines = [
|
|
355
|
+
"// Auto-generated by Tether CLI - do not edit manually",
|
|
356
|
+
`// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
|
|
357
|
+
"",
|
|
358
|
+
"import { createDatabaseProxy, type TetherDatabase } from '@tthr/client';",
|
|
359
|
+
"import {",
|
|
360
|
+
" type QueryDefinition,",
|
|
361
|
+
" type MutationDefinition,",
|
|
362
|
+
" z,",
|
|
363
|
+
"} from '@tthr/server';",
|
|
364
|
+
"import type { TetherEnv } from './env';"
|
|
365
|
+
];
|
|
366
|
+
if (jsonTypes.size > 0) {
|
|
367
|
+
const typeBlocks = extractTypeDefinitions(schemaSource, jsonTypes);
|
|
368
|
+
if (typeBlocks.length > 0) {
|
|
369
|
+
lines.push("");
|
|
370
|
+
lines.push("// Schema types (inlined from schema.ts)");
|
|
371
|
+
for (const block of typeBlocks) {
|
|
372
|
+
lines.push(block);
|
|
373
|
+
lines.push("");
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
lines.push("");
|
|
378
|
+
lines.push("// Asset type returned by the API for asset columns");
|
|
379
|
+
lines.push("export interface TetherAsset {");
|
|
380
|
+
lines.push(" id: string;");
|
|
381
|
+
lines.push(" filename: string;");
|
|
382
|
+
lines.push(" contentType: string;");
|
|
383
|
+
lines.push(" size: number;");
|
|
384
|
+
lines.push(" url: string;");
|
|
385
|
+
lines.push(" createdAt: string;");
|
|
386
|
+
lines.push("}");
|
|
387
|
+
lines.push("");
|
|
388
|
+
for (const table of tables) {
|
|
389
|
+
const interfaceName = tableNameToInterface(table.name);
|
|
390
|
+
lines.push(`export interface ${interfaceName} {`);
|
|
391
|
+
lines.push(" _id: string;");
|
|
392
|
+
for (const col of table.columns) {
|
|
393
|
+
let colType;
|
|
394
|
+
if (col.oneOf && col.oneOf.length > 0) {
|
|
395
|
+
colType = col.oneOf.map((v) => `'${v}'`).join(" | ");
|
|
396
|
+
} else {
|
|
397
|
+
colType = col.jsonType || col.type;
|
|
398
|
+
}
|
|
399
|
+
const typeStr = col.nullable ? `${colType} | null` : colType;
|
|
400
|
+
const optional = col.nullable ? "?" : "";
|
|
401
|
+
lines.push(` ${col.name}${optional}: ${typeStr};`);
|
|
402
|
+
}
|
|
403
|
+
lines.push(" _createdAt: string;");
|
|
404
|
+
lines.push(" _updatedAt?: string | null;");
|
|
405
|
+
lines.push(" _deletedAt?: string | null;");
|
|
406
|
+
lines.push("}");
|
|
407
|
+
lines.push("");
|
|
408
|
+
}
|
|
409
|
+
lines.push("export interface Schema {");
|
|
410
|
+
for (const table of tables) {
|
|
411
|
+
const interfaceName = tableNameToInterface(table.name);
|
|
412
|
+
lines.push(` ${table.name}: ${interfaceName};`);
|
|
413
|
+
}
|
|
414
|
+
lines.push("}");
|
|
415
|
+
lines.push("");
|
|
416
|
+
lines.push("// Database client with typed tables");
|
|
417
|
+
lines.push("// This is a proxy that will be populated by the Tether runtime");
|
|
418
|
+
lines.push("export const db: TetherDatabase<Schema> = createDatabaseProxy<Schema>();");
|
|
419
|
+
lines.push("");
|
|
420
|
+
lines.push("// ============================================================================");
|
|
421
|
+
lines.push("// Typed function wrappers - use these instead of importing from @tthr/server");
|
|
422
|
+
lines.push("// This ensures the `db` and `env` parameters in handlers are properly typed");
|
|
423
|
+
lines.push("// ============================================================================");
|
|
424
|
+
lines.push("");
|
|
425
|
+
lines.push("/**");
|
|
426
|
+
lines.push(" * Define a query function with typed database and environment variable access.");
|
|
427
|
+
lines.push(" * The `db` and `env` parameters in the handler will have full type safety.");
|
|
428
|
+
lines.push(" */");
|
|
429
|
+
lines.push("export function query<TArgs = void, TResult = unknown>(");
|
|
430
|
+
lines.push(" definition: QueryDefinition<TArgs, TResult, Schema, TetherEnv>");
|
|
431
|
+
lines.push("): QueryDefinition<TArgs, TResult, Schema, TetherEnv> {");
|
|
432
|
+
lines.push(" return definition;");
|
|
433
|
+
lines.push("}");
|
|
434
|
+
lines.push("");
|
|
435
|
+
lines.push("/**");
|
|
436
|
+
lines.push(" * Define a mutation function with typed database and environment variable access.");
|
|
437
|
+
lines.push(" * The `db` and `env` parameters in the handler will have full type safety.");
|
|
438
|
+
lines.push(" */");
|
|
439
|
+
lines.push("export function mutation<TArgs = void, TResult = unknown>(");
|
|
440
|
+
lines.push(" definition: MutationDefinition<TArgs, TResult, Schema, TetherEnv>");
|
|
441
|
+
lines.push("): MutationDefinition<TArgs, TResult, Schema, TetherEnv> {");
|
|
442
|
+
lines.push(" return definition;");
|
|
443
|
+
lines.push("}");
|
|
444
|
+
lines.push("");
|
|
445
|
+
lines.push("// Re-export z for convenience");
|
|
446
|
+
lines.push("export { z };");
|
|
447
|
+
lines.push("");
|
|
448
|
+
return lines.join("\n");
|
|
449
|
+
}
|
|
450
|
+
async function parseFunctionsDir(functionsDir) {
|
|
451
|
+
const functions = [];
|
|
452
|
+
if (!await fs3.pathExists(functionsDir)) {
|
|
453
|
+
return functions;
|
|
454
|
+
}
|
|
455
|
+
const files = await fs3.readdir(functionsDir);
|
|
456
|
+
for (const file of files) {
|
|
457
|
+
if (!file.endsWith(".ts") && !file.endsWith(".js")) continue;
|
|
458
|
+
const filePath = path3.join(functionsDir, file);
|
|
459
|
+
const stat = await fs3.stat(filePath);
|
|
460
|
+
if (!stat.isFile()) continue;
|
|
461
|
+
const moduleName = file.replace(/\.(ts|js)$/, "");
|
|
462
|
+
const source = await fs3.readFile(filePath, "utf-8");
|
|
463
|
+
const exportRegex = /export\s+const\s+(\w+)\s*=\s*(query|mutation)\s*\(/g;
|
|
464
|
+
let match;
|
|
465
|
+
while ((match = exportRegex.exec(source)) !== null) {
|
|
466
|
+
functions.push({
|
|
467
|
+
name: match[1],
|
|
468
|
+
moduleName
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
return functions;
|
|
473
|
+
}
|
|
474
|
+
async function generateApiFile(functionsDir) {
|
|
475
|
+
const functions = await parseFunctionsDir(functionsDir);
|
|
476
|
+
const moduleMap = /* @__PURE__ */ new Map();
|
|
477
|
+
for (const fn of functions) {
|
|
478
|
+
if (!moduleMap.has(fn.moduleName)) {
|
|
479
|
+
moduleMap.set(fn.moduleName, []);
|
|
480
|
+
}
|
|
481
|
+
moduleMap.get(fn.moduleName).push(fn.name);
|
|
482
|
+
}
|
|
483
|
+
const lines = [
|
|
484
|
+
"// Auto-generated by Tether CLI - do not edit manually",
|
|
485
|
+
`// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
|
|
486
|
+
"",
|
|
487
|
+
"import { createApiProxy } from '@tthr/client';",
|
|
488
|
+
"",
|
|
489
|
+
"/**",
|
|
490
|
+
" * API function reference type for useQuery/useMutation.",
|
|
491
|
+
' * The _name property contains the function path (e.g., "users.list").',
|
|
492
|
+
" */",
|
|
493
|
+
"export interface ApiFunction<TArgs = unknown, TResult = unknown> {",
|
|
494
|
+
" _name: string;",
|
|
495
|
+
" _args?: TArgs;",
|
|
496
|
+
" _result?: TResult;",
|
|
497
|
+
"}",
|
|
498
|
+
""
|
|
499
|
+
];
|
|
500
|
+
if (moduleMap.size > 0) {
|
|
501
|
+
for (const [moduleName, fnNames] of moduleMap) {
|
|
502
|
+
const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
|
|
503
|
+
lines.push(`export interface ${interfaceName} {`);
|
|
504
|
+
for (const fnName of fnNames) {
|
|
505
|
+
lines.push(` ${fnName}: ApiFunction;`);
|
|
506
|
+
}
|
|
507
|
+
lines.push("}");
|
|
508
|
+
lines.push("");
|
|
509
|
+
}
|
|
510
|
+
lines.push("export interface Api {");
|
|
511
|
+
for (const moduleName of moduleMap.keys()) {
|
|
512
|
+
const interfaceName = moduleName.charAt(0).toUpperCase() + moduleName.slice(1) + "Api";
|
|
513
|
+
lines.push(` ${moduleName}: ${interfaceName};`);
|
|
514
|
+
}
|
|
515
|
+
lines.push("}");
|
|
516
|
+
} else {
|
|
517
|
+
lines.push("/**");
|
|
518
|
+
lines.push(" * Flexible API type that allows access to any function path.");
|
|
519
|
+
lines.push(" * Functions are accessed as api.moduleName.functionName");
|
|
520
|
+
lines.push(" * The actual types depend on your function definitions.");
|
|
521
|
+
lines.push(" */");
|
|
522
|
+
lines.push("export type Api = {");
|
|
523
|
+
lines.push(" [module: string]: {");
|
|
524
|
+
lines.push(" [fn: string]: ApiFunction;");
|
|
525
|
+
lines.push(" };");
|
|
526
|
+
lines.push("};");
|
|
527
|
+
}
|
|
528
|
+
lines.push("");
|
|
529
|
+
lines.push("// API client proxy - provides typed access to your functions");
|
|
530
|
+
lines.push("// On the client: returns { _name } references for useQuery/useMutation");
|
|
531
|
+
lines.push("// In Tether functions: calls the actual function implementation");
|
|
532
|
+
lines.push("export const api = createApiProxy<Api>();");
|
|
533
|
+
lines.push("");
|
|
534
|
+
return lines.join("\n");
|
|
535
|
+
}
|
|
536
|
+
async function fetchEnvVarKeys(projectId, environment) {
|
|
537
|
+
const credentials = await getCredentials();
|
|
538
|
+
if (!credentials) return [];
|
|
539
|
+
const envPath = environment !== "production" ? `/projects/${projectId}/env/${environment}/env-vars` : `/projects/${projectId}/env-vars`;
|
|
540
|
+
try {
|
|
541
|
+
const response = await fetch(`${API_URL2}${envPath}`, {
|
|
542
|
+
headers: {
|
|
543
|
+
"Authorization": `Bearer ${credentials.accessToken}`
|
|
544
|
+
}
|
|
545
|
+
});
|
|
546
|
+
if (!response.ok) return [];
|
|
547
|
+
const data = await response.json();
|
|
548
|
+
return (data.envVars || []).map((v) => v.key).sort();
|
|
549
|
+
} catch {
|
|
550
|
+
return [];
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
function generateEnvFile(keys) {
|
|
554
|
+
const lines = [
|
|
555
|
+
"// Auto-generated by Tether CLI - do not edit manually",
|
|
556
|
+
`// Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}`,
|
|
557
|
+
"",
|
|
558
|
+
"/**",
|
|
559
|
+
" * Typed environment variables for this project.",
|
|
560
|
+
" * Keys are fetched from the Tether API \u2014 values are never exposed.",
|
|
561
|
+
' * Use `env.get("KEY")` in your functions to access them.',
|
|
562
|
+
" */",
|
|
563
|
+
""
|
|
564
|
+
];
|
|
565
|
+
if (keys.length > 0) {
|
|
566
|
+
lines.push("export type EnvVarKey =");
|
|
567
|
+
for (let i = 0; i < keys.length; i++) {
|
|
568
|
+
const sep = i === keys.length - 1 ? ";" : "";
|
|
569
|
+
lines.push(` | '${keys[i]}'${sep}`);
|
|
570
|
+
}
|
|
571
|
+
lines.push("");
|
|
572
|
+
lines.push("export interface TetherEnv {");
|
|
573
|
+
for (const key of keys) {
|
|
574
|
+
lines.push(` ${key}: string;`);
|
|
575
|
+
}
|
|
576
|
+
lines.push("}");
|
|
577
|
+
} else {
|
|
578
|
+
lines.push("export type EnvVarKey = string;");
|
|
579
|
+
lines.push("");
|
|
580
|
+
lines.push("export interface TetherEnv {");
|
|
581
|
+
lines.push(" [key: string]: string;");
|
|
582
|
+
lines.push("}");
|
|
583
|
+
}
|
|
584
|
+
lines.push("");
|
|
585
|
+
return lines.join("\n");
|
|
586
|
+
}
|
|
587
|
+
async function generateTypes(options = {}) {
|
|
588
|
+
const config = await loadConfig();
|
|
589
|
+
const schemaPath = resolvePath(config.schema);
|
|
590
|
+
const outputDir = resolvePath(config.output);
|
|
591
|
+
const functionsDir = resolvePath(config.functions);
|
|
592
|
+
if (!await fs3.pathExists(schemaPath)) {
|
|
593
|
+
throw new Error(`Schema file not found: ${schemaPath}`);
|
|
594
|
+
}
|
|
595
|
+
const schemaSource = await fs3.readFile(schemaPath, "utf-8");
|
|
596
|
+
const tables = parseSchemaFile(schemaSource);
|
|
597
|
+
const environment = config.environment || "development";
|
|
598
|
+
let projectId;
|
|
599
|
+
const envFilePath = path3.resolve(process.cwd(), ".env");
|
|
600
|
+
if (await fs3.pathExists(envFilePath)) {
|
|
601
|
+
const envContent = await fs3.readFile(envFilePath, "utf-8");
|
|
602
|
+
const match = envContent.match(/TETHER_PROJECT_ID=(.+)/);
|
|
603
|
+
projectId = match?.[1]?.trim();
|
|
604
|
+
}
|
|
605
|
+
const envVarKeys = projectId ? await fetchEnvVarKeys(projectId, environment) : [];
|
|
606
|
+
await fs3.ensureDir(outputDir);
|
|
607
|
+
await fs3.writeFile(
|
|
608
|
+
path3.join(outputDir, "db.ts"),
|
|
609
|
+
generateDbFile(tables, schemaSource)
|
|
610
|
+
);
|
|
611
|
+
await fs3.writeFile(
|
|
612
|
+
path3.join(outputDir, "api.ts"),
|
|
613
|
+
await generateApiFile(functionsDir)
|
|
614
|
+
);
|
|
615
|
+
await fs3.writeFile(
|
|
616
|
+
path3.join(outputDir, "env.ts"),
|
|
617
|
+
generateEnvFile(envVarKeys)
|
|
618
|
+
);
|
|
619
|
+
await fs3.writeFile(
|
|
620
|
+
path3.join(outputDir, "index.ts"),
|
|
621
|
+
`// Auto-generated by Tether CLI - do not edit manually
|
|
622
|
+
export * from './db';
|
|
623
|
+
export * from './api';
|
|
624
|
+
export * from './env';
|
|
625
|
+
`
|
|
626
|
+
);
|
|
627
|
+
return { tables, envVarKeys, outputDir };
|
|
628
|
+
}
|
|
629
|
+
async function generateCommand() {
|
|
630
|
+
await requireAuth();
|
|
631
|
+
const configPath = path3.resolve(process.cwd(), "tether.config.ts");
|
|
632
|
+
if (!await fs3.pathExists(configPath)) {
|
|
633
|
+
console.log(chalk2.red("\nError: Not a Tether project"));
|
|
634
|
+
console.log(chalk2.dim("Run `tthr init` to create a new project\n"));
|
|
635
|
+
process.exit(1);
|
|
636
|
+
}
|
|
637
|
+
console.log(chalk2.bold("\n\u26A1 Generating types from schema\n"));
|
|
638
|
+
const spinner = ora("Reading schema...").start();
|
|
639
|
+
try {
|
|
640
|
+
spinner.text = "Generating types...";
|
|
641
|
+
const { tables, envVarKeys, outputDir } = await generateTypes();
|
|
642
|
+
if (tables.length === 0) {
|
|
643
|
+
spinner.warn("No tables found in schema");
|
|
644
|
+
console.log(chalk2.dim(" Make sure your schema uses defineSchema({ ... })\n"));
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
spinner.succeed(`Types generated for ${tables.length} table(s)`);
|
|
648
|
+
console.log("\n" + chalk2.green("\u2713") + " Tables:");
|
|
649
|
+
for (const table of tables) {
|
|
650
|
+
console.log(chalk2.dim(` - ${table.name} (${table.columns.length} columns)`));
|
|
651
|
+
}
|
|
652
|
+
if (envVarKeys.length > 0) {
|
|
653
|
+
console.log("\n" + chalk2.green("\u2713") + ` Environment variables: ${envVarKeys.length} key(s)`);
|
|
654
|
+
for (const key of envVarKeys) {
|
|
655
|
+
console.log(chalk2.dim(` - ${key}`));
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
const relativeOutput = path3.relative(process.cwd(), outputDir);
|
|
659
|
+
console.log("\n" + chalk2.green("\u2713") + " Generated files:");
|
|
660
|
+
console.log(chalk2.dim(` ${relativeOutput}/db.ts`));
|
|
661
|
+
console.log(chalk2.dim(` ${relativeOutput}/api.ts`));
|
|
662
|
+
console.log(chalk2.dim(` ${relativeOutput}/env.ts`));
|
|
663
|
+
console.log(chalk2.dim(` ${relativeOutput}/index.ts
|
|
664
|
+
`));
|
|
665
|
+
} catch (error) {
|
|
666
|
+
spinner.fail("Failed to generate types");
|
|
667
|
+
console.error(chalk2.red(error instanceof Error ? error.message : "Unknown error"));
|
|
668
|
+
process.exit(1);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
export {
|
|
673
|
+
API_URL,
|
|
674
|
+
getCredentials,
|
|
675
|
+
requireAuth,
|
|
676
|
+
saveCredentials,
|
|
677
|
+
clearCredentials,
|
|
678
|
+
loadConfig,
|
|
679
|
+
resolvePath,
|
|
680
|
+
detectFramework,
|
|
681
|
+
getFrameworkDevCommand,
|
|
682
|
+
generateTypes,
|
|
683
|
+
generateCommand
|
|
684
|
+
};
|
|
@@ -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(/\s*\|\s*null/g, "").replace(/\[\]/g, "").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
|
+
};
|
package/dist/index.js
CHANGED
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
requireAuth,
|
|
12
12
|
resolvePath,
|
|
13
13
|
saveCredentials
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-CPBP6GSK.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-
|
|
1687
|
+
const { generateTypes: generateTypes2 } = await import("./generate-FTLMBVLH.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-
|
|
1907
|
+
const { generateTypes: generateTypes2 } = await import("./generate-FTLMBVLH.js");
|
|
1908
1908
|
await generateTypes2({ silent: true });
|
|
1909
1909
|
spinner.succeed("Types generated");
|
|
1910
1910
|
if (config.projectId) {
|