create-ts-saas 0.1.0 → 0.1.2

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.
@@ -1,794 +0,0 @@
1
- #!/usr/bin/env node
2
- import { os } from "@orpc/server";
3
- import { createCli } from "trpc-cli";
4
- import { z } from "zod";
5
- import { consola } from "consola";
6
- import { $ } from "execa";
7
- import pc from "picocolors";
8
- import semver from "semver";
9
- import path from "node:path";
10
- import fs from "fs-extra";
11
- import os$1 from "node:os";
12
- import { confirm, intro, isCancel, log, note, select, spinner, text } from "@clack/prompts";
13
- import open from "open";
14
- import { createWriteStream } from "node:fs";
15
- import { Readable } from "node:stream";
16
- import { pipeline } from "node:stream/promises";
17
- import unzipper from "unzipper";
18
- //#region src/lib/version.ts
19
- function getCliVersion() {
20
- return "0.1.0";
21
- }
22
- function getCliPlatform() {
23
- return `${process.platform}-${process.arch}`;
24
- }
25
- //#endregion
26
- //#region src/lib/api.ts
27
- var ApiError = class extends Error {
28
- constructor(code, message, retryable = false, status, minCliVersion) {
29
- super(message);
30
- this.code = code;
31
- this.retryable = retryable;
32
- this.status = status;
33
- this.minCliVersion = minCliVersion;
34
- this.name = "ApiError";
35
- }
36
- };
37
- function parseApiErrorBody(text) {
38
- try {
39
- const data = JSON.parse(text);
40
- if (typeof data.code === "string" && typeof data.message === "string") return {
41
- code: data.code,
42
- message: data.message,
43
- retryable: Boolean(data.retryable)
44
- };
45
- const nested = data.error;
46
- if (nested && typeof nested.code === "string" && typeof nested.message === "string") return {
47
- code: nested.code,
48
- message: nested.message,
49
- retryable: Boolean(data.retryable)
50
- };
51
- } catch {}
52
- return null;
53
- }
54
- function createApiClient(options) {
55
- const { config, accessToken, deviceId } = options;
56
- const baseUrl = config.apiBaseUrl.replace(/\/$/, "");
57
- const cliVersion = getCliVersion();
58
- const cliPlatform = getCliPlatform();
59
- async function request(path, init = {}) {
60
- const url = `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
61
- const headers = new Headers(init.headers);
62
- headers.set("Accept", "application/json");
63
- headers.set("x-cli-version", cliVersion);
64
- headers.set("x-cli-platform", cliPlatform);
65
- if (deviceId) headers.set("x-cli-device-id", deviceId);
66
- if (accessToken) headers.set("Authorization", `Bearer ${accessToken}`);
67
- let res;
68
- try {
69
- res = await fetch(url, {
70
- ...init,
71
- headers
72
- });
73
- } catch {
74
- throw new ApiError("NETWORK_ERROR", "Network error — could not connect to the server.", true);
75
- }
76
- const minCli = res.headers.get("x-min-supported-cli");
77
- if (minCli && semver.valid(cliVersion) && semver.valid(minCli) && semver.lt(cliVersion, minCli)) throw new ApiError("UPGRADE_REQUIRED", `CLI version ${cliVersion} is below minimum supported ${minCli}. Please upgrade.`, false, res.status, minCli);
78
- const text = await res.text();
79
- if (!res.ok) {
80
- const body = parseApiErrorBody(text);
81
- throw new ApiError(body?.code ?? (res.status === 401 ? "AUTH_INVALID" : "REQUEST_FAILED"), body?.message ?? res.statusText, body?.retryable ?? false, res.status, minCli ?? void 0);
82
- }
83
- if (!text) return {};
84
- return JSON.parse(text);
85
- }
86
- async function stream(url) {
87
- const headers = new Headers();
88
- headers.set("x-cli-version", cliVersion);
89
- headers.set("x-cli-platform", cliPlatform);
90
- if (deviceId) headers.set("x-cli-device-id", deviceId);
91
- if (accessToken) headers.set("Authorization", `Bearer ${accessToken}`);
92
- let res;
93
- try {
94
- res = await fetch(url, { headers });
95
- } catch {
96
- throw new ApiError("NETWORK_ERROR", "Network error — could not connect to the server.", true);
97
- }
98
- if (!res.ok) {
99
- const body = parseApiErrorBody(await res.text());
100
- throw new ApiError(body?.code ?? "DOWNLOAD_FAILED", body?.message ?? "Template download failed", false, res.status);
101
- }
102
- return res;
103
- }
104
- return {
105
- baseUrl,
106
- request,
107
- stream,
108
- deviceInit: () => request("/cli/device/init", {
109
- method: "POST",
110
- headers: { "Content-Type": "application/json" },
111
- body: JSON.stringify({})
112
- }),
113
- devicePoll: (deviceCode) => request("/cli/device/poll", {
114
- method: "POST",
115
- headers: { "Content-Type": "application/json" },
116
- body: JSON.stringify({ deviceCode })
117
- }),
118
- refresh: (refreshToken) => request("/cli/auth/refresh", {
119
- method: "POST",
120
- headers: { "Content-Type": "application/json" },
121
- body: JSON.stringify({ refreshToken })
122
- }),
123
- logoutDevice: (refreshToken) => request("/cli/device/logout", {
124
- method: "POST",
125
- headers: { "Content-Type": "application/json" },
126
- body: JSON.stringify({ refreshToken })
127
- }),
128
- me: () => request("/cli/me"),
129
- getTemplates: () => request("/cli/templates"),
130
- authorizeInit: (input) => request("/cli/init/authorize", {
131
- method: "POST",
132
- headers: { "Content-Type": "application/json" },
133
- body: JSON.stringify(input)
134
- }),
135
- getLatestVersion: () => request("/cli/latest-version")
136
- };
137
- }
138
- //#endregion
139
- //#region src/constants.ts
140
- const DEFAULT_API_BASE_URL = process.env.YOUR_SAAS_CLI_API_URL || "http://localhost:8787/api/v1";
141
- const CONFIG_DIR_NAME = "ts-saas-cli";
142
- const CONFIG_FILE_NAME = "config.json";
143
- const KEYTAR_SERVICE_NAME = "create-ts-saas";
144
- const KEYTAR_ACCOUNT_NAME = "default";
145
- //#endregion
146
- //#region src/lib/config.ts
147
- function getConfigDir() {
148
- const home = os$1.homedir();
149
- const configHome = process.env.XDG_CONFIG_HOME ?? path.join(home, ".config");
150
- return path.join(configHome, CONFIG_DIR_NAME);
151
- }
152
- function getConfigPath() {
153
- return path.join(getConfigDir(), CONFIG_FILE_NAME);
154
- }
155
- async function loadConfig() {
156
- const fromEnv = {
157
- apiBaseUrl: process.env.YOUR_SAAS_CLI_API_URL,
158
- disableTelemetry: process.env.YOUR_SAAS_CLI_DISABLE_TELEMETRY === "1" || process.env.YOUR_SAAS_CLI_DISABLE_TELEMETRY === "true"
159
- };
160
- const configPath = getConfigPath();
161
- try {
162
- if (await fs.pathExists(configPath)) {
163
- const data = await fs.readJson(configPath);
164
- return {
165
- apiBaseUrl: data.apiBaseUrl ?? fromEnv.apiBaseUrl ?? DEFAULT_API_BASE_URL,
166
- disableTelemetry: data.disableTelemetry ?? fromEnv.disableTelemetry ?? false
167
- };
168
- }
169
- } catch {}
170
- return {
171
- apiBaseUrl: fromEnv.apiBaseUrl ?? DEFAULT_API_BASE_URL,
172
- disableTelemetry: fromEnv.disableTelemetry ?? false
173
- };
174
- }
175
- //#endregion
176
- //#region src/lib/storage.ts
177
- const FALLBACK_FILE = "session.json";
178
- let cachedKeytar;
179
- function getFallbackSessionPath() {
180
- return path.join(path.dirname(getConfigPath()), FALLBACK_FILE);
181
- }
182
- async function getStoredSession() {
183
- const keytar = await getKeytar();
184
- try {
185
- const value = keytar ? await keytar.getPassword(KEYTAR_SERVICE_NAME, KEYTAR_ACCOUNT_NAME) : null;
186
- if (!value) return await getFallbackSession();
187
- const parsed = JSON.parse(value);
188
- if (typeof parsed.accessToken !== "string" || typeof parsed.refreshToken !== "string" || typeof parsed.deviceId !== "string" || typeof parsed.expiresAt !== "number") return null;
189
- return parsed;
190
- } catch {
191
- return await getFallbackSession();
192
- }
193
- }
194
- async function setStoredSession(session) {
195
- const serialized = JSON.stringify(session);
196
- const keytar = await getKeytar();
197
- try {
198
- if (keytar) {
199
- await keytar.setPassword(KEYTAR_SERVICE_NAME, KEYTAR_ACCOUNT_NAME, serialized);
200
- return;
201
- }
202
- await setFallbackSession(session);
203
- } catch {
204
- await setFallbackSession(session);
205
- }
206
- }
207
- async function clearStoredSession() {
208
- const keytar = await getKeytar();
209
- try {
210
- if (keytar) await keytar.deletePassword(KEYTAR_SERVICE_NAME, KEYTAR_ACCOUNT_NAME);
211
- } catch {}
212
- try {
213
- await fs.remove(getFallbackSessionPath());
214
- } catch {}
215
- }
216
- async function getFallbackSession() {
217
- const filePath = getFallbackSessionPath();
218
- try {
219
- if (!await fs.pathExists(filePath)) return null;
220
- const value = await fs.readJson(filePath);
221
- if (typeof value.accessToken !== "string" || typeof value.refreshToken !== "string" || typeof value.deviceId !== "string" || typeof value.expiresAt !== "number") return null;
222
- return value;
223
- } catch {
224
- return null;
225
- }
226
- }
227
- async function setFallbackSession(session) {
228
- await fs.ensureDir(path.dirname(getFallbackSessionPath()));
229
- await fs.writeJson(getFallbackSessionPath(), session, { spaces: 0 });
230
- try {
231
- await fs.chmod(getFallbackSessionPath(), 384);
232
- } catch {}
233
- }
234
- async function getKeytar() {
235
- if (cachedKeytar !== void 0) return cachedKeytar;
236
- try {
237
- const imported = await import("keytar");
238
- cachedKeytar = imported.default ?? imported;
239
- return cachedKeytar;
240
- } catch {
241
- cachedKeytar = null;
242
- return null;
243
- }
244
- }
245
- //#endregion
246
- //#region src/commands/doctor.ts
247
- async function doctorCommand() {
248
- consola.log(pc.bold("Environment checks\n"));
249
- const checks = [];
250
- checks.push({
251
- name: "Node.js",
252
- status: Number(process.versions.node.split(".")[0]) >= 20 ? "ok" : "fail",
253
- detail: process.version
254
- });
255
- try {
256
- const result = await $`pnpm --version`;
257
- checks.push({
258
- name: "pnpm",
259
- status: "ok",
260
- detail: result.stdout.trim()
261
- });
262
- } catch {
263
- checks.push({
264
- name: "pnpm",
265
- status: "fail",
266
- detail: "not found"
267
- });
268
- }
269
- try {
270
- await $`git --version`;
271
- checks.push({
272
- name: "git",
273
- status: "ok",
274
- detail: "installed"
275
- });
276
- } catch {
277
- checks.push({
278
- name: "git",
279
- status: "fail",
280
- detail: "not found"
281
- });
282
- }
283
- const config = await loadConfig();
284
- const session = await getStoredSession();
285
- checks.push({
286
- name: "session",
287
- status: session ? "ok" : "fail",
288
- detail: session ? "present" : "missing"
289
- });
290
- try {
291
- await createApiClient({
292
- config,
293
- accessToken: session?.accessToken ?? null,
294
- deviceId: session?.deviceId ?? null
295
- }).getLatestVersion();
296
- checks.push({
297
- name: "api",
298
- status: "ok",
299
- detail: config.apiBaseUrl
300
- });
301
- } catch {
302
- checks.push({
303
- name: "api",
304
- status: "fail",
305
- detail: "unreachable"
306
- });
307
- }
308
- for (const check of checks) {
309
- const icon = check.status === "ok" ? pc.green("✓") : pc.red("✗");
310
- consola.log(`${icon} ${check.name}: ${check.detail}`);
311
- }
312
- consola.log(`\nCLI version: ${getCliVersion()}`);
313
- }
314
- //#endregion
315
- //#region src/utils/open-url.ts
316
- async function openUrl(url) {
317
- try {
318
- await open(url);
319
- } catch {}
320
- }
321
- //#endregion
322
- //#region src/lib/auth.ts
323
- async function getValidSession() {
324
- const session = await getStoredSession();
325
- if (!session) return null;
326
- if (session.expiresAt <= Date.now() + 6e4) return null;
327
- return session;
328
- }
329
- async function ensureSession(apiFactory) {
330
- const valid = await getValidSession();
331
- if (valid) return valid;
332
- const current = await getStoredSession();
333
- if (current?.refreshToken) try {
334
- const refreshed = await apiFactory(current).refresh(current.refreshToken);
335
- const next = {
336
- accessToken: refreshed.accessToken,
337
- refreshToken: refreshed.refreshToken,
338
- deviceId: current.deviceId,
339
- expiresAt: Date.now() + refreshed.expiresIn * 1e3
340
- };
341
- await setStoredSession(next);
342
- return next;
343
- } catch {
344
- await clearStoredSession();
345
- }
346
- return await loginWithDeviceFlow(apiFactory());
347
- }
348
- async function loginWithDeviceFlow(api) {
349
- const init = await api.deviceInit();
350
- const verificationUrlWithCode = `${init.verificationUrl}${init.verificationUrl.includes("?") ? "&" : "?"}code=${encodeURIComponent(init.userCode)}`;
351
- note(`Open ${verificationUrlWithCode} and confirm code ${init.userCode}\nCode expires in ${Math.floor(init.expiresIn / 60)} minutes.`, "Device Login");
352
- openUrl(verificationUrlWithCode);
353
- const deadline = Date.now() + init.expiresIn * 1e3;
354
- while (Date.now() < deadline) {
355
- await new Promise((resolve) => {
356
- setTimeout(resolve, Math.max(init.interval, 3) * 1e3);
357
- });
358
- try {
359
- const token = await api.devicePoll(init.deviceCode);
360
- const session = {
361
- accessToken: token.accessToken,
362
- refreshToken: token.refreshToken,
363
- deviceId: token.deviceId,
364
- expiresAt: Date.now() + token.expiresIn * 1e3
365
- };
366
- await setStoredSession(session);
367
- return session;
368
- } catch (error) {
369
- const e = error;
370
- if (e.code === "AUTH_PENDING" || e.retryable) continue;
371
- throw error;
372
- }
373
- }
374
- throw new Error("Device code expired. Run login again.");
375
- }
376
- async function logout(apiFactory) {
377
- const session = await getStoredSession();
378
- if (session?.refreshToken) try {
379
- await apiFactory(session).logoutDevice(session.refreshToken);
380
- } catch {}
381
- await clearStoredSession();
382
- }
383
- //#endregion
384
- //#region src/lib/scaffolder.ts
385
- const IGNORED_ROOT_ENTRIES = new Set(["__MACOSX"]);
386
- async function streamAndExtractTemplate(downloadResponse, projectDir) {
387
- if (!downloadResponse.body) throw new Error("Template response body is empty.");
388
- await fs.ensureDir(projectDir);
389
- const tempDir = path.join(projectDir, "..", `.create-ts-saas-tmp-${Date.now()}`);
390
- const extractDir = path.join(tempDir, "extracted");
391
- await fs.ensureDir(tempDir);
392
- await fs.ensureDir(extractDir);
393
- const zipPath = path.join(tempDir, "template.zip");
394
- const writable = createWriteStream(zipPath);
395
- await pipeline(Readable.fromWeb(downloadResponse.body), writable);
396
- await (await unzipper.Open.file(zipPath)).extract({ path: extractDir });
397
- const meaningfulEntries = (await fs.readdir(extractDir)).filter((name) => !IGNORED_ROOT_ENTRIES.has(name));
398
- if (meaningfulEntries.length === 1 && meaningfulEntries[0]) {
399
- const singleRoot = path.join(extractDir, meaningfulEntries[0]);
400
- if ((await fs.stat(singleRoot)).isDirectory()) {
401
- const children = await fs.readdir(singleRoot);
402
- for (const child of children) await fs.move(path.join(singleRoot, child), path.join(projectDir, child), { overwrite: true });
403
- } else await fs.move(singleRoot, path.join(projectDir, meaningfulEntries[0]), { overwrite: true });
404
- } else for (const entry of meaningfulEntries) await fs.move(path.join(extractDir, entry), path.join(projectDir, entry), { overwrite: true });
405
- await fs.remove(tempDir).catch(() => {});
406
- }
407
- async function writeWatermark(projectDir, payload) {
408
- const pkgJsonPath = path.join(projectDir, "package.json");
409
- if (await fs.pathExists(pkgJsonPath)) {
410
- const pkgJson = await fs.readJson(pkgJsonPath);
411
- pkgJson["create-ts-saas"] = { wId: payload.watermarkId ?? payload.issuanceId };
412
- await fs.writeJson(pkgJsonPath, pkgJson, { spaces: 2 });
413
- }
414
- }
415
- //#endregion
416
- //#region src/prompts/install.ts
417
- async function promptInstall(defaultValue = true) {
418
- const value = await confirm({
419
- message: "Install dependencies now?",
420
- initialValue: defaultValue
421
- });
422
- if (isCancel(value)) throw new Error("Operation cancelled.");
423
- return value;
424
- }
425
- //#endregion
426
- //#region src/prompts/package-manager.ts
427
- async function promptPackageManager(initialValue) {
428
- const value = await select({
429
- message: "Select package manager",
430
- options: [
431
- {
432
- value: "pnpm",
433
- label: "pnpm"
434
- },
435
- {
436
- value: "npm",
437
- label: "npm"
438
- },
439
- {
440
- value: "bun",
441
- label: "bun"
442
- }
443
- ],
444
- initialValue
445
- });
446
- if (isCancel(value)) throw new Error("Operation cancelled.");
447
- return value;
448
- }
449
- //#endregion
450
- //#region src/prompts/project-name.ts
451
- async function promptProjectName(initialValue = "my-saas-app") {
452
- const value = await text({
453
- message: "Project name",
454
- initialValue,
455
- validate: (input) => input?.trim() ? void 0 : "Project name is required"
456
- });
457
- if (isCancel(value) || typeof value !== "string") throw new Error("Operation cancelled.");
458
- return value.trim();
459
- }
460
- //#endregion
461
- //#region src/prompts/template.ts
462
- async function promptTemplate(templates) {
463
- const value = await select({
464
- message: "Select template",
465
- options: templates.map((t) => ({
466
- value: t.slug,
467
- label: `${t.name} (${t.slug})`,
468
- hint: `latest ${t.latestVersion}`
469
- }))
470
- });
471
- if (isCancel(value) || typeof value !== "string") throw new Error("Operation cancelled.");
472
- const chosen = templates.find((t) => t.slug === value);
473
- if (!chosen) throw new Error(`Unknown template "${value}".`);
474
- return chosen;
475
- }
476
- //#endregion
477
- //#region src/prompts/variant.ts
478
- async function promptVariant(template) {
479
- const first = template.variants[0];
480
- if (!first) throw new Error(`Template "${template.slug}" has no variants.`);
481
- const value = await select({
482
- message: "Select variant",
483
- options: template.variants.map((v) => ({
484
- value: v.slug,
485
- label: v.name,
486
- hint: v.slug
487
- })),
488
- initialValue: first.slug
489
- });
490
- if (isCancel(value) || typeof value !== "string") throw new Error("Operation cancelled.");
491
- return value;
492
- }
493
- //#endregion
494
- //#region src/utils/get-package-manager.ts
495
- function getUserPackageManager() {
496
- const userAgent = process.env.npm_config_user_agent;
497
- if (userAgent?.startsWith("pnpm")) return "pnpm";
498
- if (userAgent?.startsWith("bun")) return "bun";
499
- return "npm";
500
- }
501
- //#endregion
502
- //#region src/utils/handle-cli-error.ts
503
- const DEBUG_FLAG = process.env.TS_SAAS_CLI_DEBUG === "1" || process.env.TS_SAAS_CLI_DEBUG === "true";
504
- function isNetworkError(error) {
505
- if (!(error instanceof Error)) return false;
506
- const cause = error.cause;
507
- if (cause instanceof Error) {
508
- const code = cause.code;
509
- if (code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "ETIMEDOUT" || code === "ECONNRESET") return true;
510
- }
511
- return error.message === "fetch failed";
512
- }
513
- function handleCliError(error) {
514
- if (isNetworkError(error)) {
515
- log.error(pc.red("Network error — could not connect to the server."));
516
- if (DEBUG_FLAG) console.error(error);
517
- process.exit(1);
518
- }
519
- if (error instanceof ApiError) {
520
- log.error(pc.red(error.message));
521
- if (DEBUG_FLAG) console.error(error);
522
- process.exit(getExitCode(error));
523
- }
524
- if (error instanceof Error) {
525
- log.error(pc.red(error.message || "Something went wrong"));
526
- if (DEBUG_FLAG) console.error(error);
527
- process.exit(1);
528
- }
529
- log.error(pc.red("Something went wrong"));
530
- if (DEBUG_FLAG) console.error(error);
531
- process.exit(1);
532
- }
533
- function getExitCode(error) {
534
- switch (error.code) {
535
- case "AUTH_EXPIRED":
536
- case "AUTH_INVALID": return 2;
537
- case "PLAN_FORBIDDEN": return 3;
538
- case "UPGRADE_REQUIRED": return 4;
539
- default: return error.status && error.status >= 500 ? 1 : 1;
540
- }
541
- }
542
- //#endregion
543
- //#region src/utils/project-directory.ts
544
- async function resolveProjectDirectory(initialInput) {
545
- const current = initialInput;
546
- while (true) {
547
- const fullPath = path.resolve(process.cwd(), current);
548
- if (!(await fs.pathExists(fullPath) && (await fs.readdir(fullPath)).length > 0)) {
549
- await fs.ensureDir(fullPath);
550
- return {
551
- projectDir: fullPath,
552
- projectName: path.basename(fullPath)
553
- };
554
- }
555
- log.warn(`Directory "${pc.yellow(current)}" already exists and is not empty.`);
556
- const action = await select({
557
- message: "Choose how to proceed",
558
- options: [
559
- {
560
- value: "merge",
561
- label: "Merge into existing directory"
562
- },
563
- {
564
- value: "overwrite",
565
- label: "Overwrite directory contents"
566
- },
567
- {
568
- value: "cancel",
569
- label: "Cancel"
570
- }
571
- ],
572
- initialValue: "merge"
573
- });
574
- if (isCancel(action) || action === "cancel") throw new Error("Operation cancelled.");
575
- if (action === "merge") return {
576
- projectDir: fullPath,
577
- projectName: path.basename(fullPath)
578
- };
579
- await fs.emptyDir(fullPath);
580
- return {
581
- projectDir: fullPath,
582
- projectName: path.basename(fullPath)
583
- };
584
- }
585
- }
586
- //#endregion
587
- //#region src/commands/init.ts
588
- async function initCommand(options) {
589
- intro(pc.magenta("Initialize your saas..."));
590
- try {
591
- const config = await loadConfig();
592
- const session = await ensureSession((current) => createApiClient({
593
- config,
594
- accessToken: current?.accessToken ?? null,
595
- deviceId: current?.deviceId ?? null
596
- }));
597
- const api = createApiClient({
598
- config,
599
- accessToken: session.accessToken,
600
- deviceId: session.deviceId
601
- });
602
- const { projectDir, projectName } = await resolveProjectDirectory(options.projectName || options.dir || await promptProjectName());
603
- const templates = (await api.getTemplates()).templates;
604
- if (!templates.length) throw new Error("No templates available for this account.");
605
- const selectedTemplate = options.template && templates.find((template) => template.slug === options.template) ? templates.find((template) => template.slug === options.template) : await promptTemplate(templates);
606
- if (!selectedTemplate) {
607
- log.error(pc.red("Selected template not found."));
608
- process.exit(1);
609
- }
610
- const selectedVariant = options.variant && selectedTemplate.variants.some((variant) => variant.slug === options.variant) ? options.variant : await promptVariant(selectedTemplate);
611
- const s = spinner();
612
- s.start("Authorizing template download...");
613
- try {
614
- const authz = await api.authorizeInit({
615
- templateSlug: selectedTemplate.slug,
616
- variantSlug: selectedVariant
617
- });
618
- s.message("Downloading template...");
619
- await streamAndExtractTemplate(await api.stream(authz.downloadUrl), projectDir);
620
- await writeWatermark(projectDir, authz.watermark);
621
- s.stop("Template ready.");
622
- } catch (error) {
623
- s.stop(pc.red("Failed to scaffold template."));
624
- throw error;
625
- }
626
- const packageManager = options.packageManager ?? await promptPackageManager(getUserPackageManager());
627
- if (options.install ?? (options.yes ? true : await promptInstall(true))) {
628
- s.start(`Running ${packageManager} install...`);
629
- await $({
630
- cwd: projectDir,
631
- stderr: "inherit"
632
- })`${packageManager} install`;
633
- s.stop("Dependencies installed.");
634
- }
635
- if (options.git ?? (options.yes ? true : await confirm({
636
- message: "Initialize git?",
637
- initialValue: true
638
- }))) try {
639
- await $({
640
- cwd: projectDir,
641
- stderr: "ignore",
642
- stdout: "ignore"
643
- })`git init`;
644
- } catch {
645
- log.warn("Git init failed. Continuing without repository setup.");
646
- }
647
- log.success(pc.green(`Project created at ${projectDir}`));
648
- note([
649
- `cd ${path.basename(projectDir)}`,
650
- ``,
651
- `Copy ${pc.cyan(".env.example")} → ${pc.cyan(".env")} and fill in your values`,
652
- `Run ${pc.cyan(`${packageManager} db:migrate`)} to set up the database`,
653
- `Run ${pc.cyan(`${packageManager} dev`)} to start`
654
- ].join("\n"), `Next steps (${projectName})`);
655
- } catch (error) {
656
- handleCliError(error);
657
- }
658
- }
659
- //#endregion
660
- //#region src/commands/login.ts
661
- async function loginCommand() {
662
- intro(pc.magenta("Login to ts-saas"));
663
- try {
664
- await loginWithDeviceFlow(createApiClient({ config: await loadConfig() }));
665
- log.success(pc.green("Logged in successfully."));
666
- } catch (error) {
667
- handleCliError(error);
668
- }
669
- }
670
- //#endregion
671
- //#region src/commands/logout.ts
672
- async function logoutCommand() {
673
- intro(pc.magenta("Logout from create-ts-saas"));
674
- const config = await loadConfig();
675
- await logout((session) => createApiClient({
676
- config,
677
- accessToken: session?.accessToken ?? null,
678
- deviceId: session?.deviceId ?? null
679
- }));
680
- log.success(pc.green("Logged out and local session cleared."));
681
- }
682
- //#endregion
683
- //#region src/commands/upgrade.ts
684
- async function upgradeCommand() {
685
- intro(pc.magenta("Checking for updates"));
686
- const latest = await createApiClient({ config: await loadConfig() }).getLatestVersion();
687
- const current = getCliVersion();
688
- if (latest.version !== current) {
689
- log.warn(pc.yellow(`Update available: current ${current}, latest ${latest.version}. Run: npx create-ts-saas@latest`));
690
- return;
691
- }
692
- log.success(pc.green(`You are on latest version (${current}).`));
693
- }
694
- //#endregion
695
- //#region src/commands/whoami.ts
696
- async function whoamiCommand() {
697
- intro(pc.magenta("Current CLI account"));
698
- try {
699
- const config = await loadConfig();
700
- const session = await ensureSession((current) => createApiClient({
701
- config,
702
- accessToken: current?.accessToken ?? null,
703
- deviceId: current?.deviceId ?? null
704
- }));
705
- const data = await createApiClient({
706
- config,
707
- accessToken: session.accessToken,
708
- deviceId: session.deviceId
709
- }).me();
710
- note(`Email: ${data.email}\nPlan: ${data.plan}\nActive devices: ${data.activeDevices}\nTemplates: ${data.templates.join(", ") || "none"}`, "Account");
711
- log.success(pc.green("Account lookup completed."));
712
- } catch (error) {
713
- handleCliError(error);
714
- }
715
- }
716
- //#endregion
717
- //#region src/index.ts
718
- const router = os.router({
719
- create: os.meta({
720
- description: "Create a new project from your paid SaaS template",
721
- default: true,
722
- negateBooleans: true
723
- }).input(z.tuple([z.string().optional(), z.object({
724
- dir: z.string().optional(),
725
- yes: z.boolean().optional().default(false),
726
- template: z.string().optional(),
727
- variant: z.string().optional(),
728
- packageManager: z.enum([
729
- "npm",
730
- "pnpm",
731
- "bun"
732
- ]).optional(),
733
- install: z.boolean().optional(),
734
- git: z.boolean().optional()
735
- })])).handler(async ({ input }) => {
736
- const [projectName, options] = input;
737
- await initCommand({ ...projectName ? {
738
- ...options,
739
- projectName
740
- } : options });
741
- }),
742
- init: os.meta({ description: "Alias for create command" }).input(z.tuple([z.string().optional(), z.object({
743
- dir: z.string().optional(),
744
- yes: z.boolean().optional().default(false),
745
- template: z.string().optional(),
746
- variant: z.string().optional(),
747
- packageManager: z.enum([
748
- "npm",
749
- "pnpm",
750
- "bun"
751
- ]).optional(),
752
- install: z.boolean().optional(),
753
- git: z.boolean().optional()
754
- })])).handler(async ({ input }) => {
755
- const [projectName, options] = input;
756
- await initCommand({ ...projectName ? {
757
- ...options,
758
- projectName
759
- } : options });
760
- }),
761
- login: os.meta({ description: "Login with device flow" }).handler(async () => {
762
- await loginCommand();
763
- }),
764
- logout: os.meta({ description: "Logout and clear local auth session" }).handler(async () => {
765
- await logoutCommand();
766
- }),
767
- doctor: os.meta({ description: "Run local environment checks" }).handler(async () => {
768
- await doctorCommand();
769
- }),
770
- whoami: os.meta({ description: "Show authenticated account details" }).handler(async () => {
771
- await whoamiCommand();
772
- }),
773
- upgrade: os.meta({ description: "Check CLI version status" }).handler(async () => {
774
- await upgradeCommand();
775
- })
776
- });
777
- function createCliApp() {
778
- return createCli({
779
- router,
780
- name: "create-ts-saas",
781
- version: getCliVersion()
782
- });
783
- }
784
- async function runCli() {
785
- try {
786
- await createCliApp().run();
787
- } catch (error) {
788
- handleCliError(error);
789
- }
790
- }
791
- //#endregion
792
- export { runCli as n, router as t };
793
-
794
- //# sourceMappingURL=src-D4guDFsb.mjs.map