create-rubrica 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +70 -16
  2. package/dist/index.js +1526 -660
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,79 +1,116 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { intro as intro3 } from "@clack/prompts";
4
+ import { intro as intro2, log as log6 } from "@clack/prompts";
5
5
 
6
6
  // src/commands/create.ts
7
- import { outro, select as select2, multiselect, confirm } from "@clack/prompts";
8
- import * as nodeFsPromises9 from "fs/promises";
7
+ import { outro as outro2, select as select4, confirm as confirm3, isCancel as isCancel5, cancel as cancel4, log as log2, note } from "@clack/prompts";
8
+ import * as nodeFsPromises12 from "fs/promises";
9
9
 
10
10
  // src/prompts/identityPrompt.ts
11
11
  import { text, select, isCancel, cancel } from "@clack/prompts";
12
+
13
+ // src/utils/normalize.ts
14
+ var LOCAL_HOST = /^(localhost|127\.0\.0\.1)(:|\/|$)/i;
15
+ function normalizeUrl(input) {
16
+ const trimmed = input.trim();
17
+ if (!trimmed) return "";
18
+ const scheme = /^(https?):\/\//i.exec(trimmed);
19
+ const withScheme = scheme ? `${scheme[1].toLowerCase()}://${trimmed.slice(scheme[0].length)}` : `${LOCAL_HOST.test(trimmed) ? "http" : "https"}://${trimmed}`;
20
+ return withScheme.replace(/\/+$/, "");
21
+ }
22
+ var URL_EXAMPLE = "N\xE3o parece um endere\xE7o de site. Exemplo: meusite.com";
23
+ function validateUrl(input) {
24
+ if (!input.trim()) return "Informe o endere\xE7o do site (ex: meusite.com)";
25
+ const url = normalizeUrl(input);
26
+ let host;
27
+ try {
28
+ host = new URL(url).hostname;
29
+ } catch {
30
+ return URL_EXAMPLE;
31
+ }
32
+ if (host !== "localhost" && !host.includes(".")) return URL_EXAMPLE;
33
+ return void 0;
34
+ }
35
+ function normalizeHandle(input) {
36
+ const trimmed = input.trim().replace(/[?#].*/, "").replace(/\/+$/, "");
37
+ const lastSegment = trimmed.slice(trimmed.lastIndexOf("/") + 1);
38
+ return lastSegment.replace(/^@/, "");
39
+ }
40
+ function normalizeEmail(input) {
41
+ return input.trim().toLowerCase();
42
+ }
43
+ function validateEmail(input) {
44
+ if (!/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/.test(input.trim())) {
45
+ return "Informe um e-mail v\xE1lido (ex: nome@meusite.com)";
46
+ }
47
+ return void 0;
48
+ }
49
+
50
+ // src/prompts/identityPrompt.ts
12
51
  function assertNotCancelled(value) {
13
52
  if (isCancel(value)) {
14
53
  cancel("Opera\xE7\xE3o cancelada.");
15
54
  throw new Error("Prompt cancelado pelo usu\xE1rio.");
16
55
  }
17
56
  }
18
- async function identityPrompt(defaults) {
19
- const siteName = await text({
20
- message: "Nome do site (aparece no t\xEDtulo do browser e SEO)",
21
- initialValue: defaults?.siteName ?? ""
22
- });
23
- assertNotCancelled(siteName);
24
- const siteUrl = await text({
25
- message: "URL do site (sem barra no final)",
26
- initialValue: defaults?.siteUrl ?? "",
27
- validate: (v) => {
28
- if (!v.startsWith("http://") && !v.startsWith("https://")) {
29
- return "A URL deve come\xE7ar com http:// ou https://";
30
- }
31
- }
57
+ async function ask(opts) {
58
+ const value = await text(opts);
59
+ assertNotCancelled(value);
60
+ return value.trim();
61
+ }
62
+ async function identityPrompt(defaults, options = {}) {
63
+ const skip = options.onlyMissing === true;
64
+ const given = (v) => (v ?? "").trim();
65
+ const authorName = skip && given(defaults?.authorName) ? given(defaults?.authorName) : await ask({
66
+ message: "Seu nome",
67
+ initialValue: defaults?.authorName ?? "",
68
+ validate: (v) => v.trim() ? void 0 : "Informe seu nome"
32
69
  });
33
- assertNotCancelled(siteUrl);
34
- const siteDescription = await text({
35
- message: "Descri\xE7\xE3o curta (SEO e Open Graph)",
70
+ const siteName = skip ? given(defaults?.siteName) || authorName : await ask({
71
+ message: "Nome do site (aparece na aba do navegador e no Google)",
72
+ initialValue: defaults?.siteName ?? authorName
73
+ }) || authorName;
74
+ const siteUrlGiven = skip && given(defaults?.siteUrl) && !validateUrl(given(defaults?.siteUrl));
75
+ const siteUrl = normalizeUrl(
76
+ siteUrlGiven ? given(defaults?.siteUrl) : await ask({
77
+ message: "Endere\xE7o do site (ex: meusite.com \u2014 n\xE3o precisa do https://)",
78
+ initialValue: defaults?.siteUrl ?? "",
79
+ validate: validateUrl
80
+ })
81
+ );
82
+ const siteDescription = skip ? given(defaults?.siteDescription) : await ask({
83
+ message: "Em uma frase, o que voc\xEA faz? (aparece no Google e quando algu\xE9m compartilha o link)",
36
84
  initialValue: defaults?.siteDescription ?? ""
37
85
  });
38
- assertNotCancelled(siteDescription);
39
- const authorName = await text({
40
- message: "Seu nome (para RSS e meta author)",
41
- initialValue: defaults?.authorName ?? ""
42
- });
43
- assertNotCancelled(authorName);
44
- const authorEmail = await text({
45
- message: "Seu email (para RSS \u2014 n\xE3o aparece publicamente)",
46
- initialValue: defaults?.authorEmail ?? "",
47
- validate: (v) => {
48
- if (!v.includes("@") || !v.includes(".")) {
49
- return "Informe um email v\xE1lido (ex: contato@meusite.com)";
50
- }
51
- }
52
- });
53
- assertNotCancelled(authorEmail);
54
- const twitterHandle = await text({
55
- message: "Twitter/X handle (sem @, Enter para pular)",
56
- initialValue: defaults?.twitterHandle ?? ""
57
- });
58
- assertNotCancelled(twitterHandle);
59
- const lang = await select({
60
- message: "Idioma padr\xE3o",
61
- initialValue: defaults?.lang ?? "pt-BR",
62
- options: [
63
- { value: "pt-BR", label: "Portugu\xEAs (pt-BR)" },
64
- { value: "en-US", label: "Ingl\xEAs (en-US)" }
65
- ]
66
- });
67
- assertNotCancelled(lang);
68
- return {
69
- siteName,
70
- siteUrl,
71
- siteDescription,
72
- authorName,
73
- authorEmail,
74
- twitterHandle: twitterHandle ?? "",
75
- lang
76
- };
86
+ const emailGiven = skip && given(defaults?.authorEmail) && !validateEmail(given(defaults?.authorEmail));
87
+ const authorEmail = normalizeEmail(
88
+ emailGiven ? given(defaults?.authorEmail) : await ask({
89
+ message: "Seu e-mail (n\xE3o aparece no site)",
90
+ initialValue: defaults?.authorEmail ?? "",
91
+ validate: validateEmail
92
+ })
93
+ );
94
+ const twitterHandle = normalizeHandle(
95
+ skip ? given(defaults?.twitterHandle) : await ask({
96
+ message: "Seu perfil no X/Twitter (opcional \u2014 Enter para pular)",
97
+ initialValue: defaults?.twitterHandle ?? ""
98
+ })
99
+ );
100
+ let lang = defaults?.lang ?? "pt-BR";
101
+ if (options.askLang !== false) {
102
+ const chosen = await select({
103
+ message: "Idioma do site",
104
+ initialValue: lang,
105
+ options: [
106
+ { value: "pt-BR", label: "Portugu\xEAs (pt-BR)" },
107
+ { value: "en-US", label: "Ingl\xEAs (en-US)" }
108
+ ]
109
+ });
110
+ assertNotCancelled(chosen);
111
+ lang = chosen;
112
+ }
113
+ return { siteName, siteUrl, siteDescription, authorName, authorEmail, twitterHandle, lang };
77
114
  }
78
115
 
79
116
  // src/utils/download.ts
@@ -145,32 +182,184 @@ async function downloadRelease(targetDir, version) {
145
182
  // src/transforms/applyLayout.ts
146
183
  import * as nodeFsPromises from "fs/promises";
147
184
  import * as path from "path";
148
- var LAYOUT_FILES = {
149
- cyberpunk: {
185
+
186
+ // src/layouts.ts
187
+ var TEMPLATE_PAGES = ["Home.tsx", "Resume.tsx", "Portfolio.tsx", "About.tsx", "Blog.tsx"];
188
+ var NEW_LAYOUT_REMOVE = ["Sidebar.tsx", "Navbar.tsx", "Footer.tsx"];
189
+ var LAYOUTS = [
190
+ // ---- originais (contrato de 4 cores) ----
191
+ {
192
+ id: "cyberpunk",
193
+ label: "Cyberpunk",
194
+ hint: "sidebar lateral com foto de perfil \u2014 dev, designer, freelancer",
195
+ legacy: true,
150
196
  copy: ["Layout.tsx", "Sidebar.tsx"],
151
- remove: ["Navbar.tsx", "Footer.tsx"]
197
+ remove: ["Navbar.tsx", "Footer.tsx"],
198
+ fonts: { sans: ["Chakra Petch"], mono: "JetBrains Mono" },
199
+ recommended: { scheme: "neon", mode: "dark", texture: "none" }
152
200
  },
153
- brutalist: {
201
+ {
202
+ id: "brutalist",
203
+ label: "Brutalism Terminal",
204
+ hint: "identidade hacker total \u2014 monospace, sem bordas arredondadas",
205
+ legacy: true,
154
206
  copy: ["Layout.tsx", "Navbar.tsx"],
155
207
  remove: ["Sidebar.tsx", "Footer.tsx"],
156
- pages: ["Home.tsx", "Resume.tsx", "Portfolio.tsx", "About.tsx", "Blog.tsx"]
208
+ pages: TEMPLATE_PAGES,
209
+ fonts: { sans: ["JetBrains Mono"], mono: "JetBrains Mono" },
210
+ recommended: { scheme: "paper-noir", mode: "dark", texture: "none" }
157
211
  },
158
- swiss: {
212
+ {
213
+ id: "swiss",
214
+ label: "Swiss Grid",
215
+ hint: "grid de 12 colunas, tipografia forte, design su\xED\xE7o rigoroso",
216
+ legacy: true,
159
217
  copy: ["Layout.tsx", "Sidebar.tsx", "SwissShared.tsx"],
160
218
  remove: ["Navbar.tsx", "Footer.tsx"],
161
- pages: ["Home.tsx", "Resume.tsx", "Portfolio.tsx", "About.tsx", "Blog.tsx"]
219
+ pages: TEMPLATE_PAGES,
220
+ fonts: { sans: ["Archivo"], mono: "" },
221
+ recommended: { scheme: "paper-noir", mode: "light", texture: "none" }
162
222
  },
163
- bento: {
223
+ {
224
+ id: "bento",
225
+ label: "Bento",
226
+ hint: "grid assim\xE9trico com floating dock \u2014 moderno, orientado a produto",
227
+ legacy: true,
164
228
  copy: ["Layout.tsx", "FloatingDock.tsx"],
165
229
  remove: [],
166
- pages: ["Home.tsx", "Resume.tsx", "Portfolio.tsx", "About.tsx", "Blog.tsx"]
230
+ pages: TEMPLATE_PAGES,
231
+ fonts: { sans: ["Manrope"], mono: "JetBrains Mono" },
232
+ recommended: { scheme: "editorial-cream", mode: "light", texture: "none" }
167
233
  },
168
- magazine: {
234
+ {
235
+ id: "magazine",
236
+ label: "Magazine",
237
+ hint: "editorial cl\xE1ssico \xB7 display serifado \xB7 grid assim\xE9trico \xB7 \xE1reas de respiro generosas",
238
+ legacy: true,
169
239
  copy: ["Layout.tsx", "Masthead.tsx"],
170
240
  remove: ["Sidebar.tsx", "Footer.tsx"],
171
- pages: ["Home.tsx", "Resume.tsx", "Portfolio.tsx", "About.tsx", "Blog.tsx"]
241
+ pages: TEMPLATE_PAGES,
242
+ fonts: { sans: ["Bodoni Moda", "IBM Plex Serif"], mono: "JetBrains Mono" },
243
+ recommended: { scheme: "editorial-cream", mode: "light", texture: "paper" }
244
+ },
245
+ // ---- novos (esquema completo) ----
246
+ {
247
+ id: "desktop",
248
+ label: "Desktop Retr\xF4",
249
+ hint: "cada se\xE7\xE3o \xE9 uma janela sobre a \xE1rea de trabalho \u2014 nostalgia e brincadeira",
250
+ legacy: false,
251
+ copy: ["Layout.tsx", "DesktopMenuBar.tsx", "DesktopShared.tsx"],
252
+ remove: NEW_LAYOUT_REMOVE,
253
+ pages: TEMPLATE_PAGES,
254
+ fonts: { sans: ["Instrument Sans"], mono: "IBM Plex Mono" },
255
+ recommended: { scheme: "sorbet", mode: "light", texture: "grain" }
256
+ },
257
+ {
258
+ id: "index",
259
+ label: "\xCDndice",
260
+ hint: "lista densa de museu, r\xF3tulos \xE0 esquerda e imagem que surge no hover \u2014 curadoria",
261
+ legacy: false,
262
+ copy: ["Layout.tsx", "IndexHeader.tsx", "IndexShared.tsx"],
263
+ remove: NEW_LAYOUT_REMOVE,
264
+ pages: TEMPLATE_PAGES,
265
+ fonts: { sans: ["Instrument Sans"], mono: "IBM Plex Mono" },
266
+ recommended: { scheme: "sumi", mode: "light", texture: "none" }
267
+ },
268
+ {
269
+ id: "monograph",
270
+ label: "Monografia",
271
+ hint: "o site como livro: folha de rosto, sum\xE1rio, capitulares e notas na margem",
272
+ legacy: false,
273
+ copy: ["Layout.tsx", "MonographRunningHead.tsx", "MonographShared.tsx"],
274
+ remove: NEW_LAYOUT_REMOVE,
275
+ pages: TEMPLATE_PAGES,
276
+ fonts: { sans: ["Fraunces", "Source Serif 4"], mono: "IBM Plex Mono" },
277
+ recommended: { scheme: "azulejo", mode: "light", texture: "paper" }
278
+ },
279
+ {
280
+ id: "zine",
281
+ label: "Zine",
282
+ hint: "colagem: polaroides, fita adesiva, post-its e letra \xE0 m\xE3o \u2014 autoral",
283
+ legacy: false,
284
+ copy: ["Layout.tsx", "ZineNav.tsx", "ZineShared.tsx"],
285
+ remove: NEW_LAYOUT_REMOVE,
286
+ pages: TEMPLATE_PAGES,
287
+ fonts: { sans: ["Bricolage Grotesque"], mono: "IBM Plex Mono" },
288
+ recommended: { scheme: "riso", mode: "light", texture: "paper" }
289
+ },
290
+ {
291
+ id: "blueprint",
292
+ label: "Blueprint",
293
+ hint: "folhas t\xE9cnicas numeradas sobre papel quadriculado, com cotas e carimbo",
294
+ legacy: false,
295
+ copy: ["Layout.tsx", "BlueprintHeader.tsx", "BlueprintShared.tsx"],
296
+ remove: NEW_LAYOUT_REMOVE,
297
+ pages: TEMPLATE_PAGES,
298
+ fonts: { sans: ["IBM Plex Sans"], mono: "IBM Plex Mono" },
299
+ recommended: { scheme: "cianotipia", mode: "dark", texture: "paper" }
300
+ },
301
+ {
302
+ id: "garden",
303
+ label: "Jardim Digital",
304
+ hint: "notas com est\xE1gio de crescimento, backlinks e mapa de liga\xE7\xF5es",
305
+ legacy: false,
306
+ copy: ["Layout.tsx", "GardenSidebar.tsx", "GardenShared.tsx"],
307
+ remove: NEW_LAYOUT_REMOVE,
308
+ pages: TEMPLATE_PAGES,
309
+ fonts: { sans: ["Fraunces", "Source Serif 4"], mono: "IBM Plex Mono" },
310
+ recommended: { scheme: "crepusculo", mode: "dark", texture: "grain" }
311
+ },
312
+ {
313
+ id: "chat",
314
+ label: "Conversa",
315
+ hint: "o site como conversa: cada se\xE7\xE3o responde a uma pergunta pronta",
316
+ legacy: false,
317
+ copy: ["Layout.tsx", "ChatHeader.tsx", "ChatShared.tsx"],
318
+ remove: NEW_LAYOUT_REMOVE,
319
+ pages: TEMPLATE_PAGES,
320
+ fonts: { sans: ["Instrument Sans"], mono: "IBM Plex Mono" },
321
+ recommended: { scheme: "alto-contraste", mode: "light", texture: "none" }
322
+ },
323
+ {
324
+ id: "poster",
325
+ label: "P\xF4ster Cin\xE9tico",
326
+ hint: "tipografia gigante do come\xE7o ao fim, faixas rolando \u2014 impacto",
327
+ legacy: false,
328
+ copy: ["Layout.tsx", "PosterNav.tsx", "PosterShared.tsx"],
329
+ remove: NEW_LAYOUT_REMOVE,
330
+ pages: TEMPLATE_PAGES,
331
+ fonts: { sans: ["Bricolage Grotesque"], mono: "IBM Plex Mono" },
332
+ recommended: { scheme: "tropicalia", mode: "light", texture: "grain" }
172
333
  }
173
- };
334
+ ];
335
+ function getLayout(id) {
336
+ return LAYOUTS.find((l) => l.id === id);
337
+ }
338
+ function recommendedAppearance(layoutId) {
339
+ const layout = getLayout(layoutId);
340
+ if (!layout) throw new Error(`Layout desconhecido: "${layoutId}".`);
341
+ return {
342
+ theme: layout.recommended.scheme,
343
+ colorMode: layout.recommended.mode,
344
+ colorModeToggle: true,
345
+ texture: layout.recommended.texture,
346
+ fontSans: layout.fonts.sans[0],
347
+ fontMono: layout.fonts.mono
348
+ };
349
+ }
350
+ var COLOR_MODES = [
351
+ { value: "light", label: "Claro", hint: "fundo claro" },
352
+ { value: "dark", label: "Escuro", hint: "fundo escuro" },
353
+ { value: "system", label: "Autom\xE1tico", hint: "segue o modo do sistema de quem visita" }
354
+ ];
355
+ var TEXTURES = [
356
+ { value: "none", label: "Nenhuma", hint: "superf\xEDcies lisas" },
357
+ { value: "grain", label: "Gr\xE3o de filme", hint: "ru\xEDdo fino, sensa\xE7\xE3o anal\xF3gica" },
358
+ { value: "paper", label: "Papel", hint: "fibras de papel, bom para layouts editoriais" },
359
+ { value: "scanlines", label: "Scanlines", hint: "linhas de monitor CRT" }
360
+ ];
361
+
362
+ // src/transforms/applyLayout.ts
174
363
  var defaultFs = {
175
364
  ...nodeFsPromises,
176
365
  exists: async (p) => {
@@ -183,7 +372,7 @@ var defaultFs = {
183
372
  }
184
373
  };
185
374
  async function applyLayout(layout, options, fsModule = defaultFs) {
186
- const spec = LAYOUT_FILES[layout];
375
+ const spec = getLayout(layout);
187
376
  if (!spec) {
188
377
  throw new Error(`applyLayout: layout "${layout}" n\xE3o reconhecido.`);
189
378
  }
@@ -214,7 +403,175 @@ async function applyLayout(layout, options, fsModule = defaultFs) {
214
403
 
215
404
  // src/transforms/applyTheme.ts
216
405
  import * as nodeFsPromises2 from "fs/promises";
217
- var PRESETS = {
406
+
407
+ // src/themes/schemes.ts
408
+ var ROLE_VARS = {
409
+ bg: "--bg",
410
+ surface: "--surface",
411
+ subtle: "--subtle",
412
+ text: "--text",
413
+ textMuted: "--text-muted",
414
+ line: "--line",
415
+ primary: "--primary",
416
+ onPrimary: "--on-primary",
417
+ accent: "--accent",
418
+ onAccent: "--on-accent",
419
+ accent2: "--accent-2"
420
+ };
421
+ var LEGACY_ROLES = ["bg", "text", "primary", "accent"];
422
+ function luminance(hex) {
423
+ const c = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((v) => v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
424
+ return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
425
+ }
426
+ function contrast(a, b) {
427
+ const x = luminance(a);
428
+ const y = luminance(b);
429
+ return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);
430
+ }
431
+ function onColor(fill, mode2) {
432
+ return contrast(fill, mode2.bg) >= contrast(fill, mode2.text) ? mode2.bg : mode2.text;
433
+ }
434
+ function mode(m) {
435
+ return {
436
+ ...m,
437
+ onPrimary: m.onPrimary ?? onColor(m.primary, m),
438
+ onAccent: m.onAccent ?? onColor(m.accent, m)
439
+ };
440
+ }
441
+ var SCHEMES = [
442
+ // Padrão do repositório: o visual original do Rubrica.
443
+ {
444
+ id: "neon",
445
+ label: "Neon",
446
+ hint: "o visual original do Rubrica \u2014 roxo e lima sobre grafite",
447
+ light: mode({ bg: "#F7F7F8", surface: "#EFEFF2", subtle: "#F1F1F4", text: "#141414", textMuted: "#55555C", line: "#DCDCE2", primary: "#7E22CE", accent: "#4D7C0F", accent2: "#0891B2" }),
448
+ dark: mode({ bg: "#141414", surface: "#0A0A0A", subtle: "#171717", text: "#E6E6E6", textMuted: "#A2A2A2", line: "#252525", primary: "#A855F7", onPrimary: "#FFFFFF", accent: "#BEF264", accent2: "#22D3EE" })
449
+ },
450
+ // Os 4 presets originais, agora com os dois modos e o esquema completo.
451
+ {
452
+ id: "editorial-cream",
453
+ label: "Editorial Cream",
454
+ hint: "refinado e atemporal \u2014 blogs e portf\xF3lios liter\xE1rios",
455
+ light: mode({ bg: "#FAF7F2", surface: "#F3EEE5", subtle: "#EFE9DE", text: "#1A1614", textMuted: "#5E554D", line: "#E2D9CB", primary: "#A855F7", accent: "#EF4444", accent2: "#B7832A" }),
456
+ dark: mode({ bg: "#1A1614", surface: "#231E1A", subtle: "#2A241F", text: "#F3EEE5", textMuted: "#A89E93", line: "#3A322B", primary: "#C084FC", accent: "#F87171", accent2: "#E0B25A" })
457
+ },
458
+ {
459
+ id: "paper-noir",
460
+ label: "Paper Noir",
461
+ hint: "contraste m\xE1ximo \u2014 identidade editorial forte",
462
+ light: mode({ bg: "#F0EEE9", surface: "#E8E5DE", subtle: "#E4E1D9", text: "#0A0A0A", textMuted: "#55524C", line: "#D3CFC6", primary: "#EF4444", accent: "#3B82F6", accent2: "#E8B500" }),
463
+ dark: mode({ bg: "#0D0D0D", surface: "#161616", subtle: "#1C1C1C", text: "#F0EEE9", textMuted: "#A3A09A", line: "#2C2C2C", primary: "#F05252", accent: "#60A5FA", accent2: "#F2C94C" })
464
+ },
465
+ {
466
+ id: "midnight-blue",
467
+ label: "Midnight Blue",
468
+ hint: "tech e premium \u2014 devs e designers noturnos",
469
+ light: mode({ bg: "#F3F6FB", surface: "#E9EEF7", subtle: "#E3E9F3", text: "#0A1224", textMuted: "#4B5670", line: "#CBD5E6", primary: "#0E7490", accent: "#CA8A04", accent2: "#6D28D9" }),
470
+ dark: mode({ bg: "#0A1224", surface: "#0F1A31", subtle: "#13203B", text: "#E8E6E0", textMuted: "#9AA3B5", line: "#22304D", primary: "#06B6D4", accent: "#FACC15", accent2: "#A78BFA" })
471
+ },
472
+ {
473
+ id: "solar-warm",
474
+ label: "Solar Warm",
475
+ hint: "energia e criatividade \u2014 marcas pessoais vibrantes",
476
+ light: mode({ bg: "#FFF8EF", surface: "#FBEFDF", subtle: "#F7E9D6", text: "#2A1A0E", textMuted: "#6E5A47", line: "#EAD7BE", primary: "#C2410C", accent: "#CA8A04", accent2: "#BE123C" }),
477
+ dark: mode({ bg: "#1A1410", surface: "#231B15", subtle: "#2A2019", text: "#F2EDE4", textMuted: "#ABA092", line: "#3A2E24", primary: "#F97316", accent: "#FACC15", accent2: "#FB7185" })
478
+ },
479
+ // Paletas novas.
480
+ {
481
+ id: "riso",
482
+ label: "Riso",
483
+ hint: "rosa fluorescente e azul de impress\xE3o riso sobre papel",
484
+ light: mode({ bg: "#F2EDE2", surface: "#FAF6EE", subtle: "#E5DDCC", text: "#1D2B63", textMuted: "#4E5884", line: "#D4C9B2", primary: "#E5258D", onPrimary: "#14183A", accent: "#0078BF", accent2: "#FFE800" }),
485
+ dark: mode({ bg: "#15172A", surface: "#1E2138", subtle: "#272A44", text: "#F2EDE2", textMuted: "#A9ACC8", line: "#363A5C", primary: "#FF5CBA", onPrimary: "#15172A", accent: "#4AA8E8", accent2: "#FFE45C" })
486
+ },
487
+ {
488
+ id: "cianotipia",
489
+ label: "Cianotipia",
490
+ hint: "azul-da-pr\xFAssia e branco giz, como c\xF3pia heliogr\xE1fica",
491
+ light: mode({ bg: "#EDF1F6", surface: "#F8FAFC", subtle: "#DDE5EF", text: "#0F2C57", textMuted: "#4A6286", line: "#C3D0E1", primary: "#1D4E89", onPrimary: "#FFFFFF", accent: "#6F9BCB", accent2: "#8FB3D9" }),
492
+ dark: mode({ bg: "#0E2A50", surface: "#14345F", subtle: "#1A3D6C", text: "#E9EFF7", textMuted: "#9DB4D3", line: "#2D5285", primary: "#F2F5FA", onPrimary: "#0E2A50", accent: "#7FA9DA", accent2: "#BFD3EA" })
493
+ },
494
+ {
495
+ id: "tropicalia",
496
+ label: "Tropic\xE1lia",
497
+ hint: "verde-mata, amarelo-ouro e rosa-buganv\xEDlia",
498
+ light: mode({ bg: "#FBF5E6", surface: "#FFFBF1", subtle: "#EFE6CD", text: "#0D3326", textMuted: "#4D6358", line: "#DCCFAE", primary: "#0B6E4F", onPrimary: "#FFFFFF", accent: "#F2B705", accent2: "#E2457A" }),
499
+ dark: mode({ bg: "#0A271D", surface: "#0F3427", subtle: "#143D2F", text: "#F6EFDA", textMuted: "#A7BFAF", line: "#22513F", primary: "#34C08A", onPrimary: "#062016", accent: "#F7C531", accent2: "#F26B9C" })
500
+ },
501
+ {
502
+ id: "azulejo",
503
+ label: "Azulejo",
504
+ hint: "azul-cobalto sobre branco, com terracota",
505
+ light: mode({ bg: "#F6F6F2", surface: "#FFFFFF", subtle: "#E7EAF1", text: "#14213D", textMuted: "#4F5B78", line: "#D2D7E3", primary: "#1F4FB4", onPrimary: "#FFFFFF", accent: "#C4673D", accent2: "#E9B949" }),
506
+ dark: mode({ bg: "#0D1630", surface: "#141F3D", subtle: "#1B2749", text: "#ECEFF6", textMuted: "#A1ACC8", line: "#2A3762", primary: "#7397F2", onPrimary: "#0D1630", accent: "#E58C61", accent2: "#F0C866" })
507
+ },
508
+ {
509
+ id: "sumi",
510
+ label: "Sumi",
511
+ hint: "tinta preta, papel washi e um \xFAnico vermelho de carimbo",
512
+ light: mode({ bg: "#EEEBE3", surface: "#F7F5F0", subtle: "#E1DDD2", text: "#171614", textMuted: "#5F5B53", line: "#CEC8BA", primary: "#C8102E", onPrimary: "#FFFFFF", accent: "#8A8478", accent2: "#171614" }),
513
+ dark: mode({ bg: "#121110", surface: "#1B1A18", subtle: "#24221F", text: "#E9E5DC", textMuted: "#A39E93", line: "#34312C", primary: "#E5414A", onPrimary: "#121110", accent: "#7D776C", accent2: "#E9E5DC" })
514
+ },
515
+ {
516
+ id: "fosforo",
517
+ label: "F\xF3sforo",
518
+ hint: "verde de monitor CRT e \xE2mbar; no claro, papel de formul\xE1rio cont\xEDnuo",
519
+ light: mode({ bg: "#EEF3E8", surface: "#F7FAF3", subtle: "#DDE8D3", text: "#1A3A20", textMuted: "#4C6A50", line: "#C3D4B6", primary: "#1E7A33", onPrimary: "#FFFFFF", accent: "#A86A00", accent2: "#5E9E6A" }),
520
+ dark: mode({ bg: "#070C08", surface: "#0C150E", subtle: "#102014", text: "#8CFF9E", textMuted: "#4FBF63", line: "#1C3A22", primary: "#3DFF6E", onPrimary: "#04140A", accent: "#FFB000", accent2: "#2E8B45" })
521
+ },
522
+ {
523
+ id: "crepusculo",
524
+ label: "Crep\xFAsculo",
525
+ hint: "roxo profundo indo para o laranja de fim de tarde",
526
+ light: mode({ bg: "#FFF3ED", surface: "#FFFAF7", subtle: "#F6E2DD", text: "#2A1540", textMuted: "#6B5378", line: "#EBCFCB", primary: "#6B2FA3", onPrimary: "#FFFFFF", accent: "#EF6C2A", accent2: "#E3A73B" }),
527
+ dark: mode({ bg: "#190E29", surface: "#231536", subtle: "#2D1C44", text: "#F7E9F0", textMuted: "#BCA6C9", line: "#3E2A5A", primary: "#B788F2", onPrimary: "#190E29", accent: "#FF8A4C", accent2: "#F4C15D" })
528
+ },
529
+ {
530
+ id: "concreto",
531
+ label: "Concreto",
532
+ hint: "cinzas frios e um amarelo de sinaliza\xE7\xE3o",
533
+ light: mode({ bg: "#E3E4E5", surface: "#EEEFF0", subtle: "#D3D5D7", text: "#111214", textMuted: "#55595F", line: "#B9BCC0", primary: "#1F2124", onPrimary: "#FFD400", accent: "#A87F00", accent2: "#FFD400" }),
534
+ dark: mode({ bg: "#18191B", surface: "#212325", subtle: "#2A2C2F", text: "#E8E9EA", textMuted: "#9A9EA4", line: "#3A3D41", primary: "#FFD400", onPrimary: "#111214", accent: "#6E737A", accent2: "#E8E9EA" })
535
+ },
536
+ {
537
+ id: "sorbet",
538
+ label: "Sorbet",
539
+ hint: "lil\xE1s, menta e p\xEAssego em tons Y2K",
540
+ light: mode({ bg: "#FFF6FA", surface: "#FFFFFF", subtle: "#F3E8F6", text: "#35295A", textMuted: "#6F6390", line: "#E6D6EE", primary: "#7454D6", onPrimary: "#FFFFFF", accent: "#6FD3B5", accent2: "#FFAE94" }),
541
+ dark: mode({ bg: "#211B33", surface: "#2A2340", subtle: "#332B4C", text: "#F5EEFF", textMuted: "#B9AED6", line: "#433A60", primary: "#B9A0FF", onPrimary: "#211B33", accent: "#86E3C7", accent2: "#FFB8A1" })
542
+ },
543
+ {
544
+ id: "alto-contraste",
545
+ label: "Alto Contraste",
546
+ hint: "contraste n\xEDvel AAA nos dois modos, pensado para baixa vis\xE3o",
547
+ light: mode({ bg: "#FFFFFF", surface: "#FFFFFF", subtle: "#F0F0F0", text: "#000000", textMuted: "#2B2B2B", line: "#000000", primary: "#0030B8", onPrimary: "#FFFFFF", accent: "#8A0000", accent2: "#000000" }),
548
+ dark: mode({ bg: "#000000", surface: "#0A0A0A", subtle: "#1A1A1A", text: "#FFFFFF", textMuted: "#E0E0E0", line: "#FFFFFF", primary: "#FFE14D", onPrimary: "#000000", accent: "#7FD8FF", accent2: "#FFFFFF" })
549
+ }
550
+ ];
551
+ function getScheme(id) {
552
+ return SCHEMES.find((s) => s.id === id);
553
+ }
554
+ function modeDeclarations(m, indent = " ") {
555
+ return Object.keys(ROLE_VARS).map((role) => `${indent}${ROLE_VARS[role]}: ${m[role]};`).join("\n");
556
+ }
557
+ var SCHEME_START = "/* rubrica:esquema:inicio */";
558
+ var SCHEME_END = "/* rubrica:esquema:fim */";
559
+ function schemeCss(scheme) {
560
+ return [
561
+ SCHEME_START,
562
+ `/* Esquema de cores: ${scheme.label} (${scheme.id}). Gerado pelo CLI (rubrica config \u2192 Apar\xEAncia). */`,
563
+ `:root {
564
+ ${modeDeclarations(scheme.light)}
565
+ }`,
566
+ `.dark {
567
+ ${modeDeclarations(scheme.dark)}
568
+ }`,
569
+ SCHEME_END
570
+ ].join("\n");
571
+ }
572
+
573
+ // src/transforms/applyTheme.ts
574
+ var PRE_SCHEME_PRESETS = {
218
575
  "editorial-cream": { "--bg": "#faf7f2", "--text": "#1a1614", "--primary": "#a855f7", "--accent": "#ef4444" },
219
576
  "paper-noir": { "--bg": "#f0eee9", "--text": "#0a0a0a", "--primary": "#ef4444", "--accent": "#3b82f6" },
220
577
  "midnight-blue": { "--bg": "#0a1224", "--text": "#e8e6e0", "--primary": "#06b6d4", "--accent": "#facc15" },
@@ -230,43 +587,77 @@ function setVars(css, selector, vars, addMissing) {
230
587
  const missing = [];
231
588
  for (const [name, value] of Object.entries(vars)) {
232
589
  const declRe = new RegExp(`(^|[\\s;{])(${escapeRegExp(name)}\\s*:)[^;}]*`);
233
- if (declRe.test(updated)) {
234
- updated = updated.replace(declRe, `$1$2 ${value}`);
235
- } else if (addMissing) {
236
- missing.push(` ${name}: ${value};`);
237
- }
590
+ if (declRe.test(updated)) updated = updated.replace(declRe, `$1$2 ${value}`);
591
+ else if (addMissing) missing.push(` ${name}: ${value};`);
238
592
  }
239
- if (missing.length) {
240
- updated = `${updated.replace(/\s*$/, "")}
593
+ if (missing.length) updated = `${updated.replace(/\s*$/, "")}
241
594
  ${missing.join("\n")}
242
595
  `;
243
- }
244
596
  return `${lead}${open}${updated}${close}`;
245
597
  });
246
598
  }
247
599
  async function applyTheme(options, cssPath, fsModule = nodeFsPromises2) {
248
- const theme = PRESETS[options.preset];
249
- if (!theme) {
250
- throw new Error(`applyTheme: preset "${options.preset}" n\xE3o encontrado.`);
600
+ const scheme = getScheme(options.preset);
601
+ if (!scheme) {
602
+ throw new Error(`applyTheme: esquema "${options.preset}" n\xE3o encontrado.`);
251
603
  }
252
604
  const css = await fsModule.readFile(cssPath, "utf-8");
253
- let updated = setVars(css, ":root", theme, true);
254
- updated = setVars(updated, ".dark", theme, false);
605
+ const block = new RegExp(`${escapeRegExp(SCHEME_START)}[\\s\\S]*?${escapeRegExp(SCHEME_END)}`);
606
+ let updated;
607
+ if (block.test(css)) {
608
+ updated = css.replace(block, () => schemeCss(scheme));
609
+ } else {
610
+ const legacy = PRE_SCHEME_PRESETS[scheme.id] ?? Object.fromEntries(LEGACY_ROLES.map((r) => [ROLE_VARS[r], scheme.dark[r]]));
611
+ updated = setVars(setVars(css, ":root", legacy, true), ".dark", legacy, false);
612
+ }
255
613
  await fsModule.writeFile(cssPath, updated);
256
614
  }
257
615
 
258
616
  // src/transforms/applyFont.ts
259
617
  import * as nodeFsPromises3 from "fs/promises";
260
- function fontToGoogleSlug(font) {
261
- return font.replace(/ /g, "+");
618
+
619
+ // src/themes/fonts.ts
620
+ var SANS_FONTS = [
621
+ { family: "Inter", hint: "neutra, leg\xEDvel, padr\xE3o de produtos digitais", weights: [300, 400, 500, 600, 700] },
622
+ { family: "Chakra Petch", hint: "geom\xE9trica, tech, futurista", weights: [300, 400, 500, 600, 700] },
623
+ { family: "Playfair Display", hint: "elegante, editorial cl\xE1ssico", weights: [400, 500, 600, 700, 800] },
624
+ { family: "Space Grotesk", hint: "moderna, startup", weights: [300, 400, 500, 600, 700] },
625
+ { family: "DM Sans", hint: "limpa, amig\xE1vel, vers\xE1til", weights: [300, 400, 500, 600, 700] },
626
+ { family: "Bodoni Moda", hint: "display serifado elegante, editorial cl\xE1ssico", weights: [400, 500, 600, 700, 800] },
627
+ { family: "IBM Plex Serif", hint: "serifa t\xE9cnica, confian\xE7a e rigor", weights: [300, 400, 500, 600, 700] },
628
+ { family: "Manrope", hint: "geom\xE9trica humanista, moderna e acolhedora", weights: [300, 400, 500, 600, 700, 800] },
629
+ { family: "Archivo", hint: "grotesca utilit\xE1ria, clareza e for\xE7a tipogr\xE1fica", weights: [300, 400, 500, 600, 700, 800] },
630
+ { family: "Instrument Sans", hint: "grotesca contempor\xE2nea, precisa e discreta", weights: [400, 500, 600, 700] },
631
+ { family: "IBM Plex Sans", hint: "t\xE9cnica e neutra, par natural da IBM Plex Mono", weights: [300, 400, 500, 600, 700] },
632
+ { family: "Fraunces", hint: "serifa expressiva de livro, calorosa", weights: [300, 400, 500, 600, 700, 800] },
633
+ { family: "Source Serif 4", hint: "serifa de leitura longa, s\xF3bria", weights: [300, 400, 600, 700] },
634
+ { family: "Bricolage Grotesque", hint: "display com personalidade, p\xF4ster e colagem", weights: [300, 400, 500, 600, 700, 800] },
635
+ // Principal do brutalist: monoespaçada também no corpo do texto.
636
+ { family: "JetBrains Mono", hint: "monoespa\xE7ada no texto todo, identidade de terminal", weights: [300, 400, 500, 600, 700] }
637
+ ];
638
+ var MONO_FONTS = [
639
+ { family: "JetBrains Mono", hint: "dev-friendly, clara", weights: [300, 400, 500, 600, 700] },
640
+ { family: "Fira Code", hint: "cl\xE1ssico, com ligatures", weights: [300, 400, 500, 600, 700] },
641
+ { family: "Space Mono", hint: "retro digital", weights: [400, 700] },
642
+ { family: "IBM Plex Mono", hint: "corporativo-tech", weights: [300, 400, 500, 600, 700] }
643
+ ];
644
+ var DEFAULT_WEIGHTS = [400, 700];
645
+ function weightsOf(family) {
646
+ return [...SANS_FONTS, ...MONO_FONTS].find((f) => f.family === family)?.weights ?? DEFAULT_WEIGHTS;
647
+ }
648
+ function googleFontsHref(families) {
649
+ const unique = [...new Set(families.filter(Boolean))];
650
+ const params = unique.map((f) => `family=${f.replace(/ /g, "+")}:wght@${weightsOf(f).join(";")}`).join("&");
651
+ return `https://fonts.googleapis.com/css2?${params}&display=swap`;
262
652
  }
263
- function buildFontLink(font) {
264
- const slug = fontToGoogleSlug(font);
653
+ function fontLinkTag(families) {
265
654
  return `<link
266
- href="https://fonts.googleapis.com/css2?family=${slug}:wght@300;400;500;600;700&display=swap"
655
+ href="${googleFontsHref(families)}"
267
656
  rel="stylesheet"
268
657
  />`;
269
658
  }
659
+
660
+ // src/transforms/applyFont.ts
270
661
  async function applyFont(options, paths, fsModule = nodeFsPromises3) {
271
662
  const { fontSans, fontMono } = options;
272
663
  let css = await fsModule.readFile(paths.css, "utf-8");
@@ -280,7 +671,7 @@ async function applyFont(options, paths, fsModule = nodeFsPromises3) {
280
671
  );
281
672
  await fsModule.writeFile(paths.css, css);
282
673
  let html = await fsModule.readFile(paths.html, "utf-8");
283
- const newLink = buildFontLink(fontSans);
674
+ const newLink = fontLinkTag([fontSans, fontMono]);
284
675
  html = html.replace(
285
676
  /<link\s[^>]*fonts\.googleapis\.com\/css2[^>]*(?:\s*\/>|>[^<]*<\/link>)/s,
286
677
  newLink
@@ -290,9 +681,9 @@ async function applyFont(options, paths, fsModule = nodeFsPromises3) {
290
681
 
291
682
  // src/transforms/applyPlugins.ts
292
683
  import * as nodeFsPromises4 from "fs/promises";
293
- async function applyPlugins(plugins, registryPath, fsModule = nodeFsPromises4) {
684
+ async function applyPlugins(plugins2, registryPath, fsModule = nodeFsPromises4) {
294
685
  let content = await fsModule.readFile(registryPath, "utf-8");
295
- for (const [id, enabled] of Object.entries(plugins)) {
686
+ for (const [id, enabled] of Object.entries(plugins2)) {
296
687
  if (!content.includes(`id: '${id}'`)) {
297
688
  throw new Error(`applyPlugins: plugin id "${id}" n\xE3o encontrado em "${registryPath}".`);
298
689
  }
@@ -306,18 +697,11 @@ async function applyPlugins(plugins, registryPath, fsModule = nodeFsPromises4) {
306
697
 
307
698
  // src/transforms/applyIndexHtml.ts
308
699
  import * as nodeFsPromises5 from "fs/promises";
309
- function fontToGoogleSlug2(font) {
310
- return font.replace(/ /g, "+");
311
- }
312
700
  async function applyIndexHtml(data, htmlPath, fsModule = nodeFsPromises5) {
313
701
  let html = await fsModule.readFile(htmlPath, "utf-8");
314
- const slug = fontToGoogleSlug2(data.fontFamily);
315
702
  html = html.replace(
316
703
  /<link\s[^>]*fonts\.googleapis\.com\/css2[^>]*(?:\s*\/>|>[^<]*<\/link>)/s,
317
- `<link
318
- href="https://fonts.googleapis.com/css2?family=${slug}:wght@300;400;500;600;700&display=swap"
319
- rel="stylesheet"
320
- />`
704
+ () => fontLinkTag([data.fontFamily, data.fontMono ?? ""])
321
705
  );
322
706
  html = html.replace(
323
707
  /(<meta\s+name="theme-color"\s+content=")[^"]*(")/,
@@ -453,9 +837,10 @@ function rubricaConfigInput(identity, fontSans, fontMono) {
453
837
  fontMono
454
838
  };
455
839
  }
456
- function indexHtmlInput(identity, fontSans) {
840
+ function indexHtmlInput(identity, fontSans, fontMono = "") {
457
841
  return {
458
842
  fontFamily: fontSans,
843
+ fontMono,
459
844
  themeColor: "",
460
845
  siteName: identity.siteName,
461
846
  siteUrl: identity.siteUrl,
@@ -464,30 +849,676 @@ function indexHtmlInput(identity, fontSans) {
464
849
  };
465
850
  }
466
851
 
467
- // src/commands/create.ts
468
- var TEMPLATE_FONTS = {
469
- cyberpunk: { fontSans: "Chakra Petch", fontMono: "JetBrains Mono" },
470
- magazine: { fontSans: ["Bodoni Moda", "IBM Plex Serif"], fontMono: "JetBrains Mono" },
471
- bento: { fontSans: "Manrope", fontMono: "JetBrains Mono" },
472
- brutalist: { fontSans: "JetBrains Mono", fontMono: "JetBrains Mono" },
473
- swiss: { fontSans: "Archivo", fontMono: "" }
474
- };
475
- var ALL_PLUGINS = [
476
- "contact-wizard",
477
- "proposals",
478
- "payments",
479
- "blog",
480
- "portfolio",
481
- "resume",
482
- "about",
483
- "ai-resumes",
484
- "audit-log",
485
- "media-manager",
486
- "i18n",
487
- "playground",
488
- "testimonials",
489
- "testimonials-intake"
852
+ // src/transforms/applyAppearance.ts
853
+ import * as nodeFsPromises9 from "fs/promises";
854
+ function setAttr(tag, name, value) {
855
+ const re = new RegExp(`\\s${name}="[^"]*"`);
856
+ return re.test(tag) ? tag.replace(re, ` ${name}="${value}"`) : tag.replace(/>$/, ` ${name}="${value}">`);
857
+ }
858
+ async function applyAppearance(appearance, htmlPath, fsModule = nodeFsPromises9) {
859
+ const html = await fsModule.readFile(htmlPath, "utf-8");
860
+ const updated = html.replace(/<html\b[^>]*>/, (tag) => {
861
+ let t = setAttr(tag, "data-color-mode", appearance.colorMode);
862
+ t = setAttr(t, "data-color-toggle", String(appearance.colorModeToggle));
863
+ t = setAttr(t, "data-texture", appearance.texture);
864
+ const darkClass = appearance.colorMode === "light" ? "" : "dark";
865
+ if (/\sclass="[^"]*"/.test(t)) {
866
+ t = t.replace(/\sclass="([^"]*)"/, (_m, cls) => {
867
+ const rest = cls.split(/\s+/).filter((c) => c && c !== "dark");
868
+ const all = darkClass ? [...rest, darkClass] : rest;
869
+ return all.length ? ` class="${all.join(" ")}"` : "";
870
+ });
871
+ } else if (darkClass) {
872
+ t = t.replace(/^<html/, `<html class="${darkClass}"`);
873
+ }
874
+ return t;
875
+ });
876
+ await fsModule.writeFile(htmlPath, updated);
877
+ }
878
+
879
+ // src/prompts/appearancePrompt.ts
880
+ import { select as select2, confirm, isCancel as isCancel2 } from "@clack/prompts";
881
+ async function layoutPrompt(initialValue) {
882
+ return await select2({
883
+ message: "Layout",
884
+ initialValue,
885
+ options: LAYOUTS.map((l) => ({ value: l.id, label: l.label, hint: l.hint }))
886
+ });
887
+ }
888
+ async function schemePrompt(layoutId, initialValue) {
889
+ const recommended = getLayout(layoutId)?.recommended.scheme;
890
+ return await select2({
891
+ message: "Esquema de cores",
892
+ initialValue: initialValue ?? recommended,
893
+ options: SCHEMES.map((s) => ({
894
+ value: s.id,
895
+ label: s.label,
896
+ hint: s.id === recommended ? `recomendado para este layout \u2014 ${s.hint}` : s.hint
897
+ }))
898
+ });
899
+ }
900
+ async function appearancePrompt(layoutId, current) {
901
+ const rec = getLayout(layoutId)?.recommended;
902
+ const colorMode = await select2({
903
+ message: "Modo de cor",
904
+ initialValue: current?.colorMode ?? rec?.mode ?? "dark",
905
+ options: COLOR_MODES.map((m) => ({
906
+ value: m.value,
907
+ label: m.label,
908
+ hint: m.value === rec?.mode ? `recomendado \u2014 ${m.hint}` : m.hint
909
+ }))
910
+ });
911
+ const toggle = await confirm({
912
+ message: "Mostrar um bot\xE3o para quem visita alternar entre claro e escuro?",
913
+ initialValue: current?.colorModeToggle ?? true
914
+ });
915
+ const colorModeToggle = !isCancel2(toggle) && toggle === true;
916
+ const texture = await select2({
917
+ message: "Textura",
918
+ initialValue: current?.texture ?? rec?.texture ?? "none",
919
+ options: TEXTURES.map((t) => ({
920
+ value: t.value,
921
+ label: t.label,
922
+ hint: t.value === rec?.texture ? `recomendada \u2014 ${t.hint}` : t.hint
923
+ }))
924
+ });
925
+ return { colorMode, colorModeToggle, texture };
926
+ }
927
+ async function fontPrompts(layoutId, current) {
928
+ const rec = getLayout(layoutId)?.fonts ?? { sans: [], mono: "JetBrains Mono" };
929
+ const fontSans = await select2({
930
+ message: "Fonte principal",
931
+ initialValue: current?.fontSans,
932
+ options: SANS_FONTS.map((f) => ({
933
+ value: f.family,
934
+ label: f.family,
935
+ hint: rec.sans.includes(f.family) ? "recomendada" : f.hint
936
+ }))
937
+ });
938
+ const fontMono = rec.mono === "" ? "" : await select2({
939
+ message: "Fonte mono",
940
+ initialValue: current?.fontMono,
941
+ options: MONO_FONTS.map((f) => ({
942
+ value: f.family,
943
+ label: f.family,
944
+ hint: f.family === rec.mono ? "recomendada" : f.hint
945
+ }))
946
+ });
947
+ return { fontSans, fontMono };
948
+ }
949
+
950
+ // src/prompts/pluginsPrompt.ts
951
+ import { select as select3, multiselect, isCancel as isCancel3, cancel as cancel2 } from "@clack/prompts";
952
+
953
+ // src/plugins.ts
954
+ var PLUGINS = [
955
+ { id: "contact-wizard", label: "Contato", description: "formul\xE1rio para pedirem or\xE7amento", recommended: true, needsKey: false },
956
+ { id: "proposals", label: "Propostas", description: "propostas comerciais com aceite online", recommended: true, needsKey: false },
957
+ { id: "payments", label: "Pagamentos", description: "cobran\xE7a por PIX, boleto e cart\xE3o (conta no Asaas)", recommended: false, needsKey: true },
958
+ { id: "blog", label: "Blog", description: "posts e artigos", recommended: true, needsKey: false },
959
+ { id: "portfolio", label: "Portf\xF3lio", description: "galeria de projetos e cases", recommended: true, needsKey: false },
960
+ { id: "resume", label: "Curr\xEDculo", description: "curr\xEDculo com download em PDF", recommended: true, needsKey: false },
961
+ { id: "about", label: "Sobre", description: "p\xE1gina sobre voc\xEA", recommended: true, needsKey: false },
962
+ { id: "ai-resumes", label: "Curr\xEDculo com IA", description: "gera vers\xF5es do curr\xEDculo por vaga (chave do OpenRouter)", recommended: false, needsKey: true },
963
+ { id: "audit-log", label: "Hist\xF3rico do painel", description: "registra quem mudou o qu\xEA no painel", recommended: true, needsKey: false },
964
+ { id: "media-manager", label: "Biblioteca de imagens", description: "gerenciador de arquivos e imagens", recommended: false, needsKey: false },
965
+ { id: "i18n", label: "Tradu\xE7\xE3o com IA", description: "traduz o conte\xFAdo do site (chave do OpenRouter)", recommended: false, needsKey: true },
966
+ { id: "playground", label: "Playground", description: "\xE1rea para testar prompts de IA (chave do OpenRouter)", recommended: false, needsKey: true },
967
+ { id: "testimonials", label: "Depoimentos", description: "depoimentos de clientes no site", recommended: true, needsKey: false },
968
+ { id: "testimonials-intake", label: "Coleta de depoimentos", description: "link para clientes enviarem depoimentos", recommended: true, needsKey: false }
490
969
  ];
970
+ var ALL_PLUGINS = PLUGINS.map((p) => p.id);
971
+ var PLUGIN_PRESETS = [
972
+ {
973
+ id: "recommended",
974
+ label: "Completo",
975
+ hint: "portf\xF3lio, curr\xEDculo, blog, contato, propostas e depoimentos",
976
+ plugins: PLUGINS.filter((p) => p.recommended).map((p) => p.id)
977
+ },
978
+ {
979
+ id: "freelancer",
980
+ label: "Para vender servi\xE7os",
981
+ hint: "portf\xF3lio, contato, propostas e depoimentos",
982
+ plugins: ["contact-wizard", "proposals", "portfolio", "about", "testimonials", "testimonials-intake"]
983
+ },
984
+ {
985
+ id: "simple",
986
+ label: "S\xF3 o portf\xF3lio",
987
+ hint: "portf\xF3lio, curr\xEDculo, sobre e contato",
988
+ plugins: ["contact-wizard", "portfolio", "resume", "about"]
989
+ }
990
+ ];
991
+ function pluginsRecord(selected) {
992
+ return Object.fromEntries(ALL_PLUGINS.map((id) => [id, selected.includes(id)]));
993
+ }
994
+
995
+ // src/prompts/pluginsPrompt.ts
996
+ function assertNotCancelled2(value) {
997
+ if (isCancel3(value)) {
998
+ cancel2("Opera\xE7\xE3o cancelada.");
999
+ throw new Error("Prompt cancelado pelo usu\xE1rio.");
1000
+ }
1001
+ }
1002
+ function pluginOptions() {
1003
+ return PLUGINS.map((p) => ({ value: p.id, label: `${p.label} \u2014 ${p.description}` }));
1004
+ }
1005
+ async function pluginMultiselect(initialValues) {
1006
+ const chosen = await multiselect({
1007
+ message: "O que o site vai ter? (espa\xE7o marca/desmarca, Enter confirma)",
1008
+ initialValues,
1009
+ required: false,
1010
+ options: pluginOptions()
1011
+ });
1012
+ assertNotCancelled2(chosen);
1013
+ return chosen;
1014
+ }
1015
+ async function pluginsPrompt() {
1016
+ const choice = await select3({
1017
+ message: "O que o site vai ter?",
1018
+ initialValue: PLUGIN_PRESETS[0].id,
1019
+ options: [
1020
+ ...PLUGIN_PRESETS.map((p) => ({ value: p.id, label: p.label, hint: p.hint })),
1021
+ { value: "custom", label: "Escolher um por um" }
1022
+ ]
1023
+ });
1024
+ assertNotCancelled2(choice);
1025
+ const preset = PLUGIN_PRESETS.find((p) => p.id === choice);
1026
+ if (preset) return preset.plugins;
1027
+ return pluginMultiselect(PLUGINS.filter((p) => p.recommended).map((p) => p.id));
1028
+ }
1029
+
1030
+ // src/utils/packageManager.ts
1031
+ function packageManagerFromUserAgent(userAgent) {
1032
+ return userAgent?.startsWith("pnpm/") ? "pnpm" : "npm";
1033
+ }
1034
+
1035
+ // src/recipe.ts
1036
+ var RECIPE_VERSION = 1;
1037
+ var KEYS = {
1038
+ layout: "l",
1039
+ scheme: "s",
1040
+ colorMode: "m",
1041
+ colorModeToggle: "a",
1042
+ texture: "t",
1043
+ fontSans: "f",
1044
+ fontMono: "fm",
1045
+ plugins: "p",
1046
+ identity: "i"
1047
+ };
1048
+ var IDENTITY_KEYS = {
1049
+ authorName: "n",
1050
+ siteName: "sn",
1051
+ siteUrl: "u",
1052
+ siteDescription: "d",
1053
+ authorEmail: "e",
1054
+ twitterHandle: "x",
1055
+ lang: "lg",
1056
+ profession: "pf",
1057
+ specialties: "es"
1058
+ };
1059
+ var LANGS = ["pt-BR", "en-US"];
1060
+ function fromBase64Url(code) {
1061
+ const b64 = code.replace(/-/g, "+").replace(/_/g, "/");
1062
+ const binary = atob(b64 + "=".repeat((4 - b64.length % 4) % 4));
1063
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
1064
+ }
1065
+ var INVALID = "Essa receita n\xE3o \xE9 v\xE1lida. Copie o comando de novo no site do Rubrica.";
1066
+ function decodeRecipe(code) {
1067
+ let data;
1068
+ try {
1069
+ const trimmed = code.trim();
1070
+ if (!trimmed) throw new Error("vazio");
1071
+ data = JSON.parse(fromBase64Url(trimmed));
1072
+ } catch {
1073
+ throw new Error(INVALID);
1074
+ }
1075
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error(INVALID);
1076
+ const raw = data;
1077
+ const expanded = {};
1078
+ for (const [long, short] of Object.entries(KEYS)) {
1079
+ if (raw[short] !== void 0) expanded[long] = raw[short];
1080
+ }
1081
+ const rawId = raw[KEYS.identity];
1082
+ if (rawId && typeof rawId === "object" && !Array.isArray(rawId)) {
1083
+ const id = {};
1084
+ for (const [long, short] of Object.entries(IDENTITY_KEYS)) {
1085
+ const value = rawId[short];
1086
+ if (value !== void 0) id[long] = value;
1087
+ }
1088
+ expanded.identity = id;
1089
+ }
1090
+ const result = sanitizeRecipe(expanded);
1091
+ if (typeof raw.v === "number" && raw.v > RECIPE_VERSION) {
1092
+ result.warnings.unshift(
1093
+ "Essa receita \xE9 de uma vers\xE3o mais nova do Rubrica. Rode com `npx create-rubrica@latest` para aproveitar tudo."
1094
+ );
1095
+ }
1096
+ return result;
1097
+ }
1098
+ function sanitizeRecipe(input) {
1099
+ const recipe = {};
1100
+ const warnings = [];
1101
+ const str = (v) => typeof v === "string";
1102
+ const pick = (key2, valid, what) => {
1103
+ const value = input[key2];
1104
+ if (!str(value)) return;
1105
+ if (valid(value)) recipe[key2] = value;
1106
+ else warnings.push(`${what} "${value}" n\xE3o existe nesta vers\xE3o; vou perguntar.`);
1107
+ };
1108
+ pick("layout", (v) => LAYOUTS.some((l) => l.id === v), "Layout");
1109
+ pick("scheme", (v) => SCHEMES.some((s) => s.id === v), "Esquema de cores");
1110
+ pick("colorMode", (v) => COLOR_MODES.some((m) => m.value === v), "Modo de cor");
1111
+ pick("texture", (v) => TEXTURES.some((t) => t.value === v), "Textura");
1112
+ pick("fontSans", (v) => SANS_FONTS.some((f) => f.family === v), "Fonte");
1113
+ pick("fontMono", (v) => v === "" || MONO_FONTS.some((f) => f.family === v), "Fonte mono");
1114
+ if (typeof input.colorModeToggle === "boolean") recipe.colorModeToggle = input.colorModeToggle;
1115
+ if (Array.isArray(input.plugins)) {
1116
+ recipe.plugins = [];
1117
+ for (const id of input.plugins) {
1118
+ if (str(id) && PLUGINS.some((p) => p.id === id)) recipe.plugins.push(id);
1119
+ else warnings.push(`Plugin "${String(id)}" n\xE3o existe nesta vers\xE3o; ficou de fora.`);
1120
+ }
1121
+ }
1122
+ const rawId = input.identity;
1123
+ if (rawId && typeof rawId === "object" && !Array.isArray(rawId)) {
1124
+ const id = rawId;
1125
+ const identity = {};
1126
+ for (const key2 of ["authorName", "siteName", "siteDescription", "profession", "specialties"]) {
1127
+ if (str(id[key2]) && id[key2].trim()) identity[key2] = id[key2].trim();
1128
+ }
1129
+ if (str(id.siteUrl) && id.siteUrl.trim()) {
1130
+ if (validateUrl(id.siteUrl)) warnings.push(`Endere\xE7o "${id.siteUrl}" n\xE3o parece v\xE1lido; vou perguntar.`);
1131
+ else identity.siteUrl = normalizeUrl(id.siteUrl);
1132
+ }
1133
+ if (str(id.authorEmail) && id.authorEmail.trim()) {
1134
+ if (validateEmail(id.authorEmail)) warnings.push(`E-mail "${id.authorEmail}" n\xE3o parece v\xE1lido; vou perguntar.`);
1135
+ else identity.authorEmail = normalizeEmail(id.authorEmail);
1136
+ }
1137
+ if (str(id.twitterHandle) && normalizeHandle(id.twitterHandle)) identity.twitterHandle = normalizeHandle(id.twitterHandle);
1138
+ if (str(id.lang)) {
1139
+ if (LANGS.includes(id.lang)) identity.lang = id.lang;
1140
+ else warnings.push(`Idioma "${id.lang}" n\xE3o \xE9 suportado; vou usar pt-BR.`);
1141
+ }
1142
+ if (Object.keys(identity).length) recipe.identity = identity;
1143
+ }
1144
+ return { recipe, warnings };
1145
+ }
1146
+ function recipeSummary(recipe) {
1147
+ const lines = [];
1148
+ if (recipe.layout) lines.push(`Layout: ${getLayout(recipe.layout)?.label ?? recipe.layout}`);
1149
+ const colors = [];
1150
+ if (recipe.scheme) colors.push(SCHEMES.find((s) => s.id === recipe.scheme)?.label ?? recipe.scheme);
1151
+ if (recipe.colorMode) {
1152
+ const mode2 = COLOR_MODES.find((m) => m.value === recipe.colorMode)?.label ?? recipe.colorMode;
1153
+ colors.push(`modo ${mode2.toLowerCase()}`);
1154
+ }
1155
+ if (recipe.colorModeToggle !== void 0) colors.push(recipe.colorModeToggle ? "com bot\xE3o para alternar" : "sem bot\xE3o para alternar");
1156
+ if (colors.length) lines.push(`Cores: ${colors.join(", ")}`);
1157
+ if (recipe.texture) lines.push(`Textura: ${TEXTURES.find((t) => t.value === recipe.texture)?.label ?? recipe.texture}`);
1158
+ if (recipe.fontSans) lines.push(`Fontes: ${[recipe.fontSans, recipe.fontMono].filter(Boolean).join(" e ")}`);
1159
+ if (recipe.plugins) {
1160
+ const names = recipe.plugins.map((id2) => PLUGINS.find((p) => p.id === id2)?.label ?? id2);
1161
+ lines.push(`Plugins: ${names.length ? names.join(", ") : "nenhum"}`);
1162
+ }
1163
+ const id = recipe.identity ?? {};
1164
+ if (id.authorName) lines.push(`Nome: ${id.authorName}`);
1165
+ const site = [id.siteName, id.siteUrl].filter(Boolean).join(" \u2014 ");
1166
+ if (site) lines.push(`Site: ${site}`);
1167
+ if (id.authorEmail) lines.push(`E-mail: ${id.authorEmail}`);
1168
+ if (id.profession) lines.push(`Profiss\xE3o: ${id.profession}${id.specialties ? ` (${id.specialties})` : ""}`);
1169
+ return lines;
1170
+ }
1171
+
1172
+ // src/commands/setup.ts
1173
+ import { outro, text as text2, password, confirm as confirm2, spinner, isCancel as isCancel4, cancel as cancel3, log } from "@clack/prompts";
1174
+ import * as nodeFsPromises11 from "fs/promises";
1175
+ import * as path6 from "path";
1176
+ import * as nodeCrypto from "crypto";
1177
+ import { execFileSync as defaultExecFileSync } from "child_process";
1178
+
1179
+ // src/utils/detectProject.ts
1180
+ import * as nodeFsPromises10 from "fs/promises";
1181
+ import * as path5 from "path";
1182
+ async function detectProject(startDir, fsModule = nodeFsPromises10) {
1183
+ let current = startDir;
1184
+ while (true) {
1185
+ const candidate = path5.join(current, "rubrica.json");
1186
+ try {
1187
+ await fsModule.access(candidate);
1188
+ return candidate;
1189
+ } catch {
1190
+ const parent = path5.dirname(current);
1191
+ if (parent === current) {
1192
+ throw new Error(
1193
+ `detectProject: nenhum rubrica.json encontrado em "${startDir}" nem em nenhum diret\xF3rio ancestral.`
1194
+ );
1195
+ }
1196
+ current = parent;
1197
+ }
1198
+ }
1199
+ }
1200
+
1201
+ // src/utils/generateJwtKeys.ts
1202
+ import { generateKeyPair, exportPKCS8, exportJWK } from "jose";
1203
+ async function generateJwtKeys() {
1204
+ const { privateKey, publicKey } = await generateKeyPair("RS256", { extractable: true });
1205
+ const JWT_PRIVATE_KEY = await exportPKCS8(privateKey);
1206
+ const jwk = await exportJWK(publicKey);
1207
+ const JWKS = JSON.stringify({ keys: [{ use: "sig", ...jwk }] });
1208
+ return { JWT_PRIVATE_KEY, JWKS };
1209
+ }
1210
+
1211
+ // src/utils/password.ts
1212
+ function validatePassword(password3) {
1213
+ if (password3.length < 12) return "A senha precisa ter pelo menos 12 caracteres";
1214
+ if (!/[A-Z]/.test(password3)) return "Inclua ao menos uma letra mai\xFAscula";
1215
+ if (!/[a-z]/.test(password3)) return "Inclua ao menos uma letra min\xFAscula";
1216
+ if (!/[0-9]/.test(password3)) return "Inclua ao menos um n\xFAmero";
1217
+ return void 0;
1218
+ }
1219
+
1220
+ // src/commands/setup.ts
1221
+ function parseEnvFile(content) {
1222
+ const result = {};
1223
+ for (const line of content.split("\n")) {
1224
+ const trimmed = line.trim();
1225
+ if (!trimmed || trimmed.startsWith("#")) continue;
1226
+ const eqIdx = trimmed.indexOf("=");
1227
+ if (eqIdx === -1) continue;
1228
+ const key2 = trimmed.slice(0, eqIdx).trim();
1229
+ const value = trimmed.slice(eqIdx + 1).trim();
1230
+ result[key2] = value;
1231
+ }
1232
+ return result;
1233
+ }
1234
+ async function runSetup(deps = {}) {
1235
+ const cwd = deps.cwd ?? process.cwd();
1236
+ const fs3 = deps.fs ?? {
1237
+ access: (p) => nodeFsPromises11.access(p).then(() => void 0),
1238
+ readFile: (p, enc) => nodeFsPromises11.readFile(p, enc),
1239
+ writeFile: (p, data) => nodeFsPromises11.writeFile(p, data).then(() => void 0),
1240
+ mkdir: (p, opts) => nodeFsPromises11.mkdir(p, opts).then(() => void 0)
1241
+ };
1242
+ const detectProject2 = deps.detectProject ?? detectProject;
1243
+ const generateJwtKeys2 = deps.generateJwtKeys ?? generateJwtKeys;
1244
+ const readState2 = deps.readState ?? readState;
1245
+ const randomBytes2 = deps.randomBytes ?? ((size) => nodeCrypto.randomBytes(size));
1246
+ const execFileSync = deps.execFileSync ?? ((file, args, opts) => defaultExecFileSync(file, args, opts));
1247
+ try {
1248
+ await detectProject2(cwd);
1249
+ } catch (err) {
1250
+ cancel3(err.message);
1251
+ return;
1252
+ }
1253
+ const convex = (...args) => execFileSync("npx", ["convex", ...args], { stdio: "pipe", cwd });
1254
+ const setEnv = (key2, value) => convex("env", "set", "--", key2, value);
1255
+ const envPath = path6.join(cwd, ".env.local");
1256
+ const readEnv = async () => parseEnvFile(await fs3.readFile(envPath, "utf-8"));
1257
+ let envVars = {};
1258
+ try {
1259
+ envVars = await readEnv();
1260
+ } catch {
1261
+ log.info("Conectando o projeto ao Convex (o backend do site). Se pedir, fa\xE7a login no navegador.");
1262
+ try {
1263
+ const args = ["convex", "dev", "--once"];
1264
+ if (deps.newProject) {
1265
+ args.push("--configure", "new", "--project", deps.newProject, "--dev-deployment", "cloud");
1266
+ const convexJson = path6.join(cwd, "convex.json");
1267
+ const exists = await fs3.access(convexJson).then(() => true, () => false);
1268
+ if (!exists) await fs3.writeFile(convexJson, JSON.stringify({ aiFiles: { enabled: false } }, null, 2) + "\n");
1269
+ }
1270
+ execFileSync("npx", args, { stdio: "inherit", cwd });
1271
+ envVars = await readEnv();
1272
+ } catch {
1273
+ cancel3(
1274
+ "N\xE3o deu para conectar ao Convex. Quando quiser tentar de novo, rode: " + (deps.newProject ? `cd ${deps.newProject} && npx create-rubrica setup` : "npx create-rubrica setup (nesta pasta)")
1275
+ );
1276
+ return;
1277
+ }
1278
+ }
1279
+ if (!envVars["VITE_CONVEX_URL"]) {
1280
+ cancel3(
1281
+ "VITE_CONVEX_URL n\xE3o encontrado no .env.local. Rode npx convex dev primeiro."
1282
+ );
1283
+ return;
1284
+ }
1285
+ if (!envVars["VITE_CONVEX_SITE_URL"]) {
1286
+ cancel3(
1287
+ "VITE_CONVEX_SITE_URL n\xE3o encontrado no .env.local. Rode npx convex dev primeiro."
1288
+ );
1289
+ return;
1290
+ }
1291
+ const convexSiteUrl = envVars["VITE_CONVEX_SITE_URL"];
1292
+ const state = await readState2(cwd, fs3);
1293
+ const plugins2 = state.plugins;
1294
+ const identity = state.identity ?? {};
1295
+ const s = spinner();
1296
+ s.start("Gerando chaves JWT (RS256)...");
1297
+ const { JWT_PRIVATE_KEY, JWKS } = await generateJwtKeys2();
1298
+ s.stop("Chaves JWT geradas.");
1299
+ setEnv("JWT_PRIVATE_KEY", JWT_PRIVATE_KEY);
1300
+ setEnv("JWKS", JWKS);
1301
+ let siteUrl = normalizeUrl(identity.siteUrl ?? "");
1302
+ if (siteUrl) {
1303
+ log.info(`Endere\xE7o do site: ${siteUrl} (para mudar: npx create-rubrica config)`);
1304
+ } else {
1305
+ const answer = await text2({
1306
+ message: "Endere\xE7o do site (ex: meusite.com \u2014 n\xE3o precisa do https://)",
1307
+ initialValue: "",
1308
+ validate: validateUrl
1309
+ });
1310
+ if (isCancel4(answer)) {
1311
+ cancel3("Setup cancelado.");
1312
+ return;
1313
+ }
1314
+ siteUrl = normalizeUrl(answer);
1315
+ }
1316
+ setEnv("SITE_URL", siteUrl);
1317
+ const optional = async (message, key2) => {
1318
+ const value = await text2({ message, initialValue: "" });
1319
+ if (!isCancel4(value) && value && value.trim()) setEnv(key2, value.trim());
1320
+ };
1321
+ const wants = async (message) => await confirm2({ message, initialValue: false }) === true;
1322
+ const fromSite = deps.site !== void 0;
1323
+ if (!fromSite && (plugins2["contact-wizard"] || plugins2["testimonials-intake"])) {
1324
+ if (await wants("Quer receber um aviso no Telegram a cada novo contato ou depoimento? (d\xE1 para configurar depois)")) {
1325
+ await optional("Token do bot do Telegram (quem cria \xE9 o @BotFather; Enter para pular):", "TELEGRAM_BOT_TOKEN");
1326
+ await optional("Id da conversa que recebe os avisos (Enter para pular):", "TELEGRAM_ADMIN_CHAT_ID");
1327
+ }
1328
+ }
1329
+ if (plugins2["playground"]) {
1330
+ const pepper = randomBytes2(32).toString("hex");
1331
+ setEnv("PLAYGROUND_KEY_PEPPER", pepper);
1332
+ }
1333
+ if (plugins2["ai-resumes"] || plugins2["i18n"] || plugins2["playground"]) {
1334
+ await optional("Chave do OpenRouter, usada nos recursos de IA (openrouter.ai/keys; Enter para pular):", "OPENROUTER_API_KEY");
1335
+ }
1336
+ if (plugins2["payments"]) {
1337
+ const asaasKey = await text2({
1338
+ message: "Chave da API do Asaas, de testes ou de produ\xE7\xE3o (Enter para pular):",
1339
+ initialValue: ""
1340
+ });
1341
+ if (!isCancel4(asaasKey) && asaasKey && asaasKey.trim()) {
1342
+ const key2 = asaasKey.trim();
1343
+ setEnv("ASAAS_API_KEY", key2);
1344
+ const webhookToken = randomBytes2(32).toString("hex");
1345
+ setEnv("ASAAS_WEBHOOK_TOKEN", webhookToken);
1346
+ const env = key2.startsWith("$aact_prod_") ? "produ\xE7\xE3o" : "sandbox (testes)";
1347
+ log.info(
1348
+ `Asaas configurado em ${env}. Falta cadastrar o webhook no painel do Asaas
1349
+ (Integra\xE7\xF5es \u2192 Webhooks \u2192 Adicionar), com os eventos de cobran\xE7a ligados:
1350
+
1351
+ URL: ${convexSiteUrl.replace(/\/+$/, "")}/webhooks/asaas
1352
+ Token: ${webhookToken}
1353
+
1354
+ Sem o webhook, os pagamentos nunca aparecem como pagos.`
1355
+ );
1356
+ }
1357
+ }
1358
+ const savedEmail = normalizeEmail(identity.authorEmail ?? "");
1359
+ let adminExists = false;
1360
+ try {
1361
+ adminExists = execFileSync("npx", ["convex", "run", "users:isSetupRequired"], { stdio: "pipe", cwd }).toString().trim() === "false";
1362
+ } catch {
1363
+ }
1364
+ let adminEmail = savedEmail;
1365
+ if (adminExists) {
1366
+ log.info("O painel j\xE1 tem um admin; o login continua o mesmo. Para trocar a senha: npx create-rubrica senha");
1367
+ } else {
1368
+ if (fromSite && savedEmail && !validateEmail(savedEmail)) {
1369
+ log.info(`Login do painel: ${adminEmail}. Agora escolha a senha.`);
1370
+ } else {
1371
+ const adminEmailAnswer = await text2({
1372
+ message: "E-mail para entrar no painel admin:",
1373
+ initialValue: savedEmail,
1374
+ validate: validateEmail
1375
+ });
1376
+ if (isCancel4(adminEmailAnswer)) {
1377
+ cancel3("Setup cancelado.");
1378
+ return;
1379
+ }
1380
+ adminEmail = normalizeEmail(adminEmailAnswer);
1381
+ }
1382
+ const adminPassword = await password({
1383
+ message: "Senha do painel admin (12 ou mais caracteres, com mai\xFAscula, min\xFAscula e n\xFAmero):",
1384
+ validate: validatePassword
1385
+ });
1386
+ if (isCancel4(adminPassword)) {
1387
+ cancel3("Setup cancelado.");
1388
+ return;
1389
+ }
1390
+ const adminPasswordConfirm = await password({
1391
+ message: "Confirme a senha:",
1392
+ validate: (v) => {
1393
+ if (v !== adminPassword) return "As senhas n\xE3o coincidem";
1394
+ }
1395
+ });
1396
+ if (isCancel4(adminPasswordConfirm)) {
1397
+ cancel3("Setup cancelado.");
1398
+ return;
1399
+ }
1400
+ try {
1401
+ execFileSync(
1402
+ "npx",
1403
+ ["convex", "run", "seed:setupAdmin", JSON.stringify({ email: adminEmail, password: adminPassword })],
1404
+ { stdio: "pipe", cwd }
1405
+ );
1406
+ } catch (err) {
1407
+ const e = err;
1408
+ const output = e.stdout?.toString() || e.stderr?.toString() || e.message || "";
1409
+ if (output.includes("Root user already exists")) {
1410
+ log.warn("O painel j\xE1 tinha um admin; o login continua o mesmo. Para trocar a senha: npx create-rubrica senha");
1411
+ } else {
1412
+ cancel3(`Erro ao criar usu\xE1rio root: ${output || String(err)}`);
1413
+ return;
1414
+ }
1415
+ }
1416
+ }
1417
+ const enabledPlugins = Object.entries(plugins2).filter(([, on]) => on).map(([id]) => id);
1418
+ try {
1419
+ execFileSync(
1420
+ "npx",
1421
+ ["convex", "run", "seed:seedAll", JSON.stringify({ enabledPlugins })],
1422
+ { stdio: "pipe", cwd }
1423
+ );
1424
+ } catch (err) {
1425
+ const output = err.stdout?.toString() || err.stderr?.toString() || err.message;
1426
+ log.warn(`seedAll falhou: ${output.trim() || "erro desconhecido"} \u2014 rode 'npx convex run seed:seedAll "{...}"' manualmente depois.`);
1427
+ }
1428
+ if (identity.siteName) {
1429
+ try {
1430
+ execFileSync(
1431
+ "npx",
1432
+ ["convex", "run", "siteConfig:setBatchInternal", JSON.stringify({
1433
+ items: [
1434
+ { key: "site_title", value: identity.siteName },
1435
+ { key: "site_name", value: identity.siteName },
1436
+ { key: "site_url", value: siteUrl },
1437
+ { key: "site_description", value: identity.siteDescription || "" },
1438
+ { key: "author_name", value: identity.authorName || "" },
1439
+ { key: "author_email", value: identity.authorEmail || "" },
1440
+ { key: "twitter_handle", value: identity.twitterHandle || "" },
1441
+ { key: "lang", value: identity.lang || "pt-BR" }
1442
+ ]
1443
+ })],
1444
+ { stdio: "pipe", cwd }
1445
+ );
1446
+ } catch {
1447
+ }
1448
+ if (identity.authorName) {
1449
+ try {
1450
+ execFileSync(
1451
+ "npx",
1452
+ ["convex", "run", "contactInfo:updateInternal", JSON.stringify({
1453
+ name: identity.authorName,
1454
+ email: identity.authorEmail || "",
1455
+ showEmail: false
1456
+ })],
1457
+ { stdio: "pipe", cwd }
1458
+ );
1459
+ } catch {
1460
+ }
1461
+ }
1462
+ }
1463
+ if (!fromSite && await wants("O site vai ficar na Vercel e voc\xEA quer o bot\xE3o de publicar no painel? (d\xE1 para configurar depois)")) {
1464
+ await optional("Link do Deploy Hook da Vercel (Settings \u2192 Git \u2192 Deploy Hooks; Enter para pular):", "VERCEL_DEPLOY_HOOK_URL");
1465
+ await optional("Segredo do webhook da Vercel (Enter para pular):", "VERCEL_WEBHOOK_SECRET");
1466
+ }
1467
+ const askText = async (message, placeholder) => {
1468
+ const value = await text2({ message, placeholder, initialValue: "" });
1469
+ return isCancel4(value) ? "" : (value || "").trim();
1470
+ };
1471
+ const professionStr = fromSite ? (deps.site?.profession ?? "").trim() : await askText(
1472
+ "Qual \xE9 a sua profiss\xE3o ou \xE1rea de atua\xE7\xE3o? (aparece abaixo do seu nome no site; Enter para pular)",
1473
+ "Ex: Designer UX, Fot\xF3grafa, Advogada, Engenheira Civil..."
1474
+ );
1475
+ const specialtiesStr = fromSite ? (deps.site?.specialties ?? "").trim() : await askText(
1476
+ "Quais s\xE3o suas principais especialidades? (separadas por v\xEDrgula; a IA usa nas propostas; Enter para pular)",
1477
+ "Ex: Branding, Motion Design, Fotografia de Produto"
1478
+ );
1479
+ if (professionStr) {
1480
+ const name = identity.authorName || adminEmail.split("@")[0];
1481
+ const aiContext = specialtiesStr ? `${name} \xE9 ${professionStr} com especialidade em ${specialtiesStr}. Entrega projetos com qualidade e comprometimento.` : `${name} \xE9 ${professionStr}. Entrega projetos com qualidade e comprometimento.`;
1482
+ try {
1483
+ execFileSync(
1484
+ "npx",
1485
+ [
1486
+ "convex",
1487
+ "run",
1488
+ "contactInfo:updateInternal",
1489
+ JSON.stringify({ role: professionStr, roleTranslations: { ptBR: professionStr }, proposalAiContext: aiContext })
1490
+ ],
1491
+ { stdio: "pipe", cwd }
1492
+ );
1493
+ } catch {
1494
+ }
1495
+ }
1496
+ if (fromSite) {
1497
+ log.info(
1498
+ "Avisos no Telegram e o bot\xE3o de publicar da Vercel ficam para depois: quando quiser, rode npx create-rubrica setup nesta pasta."
1499
+ );
1500
+ }
1501
+ outro(
1502
+ `Pronto!
1503
+
1504
+ Admin: ${adminEmail || "o mesmo de antes"}
1505
+ O painel fica em /login
1506
+
1507
+ Para abrir o site:
1508
+ ${deps.nextStep ?? "pnpm dev"}`
1509
+ );
1510
+ }
1511
+
1512
+ // src/commands/create.ts
1513
+ function suggestedSiteUrl(projectName) {
1514
+ return `https://${projectName.toLowerCase().replace(/_/g, "-")}.vercel.app`;
1515
+ }
1516
+ function assertNotCancelled3(value) {
1517
+ if (isCancel5(value)) {
1518
+ cancel4("Opera\xE7\xE3o cancelada.");
1519
+ throw new Error("Prompt cancelado pelo usu\xE1rio.");
1520
+ }
1521
+ }
491
1522
  function validateProjectName(name) {
492
1523
  if (/\s/.test(name)) {
493
1524
  throw new Error(
@@ -508,10 +1539,10 @@ async function removeDir(dirPath, fs3) {
508
1539
  async function runCreate(projectName, deps) {
509
1540
  validateProjectName(projectName);
510
1541
  const fs3 = deps.fs ?? {
511
- ...nodeFsPromises9,
1542
+ ...nodeFsPromises12,
512
1543
  exists: async (p) => {
513
1544
  try {
514
- await nodeFsPromises9.access(p);
1545
+ await nodeFsPromises12.access(p);
515
1546
  return true;
516
1547
  } catch {
517
1548
  return false;
@@ -527,104 +1558,90 @@ async function runCreate(projectName, deps) {
527
1558
  const applyIndexHtmlFn = deps.applyIndexHtml ?? applyIndexHtml;
528
1559
  const applyRubricalConfigFn = deps.applyRubricalConfig ?? applyRubricalConfig;
529
1560
  const writeStateFn = deps.writeState ?? writeState;
1561
+ const applyAppearanceFn = deps.applyAppearance ?? applyAppearance;
530
1562
  const execFn = deps.exec ?? (async (cmd, cwd) => {
531
1563
  const { execSync } = await import("child_process");
532
1564
  execSync(cmd, { cwd, stdio: "inherit" });
533
1565
  });
534
1566
  const doIdentityPrompt = deps.identityPrompt ?? identityPrompt;
1567
+ const setupFn = deps.setup ?? runSetup;
1568
+ const packageManager = packageManagerFromUserAgent(deps.userAgent ?? process.env.npm_config_user_agent);
535
1569
  const projectDir = `${deps.projectsDir}/${projectName}`;
536
- const version = await getVersion();
537
- await download(projectDir, version);
538
- const layout = await select2({
539
- message: "Layout",
1570
+ const recipe = deps.recipe ?? {};
1571
+ const fromRecipe = Object.keys(recipe).length > 0;
1572
+ if (fromRecipe) {
1573
+ note(recipeSummary(recipe).join("\n"), "Escolhas que vieram do site");
1574
+ const ok = await confirm3({ message: "Criar com essas escolhas? (o que faltar eu pergunto)", initialValue: true });
1575
+ if (ok !== true) {
1576
+ cancel4("Opera\xE7\xE3o cancelada.");
1577
+ throw new Error("Prompt cancelado pelo usu\xE1rio.");
1578
+ }
1579
+ }
1580
+ const mode2 = fromRecipe ? "quick" : await select4({
1581
+ message: "Como voc\xEA quer montar o site?",
1582
+ initialValue: "quick",
540
1583
  options: [
541
- { value: "cyberpunk", label: "Cyberpunk", hint: "sidebar lateral com foto de perfil \u2014 dev, designer, freelancer" },
542
- { value: "brutalist", label: "Brutalism Terminal", hint: "identidade hacker total \u2014 monospace, sem bordas arredondadas" },
543
- { value: "swiss", label: "Swiss Grid", hint: "grid de 12 colunas, tipografia forte, design su\xED\xE7o rigoroso" },
544
- { value: "bento", label: "Bento", hint: "grid assim\xE9trico com floating dock \u2014 moderno, orientado a produto" },
545
- { value: "magazine", label: "Magazine", hint: "editorial cl\xE1ssico \xB7 display serifado \xB7 grid assim\xE9trico \xB7 \xE1reas de respiro generosas" }
1584
+ { value: "quick", label: "R\xE1pido", hint: "escolho o visual, cores e fontes v\xEAm combinadas" },
1585
+ { value: "custom", label: "Personalizado", hint: "escolho cores, modo claro/escuro, textura e fontes" }
546
1586
  ]
547
1587
  });
1588
+ assertNotCancelled3(mode2);
1589
+ const custom = mode2 === "custom";
1590
+ const version = await getVersion();
1591
+ await download(projectDir, version);
1592
+ const layout = recipe.layout ?? await layoutPrompt();
1593
+ assertNotCancelled3(layout);
548
1594
  await applyLayoutFn(
549
1595
  layout,
550
1596
  { projectDir, templatesDir: `${projectDir}/templates` },
551
1597
  fs3
552
1598
  );
553
- const themeChoice = await select2({
554
- message: "Tema visual",
555
- options: [
556
- { value: "editorial-cream", label: "Editorial Cream", hint: "refinado e atemporal \u2014 blogs e portf\xF3lios liter\xE1rios" },
557
- { value: "paper-noir", label: "Paper Noir", hint: "contraste m\xE1ximo \u2014 identidade editorial forte" },
558
- { value: "midnight-blue", label: "Midnight Blue", hint: "tech e premium \u2014 devs e designers noturnos" },
559
- { value: "solar-warm", label: "Solar Warm", hint: "energia e criatividade \u2014 marcas pessoais vibrantes" }
560
- ]
561
- });
1599
+ let themeChoice;
1600
+ let appearance;
1601
+ let fontSans;
1602
+ let fontMono;
1603
+ if (custom) {
1604
+ themeChoice = await schemePrompt(layout);
1605
+ appearance = await appearancePrompt(layout);
1606
+ ({ fontSans, fontMono } = await fontPrompts(layout));
1607
+ } else {
1608
+ const rec = recommendedAppearance(layout);
1609
+ themeChoice = recipe.scheme ?? rec.theme;
1610
+ appearance = {
1611
+ colorMode: recipe.colorMode ?? rec.colorMode,
1612
+ colorModeToggle: recipe.colorModeToggle ?? rec.colorModeToggle,
1613
+ texture: recipe.texture ?? rec.texture
1614
+ };
1615
+ fontSans = recipe.fontSans ?? rec.fontSans;
1616
+ fontMono = rec.fontMono === "" ? "" : recipe.fontMono ?? rec.fontMono;
1617
+ }
562
1618
  await applyThemeFn(
563
1619
  { preset: themeChoice },
564
1620
  `${projectDir}/src/index.css`,
565
1621
  fs3
566
1622
  );
567
- const recommendedFonts = TEMPLATE_FONTS[layout] ?? { fontSans: "", fontMono: "" };
568
- const recommendedSans = Array.isArray(recommendedFonts.fontSans) ? recommendedFonts.fontSans : [recommendedFonts.fontSans];
569
- const fontSans = await select2({
570
- message: "Fonte principal",
571
- options: [
572
- { value: "Inter", label: "Inter", hint: "neutra, leg\xEDvel, padr\xE3o de produtos digitais" },
573
- { value: "Chakra Petch", label: "Chakra Petch", hint: recommendedSans.includes("Chakra Petch") ? "recomendada" : "geom\xE9trica, tech, futurista" },
574
- { value: "Playfair Display", label: "Playfair Display", hint: "elegante, editorial cl\xE1ssico" },
575
- { value: "Space Grotesk", label: "Space Grotesk", hint: "moderna, startup" },
576
- { value: "DM Sans", label: "DM Sans", hint: "limpa, amig\xE1vel, vers\xE1til" },
577
- { value: "Bodoni Moda", label: "Bodoni Moda", hint: recommendedSans.includes("Bodoni Moda") ? "recomendada" : "display serifado elegante, editorial cl\xE1ssico" },
578
- { value: "IBM Plex Serif", label: "IBM Plex Serif", hint: recommendedSans.includes("IBM Plex Serif") ? "recomendada" : "serifa t\xE9cnica, confian\xE7a e rigor" },
579
- { value: "Manrope", label: "Manrope", hint: recommendedSans.includes("Manrope") ? "recomendada" : "geom\xE9trica humanista, moderna e acolhedora" },
580
- { value: "Archivo", label: "Archivo", hint: recommendedSans.includes("Archivo") ? "recomendada" : "grotesca utilit\xE1ria, clareza e for\xE7a tipogr\xE1fica" }
581
- ]
582
- });
583
- const fontMono = recommendedFonts.fontMono === "" ? "" : await select2({
584
- message: "Fonte mono",
585
- options: [
586
- { value: "JetBrains Mono", label: "JetBrains Mono", hint: recommendedFonts.fontMono === "JetBrains Mono" ? "recomendada" : "dev-friendly, clara" },
587
- { value: "Fira Code", label: "Fira Code", hint: "cl\xE1ssico, com ligatures" },
588
- { value: "Space Mono", label: "Space Mono", hint: "retro digital" },
589
- { value: "IBM Plex Mono", label: "IBM Plex Mono", hint: "corporativo-tech" }
590
- ]
591
- });
1623
+ await applyAppearanceFn(
1624
+ appearance,
1625
+ `${projectDir}/index.html`,
1626
+ fs3
1627
+ );
592
1628
  await applyFontFn(
593
1629
  { fontSans, fontMono },
594
1630
  { css: `${projectDir}/src/index.css`, html: `${projectDir}/index.html` },
595
1631
  fs3
596
1632
  );
597
- const selectedPlugins = await multiselect({
598
- message: "Plugins ativos",
599
- options: [
600
- { value: "contact-wizard", label: "Contact Wizard \u2014 formul\xE1rio de contato multi-etapas", hint: "recomendado" },
601
- { value: "proposals", label: "Propostas \u2014 propostas comerciais com assinatura eletr\xF4nica", hint: "recomendado" },
602
- { value: "payments", label: "Pagamentos \u2014 checkout com PIX, boleto e cart\xE3o via Asaas" },
603
- { value: "blog", label: "Blog \u2014 listagem e leitura de posts", hint: "recomendado" },
604
- { value: "portfolio", label: "Portfolio \u2014 galeria de projetos", hint: "recomendado" },
605
- { value: "resume", label: "Curr\xEDculo \u2014 curr\xEDculo interativo com download de PDF", hint: "recomendado" },
606
- { value: "about", label: "Sobre \u2014 p\xE1gina sobre mim", hint: "recomendado" },
607
- { value: "ai-resumes", label: "CV com IA \u2014 gera\xE7\xE3o de curr\xEDculo customizado por IA" },
608
- { value: "audit-log", label: "Audit Log \u2014 log de auditoria do painel admin", hint: "recomendado" },
609
- { value: "media-manager", label: "Media Manager \u2014 gerenciador de arquivos e imagens" },
610
- { value: "i18n", label: "Tradu\xE7\xE3o IA \u2014 internacionaliza\xE7\xE3o autom\xE1tica de conte\xFAdo" },
611
- { value: "playground", label: "Playground \u2014 ambiente de testes interativo" },
612
- { value: "testimonials", label: "Depoimentos \u2014 se\xE7\xE3o de testimoniais de clientes", hint: "recomendado" },
613
- { value: "testimonials-intake", label: "Coleta de Depoimentos \u2014 formul\xE1rio p\xFAblico para coleta", hint: "recomendado" }
614
- ],
615
- required: false
616
- });
617
- const pluginsRecord = Object.fromEntries(
618
- ALL_PLUGINS.map((id) => [id, selectedPlugins.includes(id)])
619
- );
1633
+ const plugins2 = pluginsRecord(recipe.plugins ?? await pluginsPrompt());
620
1634
  await applyPluginsFn(
621
- pluginsRecord,
1635
+ plugins2,
622
1636
  `${projectDir}/convex/pluginRegistry.ts`,
623
1637
  fs3
624
1638
  );
625
- const identity = await doIdentityPrompt();
1639
+ const identity = await doIdentityPrompt(
1640
+ { siteUrl: suggestedSiteUrl(projectName), ...recipe.identity },
1641
+ fromRecipe ? { askLang: false, onlyMissing: true } : { askLang: custom }
1642
+ );
626
1643
  await applyIndexHtmlFn(
627
- indexHtmlInput(identity, fontSans),
1644
+ indexHtmlInput(identity, fontSans, fontMono),
628
1645
  `${projectDir}/index.html`,
629
1646
  fs3
630
1647
  );
@@ -645,9 +1662,10 @@ async function runCreate(projectName, deps) {
645
1662
  version: version.replace(/^v/, ""),
646
1663
  layout,
647
1664
  theme: themeChoice,
1665
+ ...appearance,
648
1666
  fontSans,
649
1667
  fontMono,
650
- plugins: pluginsRecord,
1668
+ plugins: plugins2,
651
1669
  identity: {
652
1670
  siteName: identity.siteName,
653
1671
  siteUrl: identity.siteUrl,
@@ -660,73 +1678,53 @@ async function runCreate(projectName, deps) {
660
1678
  },
661
1679
  fs3
662
1680
  );
663
- const doGitInit = await confirm({ message: "Inicializar reposit\xF3rio git?" });
664
- const packageManager = await select2({
665
- message: "Gerenciador de pacotes",
666
- options: [
667
- { value: "pnpm", label: "pnpm (recomendado)" },
668
- { value: "npm", label: "npm" },
669
- { value: "none", label: "N\xE3o agora" }
670
- ]
671
- });
672
- if (doGitInit) {
1681
+ try {
673
1682
  await execFn("git init", projectDir);
1683
+ } catch {
1684
+ log2.warn("N\xE3o deu para iniciar o git (ele est\xE1 instalado?). O projeto funciona sem; d\xE1 para rodar `git init` depois.");
674
1685
  }
675
- if (packageManager !== "none") {
676
- await execFn(`${packageManager} install`, projectDir);
677
- }
1686
+ await execFn(`${packageManager} install`, projectDir);
678
1687
  await removeDir(`${projectDir}/templates`, fs3);
679
1688
  await removeDir(`${projectDir}/cli`, fs3);
680
- const installStep = packageManager === "none" ? "pnpm install\n " : "";
681
- outro(
682
- `Projeto criado com sucesso!
1689
+ await removeDir(`${projectDir}/site`, fs3);
1690
+ const devCommand = `${packageManager} run dev`;
1691
+ const nextStep = `cd ${projectName} && ${devCommand}`;
1692
+ const setupNow = fromRecipe ? true : await confirm3({
1693
+ message: "Configurar o painel admin agora? Abre o login do Convex no navegador (conta gratuita).",
1694
+ initialValue: true
1695
+ });
1696
+ if (setupNow === true) {
1697
+ await setupFn({
1698
+ cwd: projectDir,
1699
+ nextStep,
1700
+ newProject: projectName,
1701
+ ...fromRecipe && {
1702
+ site: { profession: recipe.identity?.profession, specialties: recipe.identity?.specialties }
1703
+ }
1704
+ });
1705
+ return;
1706
+ }
1707
+ outro2(
1708
+ `Projeto criado!
683
1709
 
684
1710
  cd ${projectName}
685
1711
 
686
1712
  Pr\xF3ximos passos:
687
1713
 
688
- 1. Suba o backend:
689
- npx convex dev
690
- (deixe rodando em um terminal)
691
-
692
- 2. Configure o ambiente (em outro terminal, com Convex ativo):
693
- rubrica setup
1714
+ 1. Conecte o backend e crie o admin:
1715
+ npx create-rubrica setup
694
1716
 
695
- 3. Inicie o frontend:
696
- ${installStep}pnpm dev
1717
+ 2. Abra o site no navegador:
1718
+ ${devCommand}
697
1719
 
698
1720
  Boa sorte! \u{1F680}`
699
1721
  );
700
1722
  }
701
1723
 
702
1724
  // src/commands/config.ts
703
- import { outro as outro2, select as select3, multiselect as multiselect2, confirm as confirm2, isCancel as isCancel3, cancel as cancel3 } from "@clack/prompts";
704
- import * as nodeFsPromises11 from "fs/promises";
705
- import * as path6 from "path";
706
-
707
- // src/utils/detectProject.ts
708
- import * as nodeFsPromises10 from "fs/promises";
709
- import * as path5 from "path";
710
- async function detectProject(startDir, fsModule = nodeFsPromises10) {
711
- let current = startDir;
712
- while (true) {
713
- const candidate = path5.join(current, "rubrica.json");
714
- try {
715
- await fsModule.access(candidate);
716
- return candidate;
717
- } catch {
718
- const parent = path5.dirname(current);
719
- if (parent === current) {
720
- throw new Error(
721
- `detectProject: nenhum rubrica.json encontrado em "${startDir}" nem em nenhum diret\xF3rio ancestral.`
722
- );
723
- }
724
- current = parent;
725
- }
726
- }
727
- }
728
-
729
- // src/commands/config.ts
1725
+ import { outro as outro3, multiselect as multiselect2, confirm as confirm4, isCancel as isCancel6, cancel as cancel5, log as log3 } from "@clack/prompts";
1726
+ import * as nodeFsPromises13 from "fs/promises";
1727
+ import * as path7 from "path";
730
1728
  import { tmpdir as tmpdir2 } from "os";
731
1729
  async function existsIn(fs3, p) {
732
1730
  try {
@@ -738,7 +1736,7 @@ async function existsIn(fs3, p) {
738
1736
  }
739
1737
  async function runConfig(deps = {}) {
740
1738
  const cwd = deps.cwd ?? process.cwd();
741
- const fs3 = deps.fs ?? nodeFsPromises11;
1739
+ const fs3 = deps.fs ?? nodeFsPromises13;
742
1740
  const detectProjectFn = deps.detectProject ?? detectProject;
743
1741
  const readStateFn = deps.readState ?? readState;
744
1742
  const writeStateFn = deps.writeState ?? writeState;
@@ -751,82 +1749,62 @@ async function runConfig(deps = {}) {
751
1749
  const applyPluginsFn = deps.applyPlugins ?? applyPlugins;
752
1750
  const downloadReleaseFn = deps.downloadRelease ?? downloadRelease;
753
1751
  const getLatestVersionFn = deps.getLatestVersion ?? getLatestVersion;
1752
+ const applyAppearanceFn = deps.applyAppearance ?? applyAppearance;
754
1753
  const rubricaJsonPath = await detectProjectFn(cwd, fs3);
755
- const projectDir = path6.dirname(rubricaJsonPath);
1754
+ const projectDir = path7.dirname(rubricaJsonPath);
756
1755
  const currentState = await readStateFn(projectDir, fs3);
757
1756
  const stateUpdate = {};
758
1757
  const sections = await multiselect2({
759
1758
  message: "O que deseja reconfigurar?",
760
1759
  options: [
761
1760
  { value: "identity", label: "Identidade (nome, URL, SEO, RSS)" },
762
- { value: "appearance", label: "Apar\xEAncia (tema, fonte)" },
1761
+ { value: "appearance", label: "Apar\xEAncia (esquema de cores, modo claro/escuro, textura, fontes)" },
763
1762
  { value: "layout", label: "Layout" },
764
1763
  { value: "plugins", label: "Plugins" }
765
1764
  ],
766
1765
  required: false
767
1766
  });
768
- if (isCancel3(sections)) {
769
- cancel3("Opera\xE7\xE3o cancelada.");
1767
+ if (isCancel6(sections)) {
1768
+ cancel5("Opera\xE7\xE3o cancelada.");
770
1769
  return;
771
1770
  }
772
1771
  const selected = sections;
773
1772
  if (selected.includes("identity")) {
774
- const identityData = await doIdentityPrompt();
1773
+ const identityData = await doIdentityPrompt(currentState.identity);
775
1774
  await applyRubricalConfigFn(
776
1775
  rubricaConfigInput(identityData, currentState.fontSans, currentState.fontMono),
777
1776
  projectDir,
778
1777
  fs3
779
1778
  );
780
1779
  await applyIndexHtmlFn(
781
- indexHtmlInput(identityData, currentState.fontSans),
782
- path6.join(projectDir, "index.html"),
1780
+ indexHtmlInput(identityData, currentState.fontSans, currentState.fontMono),
1781
+ path7.join(projectDir, "index.html"),
783
1782
  fs3
784
1783
  );
785
1784
  stateUpdate.identity = identityData;
786
1785
  }
787
1786
  if (selected.includes("appearance")) {
788
- const theme = await select3({
789
- message: "Tema visual",
790
- initialValue: currentState.theme,
791
- options: [
792
- { value: "editorial-cream", label: "Editorial Cream", hint: "refinado e atemporal \u2014 blogs e portf\xF3lios liter\xE1rios" },
793
- { value: "paper-noir", label: "Paper Noir", hint: "contraste m\xE1ximo \u2014 identidade editorial forte" },
794
- { value: "midnight-blue", label: "Midnight Blue", hint: "tech e premium \u2014 devs e designers noturnos" },
795
- { value: "solar-warm", label: "Solar Warm", hint: "energia e criatividade \u2014 marcas pessoais vibrantes" }
796
- ]
797
- });
798
- const fontSans = await select3({
799
- message: "Fonte principal",
800
- initialValue: currentState.fontSans,
801
- options: [
802
- { value: "Inter", label: "Inter", hint: "neutra, leg\xEDvel, padr\xE3o de produtos digitais" },
803
- { value: "Chakra Petch", label: "Chakra Petch", hint: "geom\xE9trica, tech, futurista" },
804
- { value: "Playfair Display", label: "Playfair Display", hint: "elegante, editorial cl\xE1ssico" },
805
- { value: "Space Grotesk", label: "Space Grotesk", hint: "moderna, startup" },
806
- { value: "DM Sans", label: "DM Sans", hint: "limpa, amig\xE1vel, vers\xE1til" },
807
- { value: "Bodoni Moda", label: "Bodoni Moda", hint: "display serifado elegante, editorial cl\xE1ssico" },
808
- { value: "IBM Plex Serif", label: "IBM Plex Serif", hint: "serifa t\xE9cnica, confian\xE7a e rigor" },
809
- { value: "Manrope", label: "Manrope", hint: "geom\xE9trica humanista, moderna e acolhedora" },
810
- { value: "Archivo", label: "Archivo", hint: "grotesca utilit\xE1ria, clareza e for\xE7a tipogr\xE1fica" }
811
- ]
812
- });
813
- const fontMono = await select3({
814
- message: "Fonte mono",
815
- initialValue: currentState.fontMono,
816
- options: [
817
- { value: "JetBrains Mono", label: "JetBrains Mono", hint: "dev-friendly, clara" },
818
- { value: "Fira Code", label: "Fira Code", hint: "cl\xE1ssico, com ligatures" },
819
- { value: "Space Mono", label: "Space Mono", hint: "retro digital" },
820
- { value: "IBM Plex Mono", label: "IBM Plex Mono", hint: "corporativo-tech" }
821
- ]
1787
+ const theme = await schemePrompt(currentState.layout, currentState.theme);
1788
+ const appearance = await appearancePrompt(currentState.layout, {
1789
+ colorMode: currentState.colorMode,
1790
+ colorModeToggle: currentState.colorModeToggle,
1791
+ texture: currentState.texture
822
1792
  });
823
- const cssPath = path6.join(projectDir, "src", "index.css");
824
- const htmlPath = path6.join(projectDir, "index.html");
1793
+ const { fontSans, fontMono } = await fontPrompts(currentState.layout, currentState);
1794
+ const cssPath = path7.join(projectDir, "src", "index.css");
1795
+ const htmlPath = path7.join(projectDir, "index.html");
825
1796
  await applyThemeFn(
826
1797
  { preset: theme },
827
1798
  cssPath,
828
1799
  fs3
829
1800
  );
1801
+ await applyAppearanceFn(appearance, htmlPath, fs3);
1802
+ const css = await fs3.readFile(cssPath, "utf-8").catch(() => "");
1803
+ if (css && !css.includes(SCHEME_START)) {
1804
+ log3.warn(
1805
+ "Este projeto \xE9 de uma vers\xE3o sem modo claro/escuro: s\xF3 as 4 cores principais do esquema foram aplicadas. Para ter os dois modos, a altern\xE2ncia e as texturas, atualize com `npx create-rubrica@latest update` e rode o config de novo."
1806
+ );
1807
+ }
830
1808
  await applyFontFn(
831
1809
  { fontSans, fontMono },
832
1810
  { css: cssPath, html: htmlPath },
@@ -835,47 +1813,45 @@ async function runConfig(deps = {}) {
835
1813
  const identity = stateUpdate.identity ?? currentState.identity;
836
1814
  if (identity) {
837
1815
  await applyIndexHtmlFn(
838
- indexHtmlInput(identity, fontSans),
1816
+ indexHtmlInput(identity, fontSans, fontMono),
839
1817
  htmlPath,
840
1818
  fs3
841
1819
  );
842
1820
  }
843
1821
  stateUpdate.theme = theme;
1822
+ Object.assign(stateUpdate, appearance);
844
1823
  stateUpdate.fontSans = fontSans;
845
1824
  stateUpdate.fontMono = fontMono;
846
1825
  }
847
1826
  if (selected.includes("layout")) {
848
- const newLayout = await select3({
849
- message: "Layout",
850
- initialValue: currentState.layout,
851
- options: [
852
- { value: "cyberpunk", label: "Cyberpunk", hint: "sidebar lateral com foto de perfil \u2014 dev, designer, freelancer" },
853
- { value: "brutalist", label: "Brutalism Terminal", hint: "identidade hacker total \u2014 monospace, sem bordas arredondadas" },
854
- { value: "swiss", label: "Swiss Grid", hint: "grid de 12 colunas, tipografia forte, design su\xED\xE7o rigoroso" },
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
- ]
858
- });
859
- const confirmed = await confirm2({
1827
+ const newLayout = await layoutPrompt(currentState.layout);
1828
+ const confirmed = await confirm4({
860
1829
  message: "\u26A0 Isso sobrescreve Layout.tsx e arquivos de navega\xE7\xE3o. Customiza\xE7\xF5es manuais ser\xE3o perdidas. Continuar?"
861
1830
  });
862
- if (!isCancel3(confirmed) && confirmed === true) {
863
- let templatesDir = path6.join(projectDir, "templates");
1831
+ if (!isCancel6(confirmed) && confirmed === true) {
1832
+ let templatesDir = path7.join(projectDir, "templates");
864
1833
  let tmpDir;
865
1834
  if (!await existsIn(fs3, templatesDir)) {
866
- tmpDir = await nodeFsPromises11.mkdtemp(path6.join(tmpdir2(), "rubrica-config-"));
1835
+ tmpDir = await nodeFsPromises13.mkdtemp(path7.join(tmpdir2(), "rubrica-config-"));
867
1836
  const version = currentState.version === "0.1.0" ? await getLatestVersionFn() : currentState.version;
868
1837
  await downloadReleaseFn(tmpDir, version.startsWith("v") ? version : `v${version}`);
869
- templatesDir = path6.join(tmpDir, "templates");
1838
+ templatesDir = path7.join(tmpDir, "templates");
870
1839
  }
871
1840
  try {
1841
+ const layoutsDir = path7.join(templatesDir, "layouts");
1842
+ if (await existsIn(fs3, layoutsDir) && !await existsIn(fs3, path7.join(layoutsDir, newLayout))) {
1843
+ log3.warn(
1844
+ `O layout "${newLayout}" n\xE3o existe na vers\xE3o ${currentState.version} deste projeto. Atualize o projeto com \`npx create-rubrica@latest update\` e rode o config de novo.`
1845
+ );
1846
+ return;
1847
+ }
872
1848
  await applyLayoutFn(
873
1849
  newLayout,
874
1850
  { projectDir, templatesDir },
875
- { ...fs3, copyFile: nodeFsPromises11.copyFile, unlink: nodeFsPromises11.unlink, exists: (p) => existsIn(fs3, p) }
1851
+ { ...fs3, copyFile: nodeFsPromises13.copyFile, unlink: nodeFsPromises13.unlink, exists: (p) => existsIn(fs3, p) }
876
1852
  );
877
1853
  } finally {
878
- if (tmpDir) await nodeFsPromises11.rm(tmpDir, { recursive: true, force: true });
1854
+ if (tmpDir) await nodeFsPromises13.rm(tmpDir, { recursive: true, force: true });
879
1855
  }
880
1856
  stateUpdate.layout = newLayout;
881
1857
  }
@@ -885,17 +1861,17 @@ async function runConfig(deps = {}) {
885
1861
  const selectedPlugins = await multiselect2({
886
1862
  message: "Plugins ativos",
887
1863
  initialValues: activePlugins,
888
- options: ALL_PLUGINS.map((p) => ({ value: p, label: p })),
1864
+ options: pluginOptions(),
889
1865
  required: false
890
1866
  });
891
- if (!isCancel3(selectedPlugins)) {
1867
+ if (!isCancel6(selectedPlugins)) {
892
1868
  const pluginsMap = {};
893
1869
  for (const p of ALL_PLUGINS) {
894
1870
  pluginsMap[p] = selectedPlugins.includes(p);
895
1871
  }
896
1872
  await applyPluginsFn(
897
1873
  pluginsMap,
898
- path6.join(projectDir, "convex", "pluginRegistry.ts"),
1874
+ path7.join(projectDir, "convex", "pluginRegistry.ts"),
899
1875
  fs3
900
1876
  );
901
1877
  stateUpdate.plugins = pluginsMap;
@@ -904,25 +1880,25 @@ async function runConfig(deps = {}) {
904
1880
  if (Object.keys(stateUpdate).length > 0) {
905
1881
  await writeStateFn(projectDir, stateUpdate, fs3);
906
1882
  }
907
- outro2("Configura\xE7\xE3o atualizada com sucesso!");
1883
+ outro3("Configura\xE7\xE3o atualizada com sucesso!");
908
1884
  }
909
1885
 
910
1886
  // src/commands/update.ts
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";
1887
+ import { intro, outro as outro4, confirm as confirm5, text as text3, isCancel as isCancel7, cancel as cancel6, log as log4, spinner as spinner2 } from "@clack/prompts";
912
1888
  import * as fs2 from "fs/promises";
913
- import * as path9 from "path";
1889
+ import * as path10 from "path";
914
1890
  import { tmpdir as tmpdir3 } from "os";
915
1891
  import { execFile as execFile3 } from "child_process";
916
1892
  import { promisify as promisify3 } from "util";
917
1893
 
918
1894
  // src/utils/pristine.ts
919
- import * as nodeFsPromises12 from "fs/promises";
920
- import * as path7 from "path";
1895
+ import * as nodeFsPromises14 from "fs/promises";
1896
+ import * as path8 from "path";
921
1897
  var fsForTransforms = {
922
- ...nodeFsPromises12,
1898
+ ...nodeFsPromises14,
923
1899
  exists: async (p) => {
924
1900
  try {
925
- await nodeFsPromises12.access(p);
1901
+ await nodeFsPromises14.access(p);
926
1902
  return true;
927
1903
  } catch {
928
1904
  return false;
@@ -935,34 +1911,42 @@ async function buildPristine(options) {
935
1911
  const tag = options.version.startsWith("v") ? options.version : `v${options.version}`;
936
1912
  const fs3 = fsForTransforms;
937
1913
  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");
1914
+ await applyLayout(state.layout, { projectDir: dir, templatesDir: path8.join(dir, "templates") }, fs3);
1915
+ const cssPath = path8.join(dir, "src", "index.css");
1916
+ const htmlPath = path8.join(dir, "index.html");
941
1917
  await applyTheme({ preset: state.theme }, cssPath, fs3);
1918
+ if (state.colorMode) {
1919
+ await applyAppearance(
1920
+ { colorMode: state.colorMode, colorModeToggle: state.colorModeToggle ?? false, texture: state.texture ?? "none" },
1921
+ htmlPath,
1922
+ fs3
1923
+ );
1924
+ }
942
1925
  await applyFont({ fontSans: state.fontSans, fontMono: state.fontMono }, { css: cssPath, html: htmlPath }, fs3);
943
- const registryPath = path7.join(dir, "convex", "pluginRegistry.ts");
1926
+ const registryPath = path8.join(dir, "convex", "pluginRegistry.ts");
944
1927
  const knownPlugins = await knownPluginIds(registryPath);
945
- const plugins = Object.fromEntries(
1928
+ const plugins2 = Object.fromEntries(
946
1929
  Object.entries(state.plugins ?? {}).filter(([id]) => knownPlugins.has(id))
947
1930
  );
948
- await applyPlugins(plugins, registryPath, fs3);
1931
+ await applyPlugins(plugins2, registryPath, fs3);
949
1932
  const identity = state.identity;
950
1933
  if (identity) {
951
- await applyIndexHtml(indexHtmlInput(identity, state.fontSans), htmlPath, fs3);
1934
+ await applyIndexHtml(indexHtmlInput(identity, state.fontSans, state.fontMono), htmlPath, fs3);
952
1935
  await applyRubricalConfig(rubricaConfigInput(identity, state.fontSans, state.fontMono), dir, fs3);
953
1936
  }
954
1937
  if (options.packageName) {
955
- const pkgPath = path7.join(dir, "package.json");
956
- const pkg = JSON.parse(await nodeFsPromises12.readFile(pkgPath, "utf-8"));
1938
+ const pkgPath = path8.join(dir, "package.json");
1939
+ const pkg = JSON.parse(await nodeFsPromises14.readFile(pkgPath, "utf-8"));
957
1940
  pkg.name = options.packageName;
958
- await nodeFsPromises12.writeFile(pkgPath, JSON.stringify(pkg, null, 2));
1941
+ await nodeFsPromises14.writeFile(pkgPath, JSON.stringify(pkg, null, 2));
959
1942
  }
960
- await nodeFsPromises12.rm(path7.join(dir, "templates"), { recursive: true, force: true });
961
- await nodeFsPromises12.rm(path7.join(dir, "cli"), { recursive: true, force: true });
1943
+ await nodeFsPromises14.rm(path8.join(dir, "templates"), { recursive: true, force: true });
1944
+ await nodeFsPromises14.rm(path8.join(dir, "cli"), { recursive: true, force: true });
1945
+ await nodeFsPromises14.rm(path8.join(dir, "site"), { recursive: true, force: true });
962
1946
  }
963
1947
  async function knownPluginIds(registryPath) {
964
1948
  try {
965
- const content = await nodeFsPromises12.readFile(registryPath, "utf-8");
1949
+ const content = await nodeFsPromises14.readFile(registryPath, "utf-8");
966
1950
  return new Set([...content.matchAll(/id: '([^']+)'/g)].map((m) => m[1]));
967
1951
  } catch {
968
1952
  return /* @__PURE__ */ new Set();
@@ -971,7 +1955,7 @@ async function knownPluginIds(registryPath) {
971
1955
 
972
1956
  // src/utils/threeWayUpdate.ts
973
1957
  import * as fs from "fs/promises";
974
- import * as path8 from "path";
1958
+ import * as path9 from "path";
975
1959
  import { execFile as execFile2 } from "child_process";
976
1960
  import { promisify as promisify2 } from "util";
977
1961
  var execFileAsync2 = promisify2(execFile2);
@@ -1001,8 +1985,8 @@ async function listFiles(root) {
1001
1985
  return;
1002
1986
  }
1003
1987
  for (const entry of entries) {
1004
- const abs = path8.join(dir, entry.name);
1005
- const rel = path8.relative(root, abs).split(path8.sep).join("/");
1988
+ const abs = path9.join(dir, entry.name);
1989
+ const rel = path9.relative(root, abs).split(path9.sep).join("/");
1006
1990
  if (entry.isDirectory()) {
1007
1991
  if (!isProtected(`${rel}/`)) await walk(abs);
1008
1992
  } else if (entry.isFile() && !isProtected(rel)) {
@@ -1028,9 +2012,9 @@ function isBinary(buf) {
1028
2012
  return buf.subarray(0, 8e3).includes(0);
1029
2013
  }
1030
2014
  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");
2015
+ const o = path9.join(tmpDir, "ours");
2016
+ const b = path9.join(tmpDir, "base");
2017
+ const t = path9.join(tmpDir, "theirs");
1034
2018
  await fs.writeFile(o, ours);
1035
2019
  await fs.writeFile(b, base);
1036
2020
  await fs.writeFile(t, theirs);
@@ -1048,13 +2032,13 @@ async function mergeText(ours, base, theirs, tmpDir) {
1048
2032
  }
1049
2033
  async function planUpdate(dirs) {
1050
2034
  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-"));
2035
+ const tmpDir = await fs.mkdtemp(path9.join(path9.dirname(dirs.base), "merge-"));
1052
2036
  const actions = [];
1053
2037
  try {
1054
2038
  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));
2039
+ const base = await readOrNull(path9.join(dirs.base, file));
2040
+ const next = await readOrNull(path9.join(dirs.next, file));
2041
+ const ours = await readOrNull(path9.join(dirs.project, file));
1058
2042
  if (same(base, next) || same(ours, next)) continue;
1059
2043
  if (same(ours, base)) {
1060
2044
  if (next === null) actions.push({ file, kind: "remove" });
@@ -1074,7 +2058,7 @@ async function planUpdate(dirs) {
1074
2058
  actions.push({ file, kind: "keep", reason: "removido no Rubrica, mas voc\xEA o personalizou" });
1075
2059
  continue;
1076
2060
  }
1077
- if (LOCKFILES.has(path8.basename(file))) {
2061
+ if (LOCKFILES.has(path9.basename(file))) {
1078
2062
  actions.push({ file, kind: "lockfile", reason: "rode o install para atualizar as depend\xEAncias" });
1079
2063
  continue;
1080
2064
  }
@@ -1097,12 +2081,12 @@ async function planUpdate(dirs) {
1097
2081
  }
1098
2082
  async function applyPlan(projectDir, actions) {
1099
2083
  for (const action of actions) {
1100
- const target = path8.join(projectDir, action.file);
2084
+ const target = path9.join(projectDir, action.file);
1101
2085
  switch (action.kind) {
1102
2086
  case "update":
1103
2087
  case "add":
1104
2088
  case "merge":
1105
- await fs.mkdir(path8.dirname(target), { recursive: true });
2089
+ await fs.mkdir(path9.dirname(target), { recursive: true });
1106
2090
  await fs.writeFile(target, action.content);
1107
2091
  break;
1108
2092
  case "remove":
@@ -1110,7 +2094,7 @@ async function applyPlan(projectDir, actions) {
1110
2094
  break;
1111
2095
  case "conflict":
1112
2096
  if (action.incoming) {
1113
- await fs.mkdir(path8.dirname(target), { recursive: true });
2097
+ await fs.mkdir(path9.dirname(target), { recursive: true });
1114
2098
  await fs.writeFile(`${target}${NEW_SUFFIX}`, action.incoming);
1115
2099
  }
1116
2100
  break;
@@ -1200,66 +2184,66 @@ async function runUpdate(deps = {}) {
1200
2184
  const getLatestVersionFn = deps.getLatestVersion ?? getLatestVersion;
1201
2185
  const download = deps.downloadRelease ?? downloadRelease;
1202
2186
  const checkRequiredEnvFn = deps.checkRequiredEnv ?? checkRequiredEnv;
1203
- const ask = !opts.yes;
1204
- intro2("Rubrica Update");
2187
+ const ask2 = !opts.yes;
2188
+ intro("Rubrica Update");
1205
2189
  try {
1206
2190
  await execFileAsync3("git", ["--version"]);
1207
2191
  } catch {
1208
- cancel4("O update precisa do git instalado (ele \xE9 usado para mesclar suas mudan\xE7as com a vers\xE3o nova).");
2192
+ cancel6("O update precisa do git instalado (ele \xE9 usado para mesclar suas mudan\xE7as com a vers\xE3o nova).");
1209
2193
  return;
1210
2194
  }
1211
- const projectDir = path9.dirname(await detectProject(cwd));
2195
+ const projectDir = path10.dirname(await detectProject(cwd));
1212
2196
  const state = await readState(projectDir);
1213
2197
  let fromVersion = normalizeVersion(opts.from ?? state.version);
1214
2198
  if (!opts.from && fromVersion === LEGACY_PLACEHOLDER_VERSION) {
1215
- log2.warn(
2199
+ log4.warn(
1216
2200
  `O rubrica.json diz ${LEGACY_PLACEHOLDER_VERSION}, mas vers\xF5es antigas do CLI sempre gravavam esse n\xFAmero.
1217
2201
  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).`
1218
2202
  );
1219
- if (!ask) {
1220
- cancel4("Informe a vers\xE3o de origem com --from <vers\xE3o>.");
2203
+ if (!ask2) {
2204
+ cancel6("Informe a vers\xE3o de origem com --from <vers\xE3o>.");
1221
2205
  return;
1222
2206
  }
1223
- const answer = await text2({
2207
+ const answer = await text3({
1224
2208
  message: "Com qual vers\xE3o o projeto foi criado?",
1225
2209
  placeholder: "ex.: 0.3.12",
1226
2210
  validate: (v) => /^v?\d+\.\d+\.\d+$/.test(v.trim()) ? void 0 : "Use o formato 0.3.12"
1227
2211
  });
1228
- if (isCancel4(answer)) {
1229
- cancel4("Atualiza\xE7\xE3o cancelada.");
2212
+ if (isCancel7(answer)) {
2213
+ cancel6("Atualiza\xE7\xE3o cancelada.");
1230
2214
  return;
1231
2215
  }
1232
2216
  fromVersion = normalizeVersion(answer);
1233
2217
  }
1234
2218
  const toVersion = normalizeVersion(opts.to ?? await getLatestVersionFn());
1235
2219
  if (fromVersion === toVersion) {
1236
- outro3(`J\xE1 est\xE1 na vers\xE3o mais recente (${toVersion}).`);
2220
+ outro4(`J\xE1 est\xE1 na vers\xE3o mais recente (${toVersion}).`);
1237
2221
  return;
1238
2222
  }
1239
2223
  const status = await gitStatus(projectDir);
1240
2224
  if (!opts.dryRun) {
1241
2225
  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.");
2226
+ log4.warn("Este projeto n\xE3o est\xE1 num reposit\xF3rio git. Recomendado: fa\xE7a um backup antes, para poder desfazer.");
1243
2227
  } 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.");
2228
+ log4.warn("H\xE1 mudan\xE7as n\xE3o commitadas. Recomendado: fa\xE7a commit antes, para poder desfazer o update com o git.");
1245
2229
  }
1246
2230
  }
1247
2231
  if (parseMajor(toVersion) > parseMajor(fromVersion)) {
1248
- log2.warn(
2232
+ log4.warn(
1249
2233
  `Atualiza\xE7\xE3o de vers\xE3o major: ${fromVersion} \u2192 ${toVersion}.
1250
2234
  Leia o guia de atualiza\xE7\xE3o nas notas da release antes de publicar.`
1251
2235
  );
1252
2236
  }
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");
2237
+ const workDir = await fs2.mkdtemp(path10.join(tmpdir3(), "rubrica-update-"));
2238
+ const baseDir = path10.join(workDir, "base");
2239
+ const nextDir = path10.join(workDir, "next");
1256
2240
  let packageName;
1257
2241
  try {
1258
- packageName = JSON.parse(await fs2.readFile(path9.join(projectDir, "package.json"), "utf-8")).name;
2242
+ packageName = JSON.parse(await fs2.readFile(path10.join(projectDir, "package.json"), "utf-8")).name;
1259
2243
  } catch {
1260
2244
  packageName = void 0;
1261
2245
  }
1262
- const s = spinner();
2246
+ const s = spinner2();
1263
2247
  try {
1264
2248
  s.start(`Baixando ${fromVersion} e ${toVersion}`);
1265
2249
  await buildPristine({ dir: baseDir, version: fromVersion, state, packageName, download });
@@ -1268,17 +2252,17 @@ Leia o guia de atualiza\xE7\xE3o nas notas da release antes de publicar.`
1268
2252
  s.start("Comparando com o seu projeto");
1269
2253
  const actions = await planUpdate({ base: baseDir, next: nextDir, project: projectDir });
1270
2254
  s.stop("Compara\xE7\xE3o conclu\xEDda");
1271
- log2.info(`${fromVersion} \u2192 ${toVersion}
2255
+ log4.info(`${fromVersion} \u2192 ${toVersion}
1272
2256
 
1273
2257
  ${formatPlan(actions)}`);
1274
2258
  if (opts.dryRun) {
1275
- outro3("Simula\xE7\xE3o: nada foi gravado.");
2259
+ outro4("Simula\xE7\xE3o: nada foi gravado.");
1276
2260
  return;
1277
2261
  }
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.");
2262
+ if (ask2) {
2263
+ const proceed = await confirm5({ message: `Aplicar a atualiza\xE7\xE3o para ${toVersion}?` });
2264
+ if (isCancel7(proceed) || !proceed) {
2265
+ cancel6("Atualiza\xE7\xE3o cancelada.");
1282
2266
  return;
1283
2267
  }
1284
2268
  }
@@ -1301,12 +2285,12 @@ ${formatPlan(actions)}`);
1301
2285
  steps.push("Rode o site (pnpm dev) e confira antes de publicar");
1302
2286
  const missingVars = await checkRequiredEnvFn(projectDir, fs2);
1303
2287
  if (missingVars.length > 0) {
1304
- log2.warn(
2288
+ log4.warn(
1305
2289
  `Vari\xE1veis de ambiente faltando no Convex:
1306
2290
  ` + missingVars.map((v) => ` \u2022 ${v.name} \u2014 ${v.description}`).join("\n")
1307
2291
  );
1308
2292
  }
1309
- outro3(`Atualizado para ${toVersion}.
2293
+ outro4(`Atualizado para ${toVersion}.
1310
2294
 
1311
2295
  Pr\xF3ximos passos:
1312
2296
  ${steps.map((st, i) => ` ${i + 1}. ${st}`).join("\n")}`);
@@ -1315,340 +2299,222 @@ ${steps.map((st, i) => ` ${i + 1}. ${st}`).join("\n")}`);
1315
2299
  }
1316
2300
  }
1317
2301
 
1318
- // src/commands/setup.ts
1319
- import { outro as outro4, text as text3, password, spinner as spinner2, isCancel as isCancel5, cancel as cancel5, log as log3 } from "@clack/prompts";
1320
- import * as nodeFsPromises13 from "fs/promises";
1321
- import * as path10 from "path";
1322
- import * as nodeCrypto from "crypto";
1323
- import { execFileSync as defaultExecFileSync } from "child_process";
1324
-
1325
- // src/utils/generateJwtKeys.ts
1326
- import { generateKeyPair, exportPKCS8, exportJWK } from "jose";
1327
- async function generateJwtKeys() {
1328
- const { privateKey, publicKey } = await generateKeyPair("RS256", { extractable: true });
1329
- const JWT_PRIVATE_KEY = await exportPKCS8(privateKey);
1330
- const jwk = await exportJWK(publicKey);
1331
- const JWKS = JSON.stringify({ keys: [{ use: "sig", ...jwk }] });
1332
- return { JWT_PRIVATE_KEY, JWKS };
2302
+ // src/args.ts
2303
+ var VALUE_FLAGS = ["--receita", "--layout", "--esquema", "--modo", "--textura", "--fonte", "--mono", "--plugins"];
2304
+ var key = (s) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]/g, "");
2305
+ var MODES = { claro: "light", escuro: "dark", automatico: "system" };
2306
+ var TEXTURES2 = { nenhuma: "none", grao: "grain", papel: "paper" };
2307
+ function font(value, list) {
2308
+ return list.find((f) => key(f.family) === key(value))?.family ?? value;
1333
2309
  }
1334
-
1335
- // src/commands/setup.ts
1336
- function parseEnvFile(content) {
1337
- const result = {};
1338
- for (const line of content.split("\n")) {
1339
- const trimmed = line.trim();
1340
- if (!trimmed || trimmed.startsWith("#")) continue;
1341
- const eqIdx = trimmed.indexOf("=");
1342
- if (eqIdx === -1) continue;
1343
- const key = trimmed.slice(0, eqIdx).trim();
1344
- const value = trimmed.slice(eqIdx + 1).trim();
1345
- result[key] = value;
2310
+ function plugins(value) {
2311
+ if (key(value) === "nenhum") return [];
2312
+ const preset = PLUGIN_PRESETS.find((p) => p.id === value);
2313
+ if (preset) return [...preset.plugins];
2314
+ return value.split(",").map((s) => s.trim()).filter(Boolean);
2315
+ }
2316
+ function parseCreateArgs(args) {
2317
+ let projectName;
2318
+ let recipeCode;
2319
+ const flags = {};
2320
+ const parseWarnings = [];
2321
+ for (let i = 0; i < args.length; i++) {
2322
+ const arg = args[i];
2323
+ if (!arg.startsWith("--")) {
2324
+ projectName ??= arg;
2325
+ continue;
2326
+ }
2327
+ const eq = arg.indexOf("=");
2328
+ const name = eq === -1 ? arg : arg.slice(0, eq);
2329
+ if (name === "--alternancia") {
2330
+ flags.colorModeToggle = true;
2331
+ continue;
2332
+ }
2333
+ if (name === "--sem-alternancia") {
2334
+ flags.colorModeToggle = false;
2335
+ continue;
2336
+ }
2337
+ if (!VALUE_FLAGS.includes(name)) {
2338
+ parseWarnings.push(`Op\xE7\xE3o desconhecida: ${name} (ignorada).`);
2339
+ continue;
2340
+ }
2341
+ let value;
2342
+ if (eq !== -1) value = arg.slice(eq + 1);
2343
+ else if (args[i + 1] !== void 0 && !args[i + 1].startsWith("--")) value = args[++i];
2344
+ if (!value) {
2345
+ parseWarnings.push(`A op\xE7\xE3o ${name} precisa de um valor (ignorada).`);
2346
+ continue;
2347
+ }
2348
+ switch (name) {
2349
+ case "--receita":
2350
+ recipeCode = value;
2351
+ break;
2352
+ case "--layout":
2353
+ flags.layout = value;
2354
+ break;
2355
+ case "--esquema":
2356
+ flags.scheme = value;
2357
+ break;
2358
+ case "--modo":
2359
+ flags.colorMode = MODES[key(value)] ?? value;
2360
+ break;
2361
+ case "--textura":
2362
+ flags.texture = TEXTURES2[key(value)] ?? value;
2363
+ break;
2364
+ case "--fonte":
2365
+ flags.fontSans = font(value, SANS_FONTS);
2366
+ break;
2367
+ case "--mono":
2368
+ flags.fontMono = font(value, MONO_FONTS);
2369
+ break;
2370
+ case "--plugins":
2371
+ flags.plugins = plugins(value);
2372
+ break;
2373
+ }
1346
2374
  }
1347
- return result;
2375
+ const fromCode = recipeCode ? decodeRecipe(recipeCode) : { recipe: {}, warnings: [] };
2376
+ const fromFlags = sanitizeRecipe(flags);
2377
+ return {
2378
+ projectName,
2379
+ recipe: { ...fromCode.recipe, ...fromFlags.recipe },
2380
+ warnings: [...fromCode.warnings, ...fromFlags.warnings, ...parseWarnings]
2381
+ };
1348
2382
  }
1349
- async function runSetup(deps = {}) {
2383
+
2384
+ // src/commands/password.ts
2385
+ import { outro as outro5, text as text4, password as password2, select as select6, isCancel as isCancel8, cancel as cancel7, log as log5 } from "@clack/prompts";
2386
+ import * as nodeFsPromises15 from "fs/promises";
2387
+ import * as path11 from "path";
2388
+ import { execFileSync as defaultExecFileSync2 } from "child_process";
2389
+ var NOTHING_CHANGED = "Nada foi alterado.";
2390
+ async function runPassword(deps = {}) {
1350
2391
  const cwd = deps.cwd ?? process.cwd();
1351
- const fs3 = deps.fs ?? {
1352
- access: (p) => nodeFsPromises13.access(p).then(() => void 0),
1353
- readFile: (p, enc) => nodeFsPromises13.readFile(p, enc),
1354
- writeFile: (p, data) => nodeFsPromises13.writeFile(p, data).then(() => void 0),
1355
- mkdir: (p, opts) => nodeFsPromises13.mkdir(p, opts).then(() => void 0)
1356
- };
2392
+ const fs3 = deps.fs ?? { readFile: (p, e) => nodeFsPromises15.readFile(p, e) };
1357
2393
  const detectProject2 = deps.detectProject ?? detectProject;
1358
- const generateJwtKeys2 = deps.generateJwtKeys ?? generateJwtKeys;
1359
2394
  const readState2 = deps.readState ?? readState;
1360
- const randomBytes2 = deps.randomBytes ?? ((size) => nodeCrypto.randomBytes(size));
1361
- const execFileSync = deps.execFileSync ?? ((file, args, opts) => defaultExecFileSync(file, args, opts));
2395
+ const execFileSync = deps.execFileSync ?? ((file, args, opts) => defaultExecFileSync2(file, args, opts));
1362
2396
  try {
1363
2397
  await detectProject2(cwd);
1364
2398
  } catch (err) {
1365
- cancel5(err.message);
1366
- return;
1367
- }
1368
- const envPath = path10.join(cwd, ".env.local");
1369
- let envVars = {};
1370
- try {
1371
- const envContent = await fs3.readFile(envPath, "utf-8");
1372
- envVars = parseEnvFile(envContent);
1373
- } catch {
1374
- cancel5(
1375
- "Arquivo .env.local n\xE3o encontrado. Rode npx convex dev primeiro para cri\xE1-lo."
1376
- );
1377
- return;
1378
- }
1379
- if (!envVars["VITE_CONVEX_URL"]) {
1380
- cancel5(
1381
- "VITE_CONVEX_URL n\xE3o encontrado no .env.local. Rode npx convex dev primeiro."
1382
- );
1383
- return;
1384
- }
1385
- if (!envVars["VITE_CONVEX_SITE_URL"]) {
1386
- cancel5(
1387
- "VITE_CONVEX_SITE_URL n\xE3o encontrado no .env.local. Rode npx convex dev primeiro."
1388
- );
2399
+ cancel7(err.message);
1389
2400
  return;
1390
2401
  }
1391
- const siteUrlDefault = envVars["VITE_CONVEX_SITE_URL"];
1392
- const s = spinner2();
1393
- s.start("Gerando chaves JWT (RS256)...");
1394
- const { JWT_PRIVATE_KEY, JWKS } = await generateJwtKeys2();
1395
- s.stop("Chaves JWT geradas.");
1396
- execFileSync("npx", ["convex", "env", "set", "--", "JWT_PRIVATE_KEY", JWT_PRIVATE_KEY], {
1397
- stdio: "pipe"
1398
- });
1399
- execFileSync("npx", ["convex", "env", "set", "--", "JWKS", JWKS], {
1400
- stdio: "pipe"
1401
- });
1402
- const siteUrl = await text3({
1403
- message: "URL p\xFAblica do site (SITE_URL no Convex):",
1404
- initialValue: siteUrlDefault,
1405
- validate: (v) => {
1406
- if (!v || !v.startsWith("http://") && !v.startsWith("https://"))
1407
- return "URL deve come\xE7ar com http:// ou https://";
1408
- }
1409
- });
1410
- if (isCancel5(siteUrl)) {
1411
- cancel5("Setup cancelado.");
2402
+ const connected = await fs3.readFile(path11.join(cwd, ".env.local"), "utf-8").then(
2403
+ (env) => /^CONVEX_DEPLOYMENT=/m.test(env) || /^VITE_CONVEX_URL=/m.test(env),
2404
+ () => false
2405
+ );
2406
+ if (!connected) {
2407
+ cancel7("Este projeto ainda n\xE3o est\xE1 ligado ao Convex, ent\xE3o ainda n\xE3o tem painel. Rode npx create-rubrica setup primeiro.");
1412
2408
  return;
1413
2409
  }
1414
- execFileSync("npx", ["convex", "env", "set", "--", "SITE_URL", siteUrl], {
1415
- stdio: "pipe"
1416
- });
1417
2410
  const state = await readState2(cwd, fs3);
1418
- const plugins = state.plugins;
1419
- if (plugins["contact-wizard"] || plugins["testimonials-intake"]) {
1420
- const telegramToken = await text3({
1421
- message: "TELEGRAM_BOT_TOKEN (Enter para pular):",
1422
- initialValue: ""
1423
- });
1424
- if (!isCancel5(telegramToken) && telegramToken && telegramToken.trim()) {
1425
- execFileSync("npx", ["convex", "env", "set", "--", "TELEGRAM_BOT_TOKEN", telegramToken], { stdio: "pipe" });
1426
- }
1427
- const telegramChatId = await text3({
1428
- message: "TELEGRAM_ADMIN_CHAT_ID (Enter para pular):",
1429
- initialValue: ""
1430
- });
1431
- if (!isCancel5(telegramChatId) && telegramChatId && telegramChatId.trim()) {
1432
- execFileSync("npx", ["convex", "env", "set", "--", "TELEGRAM_ADMIN_CHAT_ID", telegramChatId], { stdio: "pipe" });
1433
- }
1434
- }
1435
- if (plugins["playground"]) {
1436
- const pepper = randomBytes2(32).toString("hex");
1437
- execFileSync("npx", ["convex", "env", "set", "--", "PLAYGROUND_KEY_PEPPER", pepper], { stdio: "pipe" });
1438
- }
1439
- if (plugins["ai-resumes"] || plugins["i18n"] || plugins["playground"]) {
1440
- const openrouterKey = await text3({
1441
- message: "OPENROUTER_API_KEY (Enter para pular):",
1442
- initialValue: ""
1443
- });
1444
- if (!isCancel5(openrouterKey) && openrouterKey && openrouterKey.trim()) {
1445
- execFileSync("npx", ["convex", "env", "set", "--", "OPENROUTER_API_KEY", openrouterKey], { stdio: "pipe" });
1446
- }
1447
- }
1448
- if (plugins["payments"]) {
1449
- const asaasKey = await text3({
1450
- message: "ASAAS_API_KEY \u2014 chave da API do Asaas, sandbox ou produ\xE7\xE3o (Enter para pular):",
1451
- initialValue: ""
1452
- });
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
- );
1468
- }
1469
- }
1470
- const adminEmail = await text3({
1471
- message: "Email do usu\xE1rio root:",
1472
- validate: (v) => {
1473
- if (!v.includes("@") || !v.includes("."))
1474
- return "Email inv\xE1lido \u2014 deve conter @ e pelo menos um ponto";
1475
- }
2411
+ const identity = state.identity ?? {};
2412
+ const where = await select6({
2413
+ message: "Onde voc\xEA quer trocar a senha?",
2414
+ initialValue: "prod",
2415
+ options: [
2416
+ { value: "prod", label: "No site publicado", hint: "o que est\xE1 no ar" },
2417
+ { value: "dev", label: "No site do seu computador", hint: "o que abre com npm run dev" }
2418
+ ]
1476
2419
  });
1477
- if (isCancel5(adminEmail)) {
1478
- cancel5("Setup cancelado.");
1479
- return;
1480
- }
1481
- const adminPassword = await password({
1482
- message: "Senha do usu\xE1rio root (m\xEDnimo 12 caracteres):",
1483
- validate: (v) => {
1484
- if (v.length < 12) return "Senha deve ter pelo menos 12 caracteres";
1485
- }
2420
+ if (isCancel8(where)) return void cancel7(NOTHING_CHANGED);
2421
+ const emailAnswer = await text4({
2422
+ message: "E-mail de quem entra no painel:",
2423
+ initialValue: normalizeEmail(identity.authorEmail ?? ""),
2424
+ validate: validateEmail
1486
2425
  });
1487
- if (isCancel5(adminPassword)) {
1488
- cancel5("Setup cancelado.");
1489
- return;
1490
- }
1491
- const adminPasswordConfirm = await password({
1492
- message: "Confirme a senha:",
1493
- validate: (v) => {
1494
- if (v !== adminPassword) return "As senhas n\xE3o coincidem";
1495
- }
2426
+ if (isCancel8(emailAnswer)) return void cancel7(NOTHING_CHANGED);
2427
+ const email = normalizeEmail(emailAnswer);
2428
+ const newPassword = await password2({
2429
+ message: "Senha nova (12 ou mais caracteres, com mai\xFAscula, min\xFAscula e n\xFAmero):",
2430
+ validate: validatePassword
1496
2431
  });
1497
- if (isCancel5(adminPasswordConfirm)) {
1498
- cancel5("Setup cancelado.");
1499
- return;
1500
- }
2432
+ if (isCancel8(newPassword)) return void cancel7(NOTHING_CHANGED);
2433
+ const confirmPassword = await password2({
2434
+ message: "Repita a senha nova:",
2435
+ validate: (v) => v !== newPassword ? "As senhas n\xE3o coincidem" : void 0
2436
+ });
2437
+ if (isCancel8(confirmPassword)) return void cancel7(NOTHING_CHANGED);
2438
+ const prod = where === "prod";
1501
2439
  try {
1502
2440
  execFileSync(
1503
2441
  "npx",
1504
- ["convex", "run", "seed:setupAdmin", JSON.stringify({ email: adminEmail, password: adminPassword })],
1505
- { stdio: "pipe" }
2442
+ ["convex", "run", ...prod ? ["--prod"] : [], "users:resetPasswordInternal", JSON.stringify({ email, password: newPassword })],
2443
+ { stdio: "pipe", cwd }
1506
2444
  );
1507
2445
  } catch (err) {
1508
2446
  const e = err;
1509
- const output = e.stdout?.toString() || e.stderr?.toString() || e.message || "";
1510
- if (output.includes("Root user already exists")) {
1511
- log3.warn("Admin j\xE1 configurado \u2014 credenciais mantidas. Para redefinir, acesse o Convex Dashboard.");
1512
- } else {
1513
- cancel5(`Erro ao criar usu\xE1rio root: ${output || String(err)}`);
1514
- return;
1515
- }
1516
- }
1517
- const enabledPlugins = Object.entries(plugins).filter(([, on]) => on).map(([id]) => id);
1518
- try {
1519
- execFileSync(
1520
- "npx",
1521
- ["convex", "run", "seed:seedAll", JSON.stringify({ enabledPlugins })],
1522
- { stdio: "pipe" }
1523
- );
1524
- } catch (err) {
1525
- const output = err.stdout?.toString() || err.stderr?.toString() || err.message;
1526
- log3.warn(`seedAll falhou: ${output.trim() || "erro desconhecido"} \u2014 rode 'npx convex run seed:seedAll "{...}"' manualmente depois.`);
1527
- }
1528
- const identity = state.identity;
1529
- if (identity?.siteName) {
1530
- try {
1531
- execFileSync(
1532
- "npx",
1533
- ["convex", "run", "siteConfig:setBatchInternal", JSON.stringify({
1534
- items: [
1535
- { key: "site_title", value: identity.siteName },
1536
- { key: "site_name", value: identity.siteName },
1537
- { key: "site_url", value: identity.siteUrl || "" },
1538
- { key: "site_description", value: identity.siteDescription || "" },
1539
- { key: "author_name", value: identity.authorName || "" },
1540
- { key: "author_email", value: identity.authorEmail || "" },
1541
- { key: "twitter_handle", value: identity.twitterHandle || "" },
1542
- { key: "lang", value: identity.lang || "pt-BR" }
1543
- ]
1544
- })],
1545
- { stdio: "pipe" }
2447
+ const output = `${e.stderr?.toString() ?? ""}${e.stdout?.toString() ?? ""}` || e.message || "";
2448
+ if (output.includes("Nenhum usu\xE1rio")) {
2449
+ cancel7(`Nenhum usu\xE1rio com o e-mail ${email} neste site. Confira o e-mail e rode de novo.`);
2450
+ } else if (output.includes("No functions found")) {
2451
+ cancel7(
2452
+ prod ? 'O site ainda n\xE3o foi publicado, ent\xE3o n\xE3o h\xE1 senha para trocar l\xE1. Para o site do seu computador, rode de novo e escolha "No site do seu computador".' : "O backend deste projeto est\xE1 vazio. Rode npx create-rubrica setup para configur\xE1-lo."
1546
2453
  );
1547
- } catch {
1548
- }
1549
- if (identity.authorName) {
1550
- try {
1551
- execFileSync(
1552
- "npx",
1553
- ["convex", "run", "contactInfo:updateInternal", JSON.stringify({
1554
- name: identity.authorName,
1555
- email: identity.authorEmail || "",
1556
- showEmail: false
1557
- })],
1558
- { stdio: "pipe" }
1559
- );
1560
- } catch {
1561
- }
1562
- }
1563
- }
1564
- const vercelHookUrl = await text3({
1565
- message: "VERCEL_DEPLOY_HOOK_URL (Enter para pular):",
1566
- initialValue: ""
1567
- });
1568
- if (!isCancel5(vercelHookUrl) && vercelHookUrl && vercelHookUrl.trim()) {
1569
- execFileSync("npx", ["convex", "env", "set", "--", "VERCEL_DEPLOY_HOOK_URL", vercelHookUrl], { stdio: "pipe" });
1570
- }
1571
- const vercelWebhookSecret = await text3({
1572
- message: "VERCEL_WEBHOOK_SECRET (Enter para pular):",
1573
- initialValue: ""
1574
- });
1575
- if (!isCancel5(vercelWebhookSecret) && vercelWebhookSecret && vercelWebhookSecret.trim()) {
1576
- execFileSync("npx", ["convex", "env", "set", "--", "VERCEL_WEBHOOK_SECRET", vercelWebhookSecret], { stdio: "pipe" });
1577
- }
1578
- const profession = await text3({
1579
- message: "Qual \xE9 a sua profiss\xE3o ou \xE1rea de atua\xE7\xE3o? (Enter para usar padr\xE3o tech)",
1580
- placeholder: "Ex: Designer UX, Fot\xF3grafa, Advogada, Engenheira Civil...",
1581
- initialValue: ""
1582
- });
1583
- const specialties = await text3({
1584
- message: "Quais s\xE3o suas principais especialidades? (separadas por v\xEDrgula, Enter para pular)",
1585
- placeholder: "Ex: Branding, Motion Design, Fotografia de Produto",
1586
- initialValue: ""
1587
- });
1588
- const professionStr = isCancel5(profession) ? "" : (profession || "").trim();
1589
- const specialtiesStr = isCancel5(specialties) ? "" : (specialties || "").trim();
1590
- if (professionStr || specialtiesStr) {
1591
- const tags = specialtiesStr ? specialtiesStr.split(",").map((s2) => s2.trim()).filter(Boolean).slice(0, 4).map((label, i) => ({ label, color: i % 2 === 0 ? "primary" : "secondary" })) : [
1592
- { label: "React", color: "primary" },
1593
- { label: "TypeScript", color: "primary" },
1594
- { label: "Arquitetura de Sistemas", color: "secondary" },
1595
- { label: "DevOps & Infraestrutura", color: "secondary" }
1596
- ];
1597
- try {
1598
- execFileSync(
1599
- "npx",
1600
- ["convex", "run", "homeContent:set", JSON.stringify({ key: "hero_tags", value: tags })],
1601
- { stdio: "pipe" }
2454
+ } else if (/Could not find|not found/i.test(output) && output.includes("resetPasswordInternal")) {
2455
+ cancel7(
2456
+ "Este projeto \xE9 de uma vers\xE3o sem a troca de senha pelo terminal. Atualize com npx create-rubrica@latest update" + (prod ? ", publique de novo e rode este comando outra vez." : " e rode de novo.")
2457
+ );
2458
+ } else {
2459
+ cancel7(
2460
+ `N\xE3o deu para trocar a senha:
2461
+ ${output.trim()}` + (prod ? '\n\nSe voc\xEA ainda n\xE3o publicou o site, rode de novo e escolha "No site do seu computador".' : "")
1602
2462
  );
1603
- } catch {
1604
- }
1605
- if (professionStr) {
1606
- const name = adminEmail.split("@")[0];
1607
- const aiContext = specialtiesStr ? `${name} \xE9 ${professionStr} com especialidade em ${specialtiesStr}. Entrega projetos com qualidade e comprometimento.` : `${name} \xE9 ${professionStr}. Entrega projetos com qualidade e comprometimento.`;
1608
- try {
1609
- execFileSync(
1610
- "npx",
1611
- ["convex", "run", "contactInfo:updateInternal", JSON.stringify({ proposalAiContext: aiContext })],
1612
- { stdio: "pipe" }
1613
- );
1614
- } catch {
1615
- }
1616
2463
  }
2464
+ return;
1617
2465
  }
1618
- outro4(
1619
- `Setup conclu\xEDdo!
1620
-
1621
- Admin criado: ${adminEmail}
1622
- Acesse: /login
2466
+ const loginUrl = !prod ? "http://localhost:3000/login" : identity.siteUrl ? `${identity.siteUrl.replace(/\/+$/, "")}/login` : "o /login do seu site";
2467
+ log5.info("Se o login estava bloqueado por tentativas erradas, ele tamb\xE9m foi liberado.");
2468
+ outro5(`Senha trocada!
1623
2469
 
1624
- Pr\xF3ximo passo: pnpm dev`
1625
- );
2470
+ Entre em ${loginUrl}
2471
+ com ${email}`);
1626
2472
  }
1627
2473
 
1628
2474
  // src/index.ts
1629
2475
  async function runCli(argv, cwd) {
1630
2476
  const [, , command, projectName] = argv;
1631
- intro3("Rubrica CLI");
2477
+ intro2("Rubrica CLI");
1632
2478
  if (command === "create") {
1633
2479
  if (!projectName) {
1634
2480
  console.error("Uso: rubrica create <nome-do-projeto>");
1635
2481
  process.exit(1);
1636
2482
  }
1637
- await runCreate(projectName, { projectsDir: cwd });
2483
+ await create(argv.slice(3), cwd);
1638
2484
  } else if (command === "config") {
1639
2485
  await runConfig({ cwd });
1640
2486
  } else if (command === "update") {
1641
2487
  await runUpdate({ cwd, options: parseUpdateOptions(argv.slice(3)) });
1642
2488
  } else if (command === "setup") {
1643
2489
  await runSetup({ cwd });
2490
+ } else if (command === "senha") {
2491
+ await runPassword({ cwd });
1644
2492
  } else if (command && !command.startsWith("-")) {
1645
- await runCreate(command, { projectsDir: cwd });
2493
+ await create(argv.slice(2), cwd);
1646
2494
  } else {
1647
2495
  console.log(
1648
- "Comandos dispon\xEDveis: create <nome-do-projeto> | config | setup\n update [--dry-run] [--from <vers\xE3o>] [--to <vers\xE3o>] [--yes]"
2496
+ "Comandos dispon\xEDveis: create <nome-do-projeto> [--receita <c\xF3digo>] | config | setup | senha\n update [--dry-run] [--from <vers\xE3o>] [--to <vers\xE3o>] [--yes]"
1649
2497
  );
1650
2498
  }
1651
2499
  }
2500
+ async function create(args, cwd) {
2501
+ let parsed;
2502
+ try {
2503
+ parsed = parseCreateArgs(args);
2504
+ } catch (err) {
2505
+ console.error(err.message);
2506
+ process.exitCode = 1;
2507
+ return;
2508
+ }
2509
+ if (!parsed.projectName) {
2510
+ console.error("Uso: npx create-rubrica <nome-da-pasta> [--receita <c\xF3digo>]");
2511
+ process.exitCode = 1;
2512
+ return;
2513
+ }
2514
+ for (const warning of parsed.warnings) log6.warn(warning);
2515
+ const hasRecipe = Object.keys(parsed.recipe).length > 0;
2516
+ await runCreate(parsed.projectName, hasRecipe ? { projectsDir: cwd, recipe: parsed.recipe } : { projectsDir: cwd });
2517
+ }
1652
2518
  function parseUpdateOptions(args) {
1653
2519
  const options = {};
1654
2520
  for (let i = 0; i < args.length; i++) {