@matizze/prumo-cli 0.0.0-stage → 0.5.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 (124) hide show
  1. package/README.md +120 -2
  2. package/dist/api.d.ts +10 -0
  3. package/dist/api.js +9 -0
  4. package/dist/args.d.ts +11 -0
  5. package/dist/args.js +61 -0
  6. package/dist/bin.d.ts +2 -0
  7. package/dist/bin.js +11 -0
  8. package/dist/codemod/add-route.d.ts +66 -0
  9. package/dist/codemod/add-route.js +435 -0
  10. package/dist/codemod/edit.d.ts +35 -0
  11. package/dist/codemod/edit.js +51 -0
  12. package/dist/codemod/index.d.ts +8 -0
  13. package/dist/codemod/index.js +8 -0
  14. package/dist/codemod/merge-barrel.d.ts +9 -0
  15. package/dist/codemod/merge-barrel.js +49 -0
  16. package/dist/codemod/messages.d.ts +11 -0
  17. package/dist/codemod/messages.js +46 -0
  18. package/dist/codemod/names.d.ts +62 -0
  19. package/dist/codemod/names.js +204 -0
  20. package/dist/codemod/plan.d.ts +45 -0
  21. package/dist/codemod/plan.js +147 -0
  22. package/dist/codemod/register-domain.d.ts +51 -0
  23. package/dist/codemod/register-domain.js +237 -0
  24. package/dist/codemod/register-messages.d.ts +11 -0
  25. package/dist/codemod/register-messages.js +112 -0
  26. package/dist/codemod/route-elements.d.ts +25 -0
  27. package/dist/codemod/route-elements.js +72 -0
  28. package/dist/commands/check.d.ts +16 -0
  29. package/dist/commands/check.js +47 -0
  30. package/dist/commands/doctor.d.ts +20 -0
  31. package/dist/commands/doctor.js +104 -0
  32. package/dist/commands/make-component.d.ts +33 -0
  33. package/dist/commands/make-component.js +85 -0
  34. package/dist/commands/make-domain.d.ts +30 -0
  35. package/dist/commands/make-domain.js +83 -0
  36. package/dist/commands/make-page.d.ts +30 -0
  37. package/dist/commands/make-page.js +73 -0
  38. package/dist/commands/new.d.ts +33 -0
  39. package/dist/commands/new.js +179 -0
  40. package/dist/commands/shared.d.ts +43 -0
  41. package/dist/commands/shared.js +83 -0
  42. package/dist/describe.d.ts +63 -0
  43. package/dist/describe.js +134 -0
  44. package/dist/doctor/checks.d.ts +35 -0
  45. package/dist/doctor/checks.js +283 -0
  46. package/dist/doctor/ranges.d.ts +16 -0
  47. package/dist/doctor/ranges.js +27 -0
  48. package/dist/doctor/versions.d.ts +33 -0
  49. package/dist/doctor/versions.js +44 -0
  50. package/dist/errors.d.ts +12 -0
  51. package/dist/errors.js +19 -0
  52. package/dist/generate/app.d.ts +27 -0
  53. package/dist/generate/app.js +136 -0
  54. package/dist/generate/component.d.ts +36 -0
  55. package/dist/generate/component.js +48 -0
  56. package/dist/generate/domain.d.ts +31 -0
  57. package/dist/generate/domain.js +63 -0
  58. package/dist/generate/page.d.ts +45 -0
  59. package/dist/generate/page.js +100 -0
  60. package/dist/help.d.ts +19 -0
  61. package/dist/help.js +97 -0
  62. package/dist/in-process.d.ts +26 -0
  63. package/dist/in-process.js +23 -0
  64. package/dist/index.d.ts +9 -0
  65. package/dist/index.js +9 -0
  66. package/dist/new/name.d.ts +7 -0
  67. package/dist/new/name.js +24 -0
  68. package/dist/new/packages.d.ts +6 -0
  69. package/dist/new/packages.js +40 -0
  70. package/dist/new/versions.d.ts +7 -0
  71. package/dist/new/versions.js +13 -0
  72. package/dist/process.d.ts +22 -0
  73. package/dist/process.js +45 -0
  74. package/dist/project.d.ts +22 -0
  75. package/dist/project.js +42 -0
  76. package/dist/root.d.ts +3 -0
  77. package/dist/root.js +24 -0
  78. package/dist/run.d.ts +13 -0
  79. package/dist/run.js +72 -0
  80. package/dist/runtime.d.ts +19 -0
  81. package/dist/runtime.js +1 -0
  82. package/dist/templates.d.ts +26 -0
  83. package/dist/templates.js +46 -0
  84. package/package.json +45 -3
  85. package/templates/app/AGENTS.md.tpl +50 -0
  86. package/templates/app/README.md.tpl +15 -0
  87. package/templates/app/eslint.config.js.tpl +19 -0
  88. package/templates/app/gitignore.tpl +22 -0
  89. package/templates/app/index.html.tpl +12 -0
  90. package/templates/app/mcp.json.tpl +8 -0
  91. package/templates/app/src/App.tsx.tpl +8 -0
  92. package/templates/app/src/i18n.ts.tpl +12 -0
  93. package/templates/app/src/main.tsx.tpl +12 -0
  94. package/templates/app/src/messages/index.ts.tpl +1 -0
  95. package/templates/app/src/providers/app.tsx.tpl +23 -0
  96. package/templates/app/src/providers/repository/index.ts.tpl +5 -0
  97. package/templates/app/src/queries-index.ts.tpl +1 -0
  98. package/templates/app/src/repositories/index.ts.tpl +18 -0
  99. package/templates/app/src/repositories/options.ts.tpl +8 -0
  100. package/templates/app/src/schemas-index.ts.tpl +1 -0
  101. package/templates/app/src/test/render.tsx.tpl +31 -0
  102. package/templates/app/src/test/setup.ts.tpl +4 -0
  103. package/templates/app/typescript.json.tpl +24 -0
  104. package/templates/app/vite.config.ts.tpl +16 -0
  105. package/templates/component/component-test.tsx.tpl +9 -0
  106. package/templates/component/component.tsx.tpl +11 -0
  107. package/templates/domain/queries.ts.tpl +62 -0
  108. package/templates/domain/repository-contract-test.ts.tpl +75 -0
  109. package/templates/domain/repository-contract.ts.tpl +13 -0
  110. package/templates/domain/repository-fixtures.ts.tpl +8 -0
  111. package/templates/domain/repository-index.ts.tpl +12 -0
  112. package/templates/domain/repository-mock.ts.tpl +69 -0
  113. package/templates/domain/schema.ts.tpl +23 -0
  114. package/templates/page/index-domain-test.tsx.tpl +11 -0
  115. package/templates/page/index-test.tsx.tpl +10 -0
  116. package/templates/page/index.tsx.tpl +7 -0
  117. package/templates/page/messages-domain.en.json.tpl +5 -0
  118. package/templates/page/messages-domain.pt-BR.json.tpl +5 -0
  119. package/templates/page/messages.en.json.tpl +3 -0
  120. package/templates/page/messages.pt-BR.json.tpl +3 -0
  121. package/templates/page/model-domain.ts.tpl +17 -0
  122. package/templates/page/model.ts.tpl +8 -0
  123. package/templates/page/view-domain.tsx.tpl +20 -0
  124. package/templates/page/view.tsx.tpl +9 -0
@@ -0,0 +1,435 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { Node, SyntaxKind, } from 'ts-morph';
4
+ import { UsageError } from "../errors.js";
5
+ import { applyEdits, indentOf, innerText, spliceText } from "./edit.js";
6
+ import { isNestRoute, isRouteElement, pathLiteral, patternMatches, usesIdentifier, } from "./route-elements.js";
7
+ const DISPLAY = 'src/App.tsx';
8
+ const CLONE_FILE = '__clone__.tsx';
9
+ /** Abre o `App.tsx` da origem no ts-morph do plano, sem torná-lo parte do plano (não é gravado). */
10
+ export function openOriginApp(plan, file) {
11
+ if (!existsSync(file))
12
+ throw new UsageError(`a origem não tem ${file}.`);
13
+ return { app: plan.morph.createSourceFile(file, readFileSync(file, 'utf8'), { overwrite: true }) };
14
+ }
15
+ /** O `src/App.tsx` do projeto, aberto no plano (uma costura). */
16
+ function openApp(plan) {
17
+ try {
18
+ return plan.source(plan.project.app);
19
+ }
20
+ catch {
21
+ throw new UsageError(`o projeto não tem ${DISPLAY}.`);
22
+ }
23
+ }
24
+ /** O `<Switch>` mais externo do arquivo, o das rotas do app. */
25
+ function topSwitch(app) {
26
+ return app
27
+ .getDescendantsOfKind(SyntaxKind.JsxElement)
28
+ .find((element) => isSwitch(element) &&
29
+ !element
30
+ .getAncestors()
31
+ .some((ancestor) => Node.isJsxElement(ancestor) && isSwitch(ancestor)));
32
+ }
33
+ function isSwitch(element) {
34
+ return element.getOpeningElement().getTagNameNode().getText() === 'Switch';
35
+ }
36
+ /** O `<Route>` mais próximo que envolve o nó, ou `undefined` se ele está no primeiro nível. */
37
+ function parentRoute(node) {
38
+ return node.getAncestors().find(isRouteElement);
39
+ }
40
+ /** Os `<Route>` que são filhos diretos do `<Switch>`. */
41
+ function childRoutes(switchElement) {
42
+ return switchElement.getJsxChildren().filter(isRouteElement);
43
+ }
44
+ /** Troca o recuo de uma linha de origem pelo recuo de destino nas linhas depois da primeira. */
45
+ function reindent(text, from, to) {
46
+ return text
47
+ .split('\n')
48
+ .map((line, index) => index > 0 && line.startsWith(from) ? to + line.slice(from.length) : line)
49
+ .join('\n');
50
+ }
51
+ /**
52
+ * A rota de uma tela da origem: o `<Route>` mais interno que usa o componente e tem o `path` da
53
+ * costura. O mesmo componente pode ter mais de uma rota (`/invoices/:id` e `/single-invoice`), e
54
+ * o `path` do índice diz qual é a da tela.
55
+ */
56
+ function findSourceRoute(origin, spec) {
57
+ const using = origin.app
58
+ .getDescendants()
59
+ .filter(isRouteElement)
60
+ .filter((element) => usesIdentifier(element, spec.component));
61
+ const found = using.find((element) => {
62
+ const literal = pathLiteral(element);
63
+ if (literal === undefined || innerText(literal) !== spec.path)
64
+ return false;
65
+ return !using.some((other) => other !== element && other.getAncestors().includes(element));
66
+ });
67
+ if (!found) {
68
+ throw new UsageError(`a origem não tem, no src/App.tsx dela, a rota '${spec.path}' de '${spec.component}': a especificação da rota não confere com a origem.`);
69
+ }
70
+ return found;
71
+ }
72
+ /** Abre o trecho de JSX num arquivo temporário do plano, para lê-lo, e o remove ao terminar. */
73
+ function withClone(plan, snippet, read) {
74
+ const file = plan.morph.createSourceFile(CLONE_FILE, `const clone = (\n${snippet}\n)\n`, {
75
+ overwrite: true,
76
+ });
77
+ try {
78
+ return read(file);
79
+ }
80
+ finally {
81
+ plan.morph.removeSourceFile(file);
82
+ }
83
+ }
84
+ /** Os nomes que um trecho de JSX usa, fora o nome dos atributos e das propriedades. */
85
+ function usedNames(plan, snippet) {
86
+ return withClone(plan, snippet, (file) => {
87
+ const names = new Set();
88
+ for (const id of file.getDescendantsOfKind(SyntaxKind.Identifier)) {
89
+ const parent = id.getParent();
90
+ if (Node.isJsxAttribute(parent) && parent.getNameNode() === id)
91
+ continue;
92
+ if (Node.isPropertyAccessExpression(parent) && parent.getNameNode() === id)
93
+ continue;
94
+ if (Node.isVariableDeclaration(parent) && parent.getNameNode() === id)
95
+ continue;
96
+ names.add(id.getText());
97
+ }
98
+ return names;
99
+ });
100
+ }
101
+ /** Os nomes que o arquivo declara ou importa no primeiro nível. */
102
+ function declaredNames(file) {
103
+ const names = new Set();
104
+ for (const declaration of file.getImportDeclarations()) {
105
+ const local = [
106
+ declaration.getDefaultImport(),
107
+ declaration.getNamespaceImport(),
108
+ ...declaration.getNamedImports().map((named) => named.getAliasNode() ?? named.getNameNode()),
109
+ ];
110
+ for (const id of local)
111
+ if (id)
112
+ names.add(id.getText());
113
+ }
114
+ for (const statement of file.getStatements()) {
115
+ if (Node.isFunctionDeclaration(statement) || Node.isClassDeclaration(statement)) {
116
+ const name = statement.getName();
117
+ if (name)
118
+ names.add(name);
119
+ }
120
+ else if (Node.isVariableStatement(statement)) {
121
+ for (const declaration of statement.getDeclarations())
122
+ names.add(declaration.getName());
123
+ }
124
+ }
125
+ return names;
126
+ }
127
+ /** O import de origem que traz o nome, ou `undefined` se o nome não é importado. */
128
+ function importOf(file, name) {
129
+ return file.getImportDeclarations().find((declaration) => {
130
+ const local = [
131
+ declaration.getDefaultImport(),
132
+ declaration.getNamespaceImport(),
133
+ ...declaration.getNamedImports().map((named) => named.getAliasNode() ?? named.getNameNode()),
134
+ ];
135
+ return local.some((id) => id?.getText() === name);
136
+ });
137
+ }
138
+ /** Se o projeto tem o pacote em alguma das listas de dependências do `package.json`. */
139
+ function hasPackage(plan, name) {
140
+ const file = path.join(plan.project.root, 'package.json');
141
+ if (!existsSync(file))
142
+ return false;
143
+ try {
144
+ const json = JSON.parse(readFileSync(file, 'utf8'));
145
+ return ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'].some((key) => json[key]?.[name] !== undefined);
146
+ }
147
+ catch {
148
+ return false;
149
+ }
150
+ }
151
+ /** Se o módulo de um import da origem também existe no projeto (alias `@/` ou pacote). */
152
+ function canImport(plan, specifier) {
153
+ if (specifier.startsWith('@/')) {
154
+ const base = path.join(plan.project.src, specifier.slice(2));
155
+ return ['.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.tsx'].some((ext) => plan.hasFile(base + ext));
156
+ }
157
+ if (specifier.startsWith('.'))
158
+ return false;
159
+ const name = specifier.startsWith('@')
160
+ ? specifier.split('/').slice(0, 2).join('/')
161
+ : specifier.split('/')[0];
162
+ return hasPackage(plan, name);
163
+ }
164
+ /**
165
+ * As edições que garantem os nomes que o trecho clonado usa no `App.tsx` do projeto. O nome que
166
+ * o projeto já declara ou importa fica como está. O que falta e a origem importa, de um módulo que
167
+ * o projeto também tem (um layout em `@/components/layout`, o `Redirect` do `wouter`), ganha o
168
+ * import. O que a origem declara no próprio arquivo (o `Private`) não dá para trazer: `UsageError`.
169
+ */
170
+ function importEdits(plan, app, origin, used, skip) {
171
+ const declared = declaredNames(app);
172
+ const inOrigin = declaredNames(origin.app);
173
+ const missing = [...used].filter((name) => name !== skip && inOrigin.has(name) && !declared.has(name));
174
+ const edits = [];
175
+ const cannot = [];
176
+ const lines = [];
177
+ const imports = app.getImportDeclarations();
178
+ for (const name of missing.sort()) {
179
+ const declaration = importOf(origin.app, name);
180
+ const specifier = declaration?.getModuleSpecifierValue();
181
+ if (!declaration || specifier === undefined || !canImport(plan, specifier)) {
182
+ cannot.push(name);
183
+ continue;
184
+ }
185
+ const named = declaration
186
+ .getNamedImports()
187
+ .find((item) => (item.getAliasNode() ?? item.getNameNode()).getText() === name);
188
+ const existing = imports.find((item) => item.getModuleSpecifierValue() === specifier &&
189
+ item.getNamedImports().length > 0 &&
190
+ !item.isTypeOnly());
191
+ if (named && existing) {
192
+ const last = existing.getNamedImports().at(-1);
193
+ edits.push({ pos: last.getEnd(), end: last.getEnd(), text: `, ${named.getText()}` });
194
+ }
195
+ else if (named) {
196
+ lines.push(`import { ${named.getText()} } from '${specifier}'`);
197
+ }
198
+ else {
199
+ lines.push(declaration.getDefaultImport()?.getText() === name
200
+ ? `import ${name} from '${specifier}'`
201
+ : `import * as ${name} from '${specifier}'`);
202
+ }
203
+ }
204
+ if (cannot.length > 0) {
205
+ throw new UsageError(`${DISPLAY} não declara nem importa ${cannot.map((name) => `'${name}'`).join(', ')}, que a rota usa: ${cannot.length === 1 ? 'traga-o' : 'traga-os'} para o ${DISPLAY} do projeto (a casca do app) e rode o comando de novo.`);
206
+ }
207
+ const last = imports.at(-1);
208
+ if (lines.length > 0) {
209
+ if (!last)
210
+ throw new UsageError(`${DISPLAY} não tem imports: não sei onde acrescentar.`);
211
+ edits.push({ pos: last.getEnd(), end: last.getEnd(), text: `\n${lines.join('\n')}` });
212
+ }
213
+ return edits;
214
+ }
215
+ /** O import da tela, na posição alfabética entre os imports de `@/pages`. */
216
+ function componentImportEdit(app, line, importPath) {
217
+ const imports = app.getImportDeclarations();
218
+ const pages = imports.filter((declaration) => declaration.getModuleSpecifierValue().startsWith('@/pages/'));
219
+ const next = pages.find((declaration) => declaration.getModuleSpecifierValue() > importPath);
220
+ if (next)
221
+ return { pos: next.getStart(), end: next.getStart(), text: `${line}\n` };
222
+ const last = pages.at(-1) ?? imports.at(-1);
223
+ if (!last)
224
+ throw new UsageError(`${DISPLAY} não tem imports: não sei onde acrescentar.`);
225
+ return { pos: last.getEnd(), end: last.getEnd(), text: `\n${line}` };
226
+ }
227
+ /** O import da tela como a origem o escreve, se o módulo é o da costura; senão, o import padrão. */
228
+ function originImportLine(origin, spec) {
229
+ const source = importOf(origin.app, spec.component);
230
+ return source?.getModuleSpecifierValue() === spec.importPath
231
+ ? source.getText()
232
+ : `import ${spec.component} from '${spec.importPath}'`;
233
+ }
234
+ /** A edição que põe o clone entre as rotas do `<Switch>`: depois da última com `path`, ou antes da curinga. */
235
+ function insertionEdit(app, switchElement, clone, from) {
236
+ const text = app.getFullText();
237
+ const routes = childRoutes(switchElement);
238
+ const withPath = routes.filter((route) => pathLiteral(route) !== undefined);
239
+ const anchor = withPath.at(-1);
240
+ if (anchor) {
241
+ const indent = indentOf(text, anchor.getStart());
242
+ const separator = /^[ \t]*\n[ \t]*\n/.test(text.slice(anchor.getEnd())) ? '\n\n' : '\n';
243
+ return {
244
+ pos: anchor.getEnd(),
245
+ end: anchor.getEnd(),
246
+ text: `${separator}${indent}${reindent(clone, from, indent)}`,
247
+ };
248
+ }
249
+ const catchAll = routes[0];
250
+ if (!catchAll) {
251
+ // Um <Switch> sem nenhuma rota (o de um app novo): a rota entra sozinha, entre as tags
252
+ const opening = switchElement.getOpeningElement().getEnd();
253
+ const closing = switchElement.getClosingElement().getStart();
254
+ const outer = indentOf(text, switchElement.getStart());
255
+ const inner = `${outer} `;
256
+ return {
257
+ pos: opening,
258
+ end: closing,
259
+ text: `\n${inner}${reindent(clone, from, inner)}\n${outer}`,
260
+ };
261
+ }
262
+ const indent = indentOf(text, catchAll.getStart());
263
+ return {
264
+ pos: catchAll.getStart(),
265
+ end: catchAll.getStart(),
266
+ text: `${reindent(clone, from, indent)}\n\n${indent}`,
267
+ };
268
+ }
269
+ /** Recusa o `path` que repete ou conflita com o de uma irmã (as que estão no mesmo `<Switch>`). */
270
+ function assertFree(switchElement, routePath, display = routePath) {
271
+ const siblings = childRoutes(switchElement).flatMap((route) => {
272
+ const literal = pathLiteral(route);
273
+ return literal ? [innerText(literal)] : [];
274
+ });
275
+ if (siblings.includes(routePath)) {
276
+ throw new UsageError(`${DISPLAY} já tem uma rota '${routePath}', que não é a da tela: escolha outro caminho ou tire a rota antes.`);
277
+ }
278
+ const covering = siblings.find((sibling) => patternMatches(sibling, display));
279
+ if (covering !== undefined) {
280
+ throw new UsageError(`a rota '${routePath}' conflita com a rota '${covering}' que ${DISPLAY} já tem: o wouter escolhe a primeira que casa, e uma das duas ficaria inalcançável.`);
281
+ }
282
+ }
283
+ /**
284
+ * A rota inteira de uma tela de `nest` quando o projeto ainda não tem o `<Route nest>`: o `<Route>`
285
+ * de primeiro nível da origem (com a casca, o `nest` e o layout), só com a rota da tela dentro do
286
+ * `<Switch>` das seções. Sem as irmãs da origem (que não existem no projeto) e sem a rota
287
+ * curinga que redireciona para uma delas.
288
+ */
289
+ function wrapperClone(element) {
290
+ const outer = element.getAncestors().filter(isRouteElement).at(-1);
291
+ const inner = element
292
+ .getAncestors()
293
+ .find((ancestor) => Node.isJsxElement(ancestor) && isSwitch(ancestor));
294
+ if (!outer || !inner) {
295
+ throw new UsageError('a rota da origem está num <Route nest> sem <Switch>: a especificação da rota não confere com a origem.');
296
+ }
297
+ const base = outer.getStart();
298
+ const sourceText = outer.getSourceFile().getFullText();
299
+ const edits = childRoutes(inner)
300
+ .filter((route) => route !== element)
301
+ .map((route) => {
302
+ let start = route.getStart();
303
+ while (start > 0 && /\s/.test(sourceText.charAt(start - 1)))
304
+ start--;
305
+ return { pos: start - base, end: route.getEnd() - base, text: '' };
306
+ });
307
+ return { text: spliceText(outer.getText(), edits), outer };
308
+ }
309
+ /**
310
+ * Faz no `src/App.tsx` do projeto a costura da rota de uma tela, clonando o `<Route>`
311
+ * do `src/App.tsx` da origem:
312
+ *
313
+ * - tela de primeiro nível: o `<Route>` da origem (com a casca e o layout dele) entra depois da
314
+ * última rota com `path` do `<Switch>` mais externo;
315
+ * - tela de um `<Route nest>` (`prefix`): se o projeto já tem o `nest`, a rota da tela entra no
316
+ * `<Switch>` dele; se não tem, entra o `<Route>` de primeiro nível da origem, só com ela.
317
+ *
318
+ * O import do componente entra na posição alfabética dos de `@/pages`, e os nomes que o clone usa
319
+ * (layouts, `Redirect`) ganham import se o projeto tem o módulo. Tela que o `App.tsx` já usa fica
320
+ * como está (devolve `false`). Rota repetida ou conflitante, `App.tsx` ou `<Switch>` que falta,
321
+ * nome que o `App.tsx` não tem e não dá para importar: `UsageError`, sem escrever nada.
322
+ */
323
+ export function addRoute(plan, origin, spec) {
324
+ const app = openApp(plan);
325
+ const routes = app.getDescendants().filter(isRouteElement);
326
+ if (routes.some((route) => usesIdentifier(route, spec.component)))
327
+ return false;
328
+ if (declaredNames(app).has(spec.component)) {
329
+ throw new UsageError(`${DISPLAY} já declara '${spec.component}' sem uma rota para ele: a tela é '${spec.importPath}'.`);
330
+ }
331
+ const element = findSourceRoute(origin, spec);
332
+ const sourceIndent = indentOf(origin.app.getFullText(), element.getStart());
333
+ let target;
334
+ let clone;
335
+ let from = sourceIndent;
336
+ let freePath = spec.path;
337
+ let freeDisplay = spec.path;
338
+ if (spec.prefix === undefined) {
339
+ if (parentRoute(element)) {
340
+ throw new UsageError(`a rota '${spec.path}' de '${spec.component}' está dentro de outro <Route> na origem, e a especificação não diz o prefixo: ela não confere com a origem.`);
341
+ }
342
+ target = topSwitch(app);
343
+ clone = element.getText();
344
+ }
345
+ else {
346
+ const nest = routes.find((route) => {
347
+ const literal = pathLiteral(route);
348
+ return isNestRoute(route) && literal !== undefined && innerText(literal) === spec.prefix;
349
+ });
350
+ if (nest) {
351
+ target = nest.getDescendantsOfKind(SyntaxKind.JsxElement).find(isSwitch);
352
+ clone = element.getText();
353
+ }
354
+ else {
355
+ const wrapper = wrapperClone(element);
356
+ from = indentOf(origin.app.getFullText(), wrapper.outer.getStart());
357
+ clone = wrapper.text;
358
+ target = topSwitch(app);
359
+ const literal = pathLiteral(wrapper.outer);
360
+ freePath = literal ? innerText(literal) : spec.prefix;
361
+ freeDisplay = spec.prefix;
362
+ }
363
+ }
364
+ if (!target)
365
+ throw new UsageError(`${DISPLAY} não tem o <Switch> das rotas.`);
366
+ assertFree(target, freePath, freeDisplay);
367
+ const used = usedNames(plan, clone);
368
+ const edits = [
369
+ insertionEdit(app, target, clone, from),
370
+ componentImportEdit(app, originImportLine(origin, spec), spec.importPath),
371
+ ...importEdits(plan, app, origin, used, spec.component),
372
+ ];
373
+ applyEdits(app, edits);
374
+ return true;
375
+ }
376
+ /** Confere que o trecho é um único `<Route>` com o `path` e o componente da costura. */
377
+ function assertSnippet(plan, spec) {
378
+ const problem = withClone(plan, spec.element, (file) => {
379
+ const initializer = file.getVariableDeclarations()[0]?.getInitializer();
380
+ const root = Node.isParenthesizedExpression(initializer)
381
+ ? initializer.getExpression()
382
+ : initializer;
383
+ if (!root || !isRouteElement(root))
384
+ return 'não é um único <Route>';
385
+ const literal = pathLiteral(root);
386
+ if (literal === undefined || innerText(literal) !== spec.path) {
387
+ return `não tem o path '${spec.path}' (literal) no <Route> de fora`;
388
+ }
389
+ if (!usesIdentifier(root, spec.component))
390
+ return `não usa '${spec.component}'`;
391
+ return undefined;
392
+ });
393
+ if (problem)
394
+ throw new Error(`o trecho da rota ${problem}.`);
395
+ }
396
+ /**
397
+ * Faz no `src/App.tsx` do projeto a costura da rota de uma tela a partir de um trecho de JSX
398
+ * pronto (o `<Route>` que o gerador montou), sem um `App.tsx` de origem para clonar:
399
+ *
400
+ * - o trecho entra no `<Switch>` mais externo, depois da última rota com `path` (ou antes da rota
401
+ * curinga, ou sozinho num `<Switch>` vazio), com o recuo do destino;
402
+ * - o import do componente entra na posição alfabética dos de `@/pages`.
403
+ *
404
+ * Tela que o `App.tsx` já usa fica como está (devolve `false`). Rota repetida ou conflitante,
405
+ * `App.tsx` ou `<Switch>` que falta, componente já declarado sem rota e nome do trecho (um layout,
406
+ * um guarda) que o `App.tsx` não declara nem importa: `UsageError`, sem escrever nada. Trecho que
407
+ * não é um `<Route>` com o `path` e o componente da costura é erro de quem chama (`Error`).
408
+ */
409
+ export function addRouteSnippet(plan, spec) {
410
+ const app = openApp(plan);
411
+ if (app
412
+ .getDescendants()
413
+ .filter(isRouteElement)
414
+ .some((route) => usesIdentifier(route, spec.component))) {
415
+ return false;
416
+ }
417
+ const declared = declaredNames(app);
418
+ if (declared.has(spec.component)) {
419
+ throw new UsageError(`${DISPLAY} já declara '${spec.component}' sem uma rota para ele: a tela é '${spec.importPath}'.`);
420
+ }
421
+ assertSnippet(plan, spec);
422
+ const target = topSwitch(app);
423
+ if (!target)
424
+ throw new UsageError(`${DISPLAY} não tem o <Switch> das rotas.`);
425
+ assertFree(target, spec.path);
426
+ const missing = [...usedNames(plan, spec.element)].filter((name) => /^[A-Z]/.test(name) && name !== spec.component && !declared.has(name));
427
+ if (missing.length > 0) {
428
+ throw new UsageError(`${DISPLAY} não declara nem importa ${missing.map((name) => `'${name}'`).join(', ')}, que a rota usa: ${missing.length === 1 ? 'traga-o' : 'traga-os'} para o ${DISPLAY} e rode o comando de novo.`);
429
+ }
430
+ applyEdits(app, [
431
+ insertionEdit(app, target, spec.element, ''),
432
+ componentImportEdit(app, `import ${spec.component} from '${spec.importPath}'`, spec.importPath),
433
+ ]);
434
+ return true;
435
+ }
@@ -0,0 +1,35 @@
1
+ import { Node, type SourceFile } from 'ts-morph';
2
+ /** Troca do trecho `[pos, end)` do texto por `text`. */
3
+ export interface TextEdit {
4
+ pos: number;
5
+ end: number;
6
+ text: string;
7
+ }
8
+ /** Aplica as edições a um texto, de trás para a frente, para as posições não se deslocarem. */
9
+ export declare function spliceText(source: string, edits: TextEdit[]): string;
10
+ /**
11
+ * Aplica as edições ao arquivo de uma vez, a partir das posições da árvore atual. Editar por
12
+ * posição, em vez de manipular nó a nó, preserva as aspas, os espaços e os comentários do arquivo
13
+ * (o ts-morph reescreveria o trecho) e evita nós esquecidos entre uma edição e outra.
14
+ */
15
+ export declare function applyEdits(file: SourceFile, edits: TextEdit[]): void;
16
+ /** Um literal de texto: `'abc'`, `"abc"` ou um template sem substituição. */
17
+ export type TextLiteral = Node & {
18
+ getLiteralText(): string;
19
+ };
20
+ export declare function isTextLiteral(node: Node | undefined): node is TextLiteral;
21
+ /** O conteúdo do literal como está escrito no arquivo, sem as aspas. */
22
+ export declare function innerText(literal: TextLiteral): string;
23
+ /**
24
+ * A edição que troca o conteúdo do literal e mantém as aspas. Os valores que o codemod escreve
25
+ * (nomes, namespaces, rotas) não têm aspas, barra invertida nem quebra de linha: se tiverem, é
26
+ * erro do chamador, e escrever assim quebraria o arquivo.
27
+ */
28
+ export declare function replaceInner(literal: TextLiteral, value: string): TextEdit;
29
+ /** O recuo da linha onde está a posição `pos`: os espaços do começo da linha. */
30
+ export declare function indentOf(text: string, pos: number): string;
31
+ /** Até onde vai a vírgula que vem logo depois de `end` (só espaços no meio), ou o próprio `end`. */
32
+ export declare function afterComma(text: string, end: number): {
33
+ end: number;
34
+ hasComma: boolean;
35
+ };
@@ -0,0 +1,51 @@
1
+ import { Node } from 'ts-morph';
2
+ /** Aplica as edições a um texto, de trás para a frente, para as posições não se deslocarem. */
3
+ export function spliceText(source, edits) {
4
+ const sorted = [...edits].sort((a, b) => b.pos - a.pos);
5
+ let result = source;
6
+ let limit = source.length;
7
+ for (const edit of sorted) {
8
+ if (edit.end > limit)
9
+ throw new Error('edições do codemod se sobrepõem.');
10
+ result = result.slice(0, edit.pos) + edit.text + result.slice(edit.end);
11
+ limit = edit.pos;
12
+ }
13
+ return result;
14
+ }
15
+ /**
16
+ * Aplica as edições ao arquivo de uma vez, a partir das posições da árvore atual. Editar por
17
+ * posição, em vez de manipular nó a nó, preserva as aspas, os espaços e os comentários do arquivo
18
+ * (o ts-morph reescreveria o trecho) e evita nós esquecidos entre uma edição e outra.
19
+ */
20
+ export function applyEdits(file, edits) {
21
+ if (edits.length === 0)
22
+ return;
23
+ file.replaceWithText(spliceText(file.getFullText(), edits));
24
+ }
25
+ export function isTextLiteral(node) {
26
+ return (node !== undefined && (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node)));
27
+ }
28
+ /** O conteúdo do literal como está escrito no arquivo, sem as aspas. */
29
+ export function innerText(literal) {
30
+ return literal.getText().slice(1, -1);
31
+ }
32
+ /**
33
+ * A edição que troca o conteúdo do literal e mantém as aspas. Os valores que o codemod escreve
34
+ * (nomes, namespaces, rotas) não têm aspas, barra invertida nem quebra de linha: se tiverem, é
35
+ * erro do chamador, e escrever assim quebraria o arquivo.
36
+ */
37
+ export function replaceInner(literal, value) {
38
+ if (/['"`\\\n$]/.test(value))
39
+ throw new Error(`valor inválido para um literal: ${value}`);
40
+ return { pos: literal.getStart() + 1, end: literal.getEnd() - 1, text: value };
41
+ }
42
+ /** O recuo da linha onde está a posição `pos`: os espaços do começo da linha. */
43
+ export function indentOf(text, pos) {
44
+ const lineStart = text.lastIndexOf('\n', pos - 1) + 1;
45
+ return /^[ \t]*/.exec(text.slice(lineStart))?.[0] ?? '';
46
+ }
47
+ /** Até onde vai a vírgula que vem logo depois de `end` (só espaços no meio), ou o próprio `end`. */
48
+ export function afterComma(text, end) {
49
+ const match = /^\s*,/.exec(text.slice(end));
50
+ return match ? { end: end + match[0].length, hasComma: true } : { end, hasComma: false };
51
+ }
@@ -0,0 +1,8 @@
1
+ export { addRoute, addRouteSnippet, openOriginApp, type RouteSnippet, type RouteSpec, } from './add-route.js';
2
+ export { applyEdits, spliceText, type TextEdit } from './edit.js';
3
+ export { mergeBarrel } from './merge-barrel.js';
4
+ export { messageKeys } from './messages.js';
5
+ export { assertNotReserved, assertValidName, deriveNames, domainNames, GLOBAL_NAMES, isValidName, RESERVED_WORDS, singularOf, usableNames, type DomainNames, type Names, } from './names.js';
6
+ export { ChangePlan, type PlanSummary } from './plan.js';
7
+ export { isQueriesRegistered, isRepositoryRegistered, registerDomain, registerQueries, registerQueriesEntry, registerRepository, registerRepositoryEntry, registerSchema, type QueriesEntry, type RepositoryEntry, } from './register-domain.js';
8
+ export { registerMessageNamespace } from './register-messages.js';
@@ -0,0 +1,8 @@
1
+ export { addRoute, addRouteSnippet, openOriginApp, } from "./add-route.js";
2
+ export { applyEdits, spliceText } from "./edit.js";
3
+ export { mergeBarrel } from "./merge-barrel.js";
4
+ export { messageKeys } from "./messages.js";
5
+ export { assertNotReserved, assertValidName, deriveNames, domainNames, GLOBAL_NAMES, isValidName, RESERVED_WORDS, singularOf, usableNames, } from "./names.js";
6
+ export { ChangePlan } from "./plan.js";
7
+ export { isQueriesRegistered, isRepositoryRegistered, registerDomain, registerQueries, registerQueriesEntry, registerRepository, registerRepositoryEntry, registerSchema, } from "./register-domain.js";
8
+ export { registerMessageNamespace } from "./register-messages.js";
@@ -0,0 +1,9 @@
1
+ import type { ChangePlan } from './plan.js';
2
+ /**
3
+ * Costura de um barrel que passa a ser do produto (`src/schemas/index.ts`): acrescenta, no fim da
4
+ * lista de exports do arquivo do projeto, os `export ... from` do barrel da origem que ele ainda
5
+ * não tem (a comparação é pelo módulo), na ordem da origem. Nunca remove nem reordena o que o
6
+ * projeto já tem. Devolve os módulos que acrescentou. `UsageError` se o projeto não tem nenhum
7
+ * export no barrel (não há onde acrescentar).
8
+ */
9
+ export declare function mergeBarrel(plan: ChangePlan, file: string, originFile: string): string[];
@@ -0,0 +1,49 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { UsageError } from "../errors.js";
4
+ import { applyEdits } from "./edit.js";
5
+ /** Os `export ... from '<módulo>'` de um texto, na ordem, com o módulo e o texto da linha. */
6
+ function reExports(plan, text) {
7
+ const file = plan.morph.createSourceFile('__barrel__.ts', text, { overwrite: true });
8
+ try {
9
+ return file
10
+ .getExportDeclarations()
11
+ .filter((declaration) => declaration.hasModuleSpecifier())
12
+ .map((declaration) => ({
13
+ specifier: declaration.getModuleSpecifierValue() ?? '',
14
+ text: declaration.getText(),
15
+ }));
16
+ }
17
+ finally {
18
+ plan.morph.removeSourceFile(file);
19
+ }
20
+ }
21
+ /**
22
+ * Costura de um barrel que passa a ser do produto (`src/schemas/index.ts`): acrescenta, no fim da
23
+ * lista de exports do arquivo do projeto, os `export ... from` do barrel da origem que ele ainda
24
+ * não tem (a comparação é pelo módulo), na ordem da origem. Nunca remove nem reordena o que o
25
+ * projeto já tem. Devolve os módulos que acrescentou. `UsageError` se o projeto não tem nenhum
26
+ * export no barrel (não há onde acrescentar).
27
+ */
28
+ export function mergeBarrel(plan, file, originFile) {
29
+ const index = plan.source(file);
30
+ const present = new Set(index
31
+ .getExportDeclarations()
32
+ .filter((declaration) => declaration.hasModuleSpecifier())
33
+ .map((declaration) => declaration.getModuleSpecifierValue()));
34
+ const missing = reExports(plan, readFileSync(originFile, 'utf8')).filter((item) => !present.has(item.specifier));
35
+ if (missing.length === 0)
36
+ return [];
37
+ const last = index.getExportDeclarations().at(-1);
38
+ if (!last) {
39
+ throw new UsageError(`o barrel '${path.relative(plan.project.root, file)}' não tem nenhum export: não sei onde acrescentar.`);
40
+ }
41
+ applyEdits(index, [
42
+ {
43
+ pos: last.getEnd(),
44
+ end: last.getEnd(),
45
+ text: `\n${missing.map((item) => item.text).join('\n')}`,
46
+ },
47
+ ]);
48
+ return missing.map((item) => item.specifier);
49
+ }
@@ -0,0 +1,11 @@
1
+ import type { Project } from '../project.js';
2
+ import type { ChangePlan } from './plan.js';
3
+ /** Os idiomas do projeto: as pastas de `src/messages` que têm `index.ts`, em ordem. */
4
+ export declare function messageLanguages(project: Project): string[];
5
+ /**
6
+ * As chaves completas das mensagens de uma tela (`fileManager.renameDialog.required`), do JSON de
7
+ * `src/messages/<idioma>/<arquivo>.json` em todos os idiomas do projeto: a união das chaves de
8
+ * cada um, com o namespace (`camel`) na frente. Conta o grupo (`fileManager.renameDialog`) e a
9
+ * mensagem. Idioma sem o arquivo não conta; JSON inválido: `UsageError`.
10
+ */
11
+ export declare function messageKeys(plan: ChangePlan, file: string, camel: string): Set<string>;
@@ -0,0 +1,46 @@
1
+ import { existsSync, readdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { UsageError } from "../errors.js";
4
+ /** Os idiomas do projeto: as pastas de `src/messages` que têm `index.ts`, em ordem. */
5
+ export function messageLanguages(project) {
6
+ if (!existsSync(project.messages))
7
+ throw new UsageError('o projeto não tem src/messages.');
8
+ const languages = readdirSync(project.messages, { withFileTypes: true })
9
+ .filter((entry) => entry.isDirectory() && existsSync(path.join(project.messages, entry.name, 'index.ts')))
10
+ .map((entry) => entry.name)
11
+ .sort();
12
+ if (languages.length === 0)
13
+ throw new UsageError('o projeto não tem idioma em src/messages.');
14
+ return languages;
15
+ }
16
+ /** Os caminhos de um objeto de mensagens, folhas e grupos, em notação de ponto: `a`, `a.b`. */
17
+ function keyPaths(value, prefix, into) {
18
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
19
+ return;
20
+ for (const [key, child] of Object.entries(value)) {
21
+ const full = `${prefix}.${key}`;
22
+ into.add(full);
23
+ keyPaths(child, full, into);
24
+ }
25
+ }
26
+ /**
27
+ * As chaves completas das mensagens de uma tela (`fileManager.renameDialog.required`), do JSON de
28
+ * `src/messages/<idioma>/<arquivo>.json` em todos os idiomas do projeto: a união das chaves de
29
+ * cada um, com o namespace (`camel`) na frente. Conta o grupo (`fileManager.renameDialog`) e a
30
+ * mensagem. Idioma sem o arquivo não conta; JSON inválido: `UsageError`.
31
+ */
32
+ export function messageKeys(plan, file, camel) {
33
+ const keys = new Set();
34
+ for (const language of messageLanguages(plan.project)) {
35
+ const json = path.join(plan.project.messages, language, `${file}.json`);
36
+ if (!plan.hasFile(json))
37
+ continue;
38
+ try {
39
+ keyPaths(JSON.parse(plan.readText(json)), camel, keys);
40
+ }
41
+ catch {
42
+ throw new UsageError(`src/messages/${language}/${file}.json não é um JSON válido.`);
43
+ }
44
+ }
45
+ return keys;
46
+ }