create-rubrica 0.3.17 → 1.0.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.
Files changed (3) hide show
  1. package/README.md +61 -51
  2. package/dist/index.js +504 -243
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # create-rubrica
2
2
 
3
- CLI para criar e configurar projetos [Rubrica](https://github.com/MierzwaMatheus/rubrica) — sistema de portfólio profissional com React + Convex.
3
+ CLI para criar, configurar e atualizar projetos [Rubrica](https://github.com/MierzwaMatheus/rubrica), o template de portfólio profissional com React + Convex.
4
4
 
5
- ## Instalação
5
+ Precisa de Node 20+ e do `git` instalado.
6
6
 
7
- Não é necessário instalar globalmente. Use diretamente via `pnpm create` ou `npx`:
7
+ ## Criar um projeto
8
8
 
9
9
  ```bash
10
10
  pnpm create rubrica meu-portfolio
@@ -12,75 +12,85 @@ pnpm create rubrica meu-portfolio
12
12
  npx create-rubrica meu-portfolio
13
13
  ```
14
14
 
15
- ## Comandos
16
-
17
- ### `pnpm create rubrica <nome-do-projeto>`
18
-
19
- Cria um novo projeto Rubrica a partir do template mais recente. O assistente interativo coleta:
15
+ O assistente baixa a versão mais recente do template e pergunta:
20
16
 
21
- - **Identidade** — nome do site, URL, descrição, autor, email, Twitter/X handle, idioma
22
- - **Visual** — layout (sidebar / topbar / centered), tema (cyberpunk / minimal / editorial / forest / personalizado), fonte principal, fonte mono, border radius
23
- - **Funcionalidades** — plugins ativos (blog, portfólio, currículo, etc.)
24
- - **Setup** — inicializar git, instalar dependências
17
+ - **Layout**: Cyberpunk, Brutalism Terminal, Swiss Grid, Bento ou Magazine ([guia dos layouts](https://github.com/MierzwaMatheus/rubrica/blob/main/docs/templates/README.md))
18
+ - **Paleta**: Editorial Cream, Paper Noir, Midnight Blue ou Solar Warm ([esquemas de cores](https://github.com/MierzwaMatheus/rubrica/blob/main/docs/templates/cores.md))
19
+ - **Fontes**: principal e mono (o layout sugere uma combinação)
20
+ - **Plugins**: blog, portfólio, currículo, propostas, depoimentos, IA etc.
21
+ - **Identidade**: nome do site, URL, descrição, autor, e-mail, handle do X, idioma
22
+ - **Git e dependências**: inicializar o repositório e instalar com pnpm ou npm
25
23
 
26
- Ao final, os arquivos gerados incluem:
27
- - `rubrica.config.ts` — identidade e aparência em build-time
28
- - `rubrica.json` — estado da CLI (versionado)
29
- - `src/components/Layout.tsx` e arquivos de navegação do layout escolhido
30
- - `src/index.css` — tema CSS aplicado
31
- - `convex/pluginRegistry.ts` — plugins configurados
24
+ Arquivos que saem com as suas escolhas:
32
25
 
33
- ### `rubrica config`
26
+ | Arquivo | O que tem |
27
+ |---|---|
28
+ | `rubrica.json` | Estado do CLI: versão de origem, layout, paleta, fontes, plugins e identidade. Versione junto com o projeto: o `update` depende dele. |
29
+ | `rubrica.config.ts` | Identidade, SEO e RSS usados no build |
30
+ | `src/index.css` | As 4 cores da paleta e as fontes |
31
+ | `index.html` | Meta tags e fonte do Google Fonts |
32
+ | `src/components/`, `src/pages/` | Arquivos do layout escolhido |
33
+ | `convex/pluginRegistry.ts` | Plugins ligados por padrão |
34
34
 
35
- Reconfigura um projeto Rubrica existente. Execute dentro do diretório do projeto:
35
+ Depois de criar:
36
36
 
37
37
  ```bash
38
- rubrica config
38
+ cd meu-portfolio
39
+ npx convex dev # deixe rodando: cria o backend e o .env.local
40
+ npx create-rubrica setup # em outro terminal: variáveis, admin e dados iniciais
41
+ pnpm dev # http://localhost:3000
39
42
  ```
40
43
 
41
- Permite reconfigurar:
42
- - **Identidade** — atualiza `rubrica.config.ts` com novos dados
43
- - **Aparência** — altera tema, fontes e radius; atualiza CSS e `rubrica.json`
44
- - **Layout** — troca o shell de navegação (⚠ sobrescreve customizações manuais)
45
- - **Plugins** — ativa ou desativa plugins no `convex/pluginRegistry.ts`
46
-
47
- ### `rubrica update`
44
+ ## Comandos
48
45
 
49
- Atualiza um projeto Rubrica para a versão mais recente do template (Fase 3 — em desenvolvimento).
46
+ Rode dentro da pasta do projeto (ou de qualquer subpasta).
50
47
 
51
- ## Estrutura gerada
48
+ ### `setup`
52
49
 
53
- ```
54
- meu-portfolio/
55
- ├── rubrica.config.ts ← identidade e aparência (editável)
56
- ├── rubrica.json ← estado da CLI (versionado)
57
- ├── src/
58
- │ ├── components/
59
- │ │ ├── Layout.tsx ← shell do layout escolhido
60
- │ │ └── Sidebar.tsx ← ou Navbar.tsx / Footer.tsx
61
- │ └── index.css ← tema CSS
62
- ├── convex/
63
- │ └── pluginRegistry.ts ← plugins configurados
64
- └── index.html ← meta tags preenchidas
50
+ ```bash
51
+ npx create-rubrica setup
65
52
  ```
66
53
 
67
- ## Pós-instalação
54
+ Configura o backend Convex: gera as chaves de autenticação, define `SITE_URL` e as variáveis dos plugins que você ligou (Telegram, OpenRouter, Asaas, Vercel; todas opcionais), cria o usuário root e popula os dados iniciais. Com a chave do Asaas, também gera o token do webhook e mostra a URL e o token para cadastrar no painel do Asaas. Pode ser rodado de novo: o admin existente é mantido e o seed só cria o que falta.
68
55
 
69
- Após `pnpm create rubrica`:
56
+ ### `config`
70
57
 
71
58
  ```bash
72
- cd meu-portfolio
59
+ npx create-rubrica config
60
+ ```
61
+
62
+ Muda as escolhas feitas no `create`:
73
63
 
74
- # 1. Suba o backend Convex (deixe rodando)
75
- npx convex dev
64
+ - **Identidade**: atualiza `rubrica.config.ts`, as meta tags do `index.html` e o `rubrica.json`
65
+ - **Aparência**: paleta e fontes
66
+ - **Layout**: troca o layout (⚠ sobrescreve os arquivos do layout; personalizações neles se perdem)
67
+ - **Plugins**: quais vêm ligados por padrão
76
68
 
77
- # 2. Em outro terminal, inicie o frontend
78
- pnpm dev
69
+ ### `update`
79
70
 
80
- # 3. Acesse http://localhost:3000 e crie seu usuário root em /login
81
- # (com BOOTSTRAP_ALLOWED=true no Convex Dashboard)
71
+ ```bash
72
+ npx create-rubrica@latest update --dry-run # mostra o que mudaria
73
+ npx create-rubrica@latest update # aplica
82
74
  ```
83
75
 
76
+ Atualiza o projeto para a versão mais recente **sem desfazer as suas personalizações**. O CLI compara, arquivo por arquivo, a versão de onde o projeto saiu, a versão nova e o seu projeto:
77
+
78
+ - arquivo que você não mexeu recebe a versão nova;
79
+ - arquivo que você mexeu e o Rubrica não mudou fica como está;
80
+ - quando os dois mudaram partes diferentes, as mudanças são mescladas;
81
+ - quando os dois mudaram o mesmo trecho, o seu arquivo fica intacto e a versão nova é salva ao lado, em `<arquivo>.rubrica-new`.
82
+
83
+ `.env*`, `rubrica.json` e os dados gerados no build (`public/data/`, RSS, sitemap) nunca são tocados.
84
+
85
+ | Opção | Para que serve |
86
+ |---|---|
87
+ | `--dry-run` | Só mostra o plano |
88
+ | `--to <versão>` | Atualiza para uma versão específica |
89
+ | `--from <versão>` | Versão com que o projeto foi criado (projetos criados até a v0.3.18 gravavam sempre `0.1.0`) |
90
+ | `--yes` | Aplica sem perguntar |
91
+
92
+ Guia completo: [Atualizando o seu Rubrica](https://github.com/MierzwaMatheus/rubrica/blob/main/docs/atualizacao.md).
93
+
84
94
  ## Licença
85
95
 
86
96
  MIT
package/dist/index.js CHANGED
@@ -434,6 +434,36 @@ async function writeState(projectDir, partial, fsModule = nodeFsPromises8) {
434
434
  return merged;
435
435
  }
436
436
 
437
+ // src/transforms/identityInputs.ts
438
+ function rubricaConfigInput(identity, fontSans, fontMono) {
439
+ return {
440
+ siteName: identity.siteName,
441
+ siteUrl: identity.siteUrl,
442
+ siteDescription: identity.siteDescription,
443
+ authorName: identity.authorName,
444
+ authorEmail: identity.authorEmail,
445
+ twitterHandle: identity.twitterHandle,
446
+ lang: identity.lang,
447
+ seoHomeTitle: identity.siteName,
448
+ seoHomeDescription: identity.siteDescription,
449
+ rssTitle: identity.siteName,
450
+ rssDescription: identity.siteDescription,
451
+ ogImageUrl: `${identity.siteUrl}/og.png`,
452
+ fontSans,
453
+ fontMono
454
+ };
455
+ }
456
+ function indexHtmlInput(identity, fontSans) {
457
+ return {
458
+ fontFamily: fontSans,
459
+ themeColor: "",
460
+ siteName: identity.siteName,
461
+ siteUrl: identity.siteUrl,
462
+ twitterHandle: identity.twitterHandle,
463
+ authorName: identity.authorName
464
+ };
465
+ }
466
+
437
467
  // src/commands/create.ts
438
468
  var TEMPLATE_FONTS = {
439
469
  cyberpunk: { fontSans: "Chakra Petch", fontMono: "JetBrains Mono" },
@@ -470,14 +500,14 @@ function validateProjectName(name) {
470
500
  );
471
501
  }
472
502
  }
473
- async function removeDir(dirPath, fs) {
474
- if (await fs.exists(dirPath)) {
475
- await fs.rm(dirPath, { recursive: true, force: true });
503
+ async function removeDir(dirPath, fs3) {
504
+ if (await fs3.exists(dirPath)) {
505
+ await fs3.rm(dirPath, { recursive: true, force: true });
476
506
  }
477
507
  }
478
508
  async function runCreate(projectName, deps) {
479
509
  validateProjectName(projectName);
480
- const fs = deps.fs ?? {
510
+ const fs3 = deps.fs ?? {
481
511
  ...nodeFsPromises9,
482
512
  exists: async (p) => {
483
513
  try {
@@ -518,7 +548,7 @@ async function runCreate(projectName, deps) {
518
548
  await applyLayoutFn(
519
549
  layout,
520
550
  { projectDir, templatesDir: `${projectDir}/templates` },
521
- fs
551
+ fs3
522
552
  );
523
553
  const themeChoice = await select2({
524
554
  message: "Tema visual",
@@ -532,7 +562,7 @@ async function runCreate(projectName, deps) {
532
562
  await applyThemeFn(
533
563
  { preset: themeChoice },
534
564
  `${projectDir}/src/index.css`,
535
- fs
565
+ fs3
536
566
  );
537
567
  const recommendedFonts = TEMPLATE_FONTS[layout] ?? { fontSans: "", fontMono: "" };
538
568
  const recommendedSans = Array.isArray(recommendedFonts.fontSans) ? recommendedFonts.fontSans : [recommendedFonts.fontSans];
@@ -562,14 +592,14 @@ async function runCreate(projectName, deps) {
562
592
  await applyFontFn(
563
593
  { fontSans, fontMono },
564
594
  { css: `${projectDir}/src/index.css`, html: `${projectDir}/index.html` },
565
- fs
595
+ fs3
566
596
  );
567
597
  const selectedPlugins = await multiselect({
568
598
  message: "Plugins ativos",
569
599
  options: [
570
600
  { value: "contact-wizard", label: "Contact Wizard \u2014 formul\xE1rio de contato multi-etapas", hint: "recomendado" },
571
601
  { value: "proposals", label: "Propostas \u2014 propostas comerciais com assinatura eletr\xF4nica", hint: "recomendado" },
572
- { value: "payments", label: "Pagamentos \u2014 integra\xE7\xE3o com Stripe/Asaas" },
602
+ { value: "payments", label: "Pagamentos \u2014 checkout com PIX, boleto e cart\xE3o via Asaas" },
573
603
  { value: "blog", label: "Blog \u2014 listagem e leitura de posts", hint: "recomendado" },
574
604
  { value: "portfolio", label: "Portfolio \u2014 galeria de projetos", hint: "recomendado" },
575
605
  { value: "resume", label: "Curr\xEDculo \u2014 curr\xEDculo interativo com download de PDF", hint: "recomendado" },
@@ -590,50 +620,29 @@ async function runCreate(projectName, deps) {
590
620
  await applyPluginsFn(
591
621
  pluginsRecord,
592
622
  `${projectDir}/convex/pluginRegistry.ts`,
593
- fs
623
+ fs3
594
624
  );
595
625
  const identity = await doIdentityPrompt();
596
626
  await applyIndexHtmlFn(
597
- {
598
- fontFamily: fontSans,
599
- themeColor: "",
600
- siteName: identity.siteName,
601
- siteUrl: identity.siteUrl,
602
- twitterHandle: identity.twitterHandle,
603
- authorName: identity.authorName
604
- },
627
+ indexHtmlInput(identity, fontSans),
605
628
  `${projectDir}/index.html`,
606
- fs
629
+ fs3
607
630
  );
608
631
  await applyRubricalConfigFn(
609
- {
610
- siteName: identity.siteName,
611
- siteUrl: identity.siteUrl,
612
- siteDescription: identity.siteDescription,
613
- authorName: identity.authorName,
614
- authorEmail: identity.authorEmail,
615
- twitterHandle: identity.twitterHandle,
616
- lang: identity.lang,
617
- seoHomeTitle: identity.siteName,
618
- seoHomeDescription: identity.siteDescription,
619
- rssTitle: identity.siteName,
620
- rssDescription: identity.siteDescription,
621
- ogImageUrl: `${identity.siteUrl}/og.png`,
622
- fontSans,
623
- fontMono
624
- },
632
+ rubricaConfigInput(identity, fontSans, fontMono),
625
633
  projectDir,
626
- fs
634
+ fs3
627
635
  );
628
636
  const pkgPath = `${projectDir}/package.json`;
629
- const pkgRaw = await fs.readFile(pkgPath, "utf-8");
637
+ const pkgRaw = await fs3.readFile(pkgPath, "utf-8");
630
638
  const pkg = JSON.parse(pkgRaw);
631
639
  pkg.name = projectName;
632
- await fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2));
640
+ await fs3.writeFile(pkgPath, JSON.stringify(pkg, null, 2));
633
641
  await writeStateFn(
634
642
  projectDir,
635
643
  {
636
- version: "0.1.0",
644
+ // Versão realmente baixada: o update usa como base para preservar as personalizações.
645
+ version: version.replace(/^v/, ""),
637
646
  layout,
638
647
  theme: themeChoice,
639
648
  fontSans,
@@ -649,7 +658,7 @@ async function runCreate(projectName, deps) {
649
658
  lang: identity.lang
650
659
  }
651
660
  },
652
- fs
661
+ fs3
653
662
  );
654
663
  const doGitInit = await confirm({ message: "Inicializar reposit\xF3rio git?" });
655
664
  const packageManager = await select2({
@@ -666,8 +675,8 @@ async function runCreate(projectName, deps) {
666
675
  if (packageManager !== "none") {
667
676
  await execFn(`${packageManager} install`, projectDir);
668
677
  }
669
- await removeDir(`${projectDir}/templates`, fs);
670
- await removeDir(`${projectDir}/cli`, fs);
678
+ await removeDir(`${projectDir}/templates`, fs3);
679
+ await removeDir(`${projectDir}/cli`, fs3);
671
680
  const installStep = packageManager === "none" ? "pnpm install\n " : "";
672
681
  outro(
673
682
  `Projeto criado com sucesso!
@@ -718,24 +727,18 @@ async function detectProject(startDir, fsModule = nodeFsPromises10) {
718
727
  }
719
728
 
720
729
  // src/commands/config.ts
721
- var ALL_PLUGINS2 = [
722
- "blog",
723
- "portfolio",
724
- "resume",
725
- "about",
726
- "proposals",
727
- "payments",
728
- "ai-resumes",
729
- "i18n",
730
- "playground",
731
- "testimonials",
732
- "testimonials-intake",
733
- "contact-wizard",
734
- "audit-log"
735
- ];
730
+ import { tmpdir as tmpdir2 } from "os";
731
+ async function existsIn(fs3, p) {
732
+ try {
733
+ await fs3.access(p);
734
+ return true;
735
+ } catch {
736
+ return false;
737
+ }
738
+ }
736
739
  async function runConfig(deps = {}) {
737
740
  const cwd = deps.cwd ?? process.cwd();
738
- const fs = deps.fs ?? nodeFsPromises11;
741
+ const fs3 = deps.fs ?? nodeFsPromises11;
739
742
  const detectProjectFn = deps.detectProject ?? detectProject;
740
743
  const readStateFn = deps.readState ?? readState;
741
744
  const writeStateFn = deps.writeState ?? writeState;
@@ -746,9 +749,11 @@ async function runConfig(deps = {}) {
746
749
  const applyIndexHtmlFn = deps.applyIndexHtml ?? applyIndexHtml;
747
750
  const applyLayoutFn = deps.applyLayout ?? applyLayout;
748
751
  const applyPluginsFn = deps.applyPlugins ?? applyPlugins;
749
- const rubricaJsonPath = await detectProjectFn(cwd, fs);
752
+ const downloadReleaseFn = deps.downloadRelease ?? downloadRelease;
753
+ const getLatestVersionFn = deps.getLatestVersion ?? getLatestVersion;
754
+ const rubricaJsonPath = await detectProjectFn(cwd, fs3);
750
755
  const projectDir = path6.dirname(rubricaJsonPath);
751
- const currentState = await readStateFn(projectDir, fs);
756
+ const currentState = await readStateFn(projectDir, fs3);
752
757
  const stateUpdate = {};
753
758
  const sections = await multiselect2({
754
759
  message: "O que deseja reconfigurar?",
@@ -768,25 +773,16 @@ async function runConfig(deps = {}) {
768
773
  if (selected.includes("identity")) {
769
774
  const identityData = await doIdentityPrompt();
770
775
  await applyRubricalConfigFn(
771
- {
772
- siteName: identityData.siteName,
773
- siteUrl: identityData.siteUrl,
774
- siteDescription: identityData.siteDescription,
775
- authorName: identityData.authorName,
776
- authorEmail: identityData.authorEmail,
777
- twitterHandle: identityData.twitterHandle,
778
- lang: identityData.lang,
779
- seoHomeTitle: "",
780
- seoHomeDescription: "",
781
- rssTitle: "",
782
- rssDescription: "",
783
- ogImageUrl: "",
784
- fontSans: currentState.fontSans,
785
- fontMono: currentState.fontMono
786
- },
776
+ rubricaConfigInput(identityData, currentState.fontSans, currentState.fontMono),
787
777
  projectDir,
788
- fs
778
+ fs3
779
+ );
780
+ await applyIndexHtmlFn(
781
+ indexHtmlInput(identityData, currentState.fontSans),
782
+ path6.join(projectDir, "index.html"),
783
+ fs3
789
784
  );
785
+ stateUpdate.identity = identityData;
790
786
  }
791
787
  if (selected.includes("appearance")) {
792
788
  const theme = await select3({
@@ -829,18 +825,21 @@ async function runConfig(deps = {}) {
829
825
  await applyThemeFn(
830
826
  { preset: theme },
831
827
  cssPath,
832
- fs
828
+ fs3
833
829
  );
834
830
  await applyFontFn(
835
831
  { fontSans, fontMono },
836
832
  { css: cssPath, html: htmlPath },
837
- fs
838
- );
839
- await applyIndexHtmlFn(
840
- { fontFamily: fontSans, themeColor: "", siteName: "", siteUrl: "", twitterHandle: "", authorName: "" },
841
- htmlPath,
842
- fs
833
+ fs3
843
834
  );
835
+ const identity = stateUpdate.identity ?? currentState.identity;
836
+ if (identity) {
837
+ await applyIndexHtmlFn(
838
+ indexHtmlInput(identity, fontSans),
839
+ htmlPath,
840
+ fs3
841
+ );
842
+ }
844
843
  stateUpdate.theme = theme;
845
844
  stateUpdate.fontSans = fontSans;
846
845
  stateUpdate.fontMono = fontMono;
@@ -853,18 +852,31 @@ async function runConfig(deps = {}) {
853
852
  { value: "cyberpunk", label: "Cyberpunk", hint: "sidebar lateral com foto de perfil \u2014 dev, designer, freelancer" },
854
853
  { value: "brutalist", label: "Brutalism Terminal", hint: "identidade hacker total \u2014 monospace, sem bordas arredondadas" },
855
854
  { value: "swiss", label: "Swiss Grid", hint: "grid de 12 colunas, tipografia forte, design su\xED\xE7o rigoroso" },
856
- { value: "bento", label: "Bento", hint: "grid assim\xE9trico com floating dock \u2014 moderno, orientado a produto" }
855
+ { value: "bento", label: "Bento", hint: "grid assim\xE9trico com floating dock \u2014 moderno, orientado a produto" },
856
+ { value: "magazine", label: "Magazine", hint: "editorial cl\xE1ssico \xB7 display serifado \xB7 grid assim\xE9trico \xB7 \xE1reas de respiro generosas" }
857
857
  ]
858
858
  });
859
859
  const confirmed = await confirm2({
860
860
  message: "\u26A0 Isso sobrescreve Layout.tsx e arquivos de navega\xE7\xE3o. Customiza\xE7\xF5es manuais ser\xE3o perdidas. Continuar?"
861
861
  });
862
862
  if (!isCancel3(confirmed) && confirmed === true) {
863
- await applyLayoutFn(
864
- newLayout,
865
- { projectDir, templatesDir: path6.join(projectDir, "templates") },
866
- fs
867
- );
863
+ let templatesDir = path6.join(projectDir, "templates");
864
+ let tmpDir;
865
+ if (!await existsIn(fs3, templatesDir)) {
866
+ tmpDir = await nodeFsPromises11.mkdtemp(path6.join(tmpdir2(), "rubrica-config-"));
867
+ const version = currentState.version === "0.1.0" ? await getLatestVersionFn() : currentState.version;
868
+ await downloadReleaseFn(tmpDir, version.startsWith("v") ? version : `v${version}`);
869
+ templatesDir = path6.join(tmpDir, "templates");
870
+ }
871
+ try {
872
+ await applyLayoutFn(
873
+ newLayout,
874
+ { projectDir, templatesDir },
875
+ { ...fs3, copyFile: nodeFsPromises11.copyFile, unlink: nodeFsPromises11.unlink, exists: (p) => existsIn(fs3, p) }
876
+ );
877
+ } finally {
878
+ if (tmpDir) await nodeFsPromises11.rm(tmpDir, { recursive: true, force: true });
879
+ }
868
880
  stateUpdate.layout = newLayout;
869
881
  }
870
882
  }
@@ -873,32 +885,260 @@ async function runConfig(deps = {}) {
873
885
  const selectedPlugins = await multiselect2({
874
886
  message: "Plugins ativos",
875
887
  initialValues: activePlugins,
876
- options: ALL_PLUGINS2.map((p) => ({ value: p, label: p })),
888
+ options: ALL_PLUGINS.map((p) => ({ value: p, label: p })),
877
889
  required: false
878
890
  });
879
891
  if (!isCancel3(selectedPlugins)) {
880
892
  const pluginsMap = {};
881
- for (const p of ALL_PLUGINS2) {
893
+ for (const p of ALL_PLUGINS) {
882
894
  pluginsMap[p] = selectedPlugins.includes(p);
883
895
  }
884
896
  await applyPluginsFn(
885
897
  pluginsMap,
886
898
  path6.join(projectDir, "convex", "pluginRegistry.ts"),
887
- fs
899
+ fs3
888
900
  );
889
901
  stateUpdate.plugins = pluginsMap;
890
902
  }
891
903
  }
892
904
  if (Object.keys(stateUpdate).length > 0) {
893
- await writeStateFn(projectDir, stateUpdate, fs);
905
+ await writeStateFn(projectDir, stateUpdate, fs3);
894
906
  }
895
907
  outro2("Configura\xE7\xE3o atualizada com sucesso!");
896
908
  }
897
909
 
898
910
  // src/commands/update.ts
899
- import { intro as intro2, outro as outro3, confirm as confirm3, isCancel as isCancel4, cancel as cancel4, log as log2 } from "@clack/prompts";
911
+ import { intro as intro2, outro as outro3, confirm as confirm3, text as text2, isCancel as isCancel4, cancel as cancel4, log as log2, spinner } from "@clack/prompts";
912
+ import * as fs2 from "fs/promises";
913
+ import * as path9 from "path";
914
+ import { tmpdir as tmpdir3 } from "os";
915
+ import { execFile as execFile3 } from "child_process";
916
+ import { promisify as promisify3 } from "util";
917
+
918
+ // src/utils/pristine.ts
900
919
  import * as nodeFsPromises12 from "fs/promises";
901
920
  import * as path7 from "path";
921
+ var fsForTransforms = {
922
+ ...nodeFsPromises12,
923
+ exists: async (p) => {
924
+ try {
925
+ await nodeFsPromises12.access(p);
926
+ return true;
927
+ } catch {
928
+ return false;
929
+ }
930
+ }
931
+ };
932
+ async function buildPristine(options) {
933
+ const { dir, state } = options;
934
+ const download = options.download ?? downloadRelease;
935
+ const tag = options.version.startsWith("v") ? options.version : `v${options.version}`;
936
+ const fs3 = fsForTransforms;
937
+ await download(dir, tag);
938
+ await applyLayout(state.layout, { projectDir: dir, templatesDir: path7.join(dir, "templates") }, fs3);
939
+ const cssPath = path7.join(dir, "src", "index.css");
940
+ const htmlPath = path7.join(dir, "index.html");
941
+ await applyTheme({ preset: state.theme }, cssPath, fs3);
942
+ await applyFont({ fontSans: state.fontSans, fontMono: state.fontMono }, { css: cssPath, html: htmlPath }, fs3);
943
+ const registryPath = path7.join(dir, "convex", "pluginRegistry.ts");
944
+ const knownPlugins = await knownPluginIds(registryPath);
945
+ const plugins = Object.fromEntries(
946
+ Object.entries(state.plugins ?? {}).filter(([id]) => knownPlugins.has(id))
947
+ );
948
+ await applyPlugins(plugins, registryPath, fs3);
949
+ const identity = state.identity;
950
+ if (identity) {
951
+ await applyIndexHtml(indexHtmlInput(identity, state.fontSans), htmlPath, fs3);
952
+ await applyRubricalConfig(rubricaConfigInput(identity, state.fontSans, state.fontMono), dir, fs3);
953
+ }
954
+ if (options.packageName) {
955
+ const pkgPath = path7.join(dir, "package.json");
956
+ const pkg = JSON.parse(await nodeFsPromises12.readFile(pkgPath, "utf-8"));
957
+ pkg.name = options.packageName;
958
+ await nodeFsPromises12.writeFile(pkgPath, JSON.stringify(pkg, null, 2));
959
+ }
960
+ await nodeFsPromises12.rm(path7.join(dir, "templates"), { recursive: true, force: true });
961
+ await nodeFsPromises12.rm(path7.join(dir, "cli"), { recursive: true, force: true });
962
+ }
963
+ async function knownPluginIds(registryPath) {
964
+ try {
965
+ const content = await nodeFsPromises12.readFile(registryPath, "utf-8");
966
+ return new Set([...content.matchAll(/id: '([^']+)'/g)].map((m) => m[1]));
967
+ } catch {
968
+ return /* @__PURE__ */ new Set();
969
+ }
970
+ }
971
+
972
+ // src/utils/threeWayUpdate.ts
973
+ import * as fs from "fs/promises";
974
+ import * as path8 from "path";
975
+ import { execFile as execFile2 } from "child_process";
976
+ import { promisify as promisify2 } from "util";
977
+ var execFileAsync2 = promisify2(execFile2);
978
+ var PROTECTED = [
979
+ /^\.git\//,
980
+ /(^|\/)node_modules\//,
981
+ /^dist\//,
982
+ /^\.env(\..*)?$/,
983
+ /^rubrica\.json$/,
984
+ // Conteúdo gerado a partir do banco do usuário no build.
985
+ /^public\/data\//,
986
+ /^public\/rss\.xml$/,
987
+ /^public\/sitemap\.xml$/
988
+ ];
989
+ var LOCKFILES = /* @__PURE__ */ new Set(["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb"]);
990
+ var NEW_SUFFIX = ".rubrica-new";
991
+ function isProtected(file) {
992
+ return PROTECTED.some((re) => re.test(file));
993
+ }
994
+ async function listFiles(root) {
995
+ const out = [];
996
+ async function walk(dir) {
997
+ let entries;
998
+ try {
999
+ entries = await fs.readdir(dir, { withFileTypes: true });
1000
+ } catch {
1001
+ return;
1002
+ }
1003
+ for (const entry of entries) {
1004
+ const abs = path8.join(dir, entry.name);
1005
+ const rel = path8.relative(root, abs).split(path8.sep).join("/");
1006
+ if (entry.isDirectory()) {
1007
+ if (!isProtected(`${rel}/`)) await walk(abs);
1008
+ } else if (entry.isFile() && !isProtected(rel)) {
1009
+ out.push(rel);
1010
+ }
1011
+ }
1012
+ }
1013
+ await walk(root);
1014
+ return out;
1015
+ }
1016
+ async function readOrNull(file) {
1017
+ try {
1018
+ return await fs.readFile(file);
1019
+ } catch {
1020
+ return null;
1021
+ }
1022
+ }
1023
+ function same(a, b) {
1024
+ if (a === null || b === null) return a === b;
1025
+ return a.equals(b);
1026
+ }
1027
+ function isBinary(buf) {
1028
+ return buf.subarray(0, 8e3).includes(0);
1029
+ }
1030
+ async function mergeText(ours, base, theirs, tmpDir) {
1031
+ const o = path8.join(tmpDir, "ours");
1032
+ const b = path8.join(tmpDir, "base");
1033
+ const t = path8.join(tmpDir, "theirs");
1034
+ await fs.writeFile(o, ours);
1035
+ await fs.writeFile(b, base);
1036
+ await fs.writeFile(t, theirs);
1037
+ try {
1038
+ const { stdout } = await execFileAsync2("git", ["merge-file", "-p", o, b, t], {
1039
+ encoding: "buffer",
1040
+ maxBuffer: 64 * 1024 * 1024
1041
+ });
1042
+ return stdout;
1043
+ } catch (err) {
1044
+ const code = err.code;
1045
+ if (typeof code === "number" && code > 0) return null;
1046
+ throw err;
1047
+ }
1048
+ }
1049
+ async function planUpdate(dirs) {
1050
+ const files = /* @__PURE__ */ new Set([...await listFiles(dirs.base), ...await listFiles(dirs.next)]);
1051
+ const tmpDir = await fs.mkdtemp(path8.join(path8.dirname(dirs.base), "merge-"));
1052
+ const actions = [];
1053
+ try {
1054
+ for (const file of [...files].sort()) {
1055
+ const base = await readOrNull(path8.join(dirs.base, file));
1056
+ const next = await readOrNull(path8.join(dirs.next, file));
1057
+ const ours = await readOrNull(path8.join(dirs.project, file));
1058
+ if (same(base, next) || same(ours, next)) continue;
1059
+ if (same(ours, base)) {
1060
+ if (next === null) actions.push({ file, kind: "remove" });
1061
+ else actions.push({ file, kind: base === null ? "add" : "update", content: next });
1062
+ continue;
1063
+ }
1064
+ if (ours === null) {
1065
+ actions.push({
1066
+ file,
1067
+ kind: "conflict",
1068
+ incoming: next ?? void 0,
1069
+ reason: "voc\xEA removeu este arquivo, mas o Rubrica o alterou"
1070
+ });
1071
+ continue;
1072
+ }
1073
+ if (next === null) {
1074
+ actions.push({ file, kind: "keep", reason: "removido no Rubrica, mas voc\xEA o personalizou" });
1075
+ continue;
1076
+ }
1077
+ if (LOCKFILES.has(path8.basename(file))) {
1078
+ actions.push({ file, kind: "lockfile", reason: "rode o install para atualizar as depend\xEAncias" });
1079
+ continue;
1080
+ }
1081
+ if (base === null) {
1082
+ actions.push({ file, kind: "conflict", incoming: next, reason: "voc\xEA criou um arquivo com o mesmo nome de um arquivo novo do Rubrica" });
1083
+ continue;
1084
+ }
1085
+ if (isBinary(ours) || isBinary(base) || isBinary(next)) {
1086
+ actions.push({ file, kind: "conflict", incoming: next, reason: "arquivo bin\xE1rio alterado dos dois lados" });
1087
+ continue;
1088
+ }
1089
+ const merged = await mergeText(ours, base, next, tmpDir);
1090
+ if (merged) actions.push({ file, kind: "merge", content: merged });
1091
+ else actions.push({ file, kind: "conflict", incoming: next, reason: "voc\xEA e o Rubrica mudaram o mesmo trecho" });
1092
+ }
1093
+ } finally {
1094
+ await fs.rm(tmpDir, { recursive: true, force: true });
1095
+ }
1096
+ return actions;
1097
+ }
1098
+ async function applyPlan(projectDir, actions) {
1099
+ for (const action of actions) {
1100
+ const target = path8.join(projectDir, action.file);
1101
+ switch (action.kind) {
1102
+ case "update":
1103
+ case "add":
1104
+ case "merge":
1105
+ await fs.mkdir(path8.dirname(target), { recursive: true });
1106
+ await fs.writeFile(target, action.content);
1107
+ break;
1108
+ case "remove":
1109
+ await fs.rm(target, { force: true });
1110
+ break;
1111
+ case "conflict":
1112
+ if (action.incoming) {
1113
+ await fs.mkdir(path8.dirname(target), { recursive: true });
1114
+ await fs.writeFile(`${target}${NEW_SUFFIX}`, action.incoming);
1115
+ }
1116
+ break;
1117
+ case "keep":
1118
+ case "lockfile":
1119
+ break;
1120
+ }
1121
+ }
1122
+ }
1123
+ function formatPlan(actions) {
1124
+ const groups = [
1125
+ ["update", "Atualizados"],
1126
+ ["add", "Novos"],
1127
+ ["remove", "Removidos"],
1128
+ ["merge", "Mesclados com suas mudan\xE7as"],
1129
+ ["keep", "Mantidos como voc\xEA deixou"],
1130
+ ["lockfile", "Lockfile mantido"],
1131
+ ["conflict", `Precisam da sua revis\xE3o (vers\xE3o nova salva em <arquivo>${NEW_SUFFIX})`]
1132
+ ];
1133
+ const lines = [];
1134
+ for (const [kind, title] of groups) {
1135
+ const items = actions.filter((a) => a.kind === kind);
1136
+ if (!items.length) continue;
1137
+ lines.push(`${title} (${items.length}):`);
1138
+ for (const a of items) lines.push(` \u2022 ${a.file}${a.reason ? ` \u2014 ${a.reason}` : ""}`);
1139
+ }
1140
+ return lines.length ? lines.join("\n") : "Nenhum arquivo muda.";
1141
+ }
902
1142
 
903
1143
  // src/utils/checkRequiredEnv.ts
904
1144
  function parseEnvKeys(content) {
@@ -913,173 +1153,172 @@ function parseEnvKeys(content) {
913
1153
  }
914
1154
  return keys;
915
1155
  }
916
- async function readEnvKeys(filePath, fs) {
1156
+ async function readEnvKeys(filePath, fs3) {
917
1157
  try {
918
- const content = await fs.readFile(filePath, "utf-8");
1158
+ const content = await fs3.readFile(filePath, "utf-8");
919
1159
  return parseEnvKeys(content);
920
1160
  } catch {
921
1161
  return /* @__PURE__ */ new Set();
922
1162
  }
923
1163
  }
924
- async function checkRequiredEnv(projectDir, fs) {
1164
+ async function checkRequiredEnv(projectDir, fs3) {
925
1165
  let required = [];
926
1166
  try {
927
- const raw = await fs.readFile(`${projectDir}/required-env.json`, "utf-8");
1167
+ const raw = await fs3.readFile(`${projectDir}/required-env.json`, "utf-8");
928
1168
  required = JSON.parse(raw);
929
1169
  } catch {
930
1170
  return [];
931
1171
  }
932
1172
  if (!required.length) return [];
933
- const envKeys = await readEnvKeys(`${projectDir}/.env`, fs);
934
- const envLocalKeys = await readEnvKeys(`${projectDir}/.env.local`, fs);
1173
+ const envKeys = await readEnvKeys(`${projectDir}/.env`, fs3);
1174
+ const envLocalKeys = await readEnvKeys(`${projectDir}/.env.local`, fs3);
935
1175
  const allKeys = /* @__PURE__ */ new Set([...envKeys, ...envLocalKeys]);
936
1176
  return required.filter((v) => !allKeys.has(v.name));
937
1177
  }
938
1178
 
939
1179
  // src/commands/update.ts
1180
+ var execFileAsync3 = promisify3(execFile3);
1181
+ var LEGACY_PLACEHOLDER_VERSION = "0.1.0";
1182
+ function normalizeVersion(version) {
1183
+ return version.trim().replace(/^v/, "");
1184
+ }
940
1185
  function parseMajor(version) {
941
- const clean = version.replace(/^v/, "");
942
- const major = parseInt(clean.split(".")[0] ?? "0", 10);
1186
+ const major = parseInt(normalizeVersion(version).split(".")[0] ?? "0", 10);
943
1187
  return isNaN(major) ? 0 : major;
944
1188
  }
945
- function normalizeVersion(version) {
946
- return version.replace(/^v/, "");
1189
+ async function gitStatus(projectDir) {
1190
+ try {
1191
+ const { stdout } = await execFileAsync3("git", ["status", "--porcelain"], { cwd: projectDir });
1192
+ return stdout.trim();
1193
+ } catch {
1194
+ return null;
1195
+ }
947
1196
  }
948
1197
  async function runUpdate(deps = {}) {
949
1198
  const cwd = deps.cwd ?? process.cwd();
950
- const fs = deps.fs ?? {
951
- ...nodeFsPromises12,
952
- exists: async (p) => {
953
- try {
954
- await nodeFsPromises12.access(p);
955
- return true;
956
- } catch {
957
- return false;
958
- }
959
- }
960
- };
961
- const detectProjectFn = deps.detectProject ?? detectProject;
962
- const readStateFn = deps.readState ?? readState;
963
- const writeStateFn = deps.writeState ?? writeState;
1199
+ const opts = deps.options ?? {};
964
1200
  const getLatestVersionFn = deps.getLatestVersion ?? getLatestVersion;
965
- const downloadReleaseFn = deps.downloadRelease ?? downloadRelease;
966
- const applyLayoutFn = deps.applyLayout ?? applyLayout;
967
- const applyThemeFn = deps.applyTheme ?? applyTheme;
968
- const applyFontFn = deps.applyFont ?? applyFont;
969
- const applyPluginsFn = deps.applyPlugins ?? applyPlugins;
970
- const applyIndexHtmlFn = deps.applyIndexHtml ?? applyIndexHtml;
971
- const applyRubricalConfigFn = deps.applyRubricalConfig ?? applyRubricalConfig;
1201
+ const download = deps.downloadRelease ?? downloadRelease;
972
1202
  const checkRequiredEnvFn = deps.checkRequiredEnv ?? checkRequiredEnv;
973
- const execFn = deps.exec ?? (async (cmd, cwd2) => {
974
- const { execSync } = await import("child_process");
975
- execSync(cmd, { cwd: cwd2, stdio: "inherit" });
976
- });
1203
+ const ask = !opts.yes;
977
1204
  intro2("Rubrica Update");
978
- const rubricaJsonPath = await detectProjectFn(cwd, fs);
979
- const projectDir = path7.dirname(rubricaJsonPath);
980
- const state = await readStateFn(projectDir, fs);
981
- const localVersion = normalizeVersion(state.version);
982
- const remoteVersion = normalizeVersion(await getLatestVersionFn());
983
- if (localVersion === remoteVersion) {
984
- outro3(`J\xE1 est\xE1 na vers\xE3o mais recente (${localVersion}). Nenhuma atualiza\xE7\xE3o necess\xE1ria.`);
1205
+ try {
1206
+ await execFileAsync3("git", ["--version"]);
1207
+ } catch {
1208
+ cancel4("O update precisa do git instalado (ele \xE9 usado para mesclar suas mudan\xE7as com a vers\xE3o nova).");
985
1209
  return;
986
1210
  }
987
- const localMajor = parseMajor(localVersion);
988
- const remoteMajor = parseMajor(remoteVersion);
989
- if (remoteMajor > localMajor) {
1211
+ const projectDir = path9.dirname(await detectProject(cwd));
1212
+ const state = await readState(projectDir);
1213
+ let fromVersion = normalizeVersion(opts.from ?? state.version);
1214
+ if (!opts.from && fromVersion === LEGACY_PLACEHOLDER_VERSION) {
990
1215
  log2.warn(
991
- `Atualiza\xE7\xE3o major detectada: ${localVersion} \u2192 ${remoteVersion}
992
- Atualiza\xE7\xF5es major podem conter mudan\xE7as destrutivas no schema do Convex.
993
- Consulte o guia de migra\xE7\xE3o antes de prosseguir.`
1216
+ `O rubrica.json diz ${LEGACY_PLACEHOLDER_VERSION}, mas vers\xF5es antigas do CLI sempre gravavam esse n\xFAmero.
1217
+ Para preservar suas personaliza\xE7\xF5es, o update precisa saber com qual vers\xE3o o projeto foi criado (veja a data de cria\xE7\xE3o e compare com https://github.com/MierzwaMatheus/rubrica/releases).`
994
1218
  );
995
- const majorConfirmed = await confirm3({
996
- message: `Confirmar atualiza\xE7\xE3o major (${localVersion} \u2192 ${remoteVersion})? Pode haver mudan\xE7as destrutivas.`
997
- });
998
- if (isCancel4(majorConfirmed) || !majorConfirmed) {
999
- cancel4("Atualiza\xE7\xE3o cancelada.");
1219
+ if (!ask) {
1220
+ cancel4("Informe a vers\xE3o de origem com --from <vers\xE3o>.");
1000
1221
  return;
1001
1222
  }
1002
- }
1003
- if (remoteMajor === localMajor) {
1004
- const proceed = await confirm3({
1005
- message: `Atualizar de ${localVersion} para ${remoteVersion}?`
1223
+ const answer = await text2({
1224
+ message: "Com qual vers\xE3o o projeto foi criado?",
1225
+ placeholder: "ex.: 0.3.12",
1226
+ validate: (v) => /^v?\d+\.\d+\.\d+$/.test(v.trim()) ? void 0 : "Use o formato 0.3.12"
1006
1227
  });
1007
- if (isCancel4(proceed) || !proceed) {
1228
+ if (isCancel4(answer)) {
1008
1229
  cancel4("Atualiza\xE7\xE3o cancelada.");
1009
1230
  return;
1010
1231
  }
1232
+ fromVersion = normalizeVersion(answer);
1011
1233
  }
1012
- await downloadReleaseFn(projectDir, remoteVersion);
1013
- const templatesDir = path7.join(projectDir, "templates");
1014
- await applyLayoutFn(
1015
- state.layout,
1016
- { projectDir, templatesDir },
1017
- fs
1018
- );
1019
- const cssPath = path7.join(projectDir, "src", "index.css");
1020
- await applyThemeFn({ preset: state.theme }, cssPath, fs);
1021
- const htmlPath = path7.join(projectDir, "index.html");
1022
- await applyFontFn(
1023
- { fontSans: state.fontSans, fontMono: state.fontMono },
1024
- { css: cssPath, html: htmlPath },
1025
- fs
1026
- );
1027
- const registryPath = path7.join(projectDir, "convex", "pluginRegistry.ts");
1028
- await applyPluginsFn(
1029
- state.plugins,
1030
- registryPath,
1031
- fs
1032
- );
1033
- const identity = {
1034
- siteName: "",
1035
- siteUrl: "",
1036
- siteDescription: "",
1037
- authorName: "",
1038
- authorEmail: "",
1039
- twitterHandle: "",
1040
- lang: "pt-BR",
1041
- seoHomeTitle: "",
1042
- seoHomeDescription: "",
1043
- rssTitle: "",
1044
- rssDescription: "",
1045
- ogImageUrl: "",
1046
- fontSans: state.fontSans,
1047
- fontMono: state.fontMono
1048
- };
1049
- await applyIndexHtmlFn(
1050
- {
1051
- fontFamily: identity.fontSans,
1052
- themeColor: "",
1053
- siteName: identity.siteName,
1054
- siteUrl: identity.siteUrl,
1055
- twitterHandle: identity.twitterHandle,
1056
- authorName: identity.authorName
1057
- },
1058
- htmlPath,
1059
- fs
1060
- );
1061
- await applyRubricalConfigFn(
1062
- identity,
1063
- projectDir,
1064
- fs
1065
- );
1066
- await writeStateFn(projectDir, { version: remoteVersion }, fs);
1067
- const missingVars = await checkRequiredEnvFn(projectDir, fs);
1068
- if (missingVars.length > 0) {
1069
- const varList = missingVars.map((v) => ` \u2022 ${v.name} \u2014 ${v.description}`).join("\n");
1234
+ const toVersion = normalizeVersion(opts.to ?? await getLatestVersionFn());
1235
+ if (fromVersion === toVersion) {
1236
+ outro3(`J\xE1 est\xE1 na vers\xE3o mais recente (${toVersion}).`);
1237
+ return;
1238
+ }
1239
+ const status = await gitStatus(projectDir);
1240
+ if (!opts.dryRun) {
1241
+ if (status === null) {
1242
+ log2.warn("Este projeto n\xE3o est\xE1 num reposit\xF3rio git. Recomendado: fa\xE7a um backup antes, para poder desfazer.");
1243
+ } else if (status !== "") {
1244
+ log2.warn("H\xE1 mudan\xE7as n\xE3o commitadas. Recomendado: fa\xE7a commit antes, para poder desfazer o update com o git.");
1245
+ }
1246
+ }
1247
+ if (parseMajor(toVersion) > parseMajor(fromVersion)) {
1070
1248
  log2.warn(
1071
- `Vari\xE1veis de ambiente faltantes no Convex Dashboard:
1072
- ${varList}
1073
- Configure-as em: https://dashboard.convex.dev`
1249
+ `Atualiza\xE7\xE3o de vers\xE3o major: ${fromVersion} \u2192 ${toVersion}.
1250
+ Leia o guia de atualiza\xE7\xE3o nas notas da release antes de publicar.`
1074
1251
  );
1075
1252
  }
1076
- outro3(`Rubrica atualizado para ${remoteVersion} com sucesso!`);
1253
+ const workDir = await fs2.mkdtemp(path9.join(tmpdir3(), "rubrica-update-"));
1254
+ const baseDir = path9.join(workDir, "base");
1255
+ const nextDir = path9.join(workDir, "next");
1256
+ let packageName;
1257
+ try {
1258
+ packageName = JSON.parse(await fs2.readFile(path9.join(projectDir, "package.json"), "utf-8")).name;
1259
+ } catch {
1260
+ packageName = void 0;
1261
+ }
1262
+ const s = spinner();
1263
+ try {
1264
+ s.start(`Baixando ${fromVersion} e ${toVersion}`);
1265
+ await buildPristine({ dir: baseDir, version: fromVersion, state, packageName, download });
1266
+ await buildPristine({ dir: nextDir, version: toVersion, state, packageName, download });
1267
+ s.stop("Vers\xF5es baixadas");
1268
+ s.start("Comparando com o seu projeto");
1269
+ const actions = await planUpdate({ base: baseDir, next: nextDir, project: projectDir });
1270
+ s.stop("Compara\xE7\xE3o conclu\xEDda");
1271
+ log2.info(`${fromVersion} \u2192 ${toVersion}
1272
+
1273
+ ${formatPlan(actions)}`);
1274
+ if (opts.dryRun) {
1275
+ outro3("Simula\xE7\xE3o: nada foi gravado.");
1276
+ return;
1277
+ }
1278
+ if (ask) {
1279
+ const proceed = await confirm3({ message: `Aplicar a atualiza\xE7\xE3o para ${toVersion}?` });
1280
+ if (isCancel4(proceed) || !proceed) {
1281
+ cancel4("Atualiza\xE7\xE3o cancelada.");
1282
+ return;
1283
+ }
1284
+ }
1285
+ await applyPlan(projectDir, actions);
1286
+ await writeState(projectDir, { version: toVersion });
1287
+ const changed = actions.filter((a) => ["update", "add", "remove", "merge"].includes(a.kind)).map((a) => a.file);
1288
+ const conflicts = actions.filter((a) => a.kind === "conflict");
1289
+ const steps = [];
1290
+ if (changed.includes("package.json") || actions.some((a) => a.kind === "lockfile")) {
1291
+ steps.push("Instale as depend\xEAncias: pnpm install (ou npm install)");
1292
+ }
1293
+ if (changed.some((f) => f.startsWith("convex/"))) {
1294
+ steps.push("Publique o backend: npx convex dev --once (dev) e, depois de testar, npx convex deploy (produ\xE7\xE3o)");
1295
+ }
1296
+ if (conflicts.length) {
1297
+ steps.push(
1298
+ `Revise ${conflicts.length} arquivo(s) com conflito: compare cada um com o ${NEW_SUFFIX} ao lado, leve o que quiser da vers\xE3o nova e apague o ${NEW_SUFFIX}`
1299
+ );
1300
+ }
1301
+ steps.push("Rode o site (pnpm dev) e confira antes de publicar");
1302
+ const missingVars = await checkRequiredEnvFn(projectDir, fs2);
1303
+ if (missingVars.length > 0) {
1304
+ log2.warn(
1305
+ `Vari\xE1veis de ambiente faltando no Convex:
1306
+ ` + missingVars.map((v) => ` \u2022 ${v.name} \u2014 ${v.description}`).join("\n")
1307
+ );
1308
+ }
1309
+ outro3(`Atualizado para ${toVersion}.
1310
+
1311
+ Pr\xF3ximos passos:
1312
+ ${steps.map((st, i) => ` ${i + 1}. ${st}`).join("\n")}`);
1313
+ } finally {
1314
+ await fs2.rm(workDir, { recursive: true, force: true });
1315
+ }
1077
1316
  }
1078
1317
 
1079
1318
  // src/commands/setup.ts
1080
- import { outro as outro4, text as text2, password, spinner, isCancel as isCancel5, cancel as cancel5, log as log3 } from "@clack/prompts";
1319
+ import { outro as outro4, text as text3, password, spinner as spinner2, isCancel as isCancel5, cancel as cancel5, log as log3 } from "@clack/prompts";
1081
1320
  import * as nodeFsPromises13 from "fs/promises";
1082
- import * as path8 from "path";
1321
+ import * as path10 from "path";
1083
1322
  import * as nodeCrypto from "crypto";
1084
1323
  import { execFileSync as defaultExecFileSync } from "child_process";
1085
1324
 
@@ -1109,7 +1348,7 @@ function parseEnvFile(content) {
1109
1348
  }
1110
1349
  async function runSetup(deps = {}) {
1111
1350
  const cwd = deps.cwd ?? process.cwd();
1112
- const fs = deps.fs ?? {
1351
+ const fs3 = deps.fs ?? {
1113
1352
  access: (p) => nodeFsPromises13.access(p).then(() => void 0),
1114
1353
  readFile: (p, enc) => nodeFsPromises13.readFile(p, enc),
1115
1354
  writeFile: (p, data) => nodeFsPromises13.writeFile(p, data).then(() => void 0),
@@ -1126,10 +1365,10 @@ async function runSetup(deps = {}) {
1126
1365
  cancel5(err.message);
1127
1366
  return;
1128
1367
  }
1129
- const envPath = path8.join(cwd, ".env.local");
1368
+ const envPath = path10.join(cwd, ".env.local");
1130
1369
  let envVars = {};
1131
1370
  try {
1132
- const envContent = await fs.readFile(envPath, "utf-8");
1371
+ const envContent = await fs3.readFile(envPath, "utf-8");
1133
1372
  envVars = parseEnvFile(envContent);
1134
1373
  } catch {
1135
1374
  cancel5(
@@ -1150,7 +1389,7 @@ async function runSetup(deps = {}) {
1150
1389
  return;
1151
1390
  }
1152
1391
  const siteUrlDefault = envVars["VITE_CONVEX_SITE_URL"];
1153
- const s = spinner();
1392
+ const s = spinner2();
1154
1393
  s.start("Gerando chaves JWT (RS256)...");
1155
1394
  const { JWT_PRIVATE_KEY, JWKS } = await generateJwtKeys2();
1156
1395
  s.stop("Chaves JWT geradas.");
@@ -1160,7 +1399,7 @@ async function runSetup(deps = {}) {
1160
1399
  execFileSync("npx", ["convex", "env", "set", "--", "JWKS", JWKS], {
1161
1400
  stdio: "pipe"
1162
1401
  });
1163
- const siteUrl = await text2({
1402
+ const siteUrl = await text3({
1164
1403
  message: "URL p\xFAblica do site (SITE_URL no Convex):",
1165
1404
  initialValue: siteUrlDefault,
1166
1405
  validate: (v) => {
@@ -1175,17 +1414,17 @@ async function runSetup(deps = {}) {
1175
1414
  execFileSync("npx", ["convex", "env", "set", "--", "SITE_URL", siteUrl], {
1176
1415
  stdio: "pipe"
1177
1416
  });
1178
- const state = await readState2(cwd, fs);
1417
+ const state = await readState2(cwd, fs3);
1179
1418
  const plugins = state.plugins;
1180
1419
  if (plugins["contact-wizard"] || plugins["testimonials-intake"]) {
1181
- const telegramToken = await text2({
1420
+ const telegramToken = await text3({
1182
1421
  message: "TELEGRAM_BOT_TOKEN (Enter para pular):",
1183
1422
  initialValue: ""
1184
1423
  });
1185
1424
  if (!isCancel5(telegramToken) && telegramToken && telegramToken.trim()) {
1186
1425
  execFileSync("npx", ["convex", "env", "set", "--", "TELEGRAM_BOT_TOKEN", telegramToken], { stdio: "pipe" });
1187
1426
  }
1188
- const telegramChatId = await text2({
1427
+ const telegramChatId = await text3({
1189
1428
  message: "TELEGRAM_ADMIN_CHAT_ID (Enter para pular):",
1190
1429
  initialValue: ""
1191
1430
  });
@@ -1198,7 +1437,7 @@ async function runSetup(deps = {}) {
1198
1437
  execFileSync("npx", ["convex", "env", "set", "--", "PLAYGROUND_KEY_PEPPER", pepper], { stdio: "pipe" });
1199
1438
  }
1200
1439
  if (plugins["ai-resumes"] || plugins["i18n"] || plugins["playground"]) {
1201
- const openrouterKey = await text2({
1440
+ const openrouterKey = await text3({
1202
1441
  message: "OPENROUTER_API_KEY (Enter para pular):",
1203
1442
  initialValue: ""
1204
1443
  });
@@ -1207,22 +1446,28 @@ async function runSetup(deps = {}) {
1207
1446
  }
1208
1447
  }
1209
1448
  if (plugins["payments"]) {
1210
- const stripeSecret = await text2({
1211
- message: "STRIPE_WEBHOOK_SECRET (Enter para pular):",
1212
- initialValue: ""
1213
- });
1214
- if (!isCancel5(stripeSecret) && stripeSecret && stripeSecret.trim()) {
1215
- execFileSync("npx", ["convex", "env", "set", "--", "STRIPE_WEBHOOK_SECRET", stripeSecret], { stdio: "pipe" });
1216
- }
1217
- const asaasToken = await text2({
1218
- message: "ASAAS_WEBHOOK_TOKEN (Enter para pular):",
1449
+ const asaasKey = await text3({
1450
+ message: "ASAAS_API_KEY \u2014 chave da API do Asaas, sandbox ou produ\xE7\xE3o (Enter para pular):",
1219
1451
  initialValue: ""
1220
1452
  });
1221
- if (!isCancel5(asaasToken) && asaasToken && asaasToken.trim()) {
1222
- execFileSync("npx", ["convex", "env", "set", "--", "ASAAS_WEBHOOK_TOKEN", asaasToken], { stdio: "pipe" });
1453
+ if (!isCancel5(asaasKey) && asaasKey && asaasKey.trim()) {
1454
+ const key = asaasKey.trim();
1455
+ execFileSync("npx", ["convex", "env", "set", "--", "ASAAS_API_KEY", key], { stdio: "pipe" });
1456
+ const webhookToken = randomBytes2(32).toString("hex");
1457
+ execFileSync("npx", ["convex", "env", "set", "--", "ASAAS_WEBHOOK_TOKEN", webhookToken], { stdio: "pipe" });
1458
+ const env = key.startsWith("$aact_prod_") ? "produ\xE7\xE3o" : "sandbox (testes)";
1459
+ log3.info(
1460
+ `Asaas configurado em ${env}. Falta cadastrar o webhook no painel do Asaas
1461
+ (Integra\xE7\xF5es \u2192 Webhooks \u2192 Adicionar), com os eventos de cobran\xE7a ligados:
1462
+
1463
+ URL: ${siteUrlDefault.replace(/\/+$/, "")}/webhooks/asaas
1464
+ Token: ${webhookToken}
1465
+
1466
+ Sem o webhook, os pagamentos nunca aparecem como pagos.`
1467
+ );
1223
1468
  }
1224
1469
  }
1225
- const adminEmail = await text2({
1470
+ const adminEmail = await text3({
1226
1471
  message: "Email do usu\xE1rio root:",
1227
1472
  validate: (v) => {
1228
1473
  if (!v.includes("@") || !v.includes("."))
@@ -1316,26 +1561,26 @@ async function runSetup(deps = {}) {
1316
1561
  }
1317
1562
  }
1318
1563
  }
1319
- const vercelHookUrl = await text2({
1564
+ const vercelHookUrl = await text3({
1320
1565
  message: "VERCEL_DEPLOY_HOOK_URL (Enter para pular):",
1321
1566
  initialValue: ""
1322
1567
  });
1323
1568
  if (!isCancel5(vercelHookUrl) && vercelHookUrl && vercelHookUrl.trim()) {
1324
1569
  execFileSync("npx", ["convex", "env", "set", "--", "VERCEL_DEPLOY_HOOK_URL", vercelHookUrl], { stdio: "pipe" });
1325
1570
  }
1326
- const vercelWebhookSecret = await text2({
1571
+ const vercelWebhookSecret = await text3({
1327
1572
  message: "VERCEL_WEBHOOK_SECRET (Enter para pular):",
1328
1573
  initialValue: ""
1329
1574
  });
1330
1575
  if (!isCancel5(vercelWebhookSecret) && vercelWebhookSecret && vercelWebhookSecret.trim()) {
1331
1576
  execFileSync("npx", ["convex", "env", "set", "--", "VERCEL_WEBHOOK_SECRET", vercelWebhookSecret], { stdio: "pipe" });
1332
1577
  }
1333
- const profession = await text2({
1578
+ const profession = await text3({
1334
1579
  message: "Qual \xE9 a sua profiss\xE3o ou \xE1rea de atua\xE7\xE3o? (Enter para usar padr\xE3o tech)",
1335
1580
  placeholder: "Ex: Designer UX, Fot\xF3grafa, Advogada, Engenheira Civil...",
1336
1581
  initialValue: ""
1337
1582
  });
1338
- const specialties = await text2({
1583
+ const specialties = await text3({
1339
1584
  message: "Quais s\xE3o suas principais especialidades? (separadas por v\xEDrgula, Enter para pular)",
1340
1585
  placeholder: "Ex: Branding, Motion Design, Fotografia de Produto",
1341
1586
  initialValue: ""
@@ -1393,14 +1638,30 @@ async function runCli(argv, cwd) {
1393
1638
  } else if (command === "config") {
1394
1639
  await runConfig({ cwd });
1395
1640
  } else if (command === "update") {
1396
- await runUpdate({ cwd });
1641
+ await runUpdate({ cwd, options: parseUpdateOptions(argv.slice(3)) });
1397
1642
  } else if (command === "setup") {
1398
1643
  await runSetup({ cwd });
1644
+ } else if (command && !command.startsWith("-")) {
1645
+ await runCreate(command, { projectsDir: cwd });
1399
1646
  } else {
1400
- console.log("Comandos dispon\xEDveis: create <nome-do-projeto> | config | update | setup");
1647
+ console.log(
1648
+ "Comandos dispon\xEDveis: create <nome-do-projeto> | config | setup\n update [--dry-run] [--from <vers\xE3o>] [--to <vers\xE3o>] [--yes]"
1649
+ );
1650
+ }
1651
+ }
1652
+ function parseUpdateOptions(args) {
1653
+ const options = {};
1654
+ for (let i = 0; i < args.length; i++) {
1655
+ const arg = args[i];
1656
+ if (arg === "--dry-run") options.dryRun = true;
1657
+ else if (arg === "--yes" || arg === "-y") options.yes = true;
1658
+ else if (arg === "--from") options.from = args[++i];
1659
+ else if (arg === "--to") options.to = args[++i];
1401
1660
  }
1661
+ return options;
1402
1662
  }
1403
1663
  await runCli(process.argv, process.cwd());
1404
1664
  export {
1665
+ parseUpdateOptions,
1405
1666
  runCli
1406
1667
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-rubrica",
3
- "version": "0.3.17",
3
+ "version": "1.0.0",
4
4
  "description": "CLI para criar e configurar projetos Rubrica — portfólio profissional com React + Convex",
5
5
  "type": "module",
6
6
  "bin": {