@replaystage/cli 0.3.0 → 0.4.1

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 CHANGED
@@ -33,7 +33,7 @@ async function uploadGameBundle(options) {
33
33
  const blob = new Blob([uint8], { type: "application/zip" });
34
34
  formData.append("bundle", blob, "bundle.zip");
35
35
  formData.append("title", options.title);
36
- formData.append("tagline", options.tagline);
36
+ formData.append("tagline", options.tagline ?? "");
37
37
  if (options.description) formData.append("description", options.description);
38
38
  if (options.category) formData.append("category", options.category);
39
39
  formData.append("submission_type", options.submissionType || "maker");
@@ -55,6 +55,10 @@ async function uploadGameBundle(options) {
55
55
  formData.append("ai_tool", options.aiTool);
56
56
  formData.append("aiTool", options.aiTool);
57
57
  }
58
+ if (options.tags !== void 0 && options.tags !== null) {
59
+ const tagsVal = Array.isArray(options.tags) ? JSON.stringify(options.tags) : String(options.tags);
60
+ formData.append("tags", tagsVal);
61
+ }
58
62
  if (options.coverBuffer) {
59
63
  const uint82 = new Uint8Array(options.coverBuffer);
60
64
  const fileName = options.coverFileName || "cover.png";
@@ -108,7 +112,7 @@ async function updateGameBundle(slug, options) {
108
112
  formData.append("bundle", blob, "bundle.zip");
109
113
  }
110
114
  if (options.title) formData.append("title", options.title);
111
- if (options.tagline) formData.append("tagline", options.tagline);
115
+ if (options.tagline !== void 0) formData.append("tagline", options.tagline);
112
116
  if (options.description) formData.append("description", options.description);
113
117
  if (options.visibility) formData.append("visibility", options.visibility);
114
118
  if (options.changelog) formData.append("changelog", options.changelog);
@@ -125,6 +129,10 @@ async function updateGameBundle(slug, options) {
125
129
  formData.append("ai_tool", options.aiTool);
126
130
  formData.append("aiTool", options.aiTool);
127
131
  }
132
+ if (options.tags !== void 0 && options.tags !== null) {
133
+ const tagsVal = Array.isArray(options.tags) ? JSON.stringify(options.tags) : String(options.tags);
134
+ formData.append("tags", tagsVal);
135
+ }
128
136
  if (options.coverBuffer) {
129
137
  const uint8 = new Uint8Array(options.coverBuffer);
130
138
  const fileName = options.coverFileName || "cover.png";
@@ -197,555 +205,141 @@ import path2 from "path";
197
205
  import * as fs from "fs";
198
206
  import * as os from "os";
199
207
  import * as path from "path";
200
- function resolveProjectDirectory(targetPath) {
201
- try {
202
- const resolved = path.resolve(targetPath);
203
- if (resolved.toLowerCase().endsWith(".zip")) {
204
- return null;
205
- }
206
- if (resolved.includes("seed-games")) {
207
- return null;
208
- }
209
- if (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {
210
- if (resolved === path.resolve(os.tmpdir())) {
211
- return null;
212
- }
213
- return resolved;
214
- }
215
- if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) {
216
- const parentDir = path.dirname(resolved);
217
- if (parentDir === path.resolve(os.tmpdir())) {
218
- return null;
219
- }
220
- return parentDir;
221
- }
222
- return resolved;
223
- } catch {
224
- return path.resolve(targetPath);
225
- }
226
- }
227
- function getProjectConfigPath(targetDir) {
228
- const dir = resolveProjectDirectory(targetDir);
229
- return dir ? path.join(dir, ".replaystage.json") : null;
230
- }
231
- function readProjectConfig(targetDir) {
232
- const configPath = getProjectConfigPath(targetDir);
233
- if (!configPath || !fs.existsSync(configPath)) {
234
- return null;
235
- }
236
- try {
237
- const raw = fs.readFileSync(configPath, "utf-8");
238
- const parsed = JSON.parse(raw);
239
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
240
- return null;
241
- }
242
- if ("slug" in parsed) {
243
- if (typeof parsed.slug !== "string" || !parsed.slug.trim()) {
244
- return null;
245
- }
246
- }
247
- const hasValidKey = typeof parsed.slug === "string" && parsed.slug.trim().length > 0 || typeof parsed.supportedPlatforms === "string" || typeof parsed.platforms === "string" || typeof parsed.aspectRatio === "string" || typeof parsed.aiModel === "string" || typeof parsed.aiTool === "string";
248
- if (!hasValidKey) {
249
- return null;
250
- }
251
- return parsed;
252
- } catch {
253
- return null;
254
- }
255
- }
256
- function writeProjectConfig(targetDir, config) {
257
- const configPath = getProjectConfigPath(targetDir);
258
- if (!configPath) {
259
- return;
260
- }
261
- const dir = path.dirname(configPath);
262
- if (!fs.existsSync(dir)) {
263
- fs.mkdirSync(dir, { recursive: true });
264
- }
265
- fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}
266
- `, "utf-8");
267
- }
268
- function incrementVersion(currentVersion) {
269
- if (!currentVersion || typeof currentVersion !== "string") return "0.2.0";
270
- const sanitized = currentVersion.trim().replace(/^v/i, "");
271
- const parts = sanitized.split(".").map((n) => Number.parseInt(n, 10));
272
- if (parts.length === 3 && !parts.some(Number.isNaN)) {
273
- return `${parts[0]}.${parts[1] + 1}.0`;
274
- }
275
- if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
276
- return `${parts[0]}.${parts[1] + 1}.0`;
277
- }
278
- return "0.2.0";
279
- }
280
- function promoteDraftVersion(currentVersion) {
281
- if (!currentVersion || typeof currentVersion !== "string") return "1.0.0";
282
- const sanitized = currentVersion.trim().replace(/^v/i, "");
283
- if (sanitized.startsWith("0.")) {
284
- return "1.0.0";
285
- }
286
- return incrementVersion(currentVersion);
287
- }
288
208
 
289
- // src/config.ts
290
- function getConfigDir() {
291
- return process.env.REPLAYSTAGE_CONFIG_DIR || path2.join(os2.homedir(), ".replaystage");
292
- }
293
- function getConfigPath() {
294
- return path2.join(getConfigDir(), "config.json");
295
- }
296
- function readConfig() {
297
- const dir = getConfigDir();
298
- for (const filename of ["config.json", "credentials.json"]) {
299
- const file = path2.join(dir, filename);
300
- if (fs2.existsSync(file)) {
301
- try {
302
- const raw = fs2.readFileSync(file, "utf-8");
303
- return JSON.parse(raw);
304
- } catch {
305
- }
306
- }
307
- }
308
- return {};
309
- }
310
- function writeConfig(config) {
311
- const dir = getConfigDir();
312
- fs2.mkdirSync(dir, { recursive: true, mode: 448 });
313
- const target = getConfigPath();
314
- fs2.writeFileSync(target, JSON.stringify(config, null, 2), {
315
- encoding: "utf-8",
316
- mode: 384
317
- });
318
- try {
319
- fs2.chmodSync(target, 384);
320
- } catch {
321
- }
322
- }
323
- function clearConfig() {
324
- const dir = getConfigDir();
325
- for (const filename of ["config.json", "credentials.json"]) {
326
- const file = path2.join(dir, filename);
327
- if (fs2.existsSync(file)) {
328
- try {
329
- fs2.unlinkSync(file);
330
- } catch {
331
- }
332
- }
333
- }
334
- }
335
- function getToken() {
336
- return resolveToken();
337
- }
338
- function setToken(token, user, apiUrl) {
339
- const current = readConfig();
340
- writeConfig({
341
- ...current,
342
- ...apiUrl ? { apiUrl: apiUrl.replace(/\/+$/, "") } : {},
343
- token,
344
- user: user || current.user
345
- });
346
- }
347
- function clearToken() {
348
- const current = readConfig();
349
- current.token = void 0;
350
- current.user = void 0;
351
- writeConfig(current);
352
- }
353
- function resolveToken(cliToken) {
354
- if (cliToken?.trim()) return cliToken.trim();
355
- if (process.env.REPLAYSTAGE_TOKEN?.trim()) {
356
- return process.env.REPLAYSTAGE_TOKEN.trim();
357
- }
358
- if (process.env.REPLAYSTAGE_API_TOKEN?.trim()) {
359
- return process.env.REPLAYSTAGE_API_TOKEN.trim();
360
- }
361
- const config = readConfig();
362
- return config.token || null;
363
- }
364
- function resolveApiUrl(cliApiUrl) {
365
- if (cliApiUrl?.trim()) return cliApiUrl.trim().replace(/\/+$/, "");
366
- if (process.env.REPLAYSTAGE_API_URL?.trim()) {
367
- return process.env.REPLAYSTAGE_API_URL.trim().replace(/\/+$/, "");
368
- }
369
- const config = readConfig();
370
- return (config.apiUrl || "https://replaystage.com").replace(/\/+$/, "");
371
- }
372
-
373
- // src/ui.ts
374
- import pc from "picocolors";
375
- function printJson(data) {
376
- process.stdout.write(`${JSON.stringify(data, null, 2)}
377
- `);
378
- }
379
- function printErrorJson(error, message, code = 1, extra) {
380
- process.stdout.write(
381
- `${JSON.stringify({ success: false, code, error, message, ...extra }, null, 2)}
382
- `
383
- );
384
- }
385
- function logInfo(message, isJsonMode = false) {
386
- if (isJsonMode) return;
387
- process.stderr.write(`${pc.cyan("\u2139 ") + message}
388
- `);
389
- }
390
- function logSuccess(message, isJsonMode = false) {
391
- if (isJsonMode) return;
392
- process.stderr.write(`${pc.green("\u2714 ") + message}
393
- `);
394
- }
395
- function logWarn(message, isJsonMode = false) {
396
- if (isJsonMode) return;
397
- process.stderr.write(`${pc.yellow("\u26A0 ") + message}
398
- `);
399
- }
400
- function logError(message, isJsonMode = false) {
401
- if (isJsonMode) return;
402
- process.stderr.write(`${pc.red("\u2716 ") + message}
403
- `);
404
- }
405
- function printPublishSuccess(res) {
406
- const border = "\u2550".repeat(64);
407
- console.log(`
408
- ${pc.yellow(`\u2554${border}\u2557`)}`);
409
- console.log(
410
- `${pc.yellow("\u2551")} \u{1F579}\uFE0F ${pc.bold(pc.white("REPLAYSTAGE PUBLISH SUCCESSFUL"))}${" ".repeat(30)}${pc.yellow("\u2551")}`
411
- );
412
- console.log(`${pc.yellow(`\u2560${border}\u2563`)}`);
413
- console.log(
414
- `${pc.yellow("\u2551")} ${pc.dim("Game:")} ${res.title.padEnd(48)}${pc.yellow("\u2551")}`
415
- );
416
- console.log(
417
- `${pc.yellow("\u2551")} ${pc.dim("Slug:")} ${res.slug.padEnd(48)}${pc.yellow("\u2551")}`
418
- );
419
- if (res.aiTool) {
420
- console.log(
421
- `${pc.yellow("\u2551")} ${pc.dim("AI Tool:")} ${res.aiTool.padEnd(48)}${pc.yellow("\u2551")}`
422
- );
423
- }
424
- if (res.aspectRatio) {
425
- console.log(
426
- `${pc.yellow("\u2551")} ${pc.dim("Ratio:")} ${res.aspectRatio.padEnd(48)}${pc.yellow("\u2551")}`
427
- );
428
- }
429
- const plat = res.supportedPlatforms || res.platforms;
430
- if (plat) {
431
- console.log(`${pc.yellow("\u2551")} ${pc.dim("Platforms:")} ${plat.padEnd(48)}${pc.yellow("\u2551")}`);
432
- }
433
- console.log(
434
- `${pc.yellow("\u2551")} ${pc.dim("Play URL:")} ${pc.cyan(res.url).padEnd(57)}${pc.yellow("\u2551")}`
435
- );
436
- if (res.shortUrl) {
437
- console.log(
438
- `${pc.yellow("\u2551")} ${pc.dim("Short Link:")} ${pc.magenta(res.shortUrl).padEnd(57)}${pc.yellow("\u2551")}`
439
- );
440
- }
441
- if (res.claim_token) {
442
- console.log(`${pc.yellow(`\u255F${border}\u2562`)}`);
443
- console.log(
444
- `${pc.yellow("\u2551")} \u{1F511} ${pc.bold(pc.yellow("SAFE HARBOR CLAIM TOKEN"))} (Keep private, 7-day TTL): ${pc.yellow("\u2551")}`
445
- );
446
- console.log(`${pc.yellow("\u2551")} ${pc.green(res.claim_token).padEnd(73)}${pc.yellow("\u2551")}`);
447
- if (res.claimUrl) {
448
- console.log(
449
- `${pc.yellow("\u2551")} ${pc.dim("Claim URL:")} ${pc.cyan(res.claimUrl).padEnd(57)}${pc.yellow("\u2551")}`
450
- );
451
- }
452
- }
453
- console.log(`${pc.yellow(`\u255A${border}\u255D`)}
454
- `);
455
- }
456
-
457
- // src/commands/auth.ts
458
- async function handleLogin(options = {}) {
459
- const isJson = Boolean(options.json);
460
- let token = options.token?.trim();
461
- const apiUrl = resolveApiUrl(options.apiUrl);
462
- if (!token) {
463
- if (isJson || !process.stdout.isTTY) {
464
- if (isJson) {
465
- printErrorJson("TOKEN_REQUIRED", "Authentication token is required via --token", 1);
466
- } else {
467
- console.error(pc2.red("Error: --token is required in non-interactive environment."));
468
- console.error(`Generate your token at ${apiUrl}/settings#tokens`);
469
- }
470
- process.exit(1);
471
- }
472
- console.log(pc2.cyan("\n\u{1F579}\uFE0F ReplayStage Authentication"));
473
- console.log(`To obtain a CLI token, visit: ${pc2.underline(`${apiUrl}/settings#tokens`)}
474
- `);
475
- const input = await text({
476
- message: "Enter your ReplayStage API token:",
477
- placeholder: "rps_...",
478
- validate(val) {
479
- if (!val || val.trim().length === 0) return "Token cannot be empty";
480
- }
481
- });
482
- if (typeof input !== "string") {
483
- console.log(pc2.yellow("Login cancelled."));
484
- process.exit(1);
485
- }
486
- token = input.trim();
487
- }
488
- try {
489
- let user = void 0;
490
- try {
491
- user = await fetchWhoami(apiUrl, token);
492
- } catch (err) {
493
- if (err?.status === 401 || err?.status === 403) {
494
- throw err;
495
- }
496
- user = { id: "user_cli", handle: "cli_user" };
497
- }
498
- setToken(token, user, options.apiUrl ? apiUrl : void 0);
499
- if (isJson) {
500
- printJson({ success: true, apiUrl, user, token: `${token.slice(0, 8)}...` });
501
- } else {
502
- console.log(
503
- pc2.green(`
504
- \u2714 Logged in successfully as ${pc2.bold(`@${user?.handle || "user"}`)}!`)
505
- );
506
- console.log(` ${pc2.dim("API URL:")} ${apiUrl}
507
- `);
508
- }
509
- } catch (err) {
510
- if (isJson) {
511
- printErrorJson("AUTH_FAILED", err.message, 1);
512
- } else {
513
- console.error(pc2.red(`
514
- \u2716 Login failed: ${err.message}
515
- `));
516
- }
517
- process.exit(1);
518
- }
519
- }
520
- async function handleWhoami(options = {}) {
521
- const isJson = Boolean(options.json);
522
- const config = readConfig();
523
- const token = resolveToken();
524
- const apiUrl = resolveApiUrl(options.apiUrl);
525
- if (!token) {
526
- if (isJson) {
527
- printJson({ authenticated: false, message: "Not logged in (anonymous upload mode)" });
528
- } else {
529
- console.log(
530
- pc2.yellow(
531
- "\nNot logged in. CLI commands run in anonymous mode with Safe Harbor claim tokens."
532
- )
533
- );
534
- console.log(`Run ${pc2.cyan("replaystage login --token <rps_token>")} to authenticate.
535
- `);
536
- }
537
- return;
538
- }
539
- try {
540
- let user = config.user;
541
- try {
542
- user = await fetchWhoami(apiUrl, token);
543
- if (config.token === token) {
544
- writeConfig({ ...config, user });
545
- }
546
- } catch (err) {
547
- if (err?.status === 401 || err?.status === 403) {
548
- throw err;
549
- }
550
- }
551
- if (isJson) {
552
- printJson({
553
- authenticated: true,
554
- apiUrl,
555
- user: user || null,
556
- token: `${token.slice(0, 8)}...`
557
- });
558
- } else {
559
- console.log(pc2.green("\n\u2714 Authenticated to ReplayStage"));
560
- console.log(` ${pc2.dim("API URL:")} ${apiUrl}`);
561
- if (user?.handle) console.log(` ${pc2.dim("Handle:")} @${user.handle}`);
562
- if (user?.name) console.log(` ${pc2.dim("Name:")} ${user.name}`);
563
- if (user?.email) console.log(` ${pc2.dim("Email:")} ${user.email}`);
564
- console.log(` ${pc2.dim("Token:")} ${token.slice(0, 8)}...${token.slice(-4)}
565
- `);
566
- }
567
- } catch (err) {
568
- if (isJson) {
569
- printErrorJson("WHOAMI_FAILED", err.message, 1);
570
- } else {
571
- console.error(pc2.red(`
572
- \u2716 Auth check failed: ${err.message}
573
- `));
574
- }
575
- process.exit(1);
576
- }
577
- }
578
- async function handleLogout(options = {}) {
579
- const isJson = Boolean(options.json);
580
- clearConfig();
581
- if (isJson) {
582
- printJson({ success: true, message: "Logged out successfully" });
583
- } else {
584
- console.log(pc2.green("\n\u2714 Stored credentials cleared successfully.\n"));
585
- }
586
- }
587
-
588
- // src/commands/publish.ts
589
- import fs5 from "fs";
590
- import path5 from "path";
591
-
592
- // ../shared/src/constants.ts
593
- var AI_TOOL_KEYS = [
594
- "claude-code",
595
- "antigravity",
596
- "cursor",
597
- "codex",
598
- "claude",
599
- "gemini",
600
- "chatgpt",
601
- "v0",
602
- "windsurf",
603
- "lovable",
604
- "bolt",
605
- "other"
606
- ];
607
- var AI_TOOLS = {
608
- "claude-code": {
609
- id: "claude-code",
610
- name: "Claude Code",
611
- fullName: "Anthropic Claude Code",
612
- slug: "claude-code",
613
- description: "Terminal-based agentic coding and game generation by Anthropic",
614
- badgeColor: "#D97706",
615
- badgeBg: "bg-amber-100 text-amber-900 border-amber-300 dark:bg-amber-950/60 dark:text-amber-200 dark:border-amber-700",
616
- icon: "terminal",
617
- website: "https://claude.ai/code"
618
- },
619
- antigravity: {
620
- id: "antigravity",
621
- name: "Antigravity",
622
- fullName: "Antigravity Agent Platform",
623
- slug: "antigravity",
624
- description: "Autonomous multi-agent game productions orchestrated by Antigravity",
625
- badgeColor: "#7C3AED",
626
- badgeBg: "bg-purple-100 text-purple-900 border-purple-300 dark:bg-purple-950/60 dark:text-purple-200 dark:border-purple-700",
627
- icon: "orbit",
628
- website: "https://github.com/google-gemini/antigravity"
629
- },
630
- cursor: {
631
- id: "cursor",
632
- name: "Cursor",
633
- fullName: "Cursor Composer & Agent",
634
- slug: "cursor",
635
- description: "Web games generated and iterated through Cursor AI Composer",
636
- badgeColor: "#0F172A",
637
- badgeBg: "bg-slate-100 text-slate-900 border-slate-300 dark:bg-slate-900 dark:text-slate-200 dark:border-slate-700",
638
- icon: "mouse-pointer-click",
639
- website: "https://cursor.com"
640
- },
641
- codex: {
642
- id: "codex",
643
- name: "Codex",
644
- fullName: "OpenAI Codex",
645
- slug: "codex",
646
- description: "AI code generation and interactive canvas mechanics synthesized by Codex",
647
- badgeColor: "#10A37F",
648
- badgeBg: "bg-emerald-100 text-emerald-900 border-emerald-300 dark:bg-emerald-950/60 dark:text-emerald-200 dark:border-emerald-700",
649
- icon: "code",
650
- website: "https://openai.com"
651
- },
652
- claude: {
653
- id: "claude",
654
- name: "Claude",
655
- fullName: "Anthropic Claude",
656
- slug: "claude",
657
- description: "Games designed and crafted with Anthropic Claude",
658
- badgeColor: "#D97706",
659
- badgeBg: "bg-amber-100 text-amber-900 border-amber-300 dark:bg-amber-950/60 dark:text-amber-200 dark:border-amber-700",
660
- icon: "sparkles",
661
- website: "https://anthropic.com/claude"
662
- },
663
- gemini: {
664
- id: "gemini",
665
- name: "Gemini",
666
- fullName: "Google Gemini",
667
- slug: "gemini",
668
- description: "Ultra-fast web games generated with Google Gemini models",
669
- badgeColor: "#2563EB",
670
- badgeBg: "bg-blue-100 text-blue-900 border-blue-300 dark:bg-blue-950/60 dark:text-blue-200 dark:border-blue-700",
671
- icon: "atom",
672
- website: "https://gemini.google.com"
673
- },
674
- chatgpt: {
675
- id: "chatgpt",
676
- name: "ChatGPT",
677
- fullName: "OpenAI ChatGPT & Canvas",
678
- slug: "chatgpt",
679
- description: "Games built in interactive canvas sessions with OpenAI ChatGPT",
680
- badgeColor: "#10A37F",
681
- badgeBg: "bg-emerald-100 text-emerald-900 border-emerald-300 dark:bg-emerald-950/60 dark:text-emerald-200 dark:border-emerald-700",
682
- icon: "bot",
683
- website: "https://chatgpt.com"
684
- },
685
- v0: {
686
- id: "v0",
687
- name: "v0",
688
- fullName: "v0 by Vercel",
689
- slug: "v0",
690
- description: "Generative interactive UI and canvas components synthesized by v0",
691
- badgeColor: "#18181B",
692
- badgeBg: "bg-zinc-100 text-zinc-900 border-zinc-300 dark:bg-zinc-800 dark:text-zinc-200 dark:border-zinc-700",
693
- icon: "layers",
694
- website: "https://v0.dev"
695
- },
696
- windsurf: {
697
- id: "windsurf",
698
- name: "Windsurf",
699
- fullName: "Codeium Windsurf",
700
- slug: "windsurf",
701
- description: "Agentic flow and web games developed with Codeium Windsurf",
702
- badgeColor: "#0284C7",
703
- badgeBg: "bg-sky-100 text-sky-900 border-sky-300 dark:bg-sky-950/60 dark:text-sky-200 dark:border-sky-700",
704
- icon: "wind",
705
- website: "https://codeium.com/windsurf"
706
- },
707
- lovable: {
708
- id: "lovable",
709
- name: "Lovable",
710
- fullName: "Lovable AI",
711
- slug: "lovable",
712
- description: "Full-stack web applications and games engineered with Lovable",
713
- badgeColor: "#EC4899",
714
- badgeBg: "bg-pink-100 text-pink-900 border-pink-300 dark:bg-pink-950/60 dark:text-pink-200 dark:border-pink-700",
715
- icon: "heart",
716
- website: "https://lovable.dev"
717
- },
718
- bolt: {
719
- id: "bolt",
720
- name: "Bolt",
721
- fullName: "Bolt.new by StackBlitz",
722
- slug: "bolt",
723
- description: "In-browser full-stack sandbox games generated with Bolt.new",
724
- badgeColor: "#EAB308",
725
- badgeBg: "bg-yellow-100 text-yellow-900 border-yellow-300 dark:bg-yellow-950/60 dark:text-yellow-200 dark:border-yellow-700",
726
- icon: "zap",
727
- website: "https://bolt.new"
728
- },
729
- other: {
730
- id: "other",
731
- name: "Other AI",
732
- fullName: "Other / Custom AI Engine",
733
- slug: "other",
734
- description: "Games created with custom agents, local LLMs, or custom fine-tunes",
735
- badgeColor: "#64748B",
736
- badgeBg: "bg-neutral-100 text-neutral-800 border-neutral-300 dark:bg-neutral-800 dark:text-neutral-300 dark:border-neutral-700",
737
- icon: "cpu",
738
- website: "https://replaystage.com"
209
+ // ../shared/src/constants.ts
210
+ var AI_TOOL_KEYS = [
211
+ "claude-code",
212
+ "antigravity",
213
+ "cursor",
214
+ "codex",
215
+ "windsurf",
216
+ "claude",
217
+ "gemini",
218
+ "v0",
219
+ "lovable",
220
+ "bolt"
221
+ ];
222
+ var AI_TOOLS = {
223
+ "claude-code": {
224
+ id: "claude-code",
225
+ name: "Claude Code",
226
+ fullName: "Anthropic Claude Code",
227
+ slug: "claude-code",
228
+ description: "Terminal-based agentic coding and game generation by Anthropic",
229
+ badgeColor: "#D97706",
230
+ badgeBg: "bg-amber-100 text-amber-900 border-amber-300 dark:bg-amber-950/60 dark:text-amber-200 dark:border-amber-700",
231
+ icon: "terminal",
232
+ website: "https://claude.ai/code"
233
+ },
234
+ antigravity: {
235
+ id: "antigravity",
236
+ name: "Antigravity",
237
+ fullName: "Antigravity Agent Platform",
238
+ slug: "antigravity",
239
+ description: "Autonomous multi-agent game productions orchestrated by Antigravity",
240
+ badgeColor: "#7C3AED",
241
+ badgeBg: "bg-purple-100 text-purple-900 border-purple-300 dark:bg-purple-950/60 dark:text-purple-200 dark:border-purple-700",
242
+ icon: "orbit",
243
+ website: "https://github.com/google-gemini/antigravity"
244
+ },
245
+ cursor: {
246
+ id: "cursor",
247
+ name: "Cursor",
248
+ fullName: "Cursor Composer & Agent",
249
+ slug: "cursor",
250
+ description: "Web games generated and iterated through Cursor AI Composer",
251
+ badgeColor: "#0F172A",
252
+ badgeBg: "bg-slate-100 text-slate-900 border-slate-300 dark:bg-slate-900 dark:text-slate-200 dark:border-slate-700",
253
+ icon: "mouse-pointer-click",
254
+ website: "https://cursor.com"
255
+ },
256
+ codex: {
257
+ id: "codex",
258
+ name: "ChatGPT / Codex",
259
+ fullName: "OpenAI ChatGPT & Codex",
260
+ slug: "codex",
261
+ description: "Games synthesized with OpenAI ChatGPT and Codex canvas sessions",
262
+ badgeColor: "#10A37F",
263
+ badgeBg: "bg-emerald-100 text-emerald-900 border-emerald-300 dark:bg-emerald-950/60 dark:text-emerald-200 dark:border-emerald-700",
264
+ icon: "bot",
265
+ website: "https://chatgpt.com"
266
+ },
267
+ windsurf: {
268
+ id: "windsurf",
269
+ name: "Windsurf",
270
+ fullName: "Codeium Windsurf",
271
+ slug: "windsurf",
272
+ description: "Agentic flow and web games developed with Codeium Windsurf",
273
+ badgeColor: "#0284C7",
274
+ badgeBg: "bg-sky-100 text-sky-900 border-sky-300 dark:bg-sky-950/60 dark:text-sky-200 dark:border-sky-700",
275
+ icon: "wind",
276
+ website: "https://codeium.com/windsurf"
277
+ },
278
+ claude: {
279
+ id: "claude",
280
+ name: "Claude",
281
+ fullName: "Anthropic Claude",
282
+ slug: "claude",
283
+ description: "Games designed and crafted with Anthropic Claude",
284
+ badgeColor: "#D97706",
285
+ badgeBg: "bg-amber-100 text-amber-900 border-amber-300 dark:bg-amber-950/60 dark:text-amber-200 dark:border-amber-700",
286
+ icon: "sparkles",
287
+ website: "https://anthropic.com/claude"
288
+ },
289
+ gemini: {
290
+ id: "gemini",
291
+ name: "Gemini",
292
+ fullName: "Google Gemini",
293
+ slug: "gemini",
294
+ description: "Ultra-fast web games generated with Google Gemini models",
295
+ badgeColor: "#2563EB",
296
+ badgeBg: "bg-blue-100 text-blue-900 border-blue-300 dark:bg-blue-950/60 dark:text-blue-200 dark:border-blue-700",
297
+ icon: "atom",
298
+ website: "https://gemini.google.com"
299
+ },
300
+ v0: {
301
+ id: "v0",
302
+ name: "v0",
303
+ fullName: "v0 by Vercel",
304
+ slug: "v0",
305
+ description: "Generative interactive UI and canvas components synthesized by v0",
306
+ badgeColor: "#18181B",
307
+ badgeBg: "bg-zinc-100 text-zinc-900 border-zinc-300 dark:bg-zinc-800 dark:text-zinc-200 dark:border-zinc-700",
308
+ icon: "layers",
309
+ website: "https://v0.dev"
310
+ },
311
+ lovable: {
312
+ id: "lovable",
313
+ name: "Lovable",
314
+ fullName: "Lovable AI",
315
+ slug: "lovable",
316
+ description: "Full-stack web applications and games engineered with Lovable",
317
+ badgeColor: "#EC4899",
318
+ badgeBg: "bg-pink-100 text-pink-900 border-pink-300 dark:bg-pink-950/60 dark:text-pink-200 dark:border-pink-700",
319
+ icon: "heart",
320
+ website: "https://lovable.dev"
321
+ },
322
+ bolt: {
323
+ id: "bolt",
324
+ name: "Bolt",
325
+ fullName: "Bolt.new by StackBlitz",
326
+ slug: "bolt",
327
+ description: "In-browser full-stack sandbox games generated with Bolt.new",
328
+ badgeColor: "#EAB308",
329
+ badgeBg: "bg-yellow-100 text-yellow-900 border-yellow-300 dark:bg-yellow-950/60 dark:text-yellow-200 dark:border-yellow-700",
330
+ icon: "zap",
331
+ website: "https://bolt.new"
739
332
  }
740
333
  };
741
334
  var GAME_CATEGORY_KEYS = [
742
335
  "arcade",
743
336
  "action",
744
337
  "puzzle",
338
+ "strategy",
339
+ "simulation",
745
340
  "racing",
746
- "3d",
747
- "retro",
748
- "chill"
341
+ "rpg",
342
+ "casual"
749
343
  ];
750
344
  var MAX_BUNDLE_SIZE_BYTES = 25 * 1024 * 1024;
751
345
  var MAX_HTML_SIZE_BYTES = 5 * 1024 * 1024;
@@ -5159,17 +4753,36 @@ var supportedPlatformsSchema = external_exports.preprocess((val) => {
5159
4753
  });
5160
4754
  }
5161
4755
  }).transform((val) => normalizeSupportedPlatforms(val).normalized);
4756
+ function normalizeToolSlug(input) {
4757
+ if (!input || typeof input !== "string") return "";
4758
+ let decoded = input;
4759
+ try {
4760
+ decoded = decodeURIComponent(input);
4761
+ } catch {
4762
+ decoded = input;
4763
+ }
4764
+ const slug = decoded.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
4765
+ if (slug === "chatgpt" || slug === "chatgpt-codex" || slug === "chatgptcodex" || slug === "openai-codex" || slug === "openai-chatgpt") {
4766
+ return "codex";
4767
+ }
4768
+ return slug;
4769
+ }
5162
4770
  var aiToolSchema = external_exports.preprocess(
5163
4771
  (val) => {
5164
4772
  if (val === null || val === void 0 || val === false || typeof val === "string" && val.trim() === "") {
5165
- return "other";
4773
+ return null;
5166
4774
  }
5167
4775
  if (typeof val === "string") {
5168
- return val.trim();
4776
+ const trimmed = val.trim();
4777
+ const lower = trimmed.toLowerCase();
4778
+ if (lower === "codex" || lower === "chatgpt" || lower === "chatgpt-codex" || lower === "chatgptcodex" || lower === "openai-codex" || lower === "openai-chatgpt" || lower === "chatgpt / codex" || lower === "chatgpt/codex" || normalizeToolSlug(trimmed) === "codex") {
4779
+ return "codex";
4780
+ }
4781
+ return trimmed;
5169
4782
  }
5170
4783
  return val;
5171
4784
  },
5172
- external_exports.string({ errorMap: () => ({ message: "Invalid AI tool selection" }) }).min(1, "AI tool cannot be empty").max(MAX_AI_TOOL_LENGTH, `AI tool must be ${MAX_AI_TOOL_LENGTH} characters or less`)
4785
+ external_exports.string({ errorMap: () => ({ message: "Invalid AI tool selection" }) }).max(MAX_AI_TOOL_LENGTH, `AI tool must be ${MAX_AI_TOOL_LENGTH} characters or less`).nullable().optional()
5173
4786
  );
5174
4787
  var aiModelSchema = external_exports.preprocess((val) => {
5175
4788
  if (val === null || typeof val === "string" && val.trim() === "") {
@@ -5182,15 +4795,15 @@ var aiModelSchema = external_exports.preprocess((val) => {
5182
4795
  }, external_exports.string().max(MAX_AI_MODEL_LENGTH, `AI model must be ${MAX_AI_MODEL_LENGTH} characters or less`).nullable().optional());
5183
4796
  var baseGameUploadObject = external_exports.object({
5184
4797
  title: external_exports.string().trim().min(2, "Title must be at least 2 characters").max(MAX_GAME_TITLE_LENGTH, `Title must be ${MAX_GAME_TITLE_LENGTH} characters or less`),
5185
- tagline: external_exports.string({ required_error: "Tagline is required" }).trim().max(
4798
+ tagline: external_exports.string().trim().max(
5186
4799
  MAX_GAME_TAGLINE_LENGTH,
5187
4800
  `Tagline must be ${MAX_GAME_TAGLINE_LENGTH} characters or less`
5188
- ),
4801
+ ).nullable().optional().transform((val) => val ?? ""),
5189
4802
  description: external_exports.string().max(
5190
4803
  MAX_GAME_DESCRIPTION_LENGTH,
5191
4804
  `Description must be ${MAX_GAME_DESCRIPTION_LENGTH} characters or less`
5192
4805
  ).default(""),
5193
- aiTool: aiToolSchema.default("other"),
4806
+ aiTool: aiToolSchema.default(null),
5194
4807
  aiModel: aiModelSchema.optional().nullable(),
5195
4808
  primaryCategory: external_exports.enum(GAME_CATEGORY_KEYS, {
5196
4809
  errorMap: () => ({ message: "Invalid game category selection" })
@@ -5206,7 +4819,6 @@ var baseGameUploadObject = external_exports.object({
5206
4819
  aspectRatio: aspectRatioSchema.default(DEFAULT_ASPECT_RATIO),
5207
4820
  supportedPlatforms: supportedPlatformsSchema.default(DEFAULT_SUPPORTED_PLATFORMS),
5208
4821
  changelog: external_exports.string().trim().max(500).optional(),
5209
- slug: slugSchema.optional(),
5210
4822
  fileHash: external_exports.string().regex(SHA256_REGEX, "Invalid SHA-256 hash format").optional(),
5211
4823
  sourceCode: external_exports.string().max(MAX_HTML_SIZE_BYTES, "Single-file HTML cannot exceed 5MB").optional().nullable(),
5212
4824
  thumbnailUrl: thumbnailUrlSchema.optional().nullable(),
@@ -5216,27 +4828,7 @@ var baseGameUploadObject = external_exports.object({
5216
4828
  mobile: external_exports.string().max(300).optional()
5217
4829
  }).optional().nullable()
5218
4830
  });
5219
- var gameUploadSchema = external_exports.preprocess((val) => {
5220
- if (val && typeof val === "object" && !Array.isArray(val)) {
5221
- const raw = { ...val };
5222
- if (raw.visibility === "draft" && (raw.tagline === void 0 || raw.tagline === null)) {
5223
- raw.tagline = "";
5224
- }
5225
- return raw;
5226
- }
5227
- return val;
5228
- }, baseGameUploadObject).superRefine((data, ctx) => {
5229
- if (data.visibility !== "draft" && (!data.tagline || data.tagline.trim().length < 3)) {
5230
- ctx.addIssue({
5231
- code: external_exports.ZodIssueCode.too_small,
5232
- minimum: 3,
5233
- type: "string",
5234
- inclusive: true,
5235
- path: ["tagline"],
5236
- message: "Tagline must be at least 3 characters"
5237
- });
5238
- }
5239
- }).transform((data) => {
4831
+ var gameUploadSchema = baseGameUploadObject.transform((data) => {
5240
4832
  if (data.submissionType === "hunter" && !data.isOss) {
5241
4833
  return {
5242
4834
  ...data,
@@ -5250,7 +4842,7 @@ var gameUpdateSchema = external_exports.object({
5250
4842
  tagline: external_exports.string().trim().max(
5251
4843
  MAX_GAME_TAGLINE_LENGTH,
5252
4844
  `Tagline must be ${MAX_GAME_TAGLINE_LENGTH} characters or less`
5253
- ).optional(),
4845
+ ).nullable().optional().transform((val) => val === null ? "" : val),
5254
4846
  description: external_exports.string().max(
5255
4847
  MAX_GAME_DESCRIPTION_LENGTH,
5256
4848
  `Description must be ${MAX_GAME_DESCRIPTION_LENGTH} characters or less`
@@ -5387,177 +4979,651 @@ function extractRawAiModelFromHtml(html) {
5387
4979
  return trimmed.length > 0 ? trimmed : null;
5388
4980
  }
5389
4981
  }
5390
- return null;
4982
+ return null;
4983
+ }
4984
+ function extractAiModelFromHtml(html) {
4985
+ const raw = extractRawAiModelFromHtml(html);
4986
+ if (!raw) return null;
4987
+ const truncated = raw.slice(0, MAX_AI_MODEL_LENGTH);
4988
+ const parsed = aiModelSchema.safeParse(truncated);
4989
+ if (!parsed.success || !parsed.data) return null;
4990
+ return parsed.data;
4991
+ }
4992
+
4993
+ // ../shared/src/sanitizer.ts
4994
+ var FORBIDDEN_SEGMENT_EXACT = /* @__PURE__ */ new Set([
4995
+ ".replaystage.json",
4996
+ ".git",
4997
+ ".github",
4998
+ "node_modules",
4999
+ ".aws",
5000
+ ".ssh",
5001
+ ".bashrc",
5002
+ ".bash_profile",
5003
+ ".bash_history",
5004
+ ".bash_logout",
5005
+ ".zshrc",
5006
+ ".zprofile",
5007
+ ".zsh_history",
5008
+ ".profile",
5009
+ ".npmrc",
5010
+ ".netrc"
5011
+ ]);
5012
+ function validateZipEntryPath(rawPath) {
5013
+ if (typeof rawPath !== "string") {
5014
+ return { valid: false, error: "Zip entry path must be a string" };
5015
+ }
5016
+ const trimmed = rawPath.trim();
5017
+ if (trimmed === "") {
5018
+ return { valid: false, error: "Zip entry path cannot be empty" };
5019
+ }
5020
+ let normalized = trimmed.replace(/\\/g, "/");
5021
+ if (normalized.includes("\0")) {
5022
+ return { valid: false, error: "Null byte detected in zip entry path" };
5023
+ }
5024
+ if (normalized.startsWith("/") || /^[a-zA-Z]:/.test(normalized)) {
5025
+ return { valid: false, error: "Absolute paths are prohibited in zip archive entries" };
5026
+ }
5027
+ normalized = normalized.replace(/^\.?\//, "");
5028
+ const parts = normalized.split("/");
5029
+ const resolvedParts = [];
5030
+ for (const part of parts) {
5031
+ const trimmedPart = part.trim();
5032
+ if (trimmedPart === "" || trimmedPart === ".") {
5033
+ continue;
5034
+ }
5035
+ if (trimmedPart === ".." || /^\.{2,}$/.test(trimmedPart)) {
5036
+ return { valid: false, error: "Directory traversal ('..') is prohibited in zip entry path" };
5037
+ }
5038
+ const cleanSegment = trimmedPart.replace(/[\s.]+$/, "");
5039
+ if (cleanSegment === "") {
5040
+ continue;
5041
+ }
5042
+ resolvedParts.push(cleanSegment);
5043
+ }
5044
+ const cleanPath = resolvedParts.join("/");
5045
+ if (cleanPath === "") {
5046
+ return { valid: false, error: "Invalid zip entry path: resolves to empty path" };
5047
+ }
5048
+ if (isProhibitedExtension(cleanPath)) {
5049
+ return { valid: false, error: `Prohibited file extension detected: ${cleanPath}` };
5050
+ }
5051
+ for (const seg of resolvedParts) {
5052
+ const lower = seg.toLowerCase();
5053
+ if (lower === ".replaystage.json" || lower.startsWith(".replaystage")) {
5054
+ return {
5055
+ valid: false,
5056
+ error: `Prohibited ReplayStage state file in archive: ${cleanPath}`
5057
+ };
5058
+ }
5059
+ if (lower === ".env" || lower.startsWith(".env.") || lower.startsWith(".env-") || lower.startsWith(".env_") || FORBIDDEN_SEGMENT_EXACT.has(lower)) {
5060
+ return { valid: false, error: `Prohibited system or environment file: ${cleanPath}` };
5061
+ }
5062
+ }
5063
+ return {
5064
+ valid: true,
5065
+ normalizedPath: cleanPath
5066
+ };
5067
+ }
5068
+ function isIgnoredZipEntry(entryPath) {
5069
+ const normalized = entryPath.replace(/\\/g, "/");
5070
+ return normalized.startsWith("__MACOSX/") || normalized.includes("/__MACOSX/") || normalized.endsWith(".DS_Store") || normalized.endsWith("Thumbs.db") || normalized.startsWith("._") || normalized.includes("/._");
5071
+ }
5072
+ var MAX_COVER_IMAGE_BYTES = 2 * 1024 * 1024;
5073
+ function validateCoverImageBytes(bytes) {
5074
+ if (!bytes || bytes.byteLength < 12) {
5075
+ return { valid: false, error: "Cover image is empty or truncated" };
5076
+ }
5077
+ if (bytes.byteLength > MAX_COVER_IMAGE_BYTES) {
5078
+ return { valid: false, error: "Cover image exceeds the 2 MB maximum limit" };
5079
+ }
5080
+ if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71 && bytes[4] === 13 && bytes[5] === 10 && bytes[6] === 26 && bytes[7] === 10) {
5081
+ return { valid: true, mimeType: "image/png", ext: "png" };
5082
+ }
5083
+ if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) {
5084
+ return { valid: true, mimeType: "image/jpeg", ext: "jpg" };
5085
+ }
5086
+ if (bytes[0] === 82 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 70 && bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80) {
5087
+ return { valid: true, mimeType: "image/webp", ext: "webp" };
5088
+ }
5089
+ if (bytes[0] === 71 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 56 && (bytes[4] === 55 || bytes[4] === 57) && bytes[5] === 97) {
5090
+ return { valid: true, mimeType: "image/gif", ext: "gif" };
5091
+ }
5092
+ return {
5093
+ valid: false,
5094
+ error: "Unsupported cover image format (must be PNG, JPEG, WebP, or GIF)"
5095
+ };
5096
+ }
5097
+ function findEntryHtmlFile(paths) {
5098
+ const cleanPaths = paths.filter((p) => !isIgnoredZipEntry(p)).map((p) => p.replace(/\\/g, "/").replace(/^\.?\//, ""));
5099
+ if (cleanPaths.includes("index.html")) {
5100
+ return { entryPath: "index.html", prefix: "" };
5101
+ }
5102
+ if (cleanPaths.includes("index.htm")) {
5103
+ return { entryPath: "index.htm", prefix: "" };
5104
+ }
5105
+ const nestedIndices = cleanPaths.filter((p) => {
5106
+ const parts = p.split("/");
5107
+ return parts.length === 2 && (parts[1] === "index.html" || parts[1] === "index.htm");
5108
+ });
5109
+ if (nestedIndices.length === 1) {
5110
+ const entryPath = nestedIndices[0];
5111
+ const prefix = `${entryPath.split("/")[0]}/`;
5112
+ return { entryPath, prefix };
5113
+ }
5114
+ if (nestedIndices.length > 1) {
5115
+ const folders = new Set(nestedIndices.map((p) => p.split("/")[0]));
5116
+ if (folders.size === 1) {
5117
+ const htmlEntry = nestedIndices.find((p) => p.endsWith("/index.html"));
5118
+ if (htmlEntry) {
5119
+ return { entryPath: htmlEntry, prefix: `${htmlEntry.split("/")[0]}/` };
5120
+ }
5121
+ }
5122
+ return { entryPath: null, prefix: "" };
5123
+ }
5124
+ const allIndices = cleanPaths.filter(
5125
+ (p) => p.endsWith("/index.html") || p === "index.html" || p.endsWith("/index.htm") || p === "index.htm"
5126
+ );
5127
+ if (allIndices.length === 1) {
5128
+ const entryPath = allIndices[0];
5129
+ const lastSlash = entryPath.lastIndexOf("/");
5130
+ const prefix = lastSlash >= 0 ? entryPath.slice(0, lastSlash + 1) : "";
5131
+ return { entryPath, prefix };
5132
+ }
5133
+ if (allIndices.length > 1) {
5134
+ const dirs = new Set(
5135
+ allIndices.map((p) => {
5136
+ const lastSlash = p.lastIndexOf("/");
5137
+ return lastSlash >= 0 ? p.slice(0, lastSlash + 1) : "";
5138
+ })
5139
+ );
5140
+ if (dirs.size === 1) {
5141
+ const htmlEntry = allIndices.find((p) => p.endsWith("/index.html") || p === "index.html");
5142
+ if (htmlEntry) {
5143
+ const lastSlash = htmlEntry.lastIndexOf("/");
5144
+ const prefix = lastSlash >= 0 ? htmlEntry.slice(0, lastSlash + 1) : "";
5145
+ return { entryPath: htmlEntry, prefix };
5146
+ }
5147
+ }
5148
+ }
5149
+ return { entryPath: null, prefix: "" };
5150
+ }
5151
+
5152
+ // ../shared/src/tags.ts
5153
+ function normalizeTags(input) {
5154
+ if (input === null || input === void 0) return [];
5155
+ let rawList = [];
5156
+ if (Array.isArray(input)) {
5157
+ rawList = input;
5158
+ } else if (typeof input === "string") {
5159
+ const trimmed = input.trim();
5160
+ if (trimmed === "" || trimmed === "null" || trimmed === "undefined") {
5161
+ return [];
5162
+ }
5163
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
5164
+ try {
5165
+ const parsed = JSON.parse(trimmed);
5166
+ if (Array.isArray(parsed)) {
5167
+ rawList = parsed;
5168
+ } else {
5169
+ rawList = trimmed.slice(1, -1).split(",");
5170
+ }
5171
+ } catch {
5172
+ rawList = trimmed.slice(1, -1).split(",");
5173
+ }
5174
+ } else {
5175
+ rawList = trimmed.split(",");
5176
+ }
5177
+ } else {
5178
+ return [];
5179
+ }
5180
+ const result = [];
5181
+ const seen = /* @__PURE__ */ new Set();
5182
+ for (const item of rawList) {
5183
+ if (typeof item !== "string") continue;
5184
+ const formatted = item.trim().toLowerCase().replace(/[\s_]+/g, "-").replace(/^-+|-+$/g, "");
5185
+ if (!formatted) continue;
5186
+ const parseResult = tagSchema.safeParse(formatted);
5187
+ if (!parseResult.success) continue;
5188
+ const validTag = parseResult.data;
5189
+ if (!seen.has(validTag)) {
5190
+ seen.add(validTag);
5191
+ result.push(validTag);
5192
+ if (result.length >= MAX_TAGS_COUNT) {
5193
+ break;
5194
+ }
5195
+ }
5196
+ }
5197
+ return result;
5198
+ }
5199
+ function extractRawTagsFromHtml(html) {
5200
+ if (!html || typeof html !== "string") return null;
5201
+ const cleanHtml = html.replace(/<!--[\s\S]*?-->/g, "");
5202
+ const metaTagRegex = /<meta\b([^>]*)>/gi;
5203
+ for (const match of cleanHtml.matchAll(metaTagRegex)) {
5204
+ const attrs = match[1];
5205
+ const isTagsMeta = /(?:^|\s)name\s*=\s*(["']?)replaystage:tags?\1(?:\s|$|\/)/i.test(attrs);
5206
+ if (!isTagsMeta) continue;
5207
+ const contentMatch = /(?:^|\s)content\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(attrs);
5208
+ if (contentMatch) {
5209
+ const content = contentMatch[1] ?? contentMatch[2] ?? contentMatch[3] ?? "";
5210
+ const trimmed = content.trim();
5211
+ return trimmed.length > 0 ? trimmed : null;
5212
+ }
5213
+ }
5214
+ return null;
5215
+ }
5216
+ function extractTagsFromHtml(html) {
5217
+ const raw = extractRawTagsFromHtml(html);
5218
+ if (!raw) return [];
5219
+ return normalizeTags(raw);
5220
+ }
5221
+
5222
+ // src/project.ts
5223
+ function resolveProjectDirectory(targetPath) {
5224
+ try {
5225
+ const resolved = path.resolve(targetPath);
5226
+ if (resolved.toLowerCase().endsWith(".zip")) {
5227
+ return null;
5228
+ }
5229
+ if (resolved.includes("seed-games")) {
5230
+ return null;
5231
+ }
5232
+ if (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {
5233
+ if (resolved === path.resolve(os.tmpdir())) {
5234
+ return null;
5235
+ }
5236
+ return resolved;
5237
+ }
5238
+ if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) {
5239
+ const parentDir = path.dirname(resolved);
5240
+ if (parentDir === path.resolve(os.tmpdir())) {
5241
+ return null;
5242
+ }
5243
+ return parentDir;
5244
+ }
5245
+ return resolved;
5246
+ } catch {
5247
+ return path.resolve(targetPath);
5248
+ }
5391
5249
  }
5392
- function extractAiModelFromHtml(html) {
5393
- const raw = extractRawAiModelFromHtml(html);
5394
- if (!raw) return null;
5395
- const truncated = raw.slice(0, MAX_AI_MODEL_LENGTH);
5396
- const parsed = aiModelSchema.safeParse(truncated);
5397
- if (!parsed.success || !parsed.data) return null;
5398
- return parsed.data;
5250
+ function getProjectConfigPath(targetDir) {
5251
+ const dir = resolveProjectDirectory(targetDir);
5252
+ return dir ? path.join(dir, ".replaystage.json") : null;
5399
5253
  }
5400
-
5401
- // ../shared/src/sanitizer.ts
5402
- var FORBIDDEN_SEGMENT_EXACT = /* @__PURE__ */ new Set([
5403
- ".replaystage.json",
5404
- ".git",
5405
- ".github",
5406
- "node_modules",
5407
- ".aws",
5408
- ".ssh",
5409
- ".bashrc",
5410
- ".bash_profile",
5411
- ".bash_history",
5412
- ".bash_logout",
5413
- ".zshrc",
5414
- ".zprofile",
5415
- ".zsh_history",
5416
- ".profile",
5417
- ".npmrc",
5418
- ".netrc"
5419
- ]);
5420
- function validateZipEntryPath(rawPath) {
5421
- if (typeof rawPath !== "string") {
5422
- return { valid: false, error: "Zip entry path must be a string" };
5423
- }
5424
- const trimmed = rawPath.trim();
5425
- if (trimmed === "") {
5426
- return { valid: false, error: "Zip entry path cannot be empty" };
5427
- }
5428
- let normalized = trimmed.replace(/\\/g, "/");
5429
- if (normalized.includes("\0")) {
5430
- return { valid: false, error: "Null byte detected in zip entry path" };
5431
- }
5432
- if (normalized.startsWith("/") || /^[a-zA-Z]:/.test(normalized)) {
5433
- return { valid: false, error: "Absolute paths are prohibited in zip archive entries" };
5254
+ function readProjectConfig(targetDir) {
5255
+ const configPath = getProjectConfigPath(targetDir);
5256
+ if (!configPath || !fs.existsSync(configPath)) {
5257
+ return null;
5434
5258
  }
5435
- normalized = normalized.replace(/^\.?\//, "");
5436
- const parts = normalized.split("/");
5437
- const resolvedParts = [];
5438
- for (const part of parts) {
5439
- const trimmedPart = part.trim();
5440
- if (trimmedPart === "" || trimmedPart === ".") {
5441
- continue;
5259
+ try {
5260
+ const raw = fs.readFileSync(configPath, "utf-8");
5261
+ const parsed = JSON.parse(raw);
5262
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
5263
+ return null;
5442
5264
  }
5443
- if (trimmedPart === ".." || /^\.{2,}$/.test(trimmedPart)) {
5444
- return { valid: false, error: "Directory traversal ('..') is prohibited in zip entry path" };
5265
+ if ("slug" in parsed) {
5266
+ if (typeof parsed.slug !== "string" || !parsed.slug.trim()) {
5267
+ return null;
5268
+ }
5445
5269
  }
5446
- const cleanSegment = trimmedPart.replace(/[\s.]+$/, "");
5447
- if (cleanSegment === "") {
5448
- continue;
5270
+ const hasValidKey = typeof parsed.slug === "string" && parsed.slug.trim().length > 0 || typeof parsed.tagline === "string" || typeof parsed.supportedPlatforms === "string" || typeof parsed.platforms === "string" || typeof parsed.aspectRatio === "string" || typeof parsed.aiModel === "string" || typeof parsed.aiTool === "string" || Array.isArray(parsed.tags) || typeof parsed.tags === "string";
5271
+ if (!hasValidKey) {
5272
+ return null;
5449
5273
  }
5450
- resolvedParts.push(cleanSegment);
5274
+ if (parsed.tags !== void 0) {
5275
+ parsed.tags = normalizeTags(parsed.tags);
5276
+ }
5277
+ return parsed;
5278
+ } catch {
5279
+ return null;
5451
5280
  }
5452
- const cleanPath = resolvedParts.join("/");
5453
- if (cleanPath === "") {
5454
- return { valid: false, error: "Invalid zip entry path: resolves to empty path" };
5281
+ }
5282
+ function writeProjectConfig(targetDir, config) {
5283
+ const configPath = getProjectConfigPath(targetDir);
5284
+ if (!configPath) {
5285
+ return;
5455
5286
  }
5456
- if (isProhibitedExtension(cleanPath)) {
5457
- return { valid: false, error: `Prohibited file extension detected: ${cleanPath}` };
5287
+ const dir = path.dirname(configPath);
5288
+ if (!fs.existsSync(dir)) {
5289
+ fs.mkdirSync(dir, { recursive: true });
5458
5290
  }
5459
- for (const seg of resolvedParts) {
5460
- const lower = seg.toLowerCase();
5461
- if (lower === ".replaystage.json" || lower.startsWith(".replaystage")) {
5462
- return {
5463
- valid: false,
5464
- error: `Prohibited ReplayStage state file in archive: ${cleanPath}`
5465
- };
5291
+ const toWrite = { ...config };
5292
+ if (toWrite.tags !== void 0) {
5293
+ toWrite.tags = normalizeTags(toWrite.tags);
5294
+ }
5295
+ fs.writeFileSync(configPath, `${JSON.stringify(toWrite, null, 2)}
5296
+ `, "utf-8");
5297
+ }
5298
+ function incrementVersion(currentVersion) {
5299
+ if (!currentVersion || typeof currentVersion !== "string") return "0.2.0";
5300
+ const sanitized = currentVersion.trim().replace(/^v/i, "");
5301
+ const parts = sanitized.split(".").map((n) => Number.parseInt(n, 10));
5302
+ if (parts.length === 3 && !parts.some(Number.isNaN)) {
5303
+ return `${parts[0]}.${parts[1] + 1}.0`;
5304
+ }
5305
+ if (parts.length >= 2 && Number.isFinite(parts[0]) && Number.isFinite(parts[1])) {
5306
+ return `${parts[0]}.${parts[1] + 1}.0`;
5307
+ }
5308
+ return "0.2.0";
5309
+ }
5310
+ function promoteDraftVersion(currentVersion) {
5311
+ if (!currentVersion || typeof currentVersion !== "string") return "1.0.0";
5312
+ const sanitized = currentVersion.trim().replace(/^v/i, "");
5313
+ if (sanitized.startsWith("0.")) {
5314
+ return "1.0.0";
5315
+ }
5316
+ return incrementVersion(currentVersion);
5317
+ }
5318
+
5319
+ // src/config.ts
5320
+ function getConfigDir() {
5321
+ return process.env.REPLAYSTAGE_CONFIG_DIR || path2.join(os2.homedir(), ".replaystage");
5322
+ }
5323
+ function getConfigPath() {
5324
+ return path2.join(getConfigDir(), "config.json");
5325
+ }
5326
+ function readConfig() {
5327
+ const dir = getConfigDir();
5328
+ for (const filename of ["config.json", "credentials.json"]) {
5329
+ const file = path2.join(dir, filename);
5330
+ if (fs2.existsSync(file)) {
5331
+ try {
5332
+ const raw = fs2.readFileSync(file, "utf-8");
5333
+ return JSON.parse(raw);
5334
+ } catch {
5335
+ }
5466
5336
  }
5467
- if (lower === ".env" || lower.startsWith(".env.") || lower.startsWith(".env-") || lower.startsWith(".env_") || FORBIDDEN_SEGMENT_EXACT.has(lower)) {
5468
- return { valid: false, error: `Prohibited system or environment file: ${cleanPath}` };
5337
+ }
5338
+ return {};
5339
+ }
5340
+ function writeConfig(config) {
5341
+ const dir = getConfigDir();
5342
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
5343
+ const target = getConfigPath();
5344
+ fs2.writeFileSync(target, JSON.stringify(config, null, 2), {
5345
+ encoding: "utf-8",
5346
+ mode: 384
5347
+ });
5348
+ try {
5349
+ fs2.chmodSync(target, 384);
5350
+ } catch {
5351
+ }
5352
+ }
5353
+ function clearConfig() {
5354
+ const dir = getConfigDir();
5355
+ for (const filename of ["config.json", "credentials.json"]) {
5356
+ const file = path2.join(dir, filename);
5357
+ if (fs2.existsSync(file)) {
5358
+ try {
5359
+ fs2.unlinkSync(file);
5360
+ } catch {
5361
+ }
5469
5362
  }
5470
5363
  }
5471
- return {
5472
- valid: true,
5473
- normalizedPath: cleanPath
5474
- };
5475
5364
  }
5476
- function isIgnoredZipEntry(entryPath) {
5477
- const normalized = entryPath.replace(/\\/g, "/");
5478
- return normalized.startsWith("__MACOSX/") || normalized.includes("/__MACOSX/") || normalized.endsWith(".DS_Store") || normalized.endsWith("Thumbs.db") || normalized.startsWith("._") || normalized.includes("/._");
5365
+ function getToken() {
5366
+ return resolveToken();
5479
5367
  }
5480
- var MAX_COVER_IMAGE_BYTES = 2 * 1024 * 1024;
5481
- function validateCoverImageBytes(bytes) {
5482
- if (!bytes || bytes.byteLength < 12) {
5483
- return { valid: false, error: "Cover image is empty or truncated" };
5368
+ function setToken(token, user, apiUrl) {
5369
+ const current = readConfig();
5370
+ writeConfig({
5371
+ ...current,
5372
+ ...apiUrl ? { apiUrl: apiUrl.replace(/\/+$/, "") } : {},
5373
+ token,
5374
+ user: user || current.user
5375
+ });
5376
+ }
5377
+ function clearToken() {
5378
+ const current = readConfig();
5379
+ current.token = void 0;
5380
+ current.user = void 0;
5381
+ writeConfig(current);
5382
+ }
5383
+ function resolveToken(cliToken) {
5384
+ if (cliToken?.trim()) return cliToken.trim();
5385
+ if (process.env.REPLAYSTAGE_TOKEN?.trim()) {
5386
+ return process.env.REPLAYSTAGE_TOKEN.trim();
5387
+ }
5388
+ if (process.env.REPLAYSTAGE_API_TOKEN?.trim()) {
5389
+ return process.env.REPLAYSTAGE_API_TOKEN.trim();
5390
+ }
5391
+ const config = readConfig();
5392
+ return config.token || null;
5393
+ }
5394
+ function resolveApiUrl(cliApiUrl) {
5395
+ if (cliApiUrl?.trim()) return cliApiUrl.trim().replace(/\/+$/, "");
5396
+ if (process.env.REPLAYSTAGE_API_URL?.trim()) {
5397
+ return process.env.REPLAYSTAGE_API_URL.trim().replace(/\/+$/, "");
5398
+ }
5399
+ const config = readConfig();
5400
+ return (config.apiUrl || "https://replaystage.com").replace(/\/+$/, "");
5401
+ }
5402
+
5403
+ // src/ui.ts
5404
+ import pc from "picocolors";
5405
+ function printJson(data) {
5406
+ process.stdout.write(`${JSON.stringify(data, null, 2)}
5407
+ `);
5408
+ }
5409
+ function printErrorJson(error, message, code = 1, extra) {
5410
+ process.stdout.write(
5411
+ `${JSON.stringify({ success: false, code, error, message, ...extra }, null, 2)}
5412
+ `
5413
+ );
5414
+ }
5415
+ function logInfo(message, isJsonMode = false) {
5416
+ if (isJsonMode) return;
5417
+ process.stderr.write(`${pc.cyan("\u2139 ") + message}
5418
+ `);
5419
+ }
5420
+ function logSuccess(message, isJsonMode = false) {
5421
+ if (isJsonMode) return;
5422
+ process.stderr.write(`${pc.green("\u2714 ") + message}
5423
+ `);
5424
+ }
5425
+ function logWarn(message, isJsonMode = false) {
5426
+ if (isJsonMode) return;
5427
+ process.stderr.write(`${pc.yellow("\u26A0 ") + message}
5428
+ `);
5429
+ }
5430
+ function logError(message, isJsonMode = false) {
5431
+ if (isJsonMode) return;
5432
+ process.stderr.write(`${pc.red("\u2716 ") + message}
5433
+ `);
5434
+ }
5435
+ function printPublishSuccess(res) {
5436
+ const border = "\u2550".repeat(64);
5437
+ console.log(`
5438
+ ${pc.yellow(`\u2554${border}\u2557`)}`);
5439
+ console.log(
5440
+ `${pc.yellow("\u2551")} \u{1F579}\uFE0F ${pc.bold(pc.white("REPLAYSTAGE PUBLISH SUCCESSFUL"))}${" ".repeat(30)}${pc.yellow("\u2551")}`
5441
+ );
5442
+ console.log(`${pc.yellow(`\u2560${border}\u2563`)}`);
5443
+ console.log(
5444
+ `${pc.yellow("\u2551")} ${pc.dim("Game:")} ${res.title.padEnd(48)}${pc.yellow("\u2551")}`
5445
+ );
5446
+ console.log(
5447
+ `${pc.yellow("\u2551")} ${pc.dim("Slug:")} ${res.slug.padEnd(48)}${pc.yellow("\u2551")}`
5448
+ );
5449
+ if (res.aiTool) {
5450
+ console.log(
5451
+ `${pc.yellow("\u2551")} ${pc.dim("AI Tool:")} ${res.aiTool.padEnd(48)}${pc.yellow("\u2551")}`
5452
+ );
5484
5453
  }
5485
- if (bytes.byteLength > MAX_COVER_IMAGE_BYTES) {
5486
- return { valid: false, error: "Cover image exceeds the 2 MB maximum limit" };
5454
+ if (res.tags && res.tags.length > 0) {
5455
+ const formattedTags = res.tags.map((t) => `#${t}`).join(" ");
5456
+ console.log(
5457
+ `${pc.yellow("\u2551")} ${pc.dim("Tags:")} ${formattedTags.padEnd(48)}${pc.yellow("\u2551")}`
5458
+ );
5487
5459
  }
5488
- if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71 && bytes[4] === 13 && bytes[5] === 10 && bytes[6] === 26 && bytes[7] === 10) {
5489
- return { valid: true, mimeType: "image/png", ext: "png" };
5460
+ if (res.aspectRatio) {
5461
+ console.log(
5462
+ `${pc.yellow("\u2551")} ${pc.dim("Ratio:")} ${res.aspectRatio.padEnd(48)}${pc.yellow("\u2551")}`
5463
+ );
5490
5464
  }
5491
- if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) {
5492
- return { valid: true, mimeType: "image/jpeg", ext: "jpg" };
5465
+ const plat = res.supportedPlatforms || res.platforms;
5466
+ if (plat) {
5467
+ console.log(`${pc.yellow("\u2551")} ${pc.dim("Platforms:")} ${plat.padEnd(48)}${pc.yellow("\u2551")}`);
5493
5468
  }
5494
- if (bytes[0] === 82 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 70 && bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80) {
5495
- return { valid: true, mimeType: "image/webp", ext: "webp" };
5469
+ console.log(
5470
+ `${pc.yellow("\u2551")} ${pc.dim("Play URL:")} ${pc.cyan(res.url).padEnd(57)}${pc.yellow("\u2551")}`
5471
+ );
5472
+ if (res.shortUrl) {
5473
+ console.log(
5474
+ `${pc.yellow("\u2551")} ${pc.dim("Short Link:")} ${pc.magenta(res.shortUrl).padEnd(57)}${pc.yellow("\u2551")}`
5475
+ );
5496
5476
  }
5497
- if (bytes[0] === 71 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 56 && (bytes[4] === 55 || bytes[4] === 57) && bytes[5] === 97) {
5498
- return { valid: true, mimeType: "image/gif", ext: "gif" };
5477
+ if (res.claim_token) {
5478
+ console.log(`${pc.yellow(`\u255F${border}\u2562`)}`);
5479
+ console.log(
5480
+ `${pc.yellow("\u2551")} \u{1F511} ${pc.bold(pc.yellow("SAFE HARBOR CLAIM TOKEN"))} (Keep private, 7-day TTL): ${pc.yellow("\u2551")}`
5481
+ );
5482
+ console.log(`${pc.yellow("\u2551")} ${pc.green(res.claim_token).padEnd(73)}${pc.yellow("\u2551")}`);
5483
+ if (res.claimUrl) {
5484
+ console.log(
5485
+ `${pc.yellow("\u2551")} ${pc.dim("Claim URL:")} ${pc.cyan(res.claimUrl).padEnd(57)}${pc.yellow("\u2551")}`
5486
+ );
5487
+ }
5499
5488
  }
5500
- return {
5501
- valid: false,
5502
- error: "Unsupported cover image format (must be PNG, JPEG, WebP, or GIF)"
5503
- };
5489
+ console.log(`${pc.yellow(`\u255A${border}\u255D`)}
5490
+ `);
5504
5491
  }
5505
- function findEntryHtmlFile(paths) {
5506
- const cleanPaths = paths.filter((p) => !isIgnoredZipEntry(p)).map((p) => p.replace(/\\/g, "/").replace(/^\.?\//, ""));
5507
- if (cleanPaths.includes("index.html")) {
5508
- return { entryPath: "index.html", prefix: "" };
5509
- }
5510
- if (cleanPaths.includes("index.htm")) {
5511
- return { entryPath: "index.htm", prefix: "" };
5512
- }
5513
- const nestedIndices = cleanPaths.filter((p) => {
5514
- const parts = p.split("/");
5515
- return parts.length === 2 && (parts[1] === "index.html" || parts[1] === "index.htm");
5516
- });
5517
- if (nestedIndices.length === 1) {
5518
- const entryPath = nestedIndices[0];
5519
- const prefix = `${entryPath.split("/")[0]}/`;
5520
- return { entryPath, prefix };
5492
+
5493
+ // src/commands/auth.ts
5494
+ async function handleLogin(options = {}) {
5495
+ const isJson = Boolean(options.json);
5496
+ let token = options.token?.trim();
5497
+ const apiUrl = resolveApiUrl(options.apiUrl);
5498
+ if (!token) {
5499
+ if (isJson || !process.stdout.isTTY) {
5500
+ if (isJson) {
5501
+ printErrorJson("TOKEN_REQUIRED", "Authentication token is required via --token", 1);
5502
+ } else {
5503
+ console.error(pc2.red("Error: --token is required in non-interactive environment."));
5504
+ console.error(`Generate your token at ${apiUrl}/settings#tokens`);
5505
+ }
5506
+ process.exit(1);
5507
+ }
5508
+ console.log(pc2.cyan("\n\u{1F579}\uFE0F ReplayStage Authentication"));
5509
+ console.log(`To obtain a CLI token, visit: ${pc2.underline(`${apiUrl}/settings#tokens`)}
5510
+ `);
5511
+ const input = await text({
5512
+ message: "Enter your ReplayStage API token:",
5513
+ placeholder: "rps_...",
5514
+ validate(val) {
5515
+ if (!val || val.trim().length === 0) return "Token cannot be empty";
5516
+ }
5517
+ });
5518
+ if (typeof input !== "string") {
5519
+ console.log(pc2.yellow("Login cancelled."));
5520
+ process.exit(1);
5521
+ }
5522
+ token = input.trim();
5521
5523
  }
5522
- if (nestedIndices.length > 1) {
5523
- const folders = new Set(nestedIndices.map((p) => p.split("/")[0]));
5524
- if (folders.size === 1) {
5525
- const htmlEntry = nestedIndices.find((p) => p.endsWith("/index.html"));
5526
- if (htmlEntry) {
5527
- return { entryPath: htmlEntry, prefix: `${htmlEntry.split("/")[0]}/` };
5524
+ try {
5525
+ let user = void 0;
5526
+ try {
5527
+ user = await fetchWhoami(apiUrl, token);
5528
+ } catch (err) {
5529
+ if (err?.status === 401 || err?.status === 403) {
5530
+ throw err;
5528
5531
  }
5532
+ user = { id: "user_cli", handle: "cli_user" };
5529
5533
  }
5530
- return { entryPath: null, prefix: "" };
5534
+ setToken(token, user, options.apiUrl ? apiUrl : void 0);
5535
+ if (isJson) {
5536
+ printJson({ success: true, apiUrl, user, token: `${token.slice(0, 8)}...` });
5537
+ } else {
5538
+ console.log(
5539
+ pc2.green(`
5540
+ \u2714 Logged in successfully as ${pc2.bold(`@${user?.handle || "user"}`)}!`)
5541
+ );
5542
+ console.log(` ${pc2.dim("API URL:")} ${apiUrl}
5543
+ `);
5544
+ }
5545
+ } catch (err) {
5546
+ if (isJson) {
5547
+ printErrorJson("AUTH_FAILED", err.message, 1);
5548
+ } else {
5549
+ console.error(pc2.red(`
5550
+ \u2716 Login failed: ${err.message}
5551
+ `));
5552
+ }
5553
+ process.exit(1);
5531
5554
  }
5532
- const allIndices = cleanPaths.filter(
5533
- (p) => p.endsWith("/index.html") || p === "index.html" || p.endsWith("/index.htm") || p === "index.htm"
5534
- );
5535
- if (allIndices.length === 1) {
5536
- const entryPath = allIndices[0];
5537
- const lastSlash = entryPath.lastIndexOf("/");
5538
- const prefix = lastSlash >= 0 ? entryPath.slice(0, lastSlash + 1) : "";
5539
- return { entryPath, prefix };
5555
+ }
5556
+ async function handleWhoami(options = {}) {
5557
+ const isJson = Boolean(options.json);
5558
+ const config = readConfig();
5559
+ const token = resolveToken();
5560
+ const apiUrl = resolveApiUrl(options.apiUrl);
5561
+ if (!token) {
5562
+ if (isJson) {
5563
+ printJson({ authenticated: false, message: "Not logged in (anonymous upload mode)" });
5564
+ } else {
5565
+ console.log(
5566
+ pc2.yellow(
5567
+ "\nNot logged in. CLI commands run in anonymous mode with Safe Harbor claim tokens."
5568
+ )
5569
+ );
5570
+ console.log(`Run ${pc2.cyan("replaystage login --token <rps_token>")} to authenticate.
5571
+ `);
5572
+ }
5573
+ return;
5540
5574
  }
5541
- if (allIndices.length > 1) {
5542
- const dirs = new Set(
5543
- allIndices.map((p) => {
5544
- const lastSlash = p.lastIndexOf("/");
5545
- return lastSlash >= 0 ? p.slice(0, lastSlash + 1) : "";
5546
- })
5547
- );
5548
- if (dirs.size === 1) {
5549
- const htmlEntry = allIndices.find((p) => p.endsWith("/index.html") || p === "index.html");
5550
- if (htmlEntry) {
5551
- const lastSlash = htmlEntry.lastIndexOf("/");
5552
- const prefix = lastSlash >= 0 ? htmlEntry.slice(0, lastSlash + 1) : "";
5553
- return { entryPath: htmlEntry, prefix };
5575
+ try {
5576
+ let user = config.user;
5577
+ try {
5578
+ user = await fetchWhoami(apiUrl, token);
5579
+ if (config.token === token) {
5580
+ writeConfig({ ...config, user });
5581
+ }
5582
+ } catch (err) {
5583
+ if (err?.status === 401 || err?.status === 403) {
5584
+ throw err;
5554
5585
  }
5555
5586
  }
5587
+ if (isJson) {
5588
+ printJson({
5589
+ authenticated: true,
5590
+ apiUrl,
5591
+ user: user || null,
5592
+ token: `${token.slice(0, 8)}...`
5593
+ });
5594
+ } else {
5595
+ console.log(pc2.green("\n\u2714 Authenticated to ReplayStage"));
5596
+ console.log(` ${pc2.dim("API URL:")} ${apiUrl}`);
5597
+ if (user?.handle) console.log(` ${pc2.dim("Handle:")} @${user.handle}`);
5598
+ if (user?.name) console.log(` ${pc2.dim("Name:")} ${user.name}`);
5599
+ if (user?.email) console.log(` ${pc2.dim("Email:")} ${user.email}`);
5600
+ console.log(` ${pc2.dim("Token:")} ${token.slice(0, 8)}...${token.slice(-4)}
5601
+ `);
5602
+ }
5603
+ } catch (err) {
5604
+ if (isJson) {
5605
+ printErrorJson("WHOAMI_FAILED", err.message, 1);
5606
+ } else {
5607
+ console.error(pc2.red(`
5608
+ \u2716 Auth check failed: ${err.message}
5609
+ `));
5610
+ }
5611
+ process.exit(1);
5612
+ }
5613
+ }
5614
+ async function handleLogout(options = {}) {
5615
+ const isJson = Boolean(options.json);
5616
+ clearConfig();
5617
+ if (isJson) {
5618
+ printJson({ success: true, message: "Logged out successfully" });
5619
+ } else {
5620
+ console.log(pc2.green("\n\u2714 Stored credentials cleared successfully.\n"));
5556
5621
  }
5557
- return { entryPath: null, prefix: "" };
5558
5622
  }
5559
5623
 
5560
5624
  // src/commands/publish.ts
5625
+ import fs5 from "fs";
5626
+ import path5 from "path";
5561
5627
  import pc3 from "picocolors";
5562
5628
 
5563
5629
  // src/packager.ts
@@ -5664,12 +5730,14 @@ function extractHtmlMetadata(html) {
5664
5730
  const rawAspect = extractRawAspectRatioFromHtml(html);
5665
5731
  const aspectNorm = rawAspect ? normalizeAspectRatio(rawAspect) : null;
5666
5732
  const model = extractAiModelFromHtml(html);
5733
+ const tags = extractTagsFromHtml(html);
5667
5734
  return {
5668
5735
  title,
5669
5736
  tagline,
5670
5737
  rawAspectRatio: rawAspect ?? void 0,
5671
5738
  aspectRatio: aspectNorm?.valid ? aspectNorm.normalized : void 0,
5672
- model: model ?? null
5739
+ model: model ?? null,
5740
+ tags: tags.length > 0 ? tags : void 0
5673
5741
  };
5674
5742
  }
5675
5743
  function computeSha256(buf) {
@@ -5720,7 +5788,8 @@ async function packageGame(targetPath) {
5720
5788
  extractedTitle: meta.title,
5721
5789
  extractedTagline: meta.tagline,
5722
5790
  extractedAspectRatio: meta.aspectRatio,
5723
- extractedModel: meta.model ?? null
5791
+ extractedModel: meta.model ?? null,
5792
+ extractedTags: meta.tags
5724
5793
  };
5725
5794
  }
5726
5795
  if (ext === ".zip") {
@@ -5761,6 +5830,7 @@ async function packageGame(targetPath) {
5761
5830
  let extractedTagline;
5762
5831
  let extractedAspectRatio;
5763
5832
  let extractedModel;
5833
+ let extractedTags;
5764
5834
  if (unzipped[entryRes.entryPath]) {
5765
5835
  const meta = extractHtmlMetadata(
5766
5836
  Buffer.from(unzipped[entryRes.entryPath]).toString("utf-8")
@@ -5769,6 +5839,7 @@ async function packageGame(targetPath) {
5769
5839
  extractedTagline = meta.tagline;
5770
5840
  extractedAspectRatio = meta.aspectRatio;
5771
5841
  extractedModel = meta.model;
5842
+ extractedTags = meta.tags;
5772
5843
  }
5773
5844
  return {
5774
5845
  format: "zip",
@@ -5783,7 +5854,8 @@ async function packageGame(targetPath) {
5783
5854
  extractedTitle,
5784
5855
  extractedTagline,
5785
5856
  extractedAspectRatio,
5786
- extractedModel: extractedModel ?? null
5857
+ extractedModel: extractedModel ?? null,
5858
+ extractedTags
5787
5859
  };
5788
5860
  }
5789
5861
  throw new Error(
@@ -5848,6 +5920,7 @@ async function packageGame(targetPath) {
5848
5920
  let extractedTagline;
5849
5921
  let extractedAspectRatio;
5850
5922
  let extractedModel;
5923
+ let extractedTags;
5851
5924
  const entryBuf = fileEntries[entryResolution.entryPath];
5852
5925
  if (entryBuf) {
5853
5926
  const meta = extractHtmlMetadata(entryBuf.toString("utf-8"));
@@ -5855,6 +5928,7 @@ async function packageGame(targetPath) {
5855
5928
  extractedTagline = meta.tagline;
5856
5929
  extractedAspectRatio = meta.aspectRatio;
5857
5930
  extractedModel = meta.model;
5931
+ extractedTags = meta.tags;
5858
5932
  }
5859
5933
  const zipBuffer = createZipFromFiles(fileEntries);
5860
5934
  const fileHash = computeSha256(zipBuffer);
@@ -5871,7 +5945,8 @@ async function packageGame(targetPath) {
5871
5945
  extractedTitle,
5872
5946
  extractedTagline,
5873
5947
  extractedAspectRatio,
5874
- extractedModel: extractedModel ?? null
5948
+ extractedModel: extractedModel ?? null,
5949
+ extractedTags
5875
5950
  };
5876
5951
  }
5877
5952
  throw new Error(`Invalid target path: '${targetPath}' is neither a file nor a directory.`);
@@ -6163,6 +6238,7 @@ async function validateGamePackage(targetPath) {
6163
6238
  supportedPlatforms: detectedPlatforms,
6164
6239
  platforms: detectedPlatforms,
6165
6240
  hasPlatformMeta,
6241
+ tags: pkg.extractedTags ?? [],
6166
6242
  errors: [],
6167
6243
  warnings
6168
6244
  };
@@ -6236,15 +6312,6 @@ async function handlePublish(targetPath = ".", options = {}) {
6236
6312
  }
6237
6313
  if (title.length < 2) title = "Web Game";
6238
6314
  if (title.length > 60) title = title.slice(0, 60);
6239
- let tagline = options.tagline?.trim();
6240
- if (!tagline && bundle.extractedTagline) {
6241
- tagline = bundle.extractedTagline;
6242
- }
6243
- if (!tagline) {
6244
- tagline = "Playable web game deployed to ReplayStage";
6245
- }
6246
- if (tagline.length < 3) tagline = "An arcade game on ReplayStage";
6247
- if (tagline.length > 120) tagline = tagline.slice(0, 120);
6248
6315
  let category = options.category?.toLowerCase().trim();
6249
6316
  if (category && !GAME_CATEGORY_KEYS.includes(category)) {
6250
6317
  category = void 0;
@@ -6252,7 +6319,16 @@ async function handlePublish(targetPath = ".", options = {}) {
6252
6319
  const token = options.anonymous ? null : resolveToken(options.token);
6253
6320
  const apiUrl = resolveApiUrl(options.apiUrl);
6254
6321
  const existingConfig = !options.fresh ? readProjectConfig(resolvedPath) : null;
6255
- let aiTool = "other";
6322
+ let tagline = "";
6323
+ if (options.tagline !== void 0) {
6324
+ tagline = options.tagline.trim();
6325
+ } else if (bundle.extractedTagline?.trim()) {
6326
+ tagline = bundle.extractedTagline.trim();
6327
+ } else if (existingConfig?.tagline?.trim()) {
6328
+ tagline = existingConfig.tagline.trim();
6329
+ }
6330
+ if (tagline.length > 120) tagline = tagline.slice(0, 120);
6331
+ let aiTool = "";
6256
6332
  if (options.tool !== void 0) {
6257
6333
  const parsedTool = aiToolSchema.safeParse(options.tool);
6258
6334
  if (!parsedTool.success) {
@@ -6267,11 +6343,15 @@ async function handlePublish(targetPath = ".", options = {}) {
6267
6343
  process.exit(1);
6268
6344
  }
6269
6345
  const rawTool = parsedTool.data;
6270
- const matchedPreset = AI_TOOL_KEYS.find(
6271
- (key) => key.toLowerCase() === rawTool.toLowerCase() || AI_TOOLS[key] && AI_TOOLS[key].name.toLowerCase() === rawTool.toLowerCase()
6272
- );
6273
- aiTool = matchedPreset ? matchedPreset : rawTool;
6274
- } else if (existingConfig?.aiTool) {
6346
+ if (rawTool) {
6347
+ const matchedPreset = AI_TOOL_KEYS.find(
6348
+ (key) => key.toLowerCase() === rawTool.toLowerCase() || AI_TOOLS[key] && AI_TOOLS[key].name.toLowerCase() === rawTool.toLowerCase()
6349
+ );
6350
+ aiTool = matchedPreset ? matchedPreset : rawTool;
6351
+ } else {
6352
+ aiTool = "";
6353
+ }
6354
+ } else if (existingConfig?.aiTool && existingConfig.aiTool !== "other") {
6275
6355
  aiTool = existingConfig.aiTool;
6276
6356
  }
6277
6357
  let resolvedModel = null;
@@ -6401,6 +6481,47 @@ async function handlePublish(targetPath = ".", options = {}) {
6401
6481
  } else if (validation.supportedPlatforms) {
6402
6482
  resolvedPlatforms = validation.supportedPlatforms;
6403
6483
  }
6484
+ let resolvedTags = [];
6485
+ if (options.tags !== void 0) {
6486
+ const rawTags = options.tags.split(",").map((t) => t.trim()).filter(Boolean);
6487
+ if (rawTags.length > 0) {
6488
+ if (rawTags.length > MAX_TAGS_COUNT) {
6489
+ const errorMsg = `Too many tags: maximum ${MAX_TAGS_COUNT} tags allowed, but received ${rawTags.length}`;
6490
+ if (isJson) {
6491
+ printErrorJson("INVALID_OPTIONS", errorMsg, 1);
6492
+ } else {
6493
+ console.error(pc3.red(`
6494
+ \u2716 Invalid option: ${errorMsg}
6495
+ `));
6496
+ }
6497
+ process.exit(1);
6498
+ }
6499
+ for (const rawTag of rawTags) {
6500
+ const formatted = rawTag.toLowerCase().replace(/[\s_]+/g, "-").replace(/^-+|-+$/g, "");
6501
+ const parsedTag = tagSchema.safeParse(formatted);
6502
+ if (!parsedTag.success) {
6503
+ const errorMsg = `Invalid tag '${rawTag}': ${parsedTag.error.errors[0]?.message || "invalid tag format"}`;
6504
+ if (isJson) {
6505
+ printErrorJson("INVALID_OPTIONS", errorMsg, 1);
6506
+ } else {
6507
+ console.error(pc3.red(`
6508
+ \u2716 Invalid option: ${errorMsg}
6509
+ `));
6510
+ }
6511
+ process.exit(1);
6512
+ }
6513
+ }
6514
+ resolvedTags = normalizeTags(rawTags);
6515
+ } else {
6516
+ resolvedTags = [];
6517
+ }
6518
+ } else if (bundle.extractedTags && bundle.extractedTags.length > 0) {
6519
+ resolvedTags = bundle.extractedTags;
6520
+ } else if (existingConfig?.tags && Array.isArray(existingConfig.tags) && existingConfig.tags.length > 0) {
6521
+ resolvedTags = normalizeTags(existingConfig.tags);
6522
+ } else {
6523
+ resolvedTags = [];
6524
+ }
6404
6525
  if (existingConfig?.slug) {
6405
6526
  logInfo(
6406
6527
  `Updating existing stage '${existingConfig.slug}' (current version: ${existingConfig.version || "0.1.0"})...`,
@@ -6411,7 +6532,7 @@ async function handlePublish(targetPath = ".", options = {}) {
6411
6532
  apiUrl,
6412
6533
  bundleBuffer: bundle.bundleBuffer,
6413
6534
  title,
6414
- tagline,
6535
+ tagline: options.tagline !== void 0 ? tagline : tagline || void 0,
6415
6536
  description: options.description,
6416
6537
  visibility,
6417
6538
  changelog: options.changelog,
@@ -6421,6 +6542,7 @@ async function handlePublish(targetPath = ".", options = {}) {
6421
6542
  token,
6422
6543
  aiModel: resolvedModel,
6423
6544
  aiTool,
6545
+ tags: resolvedTags,
6424
6546
  coverBuffer,
6425
6547
  coverFileName,
6426
6548
  errorMsgFallback: "Failed to update stage"
@@ -6433,13 +6555,15 @@ async function handlePublish(targetPath = ".", options = {}) {
6433
6555
  apiUrl,
6434
6556
  version: newVersion,
6435
6557
  title: title || existingConfig.title,
6558
+ tagline: tagline || void 0,
6436
6559
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
6437
6560
  visibility: resolvedVis,
6438
6561
  aspectRatio: resolvedAspectRatio,
6439
6562
  supportedPlatforms: resolvedPlatforms,
6440
6563
  platforms: resolvedPlatforms,
6441
6564
  aiModel: resolvedModel !== void 0 ? resolvedModel : existingConfig.aiModel ?? null,
6442
- aiTool: aiTool || existingConfig.aiTool
6565
+ aiTool: aiTool || void 0,
6566
+ tags: resolvedTags
6443
6567
  };
6444
6568
  writeProjectConfig(resolvedPath, updatedConfig);
6445
6569
  if (isJson) {
@@ -6457,6 +6581,7 @@ async function handlePublish(targetPath = ".", options = {}) {
6457
6581
  platforms: resolvedPlatforms,
6458
6582
  aiModel: updatedConfig.aiModel,
6459
6583
  aiTool: updatedConfig.aiTool,
6584
+ tags: resolvedTags,
6460
6585
  promotedToPublic: updateResult.promotedToPublic,
6461
6586
  fileHash: updateResult.fileHash || bundle.fileHash,
6462
6587
  updated: true
@@ -6477,6 +6602,9 @@ async function handlePublish(targetPath = ".", options = {}) {
6477
6602
  if (updatedConfig.supportedPlatforms) {
6478
6603
  console.log(` Platforms: ${pc3.bold(updatedConfig.supportedPlatforms)}`);
6479
6604
  }
6605
+ if (resolvedTags.length > 0) {
6606
+ console.log(` Tags: ${resolvedTags.map((t) => pc3.cyan(`#${t}`)).join(" ")}`);
6607
+ }
6480
6608
  if (options.changelog) {
6481
6609
  console.log(` Changelog: "${options.changelog}"`);
6482
6610
  }
@@ -6515,6 +6643,7 @@ async function handlePublish(targetPath = ".", options = {}) {
6515
6643
  description: options.description,
6516
6644
  aiTool,
6517
6645
  aiModel: resolvedModel,
6646
+ tags: resolvedTags,
6518
6647
  coverBuffer,
6519
6648
  coverFileName,
6520
6649
  category,
@@ -6536,13 +6665,15 @@ async function handlePublish(targetPath = ".", options = {}) {
6536
6665
  apiUrl,
6537
6666
  version: initialVersion,
6538
6667
  title,
6668
+ tagline: tagline || void 0,
6539
6669
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
6540
6670
  visibility: initialVisibility,
6541
6671
  aspectRatio: resolvedAspectRatio,
6542
6672
  supportedPlatforms: resolvedPlatforms,
6543
6673
  platforms: resolvedPlatforms,
6544
6674
  aiModel: resolvedModel,
6545
- aiTool
6675
+ aiTool: aiTool || void 0,
6676
+ tags: resolvedTags
6546
6677
  });
6547
6678
  if (isJson) {
6548
6679
  printJson({
@@ -6563,7 +6694,8 @@ async function handlePublish(targetPath = ".", options = {}) {
6563
6694
  supportedPlatforms: resolvedPlatforms,
6564
6695
  platforms: resolvedPlatforms,
6565
6696
  aiModel: resolvedModel,
6566
- aiTool
6697
+ aiTool: aiTool || void 0,
6698
+ tags: resolvedTags
6567
6699
  });
6568
6700
  } else {
6569
6701
  printPublishSuccess({
@@ -6574,6 +6706,7 @@ async function handlePublish(targetPath = ".", options = {}) {
6574
6706
  claim_token: result.claim_token,
6575
6707
  claimUrl: result.claimUrl,
6576
6708
  aiTool,
6709
+ tags: resolvedTags,
6577
6710
  fileHash: bundle.fileHash,
6578
6711
  aspectRatio: resolvedAspectRatio,
6579
6712
  supportedPlatforms: resolvedPlatforms
@@ -6654,19 +6787,22 @@ async function computeFileFingerprint(filePath) {
6654
6787
  // src/index.ts
6655
6788
  function createProgram() {
6656
6789
  const program = new Command();
6657
- program.name("replaystage").description("ReplayStage CLI: Deploy and share web games from command line and AI agents").version("0.3.0");
6658
- program.command("publish [path]").description("Package and deploy a web game to ReplayStage").option("-t, --title <title>", "Game title (2-60 characters)").option("-g, --tagline <tagline>", "Catchy one-line arcade tagline (3-120 characters)").option("-d, --description <desc>", "Gameplay instructions or description").option(
6790
+ program.name("replaystage").description("ReplayStage CLI: Deploy and share web games from command line and AI agents").version("0.4.1");
6791
+ program.command("publish [path]").description("Package and deploy a web game to ReplayStage").option("-t, --title <title>", "Game title (2-60 characters)").option("-g, --tagline <tagline>", "Optional one-line arcade tagline (max 120 characters)").option("-d, --description <desc>", "Gameplay instructions or description").option(
6659
6792
  "--tool <tool>",
6660
6793
  "AI tool used to generate the game (claude, gemini, antigravity, cursor, etc.)"
6661
6794
  ).option(
6662
6795
  "-m, --model <model>",
6663
- "AI model used to synthesize the game (e.g., claude-3-7-sonnet, gpt-4o, gemini-2.5-pro)"
6796
+ "AI model used to synthesize the game (e.g., Claude Sonnet 5.5, GPT-6 Astra, Gemini 4 Carbon)"
6664
6797
  ).option(
6665
6798
  "--cover <path>",
6666
6799
  "Path to custom cartridge cover image (PNG, JPG, WebP, GIF, max 2MB)"
6667
6800
  ).option(
6668
6801
  "--category <category>",
6669
- "Game category (arcade, action, puzzle, racing, 3d, retro, chill)"
6802
+ "Game category (arcade, action, puzzle, strategy, simulation, racing, rpg, casual)"
6803
+ ).option(
6804
+ "--tags <tags>",
6805
+ "Comma-separated feature tags (e.g., 3d, retro, physics, roguelike, cozy; max 6 tags)"
6670
6806
  ).option(
6671
6807
  "--aspect-ratio <ratio>",
6672
6808
  "Display aspect ratio (auto, 16:9, 9:16, 4:3, 3:4, 1:1, or custom W:H)"