ansensational 0.0.0-stage → 1.2.0

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/index.js ADDED
@@ -0,0 +1,1249 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command } from "commander";
5
+ import pc3 from "picocolors";
6
+
7
+ // src/registry.ts
8
+ import fs from "fs-extra";
9
+ import path from "path";
10
+ import os from "os";
11
+
12
+ // ../../packages/schema/dist/index.mjs
13
+ import { z } from "zod";
14
+ var TemplateTierSchema = z.enum(["free", "premium"]);
15
+ var SourcePlatformSchema = z.enum(["github", "gitlab", "custom"]);
16
+ var TemplateTypeSchema = z.enum([
17
+ "frontend",
18
+ "backend",
19
+ "fullstack",
20
+ "mobile",
21
+ "cli",
22
+ "library",
23
+ "other"
24
+ ]);
25
+ var FrameworkSchema = z.enum([
26
+ // Frontend
27
+ "react",
28
+ "vue",
29
+ "svelte",
30
+ "angular",
31
+ "nextjs",
32
+ "nuxt",
33
+ "astro",
34
+ "solid",
35
+ "qwik",
36
+ // Backend
37
+ "express",
38
+ "fastify",
39
+ "hono",
40
+ "elysia",
41
+ "nestjs",
42
+ "koa",
43
+ // Fullstack
44
+ "remix",
45
+ "sveltekit",
46
+ // Mobile
47
+ "react-native",
48
+ "expo",
49
+ "flutter",
50
+ // Other
51
+ "none",
52
+ "other"
53
+ ]);
54
+ var PricingSchema = z.object({
55
+ amount: z.number().positive(),
56
+ currency: z.string().length(3).default("USD"),
57
+ purchaseUrl: z.string().url().optional()
58
+ });
59
+ var AuthorSchema = z.object({
60
+ name: z.string().trim().min(1),
61
+ github: z.string().trim().min(1).optional(),
62
+ url: z.string().trim().url().optional()
63
+ });
64
+ var CommunityTemplateSchema = z.object({
65
+ /** Unique slug for CLI usage (e.g., "nextjs-starter") */
66
+ slug: z.string().trim().min(1).regex(/^[a-z0-9-]+$/, "Slug must be lowercase alphanumeric with hyphens"),
67
+ /** Human-readable name */
68
+ name: z.string().trim().min(1),
69
+ /** Git repository URL */
70
+ url: z.string().trim().url(),
71
+ /** Source platform (github, gitlab, custom) */
72
+ platform: SourcePlatformSchema.default("github"),
73
+ /** Template type/category */
74
+ type: TemplateTypeSchema,
75
+ /** Primary framework */
76
+ framework: FrameworkSchema.default("other"),
77
+ /** Short description */
78
+ description: z.string().trim().optional(),
79
+ /** Searchable tags */
80
+ tags: z.array(z.string().trim().min(1)).default([]),
81
+ /** Feature list for display */
82
+ features: z.array(z.string().trim().min(1)).default([]),
83
+ /** Template author */
84
+ author: AuthorSchema,
85
+ /** Pricing tier */
86
+ tier: TemplateTierSchema.default("free"),
87
+ /** Pricing details (only for premium tier) */
88
+ pricing: PricingSchema.optional(),
89
+ /** License identifier */
90
+ license: z.string().trim().min(1).default("MIT")
91
+ });
92
+ var RegistrySchema = z.object({
93
+ version: z.string().default("1.0.0"),
94
+ lastUpdated: z.string().datetime({ offset: true }).default(() => (/* @__PURE__ */ new Date()).toISOString()),
95
+ templates: z.record(z.string(), z.array(CommunityTemplateSchema))
96
+ });
97
+ var UserTemplatesSchema = z.object({
98
+ templates: z.array(CommunityTemplateSchema)
99
+ });
100
+ function formatZodError(error) {
101
+ return error.issues.map((issue) => {
102
+ const location = issue.path.length > 0 ? issue.path.join(".") : "value";
103
+ return ` - ${location}: ${issue.message}`;
104
+ }).join("\n");
105
+ }
106
+
107
+ // src/helpers/ui.ts
108
+ import pc from "picocolors";
109
+ var INSTALL_COMMANDS = {
110
+ npm: "npm install",
111
+ pnpm: "pnpm install",
112
+ yarn: "yarn",
113
+ bun: "bun install"
114
+ };
115
+ var DEV_COMMANDS = {
116
+ npm: "npm run dev",
117
+ pnpm: "pnpm dev",
118
+ yarn: "yarn dev",
119
+ bun: "bun dev"
120
+ };
121
+ var UI = {
122
+ header: (text) => console.log(pc.cyan(`
123
+ ${text}
124
+ `)),
125
+ success: (text) => console.log(pc.green(`
126
+ \u2705 ${text}`)),
127
+ warn: (text) => console.error(pc.yellow(`
128
+ \u26A0 ${text}`)),
129
+ // Errors and warnings go to stderr so `--json` stdout stays machine-readable.
130
+ error: (text) => console.error(pc.red(`
131
+ \u274C Error: ${text}`)),
132
+ info: (text) => console.log(pc.blue(text)),
133
+ dim: (text) => console.log(pc.dim(text)),
134
+ templateItem: (t) => {
135
+ const name = pc.bold(pc.cyan(`@${t.username}/${t.slug}`));
136
+ const tierBadge = t.tier === "premium" ? pc.yellow(" [PREMIUM]") : pc.green(" [FREE]");
137
+ const typeBadge = pc.dim(`[${t.type}]`);
138
+ const frameworkBadge = t.framework !== "other" ? pc.blue(` (${t.framework})`) : "";
139
+ console.log(`${name}${tierBadge}`);
140
+ console.log(
141
+ `${typeBadge}${frameworkBadge} ${t.description || "No description"}`
142
+ );
143
+ if (t.tags.length > 0) {
144
+ console.log(`Tags: ${t.tags.map((tag) => pc.magenta(tag)).join(", ")}`);
145
+ }
146
+ if (t.author.name) {
147
+ console.log(
148
+ `${pc.dim("Author:")} ${t.author.name}${t.author.github ? ` (@${t.author.github})` : ""}`
149
+ );
150
+ }
151
+ console.log("");
152
+ },
153
+ ansensationalSuccess: (slug, dest, url, packageManager) => {
154
+ UI.success(`Successfully ansensationaled @${slug} into ${dest}`);
155
+ const manager = packageManager === "unknown" ? "npm" : packageManager;
156
+ const installCommand = packageManager === "unknown" ? "install dependencies with your package manager" : INSTALL_COMMANDS[manager];
157
+ const devCommand = packageManager === "unknown" ? "run your dev script" : DEV_COMMANDS[manager];
158
+ console.log(pc.dim("\nNext steps:"));
159
+ console.log(pc.cyan(` cd ${dest}`));
160
+ console.log(pc.cyan(` ${installCommand}`));
161
+ console.log(pc.cyan(` ${devCommand}`));
162
+ try {
163
+ const host = new URL(url).hostname.replace(/^www\./, "").toLowerCase();
164
+ if (host === "github.com" || host.endsWith(".github.com")) {
165
+ console.log(pc.yellow("\n\u2B50 Like this template? Star it on GitHub:"));
166
+ console.log(pc.blue(` ${url}
167
+ `));
168
+ } else if (host === "gitlab.com" || host.endsWith(".gitlab.com")) {
169
+ console.log(pc.yellow("\n\u2B50 Like this template? Star it on GitLab:"));
170
+ console.log(pc.blue(` ${url}
171
+ `));
172
+ } else {
173
+ console.log("");
174
+ }
175
+ } catch {
176
+ console.log("");
177
+ }
178
+ }
179
+ };
180
+
181
+ // src/helpers/errors.ts
182
+ var CliError = class extends Error {
183
+ exitCode;
184
+ constructor(message, exitCode = 1) {
185
+ super(message);
186
+ this.name = "CliError";
187
+ this.exitCode = exitCode;
188
+ }
189
+ };
190
+ function isPromptCancellation(error) {
191
+ if (!(error instanceof Error)) return false;
192
+ const name = error.name.toLowerCase();
193
+ const message = error.message.toLowerCase();
194
+ return name === "exitprompterror" || name === "cancelprompterror" || message.includes("force closed") || message.includes("prompt was canceled");
195
+ }
196
+ function getErrorMessage(error) {
197
+ if (error instanceof Error) return error.message;
198
+ if (typeof error === "string") return error;
199
+ return "An unknown error occurred.";
200
+ }
201
+
202
+ // src/version.ts
203
+ import { createRequire } from "module";
204
+ var require2 = createRequire(import.meta.url);
205
+ var pkg = require2("../package.json");
206
+ var VERSION = pkg.version ?? "0.0.0";
207
+
208
+ // src/registry.ts
209
+ var DEFAULT_REGISTRY_URL = "https://raw.githubusercontent.com/andi-nugroho/ansensational/main/registry/registry.json";
210
+ var configuredHome = process.env.ANSENSATIONAL_HOME?.trim();
211
+ var ANSENSATIONAL_DIR = configuredHome ? path.resolve(configuredHome) : path.join(os.homedir(), ".ansensational");
212
+ var LOCAL_REGISTRY_PATH = path.join(ANSENSATIONAL_DIR, "registry.json");
213
+ var LOCAL_AUTHOR = "local";
214
+ var REMOTE_REGISTRY_URL = process.env.ANSENSATIONAL_REGISTRY_URL?.trim() || DEFAULT_REGISTRY_URL;
215
+ var FETCH_TIMEOUT_MS = (() => {
216
+ const configured = Number(process.env.ANSENSATIONAL_REGISTRY_TIMEOUT);
217
+ return Number.isFinite(configured) && configured > 0 ? configured : 15e3;
218
+ })();
219
+ async function ensureAnsensationalDir() {
220
+ await fs.ensureDir(ANSENSATIONAL_DIR);
221
+ }
222
+ function createEmptyRegistry() {
223
+ return {
224
+ version: "1.0.0",
225
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
226
+ templates: {}
227
+ };
228
+ }
229
+ function flattenTemplates(registry) {
230
+ const result = [];
231
+ for (const [username, templates] of Object.entries(registry.templates)) {
232
+ for (const template of templates) {
233
+ result.push({ ...template, username });
234
+ }
235
+ }
236
+ return result;
237
+ }
238
+ function findAuthorKey(registry, author) {
239
+ if (registry.templates[author]) return author;
240
+ const normalized = author.toLowerCase();
241
+ return Object.keys(registry.templates).find(
242
+ (key) => key.toLowerCase() === normalized
243
+ );
244
+ }
245
+ function getAuthorTemplatesFromRegistry(registry, author) {
246
+ const key = findAuthorKey(registry, author);
247
+ if (!key) return [];
248
+ return (registry.templates[key] ?? []).map((template) => ({
249
+ ...template,
250
+ username: key
251
+ }));
252
+ }
253
+ function findTemplateInRegistry(registry, author, slug) {
254
+ if (author) {
255
+ const key = findAuthorKey(registry, author);
256
+ if (!key) return void 0;
257
+ return registry.templates[key]?.find((template) => template.slug === slug);
258
+ }
259
+ return flattenTemplates(registry).find((template) => template.slug === slug);
260
+ }
261
+ async function readLocalRegistry() {
262
+ if (!await fs.pathExists(LOCAL_REGISTRY_PATH)) {
263
+ return createEmptyRegistry();
264
+ }
265
+ try {
266
+ const data = await fs.readJson(LOCAL_REGISTRY_PATH);
267
+ const result = RegistrySchema.safeParse(data);
268
+ if (!result.success) {
269
+ throw new Error(formatZodError(result.error));
270
+ }
271
+ return result.data;
272
+ } catch {
273
+ const backupPath = path.join(
274
+ ANSENSATIONAL_DIR,
275
+ `registry.corrupt-${Date.now()}.json`
276
+ );
277
+ let backedUp = false;
278
+ try {
279
+ await fs.move(LOCAL_REGISTRY_PATH, backupPath, { overwrite: true });
280
+ backedUp = true;
281
+ } catch {
282
+ }
283
+ UI.warn(
284
+ backedUp ? `Your local registry was invalid and has been backed up to:
285
+ ${backupPath}
286
+
287
+ Run "ansensational sync" to rebuild the local registry.` : `Your local registry at ${LOCAL_REGISTRY_PATH} is invalid and could not be backed up.
288
+
289
+ Run "ansensational sync" to rebuild the local registry.`
290
+ );
291
+ return createEmptyRegistry();
292
+ }
293
+ }
294
+ async function writeLocalRegistry(registry) {
295
+ const validated = RegistrySchema.parse(registry);
296
+ await ensureAnsensationalDir();
297
+ const tempPath = `${LOCAL_REGISTRY_PATH}.${process.pid}.tmp`;
298
+ try {
299
+ await fs.writeJson(tempPath, validated, { spaces: 2 });
300
+ await fs.move(tempPath, LOCAL_REGISTRY_PATH, { overwrite: true });
301
+ } finally {
302
+ await fs.remove(tempPath).catch(() => void 0);
303
+ }
304
+ }
305
+ async function fetchRemoteRegistryResult() {
306
+ let response;
307
+ try {
308
+ response = await fetch(REMOTE_REGISTRY_URL, {
309
+ headers: {
310
+ Accept: "application/json",
311
+ "User-Agent": `ansensational-cli/${VERSION}`
312
+ },
313
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
314
+ });
315
+ } catch (error) {
316
+ const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
317
+ return {
318
+ registry: null,
319
+ error: timedOut ? `Request timed out after ${FETCH_TIMEOUT_MS / 1e3}s.` : "Could not reach the remote registry. Check your internet connection."
320
+ };
321
+ }
322
+ if (!response.ok) {
323
+ return {
324
+ registry: null,
325
+ error: `Remote registry returned HTTP ${response.status} (${response.statusText}).`
326
+ };
327
+ }
328
+ try {
329
+ const data = await response.json();
330
+ const result = RegistrySchema.safeParse(data);
331
+ if (!result.success) {
332
+ return {
333
+ registry: null,
334
+ error: `Remote registry is invalid:
335
+ ${formatZodError(result.error)}`
336
+ };
337
+ }
338
+ return { registry: result.data };
339
+ } catch {
340
+ return {
341
+ registry: null,
342
+ error: "Remote registry did not contain valid JSON."
343
+ };
344
+ }
345
+ }
346
+ async function fetchRemoteRegistry() {
347
+ return (await fetchRemoteRegistryResult()).registry;
348
+ }
349
+ function parseTemplateSlug(input) {
350
+ const value = input.trim().replace(/^@/, "");
351
+ if (!value) return null;
352
+ const parts = value.split("/");
353
+ if (parts.some((part) => part.length === 0)) return null;
354
+ const slug = parts[parts.length - 1]?.toLowerCase();
355
+ if (!slug) return null;
356
+ if (parts.length === 1) return { slug };
357
+ if (parts.length === 2) {
358
+ return { author: parts[0]?.toLowerCase(), slug };
359
+ }
360
+ return null;
361
+ }
362
+ async function findTemplateBySlug(input) {
363
+ const parsed = parseTemplateSlug(input);
364
+ if (!parsed) return void 0;
365
+ const local = await readLocalRegistry();
366
+ const localTemplate = findTemplateInRegistry(
367
+ local,
368
+ parsed.author,
369
+ parsed.slug
370
+ );
371
+ if (localTemplate) return localTemplate;
372
+ const remoteResult = await fetchRemoteRegistryResult();
373
+ if (!remoteResult.registry) {
374
+ throw new CliError(
375
+ `Could not load the community registry.${remoteResult.error ? `
376
+ ${remoteResult.error}` : ""}
377
+
378
+ If the template is local, check the @author/slug spelling. Otherwise try again or run "ansensational sync".`
379
+ );
380
+ }
381
+ return findTemplateInRegistry(
382
+ remoteResult.registry,
383
+ parsed.author,
384
+ parsed.slug
385
+ );
386
+ }
387
+ async function getAuthorTemplates(author, options = {}) {
388
+ const normalizedAuthor = author.trim().replace(/^@/, "");
389
+ const local = await readLocalRegistry();
390
+ const localTemplates = getAuthorTemplatesFromRegistry(
391
+ local,
392
+ normalizedAuthor
393
+ );
394
+ if (!options.remote) return localTemplates;
395
+ const remote = await fetchRemoteRegistry();
396
+ if (!remote) return localTemplates;
397
+ const remoteTemplates = getAuthorTemplatesFromRegistry(
398
+ remote,
399
+ normalizedAuthor
400
+ );
401
+ const seen = new Set(
402
+ localTemplates.map((template) => `${template.username}/${template.slug}`)
403
+ );
404
+ return [
405
+ ...localTemplates,
406
+ ...remoteTemplates.filter(
407
+ (template) => !seen.has(`${template.username}/${template.slug}`)
408
+ )
409
+ ];
410
+ }
411
+ async function authorExists(author) {
412
+ const normalizedAuthor = author.trim().replace(/^@/, "");
413
+ const local = await readLocalRegistry();
414
+ if (findAuthorKey(local, normalizedAuthor)) return true;
415
+ const remote = await fetchRemoteRegistry();
416
+ return remote ? Boolean(findAuthorKey(remote, normalizedAuthor)) : false;
417
+ }
418
+ function matchesAuthor(template, author) {
419
+ const normalized = author.trim().replace(/^@/, "").toLowerCase();
420
+ return template.username.toLowerCase() === normalized || template.author.github?.toLowerCase() === normalized;
421
+ }
422
+ async function searchTemplates(options = {}) {
423
+ const local = await readLocalRegistry();
424
+ const remote = options.includeRemote === false ? null : await fetchRemoteRegistry();
425
+ const localTemplates = flattenTemplates(local);
426
+ const remoteTemplates = remote ? flattenTemplates(remote) : [];
427
+ const seen = new Set(
428
+ localTemplates.map((template) => `${template.username}/${template.slug}`)
429
+ );
430
+ const allTemplates = [
431
+ ...localTemplates,
432
+ ...remoteTemplates.filter(
433
+ (template) => !seen.has(`${template.username}/${template.slug}`)
434
+ )
435
+ ];
436
+ return allTemplates.filter((template) => {
437
+ if (options.type && template.type !== options.type) return false;
438
+ if (options.framework && template.framework !== options.framework) {
439
+ return false;
440
+ }
441
+ if (options.tag) {
442
+ const tag = options.tag.toLowerCase();
443
+ if (!template.tags.some((value) => value.toLowerCase() === tag)) {
444
+ return false;
445
+ }
446
+ }
447
+ if (options.author && !matchesAuthor(template, options.author)) {
448
+ return false;
449
+ }
450
+ if (options.query) {
451
+ const query = options.query.toLowerCase();
452
+ const searchable = [
453
+ template.slug,
454
+ template.name,
455
+ template.description ?? "",
456
+ template.username,
457
+ template.author.name,
458
+ ...template.tags,
459
+ ...template.features
460
+ ].join(" ").toLowerCase();
461
+ if (!searchable.includes(query)) return false;
462
+ }
463
+ return true;
464
+ });
465
+ }
466
+ async function addTemplateToRegistry(template) {
467
+ const validated = CommunityTemplateSchema.parse(template);
468
+ const registry = await readLocalRegistry();
469
+ const templates = registry.templates[LOCAL_AUTHOR] ?? [];
470
+ const existingIndex = templates.findIndex(
471
+ (entry) => entry.slug === validated.slug
472
+ );
473
+ const updated = existingIndex !== -1;
474
+ if (updated) {
475
+ templates[existingIndex] = validated;
476
+ } else {
477
+ templates.push(validated);
478
+ }
479
+ registry.templates[LOCAL_AUTHOR] = [...templates].sort(
480
+ (a, b) => a.slug.localeCompare(b.slug)
481
+ );
482
+ registry.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
483
+ await writeLocalRegistry(registry);
484
+ return { updated };
485
+ }
486
+ async function syncRegistry() {
487
+ const remoteResult = await fetchRemoteRegistryResult();
488
+ if (!remoteResult.registry) {
489
+ return {
490
+ ok: false,
491
+ error: remoteResult.error,
492
+ preserved: 0,
493
+ total: 0
494
+ };
495
+ }
496
+ const remote = remoteResult.registry;
497
+ const local = await readLocalRegistry();
498
+ const localTemplates = local.templates[LOCAL_AUTHOR] ?? [];
499
+ const templates = { ...remote.templates };
500
+ if (localTemplates.length > 0) {
501
+ const mergedBySlug = /* @__PURE__ */ new Map();
502
+ for (const template of remote.templates[LOCAL_AUTHOR] ?? []) {
503
+ mergedBySlug.set(template.slug, template);
504
+ }
505
+ for (const template of localTemplates) {
506
+ mergedBySlug.set(template.slug, template);
507
+ }
508
+ templates[LOCAL_AUTHOR] = [...mergedBySlug.values()].sort(
509
+ (a, b) => a.slug.localeCompare(b.slug)
510
+ );
511
+ }
512
+ const registry = {
513
+ ...remote,
514
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
515
+ templates
516
+ };
517
+ await writeLocalRegistry(registry);
518
+ return {
519
+ ok: true,
520
+ preserved: localTemplates.length,
521
+ total: Object.values(templates).flat().length
522
+ };
523
+ }
524
+
525
+ // src/helpers/options.ts
526
+ function normalizeEnum(value, schema, label) {
527
+ if (value === void 0) return void 0;
528
+ const normalized = value.trim().toLowerCase();
529
+ if (!normalized) {
530
+ throw new CliError(`--${label} requires a value.`);
531
+ }
532
+ const result = schema.safeParse(normalized);
533
+ if (!result.success) {
534
+ throw new CliError(
535
+ `Invalid ${label} "${value}".
536
+ Valid values: ${schema.options.join(", ")}.`
537
+ );
538
+ }
539
+ return result.data;
540
+ }
541
+ function normalizeType(value) {
542
+ return normalizeEnum(value, TemplateTypeSchema, "type");
543
+ }
544
+ function normalizeFramework(value) {
545
+ return normalizeEnum(value, FrameworkSchema, "framework");
546
+ }
547
+ function normalizeAuthor(value) {
548
+ if (value === void 0) return void 0;
549
+ const author = value.trim().replace(/^@/, "");
550
+ if (!author) {
551
+ throw new CliError("--author requires a username.");
552
+ }
553
+ return author;
554
+ }
555
+ function parseCommaSeparated(value) {
556
+ if (!value) return [];
557
+ const seen = /* @__PURE__ */ new Set();
558
+ const result = [];
559
+ for (const entry of value.split(",")) {
560
+ const trimmed = entry.trim();
561
+ if (!trimmed) continue;
562
+ const key = trimmed.toLowerCase();
563
+ if (seen.has(key)) continue;
564
+ seen.add(key);
565
+ result.push(trimmed);
566
+ }
567
+ return result;
568
+ }
569
+
570
+ // src/commands/list.ts
571
+ async function listCommand(options) {
572
+ const type = normalizeType(options.type);
573
+ const framework = normalizeFramework(options.framework);
574
+ const author = normalizeAuthor(options.author);
575
+ if (options.remote && !options.json) {
576
+ UI.info("Fetching from remote registry...");
577
+ }
578
+ const templates = await searchTemplates({
579
+ type,
580
+ framework,
581
+ author,
582
+ includeRemote: Boolean(options.remote)
583
+ });
584
+ const sorted = [...templates].sort((a, b) => {
585
+ const authorCompare = a.username.localeCompare(b.username);
586
+ return authorCompare !== 0 ? authorCompare : a.slug.localeCompare(b.slug);
587
+ });
588
+ if (options.json) {
589
+ console.log(JSON.stringify(sorted, null, 2));
590
+ return;
591
+ }
592
+ if (sorted.length === 0) {
593
+ if (author) {
594
+ UI.warn(`No templates found for user '@${author}'.`);
595
+ } else {
596
+ UI.warn("No templates found.");
597
+ }
598
+ if (!options.remote) {
599
+ UI.dim("Tip: Use --remote to include the community registry.");
600
+ }
601
+ return;
602
+ }
603
+ UI.header("Available Templates:");
604
+ sorted.forEach((template) => UI.templateItem(template));
605
+ UI.dim(`Total: ${sorted.length} template(s)
606
+ `);
607
+ }
608
+
609
+ // src/commands/search.ts
610
+ async function searchCommand(query, options) {
611
+ const type = normalizeType(options.type);
612
+ const framework = normalizeFramework(options.framework);
613
+ const author = normalizeAuthor(options.author);
614
+ const normalizedQuery = query.trim();
615
+ if (!normalizedQuery) {
616
+ throw new CliError("Search query cannot be empty.");
617
+ }
618
+ if (!options.json) {
619
+ UI.info(`Searching for "${normalizedQuery}"...`);
620
+ }
621
+ const templates = await searchTemplates({
622
+ query: normalizedQuery,
623
+ type,
624
+ framework,
625
+ author
626
+ });
627
+ const sorted = [...templates].sort((a, b) => {
628
+ const authorCompare = a.username.localeCompare(b.username);
629
+ return authorCompare !== 0 ? authorCompare : a.slug.localeCompare(b.slug);
630
+ });
631
+ if (options.json) {
632
+ console.log(JSON.stringify(sorted, null, 2));
633
+ return;
634
+ }
635
+ if (sorted.length === 0) {
636
+ if (author) {
637
+ UI.warn(
638
+ `No templates found matching "${normalizedQuery}" for user '@${author}'.`
639
+ );
640
+ } else {
641
+ UI.warn(`No templates found matching "${normalizedQuery}".`);
642
+ }
643
+ return;
644
+ }
645
+ UI.header(`Found ${sorted.length} template(s):`);
646
+ sorted.forEach((template) => UI.templateItem(template));
647
+ }
648
+
649
+ // src/commands/sync.ts
650
+ async function syncCommand() {
651
+ UI.info("Syncing from remote registry...");
652
+ UI.dim(REMOTE_REGISTRY_URL);
653
+ const result = await syncRegistry();
654
+ if (!result.ok) {
655
+ throw new CliError(
656
+ `Failed to sync registry.${result.error ? `
657
+ ${result.error}` : ""}`
658
+ );
659
+ }
660
+ UI.success(
661
+ `Registry synced successfully! ${result.total} template(s) available.`
662
+ );
663
+ if (result.preserved > 0) {
664
+ UI.dim(
665
+ `Preserved ${result.preserved} locally added template(s) under @local.`
666
+ );
667
+ }
668
+ }
669
+
670
+ // src/utils.ts
671
+ import { simpleGit } from "simple-git";
672
+ import fs2 from "fs-extra";
673
+ import path2 from "path";
674
+ import pc2 from "picocolors";
675
+ import inquirer from "inquirer";
676
+
677
+ // src/helpers/prompt.ts
678
+ function isInteractive() {
679
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
680
+ }
681
+ function canPrompt(options = {}) {
682
+ return !options.yes && isInteractive();
683
+ }
684
+
685
+ // src/utils.ts
686
+ var GIT_STRATEGIES = ["keep", "fresh", "remove"];
687
+ var PACKAGE_MANAGERS = [
688
+ "npm",
689
+ "pnpm",
690
+ "yarn",
691
+ "bun"
692
+ ];
693
+ function isPackageManager(value) {
694
+ return PACKAGE_MANAGERS.includes(value);
695
+ }
696
+ function toHttpsGitUrl(input) {
697
+ const value = input.trim();
698
+ const scpLike = value.match(/^git@([^:]+):(.+)$/);
699
+ if (scpLike) {
700
+ return `https://${scpLike[1]}/${scpLike[2]}`;
701
+ }
702
+ if (value.startsWith("ssh://")) {
703
+ try {
704
+ const sshUrl = new URL(value);
705
+ if (sshUrl.hostname) {
706
+ return `https://${sshUrl.hostname}${sshUrl.pathname}${sshUrl.search}`;
707
+ }
708
+ } catch {
709
+ }
710
+ }
711
+ return value;
712
+ }
713
+ function normalizeRepoUrl(input) {
714
+ const normalized = toHttpsGitUrl(input);
715
+ let url;
716
+ try {
717
+ url = new URL(normalized);
718
+ } catch {
719
+ throw new CliError(`Invalid repository URL: ${input}`);
720
+ }
721
+ if (url.protocol !== "https:" && url.protocol !== "http:" && url.protocol !== "file:") {
722
+ throw new CliError(
723
+ `Unsupported repository URL: ${input}
724
+ Only http(s) and file Git URLs are supported.`
725
+ );
726
+ }
727
+ if (url.protocol !== "file:" && !url.hostname) {
728
+ throw new CliError(`Invalid repository URL: ${input}`);
729
+ }
730
+ if (/\/[^/]+\/[^/]+\.git\/?$/.test(url.pathname)) {
731
+ url.pathname = url.pathname.replace(/\.git\/?$/, "");
732
+ }
733
+ url.hash = "";
734
+ return url.toString().replace(/\/$/, "");
735
+ }
736
+ function parseTemplateSource(input) {
737
+ const url = new URL(normalizeRepoUrl(input));
738
+ const host = url.hostname.replace(/^www\./, "").toLowerCase();
739
+ const segments = url.pathname.split("/").filter(Boolean).map((segment) => {
740
+ try {
741
+ return decodeURIComponent(segment);
742
+ } catch {
743
+ return segment;
744
+ }
745
+ });
746
+ const cloneRoot = (repoSegments) => {
747
+ const repoPath = repoSegments.join("/").replace(/\.git$/, "");
748
+ return `${url.protocol}//${url.host}/${repoPath}.git`;
749
+ };
750
+ const dashIndex = segments.indexOf("-");
751
+ if (dashIndex > 0 && segments[dashIndex + 1] === "tree") {
752
+ const branch = segments[dashIndex + 2];
753
+ const subdirSegments = segments.slice(dashIndex + 3);
754
+ return {
755
+ cloneUrl: cloneRoot(segments.slice(0, dashIndex)),
756
+ branch,
757
+ subdir: subdirSegments.length > 0 ? subdirSegments.join("/") : void 0
758
+ };
759
+ }
760
+ if (dashIndex > 0 && segments[dashIndex + 1] === "blob") {
761
+ throw new CliError(
762
+ "Template URLs must point to a repository or a directory, not a single file."
763
+ );
764
+ }
765
+ if (segments.length >= 3 && segments[2] === "tree") {
766
+ const branch = segments[3];
767
+ const subdirSegments = segments.slice(4);
768
+ return {
769
+ cloneUrl: cloneRoot(segments.slice(0, 2)),
770
+ branch,
771
+ subdir: subdirSegments.length > 0 ? subdirSegments.join("/") : void 0
772
+ };
773
+ }
774
+ if (segments.length >= 3 && segments[2] === "blob") {
775
+ throw new CliError(
776
+ "Template URLs must point to a repository or a directory, not a single file."
777
+ );
778
+ }
779
+ const isGitHub = host === "github.com" || host.endsWith(".github.com");
780
+ const isGitLab = host === "gitlab.com" || host.endsWith(".gitlab.com");
781
+ if (isGitLab && segments.length >= 2) {
782
+ return { cloneUrl: cloneRoot(segments) };
783
+ }
784
+ if (isGitHub && segments.length >= 2) {
785
+ return { cloneUrl: cloneRoot(segments.slice(0, 2)) };
786
+ }
787
+ return { cloneUrl: normalizeRepoUrl(input) };
788
+ }
789
+ async function cloneRepository(source, targetDir, gitStrategy) {
790
+ const options = [];
791
+ if (source.branch) {
792
+ options.push("--branch", source.branch, "--single-branch");
793
+ }
794
+ if (gitStrategy !== "keep") {
795
+ options.push("--depth", "1");
796
+ }
797
+ try {
798
+ await simpleGit().clone(source.cloneUrl, targetDir, options);
799
+ } catch (error) {
800
+ const detail = error instanceof Error && error.message ? `
801
+ ${error.message.split("\n")[0]}` : "";
802
+ throw new CliError(
803
+ `Failed to clone ${source.cloneUrl}. Check that the repository exists and that you have access to it.${detail}`
804
+ );
805
+ }
806
+ }
807
+ async function cloneTemplate(url, dest, gitStrategy = "fresh") {
808
+ const source = parseTemplateSource(url);
809
+ console.log(pc2.blue(`Cloning template from ${source.cloneUrl}...`));
810
+ if (source.branch) {
811
+ console.log(pc2.dim(`Using branch: ${source.branch}`));
812
+ }
813
+ if (source.subdir) {
814
+ console.log(pc2.dim(`Using subdirectory: ${source.subdir}`));
815
+ const repoDir = path2.join(dest, ".ansensational-repo");
816
+ await cloneRepository(source, repoDir, gitStrategy);
817
+ const sourceDir = path2.resolve(repoDir, source.subdir);
818
+ const relative = path2.relative(repoDir, sourceDir);
819
+ if (relative.startsWith("..") || path2.isAbsolute(relative)) {
820
+ throw new CliError(`Invalid template subdirectory: ${source.subdir}`);
821
+ }
822
+ if (!await fs2.pathExists(sourceDir)) {
823
+ throw new CliError(
824
+ `Template subdirectory "${source.subdir}" does not exist in ${source.cloneUrl}.`
825
+ );
826
+ }
827
+ await fs2.copy(sourceDir, dest, { overwrite: true });
828
+ if (gitStrategy === "keep") {
829
+ const gitDir2 = path2.join(repoDir, ".git");
830
+ if (await fs2.pathExists(gitDir2)) {
831
+ await fs2.copy(gitDir2, path2.join(dest, ".git"));
832
+ }
833
+ }
834
+ await fs2.remove(repoDir);
835
+ } else {
836
+ await cloneRepository(source, dest, gitStrategy);
837
+ }
838
+ const gitDir = path2.join(dest, ".git");
839
+ if (gitStrategy === "keep") {
840
+ if (await fs2.pathExists(gitDir)) {
841
+ console.log(pc2.green("Kept original git history."));
842
+ }
843
+ return;
844
+ }
845
+ if (await fs2.pathExists(gitDir)) {
846
+ await fs2.remove(gitDir);
847
+ console.log(pc2.green("Removed original .git history."));
848
+ }
849
+ }
850
+ async function detectPackageManager(dir) {
851
+ if (await fs2.pathExists(path2.join(dir, "package-lock.json"))) return "npm";
852
+ if (await fs2.pathExists(path2.join(dir, "npm-shrinkwrap.json"))) return "npm";
853
+ if (await fs2.pathExists(path2.join(dir, "pnpm-lock.yaml"))) return "pnpm";
854
+ if (await fs2.pathExists(path2.join(dir, "yarn.lock"))) return "yarn";
855
+ if (await fs2.pathExists(path2.join(dir, "bun.lockb"))) return "bun";
856
+ if (await fs2.pathExists(path2.join(dir, "bun.lock"))) return "bun";
857
+ const pkgPath = path2.join(dir, "package.json");
858
+ if (await fs2.pathExists(pkgPath)) {
859
+ try {
860
+ const pkg2 = await fs2.readJson(pkgPath);
861
+ const declared = String(pkg2.packageManager ?? "").split("@")[0] ?? "";
862
+ if (isPackageManager(declared)) return declared;
863
+ } catch {
864
+ }
865
+ }
866
+ return "unknown";
867
+ }
868
+ var LOCKFILES = {
869
+ npm: ["package-lock.json", "npm-shrinkwrap.json"],
870
+ pnpm: ["pnpm-lock.yaml"],
871
+ yarn: ["yarn.lock"],
872
+ bun: ["bun.lock", "bun.lockb"]
873
+ };
874
+ async function removeLockfiles(dir, manager) {
875
+ for (const lockfile of LOCKFILES[manager]) {
876
+ await fs2.remove(path2.join(dir, lockfile));
877
+ }
878
+ }
879
+ async function syncPackageManagerField(dir, previous, next) {
880
+ const pkgPath = path2.join(dir, "package.json");
881
+ if (!await fs2.pathExists(pkgPath)) return;
882
+ try {
883
+ const pkg2 = await fs2.readJson(pkgPath);
884
+ const declared = String(pkg2.packageManager ?? "").split("@")[0] ?? "";
885
+ if (declared === previous && previous !== next) {
886
+ delete pkg2.packageManager;
887
+ await fs2.writeJson(pkgPath, pkg2, { spaces: 2 });
888
+ }
889
+ } catch {
890
+ }
891
+ }
892
+ async function handlePackageManagerTransition(dir, requested, options = {}) {
893
+ const detected = await detectPackageManager(dir);
894
+ let requestedManager;
895
+ if (requested) {
896
+ const normalized = requested.trim().toLowerCase();
897
+ if (!isPackageManager(normalized)) {
898
+ throw new CliError(
899
+ `Invalid package manager "${requested}". Use one of: ${PACKAGE_MANAGERS.join(", ")}.`
900
+ );
901
+ }
902
+ requestedManager = normalized;
903
+ }
904
+ let selected = requestedManager ?? detected;
905
+ if (!requestedManager && detected !== "unknown" && canPrompt(options)) {
906
+ const answers = await inquirer.prompt([
907
+ {
908
+ type: "list",
909
+ name: "usePreferred",
910
+ message: `Detected ${detected} in template. Which package manager do you want to use?`,
911
+ choices: [...PACKAGE_MANAGERS, "keep original"],
912
+ default: detected
913
+ }
914
+ ]);
915
+ selected = answers.usePreferred === "keep original" ? detected : answers.usePreferred;
916
+ }
917
+ if (selected === "unknown" || selected === detected) {
918
+ return { manager: selected, changed: false };
919
+ }
920
+ console.log(pc2.yellow(`Switching from ${detected} to ${selected}...`));
921
+ if (detected !== "unknown") {
922
+ await removeLockfiles(dir, detected);
923
+ await syncPackageManagerField(dir, detected, selected);
924
+ }
925
+ return { manager: selected, changed: true };
926
+ }
927
+ async function initNewGitRepo(dir) {
928
+ const newGit = simpleGit(dir);
929
+ try {
930
+ await newGit.init();
931
+ try {
932
+ const status = await newGit.status();
933
+ if (status.current !== "main") {
934
+ await newGit.checkoutLocalBranch("main");
935
+ }
936
+ } catch {
937
+ console.warn(
938
+ pc2.yellow("Could not switch to the 'main' branch; using the default.")
939
+ );
940
+ }
941
+ await newGit.add(".");
942
+ await newGit.commit("Initial commit from ansensational");
943
+ console.log(pc2.green("Initialized new git repository with 'main' branch."));
944
+ return true;
945
+ } catch (error) {
946
+ const detail = error instanceof Error ? ` ${error.message.split("\n")[0]}` : "";
947
+ console.warn(
948
+ pc2.yellow(
949
+ `Initialized git repository, but the initial commit failed.${detail}
950
+ Set git user.name/user.email and commit manually.`
951
+ )
952
+ );
953
+ return false;
954
+ }
955
+ }
956
+ function toPackageName(folderName) {
957
+ const name = folderName.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[._-]+|[._-]+$/g, "").replace(/-{2,}/g, "-");
958
+ return name || "app";
959
+ }
960
+ async function updatePackageJson(dir, name) {
961
+ const pkgPath = path2.join(dir, "package.json");
962
+ if (!await fs2.pathExists(pkgPath)) return;
963
+ try {
964
+ const pkg2 = await fs2.readJson(pkgPath);
965
+ const packageName = toPackageName(name);
966
+ if (pkg2.name === packageName) return;
967
+ pkg2.name = packageName;
968
+ await fs2.writeJson(pkgPath, pkg2, { spaces: 2 });
969
+ console.log(pc2.green(`Updated package.json name to "${packageName}".`));
970
+ } catch {
971
+ console.warn(pc2.yellow("Failed to update package.json name. Skipping..."));
972
+ }
973
+ }
974
+
975
+ // src/commands/add.ts
976
+ function detectPlatform(url) {
977
+ try {
978
+ const hostname = new URL(url).hostname.replace(/^www\./, "").toLowerCase();
979
+ if (hostname === "github.com") return "github";
980
+ if (hostname === "gitlab.com") return "gitlab";
981
+ } catch {
982
+ }
983
+ return "custom";
984
+ }
985
+ function titleFromSlug(slug) {
986
+ return slug.split("-").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
987
+ }
988
+ async function addCommand(slug, url, options) {
989
+ const normalizedSlug = slug.trim().replace(/^@/, "");
990
+ if (normalizedSlug.includes("/")) {
991
+ throw new CliError(
992
+ `Invalid slug "${slug}". Use a plain slug such as "my-template" (without an author).`
993
+ );
994
+ }
995
+ const type = normalizeType(options.type);
996
+ const framework = normalizeFramework(options.framework);
997
+ const normalizedUrl = normalizeRepoUrl(url);
998
+ const name = options.name?.trim() || titleFromSlug(normalizedSlug);
999
+ const template = {
1000
+ slug: normalizedSlug,
1001
+ name,
1002
+ url: normalizedUrl,
1003
+ platform: detectPlatform(normalizedUrl),
1004
+ type: type ?? "other",
1005
+ framework: framework ?? "other",
1006
+ description: options.description?.trim() || void 0,
1007
+ tags: parseCommaSeparated(options.tags),
1008
+ features: parseCommaSeparated(options.features),
1009
+ author: {
1010
+ name: "Local"
1011
+ },
1012
+ tier: "free",
1013
+ license: options.license?.trim() || "MIT"
1014
+ };
1015
+ const result = CommunityTemplateSchema.safeParse(template);
1016
+ if (!result.success) {
1017
+ throw new CliError(`Invalid template:
1018
+ ${formatZodError(result.error)}`);
1019
+ }
1020
+ const { updated } = await addTemplateToRegistry(result.data);
1021
+ UI.success(
1022
+ `Template @${LOCAL_AUTHOR}/${result.data.slug} ${updated ? "updated in" : "added to"} your local registry.`
1023
+ );
1024
+ UI.dim(`ANSensational it with: ansensational @${LOCAL_AUTHOR}/${result.data.slug}`);
1025
+ }
1026
+
1027
+ // src/commands/ansensational.ts
1028
+ import path3 from "path";
1029
+ import fs3 from "fs-extra";
1030
+ import inquirer2 from "inquirer";
1031
+ async function resolveGitStrategy(options) {
1032
+ if (options.git) {
1033
+ const strategy = options.git.trim().toLowerCase();
1034
+ if (!GIT_STRATEGIES.includes(strategy)) {
1035
+ throw new CliError(
1036
+ `Invalid git strategy "${options.git}". Use one of: ${GIT_STRATEGIES.join(", ")}.`
1037
+ );
1038
+ }
1039
+ return strategy;
1040
+ }
1041
+ if (!canPrompt({ yes: options.yes })) {
1042
+ return "fresh";
1043
+ }
1044
+ const { gitChoice } = await inquirer2.prompt([
1045
+ {
1046
+ type: "list",
1047
+ name: "gitChoice",
1048
+ message: "How would you like to handle git?",
1049
+ choices: [
1050
+ {
1051
+ name: "Fresh start (new repo with initial commit)",
1052
+ value: "fresh"
1053
+ },
1054
+ { name: "Keep original git history", value: "keep" },
1055
+ { name: "No git (remove .git entirely)", value: "remove" }
1056
+ ],
1057
+ default: "fresh"
1058
+ }
1059
+ ]);
1060
+ return gitChoice;
1061
+ }
1062
+ async function prepareDestination(destination, force) {
1063
+ const absoluteDest = path3.resolve(process.cwd(), destination);
1064
+ if (!await fs3.pathExists(absoluteDest)) {
1065
+ await fs3.ensureDir(path3.dirname(absoluteDest));
1066
+ return { absoluteDest, exists: false };
1067
+ }
1068
+ const stat = await fs3.stat(absoluteDest);
1069
+ if (!stat.isDirectory()) {
1070
+ throw new CliError(
1071
+ `Destination ${destination} exists and is not a directory.`
1072
+ );
1073
+ }
1074
+ const entries = await fs3.readdir(absoluteDest);
1075
+ if (entries.length > 0 && !force) {
1076
+ throw new CliError(
1077
+ `Destination ${destination} already exists and is not empty.
1078
+ Choose a different directory, or pass --force to overwrite conflicting files.`
1079
+ );
1080
+ }
1081
+ return { absoluteDest, exists: true };
1082
+ }
1083
+ async function ansensationalCommand(slugInput, dest, options = {}) {
1084
+ if (!slugInput || !slugInput.trim()) {
1085
+ throw new CliError(
1086
+ "Missing template name.\nUsage: ansensational <@author/slug> [destination]"
1087
+ );
1088
+ }
1089
+ const requestedManager = options.pm?.trim().toLowerCase();
1090
+ if (requestedManager && !isPackageManager(requestedManager)) {
1091
+ throw new CliError(
1092
+ `Invalid package manager "${options.pm}". Use one of: ${PACKAGE_MANAGERS.join(", ")}.`
1093
+ );
1094
+ }
1095
+ const parsed = parseTemplateSlug(slugInput);
1096
+ if (!parsed) {
1097
+ throw new CliError(
1098
+ `Invalid template format: ${slugInput}
1099
+ Use @author/slug or author/slug (for example @andi-nugroho/nest-backend).`
1100
+ );
1101
+ }
1102
+ const template = await findTemplateBySlug(slugInput);
1103
+ if (!template) {
1104
+ if (parsed.author) {
1105
+ const userExists = await authorExists(parsed.author);
1106
+ if (userExists) {
1107
+ const suggestions = await getAuthorTemplates(parsed.author, {
1108
+ remote: true
1109
+ });
1110
+ throw new CliError(
1111
+ `Template "${parsed.slug}" not found for user @${parsed.author}.` + (suggestions.length > 0 ? `
1112
+
1113
+ Available templates for @${parsed.author}:
1114
+ ${suggestions.map((entry) => ` - ${entry.slug}`).join("\n")}` : "")
1115
+ );
1116
+ }
1117
+ throw new CliError(
1118
+ `User @${parsed.author} not found in the registry.
1119
+ Run "ansensational sync" or "ansensational list --remote" to refresh the registry.`
1120
+ );
1121
+ }
1122
+ throw new CliError(
1123
+ `Template "${parsed.slug}" not found.
1124
+ Try the @author/slug form, or run "ansensational search <query>" to find templates.`
1125
+ );
1126
+ }
1127
+ if (template.tier === "premium") {
1128
+ const purchase = template.pricing?.purchaseUrl ? `
1129
+ Learn more: ${template.pricing.purchaseUrl}` : "";
1130
+ throw new CliError(
1131
+ `"${template.name}" is a premium template and cannot be ansensationaled yet.${purchase}`
1132
+ );
1133
+ }
1134
+ const gitChoice = await resolveGitStrategy(options);
1135
+ const destination = dest || `./${template.slug}`;
1136
+ const { absoluteDest, exists } = await prepareDestination(
1137
+ destination,
1138
+ Boolean(options.force)
1139
+ );
1140
+ const tempDest = await fs3.mkdtemp(
1141
+ path3.join(path3.dirname(absoluteDest), ".ansensational-")
1142
+ );
1143
+ let placed = false;
1144
+ try {
1145
+ UI.info(
1146
+ `ANSensationaling @${template.author.github || parsed.author || "local"}/${template.slug}...`
1147
+ );
1148
+ UI.dim(`Name: ${template.name}`);
1149
+ UI.dim(`Type: ${template.type}`);
1150
+ if (template.framework !== "other") {
1151
+ UI.dim(`Framework: ${template.framework}`);
1152
+ }
1153
+ console.log("");
1154
+ await cloneTemplate(template.url, tempDest, gitChoice);
1155
+ const projectName = path3.basename(absoluteDest);
1156
+ await updatePackageJson(tempDest, projectName);
1157
+ const packageManager = await handlePackageManagerTransition(
1158
+ tempDest,
1159
+ requestedManager,
1160
+ { yes: options.yes }
1161
+ );
1162
+ if (gitChoice === "fresh") {
1163
+ await initNewGitRepo(tempDest);
1164
+ }
1165
+ if (!exists) {
1166
+ await fs3.move(tempDest, absoluteDest);
1167
+ } else {
1168
+ await fs3.copy(tempDest, absoluteDest, {
1169
+ overwrite: Boolean(options.force),
1170
+ errorOnExist: false
1171
+ });
1172
+ await fs3.remove(tempDest);
1173
+ }
1174
+ placed = true;
1175
+ UI.ansensationalSuccess(
1176
+ `${template.author.github || parsed.author || "local"}/${template.slug}`,
1177
+ destination,
1178
+ template.url,
1179
+ packageManager.manager
1180
+ );
1181
+ } catch (error) {
1182
+ await fs3.remove(tempDest).catch(() => void 0);
1183
+ if (!exists && !placed) {
1184
+ await fs3.remove(absoluteDest).catch(() => void 0);
1185
+ }
1186
+ if (error instanceof CliError) throw error;
1187
+ const detail = error instanceof Error ? error.message : String(error);
1188
+ throw new CliError(`ANSensationaling failed: ${detail}`);
1189
+ }
1190
+ }
1191
+
1192
+ // src/index.ts
1193
+ var program = new Command();
1194
+ program.name("ansensational").description("ANSensational new projects from GitHub/GitLab templates").version(VERSION, "-v, --version", "output the version number").showHelpAfterError().showSuggestionAfterError();
1195
+ program.command("ansensational", { isDefault: true }).description("ANSensational a template (default command)").argument("[slug]", "Template slug (e.g., @andi-nugroho/backend)").argument("[dest]", "Destination directory").option(
1196
+ "-g, --git <strategy>",
1197
+ "Git handling: keep, fresh, or remove (default: prompt)"
1198
+ ).option(
1199
+ "-p, --pm <manager>",
1200
+ "Package manager: npm, pnpm, yarn, or bun (default: detect/prompt)"
1201
+ ).option("-f, --force", "Overwrite files in a non-empty destination").option("-y, --yes", "Skip prompts and use defaults").action(
1202
+ async (slug, dest, options) => {
1203
+ if (!slug) {
1204
+ program.help();
1205
+ return;
1206
+ }
1207
+ await ansensationalCommand(slug, dest, options);
1208
+ }
1209
+ );
1210
+ program.command("list").description("List templates from the local registry").option("-r, --remote", "Include templates from the remote registry").option("-t, --type <type>", "Filter by type (frontend, backend, etc.)").option("-f, --framework <framework>", "Filter by framework").option("-a, --author <author>", "Filter by author username").option("--json", "Output machine-readable JSON").action(listCommand);
1211
+ program.command("search <query>").description("Search templates by name, description, author, or tags").option("-t, --type <type>", "Filter by type").option("-f, --framework <framework>", "Filter by framework").option("-a, --author <author>", "Filter by author username").option("--json", "Output machine-readable JSON").action(searchCommand);
1212
+ program.command("sync").description("Sync templates from the remote registry to the local cache").action(syncCommand);
1213
+ program.command("add <slug> <url>").description("Add or update a template in your local registry").option("-t, --type <type>", "Template type", "other").option("-f, --framework <framework>", "Template framework", "other").option("-d, --description <description>", "Template description").option("--tags <tags>", "Comma-separated tags").option("--features <features>", "Comma-separated features").option("-n, --name <name>", "Human-readable template name").option("--license <license>", "License identifier", "MIT").action(addCommand);
1214
+ program.addHelpText(
1215
+ "after",
1216
+ `
1217
+ Examples:
1218
+ $ ansensational @andi-nugroho/nest-backend my-app
1219
+ $ ansensational list --remote --type backend
1220
+ $ ansensational search nextjs --framework nextjs
1221
+ $ ansensational add my-template https://github.com/me/my-template --type fullstack
1222
+ $ ansensational sync
1223
+
1224
+ Documentation:
1225
+ https://github.com/andi-nugroho/ansensational
1226
+ `
1227
+ );
1228
+ async function main() {
1229
+ try {
1230
+ await program.parseAsync(process.argv);
1231
+ } catch (error) {
1232
+ if (isPromptCancellation(error)) {
1233
+ console.log(pc3.dim("\nCancelled."));
1234
+ process.exit(130);
1235
+ }
1236
+ const isDebug = process.env.ANSENSATIONAL_DEBUG;
1237
+ if (error instanceof CliError) {
1238
+ UI.error(error.message);
1239
+ if (isDebug) console.error(error.stack);
1240
+ process.exit(error.exitCode);
1241
+ }
1242
+ UI.error(getErrorMessage(error));
1243
+ if (isDebug && error instanceof Error) {
1244
+ console.error(error.stack);
1245
+ }
1246
+ process.exit(1);
1247
+ }
1248
+ }
1249
+ void main();