critiqs-react 0.3.0 → 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.
- package/AGENT_SETUP.md +198 -66
- package/README.md +214 -31
- package/bin/critiqs.mjs +3 -1
- package/dist/index.js +16877 -4770
- package/dist/server/index.d.ts +1 -87
- package/dist/server/index.js +1 -4889
- package/package.json +6 -5
- package/bin/cli.d.mts +0 -21
- package/bin/cli.mjs +0 -293
- package/bin/env.d.mts +0 -41
- package/bin/env.mjs +0 -384
- package/bin/init.d.mts +0 -126
- package/bin/init.mjs +0 -965
- package/bin/mcp.d.mts +0 -20
- package/bin/mcp.mjs +0 -314
- package/bin/setup.d.mts +0 -183
- package/bin/setup.mjs +0 -1054
- package/dist/backend/convex/_generated/api.d.ts +0 -95
- package/dist/backend/convex/_generated/api.js +0 -23
- package/dist/backend/convex/_generated/dataModel.d.ts +0 -60
- package/dist/backend/convex/_generated/server.d.ts +0 -162
- package/dist/backend/convex/_generated/server.js +0 -101
- package/dist/backend/convex/ai.ts +0 -93
- package/dist/backend/convex/aiSettings.ts +0 -43
- package/dist/backend/convex/auth.config.ts +0 -18
- package/dist/backend/convex/captureHttp.ts +0 -96
- package/dist/backend/convex/captures.ts +0 -167
- package/dist/backend/convex/crons.ts +0 -14
- package/dist/backend/convex/deviceSignIn.ts +0 -151
- package/dist/backend/convex/grouping.ts +0 -41
- package/dist/backend/convex/http.ts +0 -724
- package/dist/backend/convex/lib/ai.ts +0 -6
- package/dist/backend/convex/lib/links.ts +0 -12
- package/dist/backend/convex/lib/pages.ts +0 -207
- package/dist/backend/convex/lib/r2.ts +0 -75
- package/dist/backend/convex/lib/store.ts +0 -509
- package/dist/backend/convex/lib/tokens.ts +0 -101
- package/dist/backend/convex/lib/validators.ts +0 -73
- package/dist/backend/convex/lib/vendor/aws4fetch.js +0 -289
- package/dist/backend/convex/lib/vendor/critiqs_ai.js +0 -49081
- package/dist/backend/convex/lib/vendor/critiqs_core.js +0 -385
- package/dist/backend/convex/lib/vendor/critiqs_server.js +0 -3108
- package/dist/backend/convex/notificationEmails.ts +0 -61
- package/dist/backend/convex/notifications.ts +0 -182
- package/dist/backend/convex/plans.ts +0 -67
- package/dist/backend/convex/projects.ts +0 -46
- package/dist/backend/convex/schema.ts +0 -343
- package/dist/backend/convex/search.ts +0 -26
- package/dist/backend/convex/signIn.ts +0 -368
- package/dist/backend/convex/tags.ts +0 -68
- package/dist/backend/convex/threads.ts +0 -146
- package/dist/backend/convex/users.ts +0 -13
- package/dist/server/chunks/driver-n9zpr0k3.js +0 -21
- package/dist/server/chunks/index-9bg7tmnq.js +0 -522
- package/dist/server/chunks/index-askcfn7t.js +0 -148
- package/dist/server/chunks/providers-rv184xvj.js +0 -48444
- package/dist/server/chunks/token-kzddms7r.js +0 -63
- package/dist/server/chunks/token-util-k8bee1wc.js +0 -4
package/bin/init.mjs
DELETED
|
@@ -1,965 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `critiqs init`: writes a project ID into the prototype's single `<Critiqs />`
|
|
3
|
-
* component. Dependency-free so it runs under Node and Bun without a build.
|
|
4
|
-
*/
|
|
5
|
-
import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
6
|
-
import { extname, relative, resolve, sep } from "node:path";
|
|
7
|
-
import { applyEnv, describeApp, envVariableOf, planEnv, workspaceMembers, workspacePatterns } from "./env.mjs";
|
|
8
|
-
|
|
9
|
-
/** Convex document IDs (lowercase letters and digits, about 32 characters), or a self-hosted server's (`p_` and 32 hex digits). */
|
|
10
|
-
export const PROJECT_ID_PATTERN = /^([a-z0-9]{16,64}|p_[0-9a-f]{32})$/;
|
|
11
|
-
|
|
12
|
-
export const SOURCE_EXTENSIONS = new Set([".tsx", ".jsx", ".ts", ".js", ".mts", ".mjs"]);
|
|
13
|
-
export const IGNORED_DIRECTORIES = new Set(["node_modules", "dist", "build", "coverage"]);
|
|
14
|
-
|
|
15
|
-
/** Extensions where `<` can start JSX; in .ts and .mts it is a type assertion or generic. */
|
|
16
|
-
const JSX_EXTENSIONS = new Set([".tsx", ".jsx", ".js"]);
|
|
17
|
-
|
|
18
|
-
export const HELP = `Usage: critiqs init <projectId> [--dir <path>] [--entry <file>] [--mount <Element>] [--project-env-file <file>] [--dry-run]
|
|
19
|
-
|
|
20
|
-
Connects the prototype's <Critiqs /> component to a project. Without one, adds
|
|
21
|
-
it where the app renders: a React root (createRoot(…).render), a Next.js root
|
|
22
|
-
layout, or a Next.js custom App. In Vite and Next.js apps the component reads
|
|
23
|
-
the project ID from the app's environment variable, and init sets it in
|
|
24
|
-
.env.local; otherwise init writes the ID into the component. Copy the project
|
|
25
|
-
ID from project setup in the Critiqs sidebar.
|
|
26
|
-
|
|
27
|
-
Options:
|
|
28
|
-
--dir <path> The app's folder (default: current folder)
|
|
29
|
-
--entry <file> The file where the app renders, relative to --dir
|
|
30
|
-
--mount <Element> The element to add <Critiqs /> beside, such as App
|
|
31
|
-
--project-env-file <file> The .env file to set the project ID in, relative to --dir (default: .env.local)
|
|
32
|
-
--dry-run Show the change without writing it
|
|
33
|
-
-h, --help Show this help`;
|
|
34
|
-
|
|
35
|
-
export function isValidProjectId(id) {
|
|
36
|
-
return PROJECT_ID_PATTERN.test(id);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** Source files under `root`, skipping dependencies, build output, dot-directories, and symlinks. */
|
|
40
|
-
export function findSourceFiles(root) {
|
|
41
|
-
const files = [];
|
|
42
|
-
const visit = (dir) => {
|
|
43
|
-
const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1));
|
|
44
|
-
for (const entry of entries) {
|
|
45
|
-
const path = resolve(dir, entry.name);
|
|
46
|
-
if (entry.isDirectory()) {
|
|
47
|
-
if (!entry.name.startsWith(".") && !IGNORED_DIRECTORIES.has(entry.name)) visit(path);
|
|
48
|
-
} else if (entry.isFile() && SOURCE_EXTENSIONS.has(extname(entry.name)) && !/\.d\.m?ts$/.test(entry.name)) {
|
|
49
|
-
files.push(path);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
};
|
|
53
|
-
visit(root);
|
|
54
|
-
return files;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
const ID_START = /[\p{ID_Start}$_]/u;
|
|
58
|
-
const ID_PART = /[\p{ID_Continue}$]/u;
|
|
59
|
-
const WHITESPACE = /\s/;
|
|
60
|
-
/** Previous tokens after which `/` starts a regex and `<` may start JSX. */
|
|
61
|
-
const EXPRESSION_PUNCTUATION = new Set([..."(,=:[!&|?{};+-*%<>~^}"]);
|
|
62
|
-
const EXPRESSION_KEYWORDS = new Set([
|
|
63
|
-
"return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw",
|
|
64
|
-
"case", "do", "else", "yield", "await", "default", "extends",
|
|
65
|
-
]);
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* Finds JSX elements and comments in a source file. A small lexer skips strings,
|
|
69
|
-
* templates, regexes, and comments; JSX is parsed recursively and abandoned when it
|
|
70
|
-
* does not close, so a `<` that was a comparison or TypeScript generic is re-read as code.
|
|
71
|
-
*
|
|
72
|
-
* Returns `elements` named `tagName` (in source order) with their attributes, and
|
|
73
|
-
* `comments` and string/template `literals` as [start, end) ranges.
|
|
74
|
-
*/
|
|
75
|
-
export function scanSource(source, { jsx = true, tagName = "Critiqs" } = {}) {
|
|
76
|
-
const s = source;
|
|
77
|
-
const n = s.length;
|
|
78
|
-
const elements = [];
|
|
79
|
-
/** Every JSX element, with where its children close, for placing a new element. */
|
|
80
|
-
const all = [];
|
|
81
|
-
const comments = [];
|
|
82
|
-
const literals = [];
|
|
83
|
-
/** How many elements enclose the one being parsed. */
|
|
84
|
-
let depth = 0;
|
|
85
|
-
|
|
86
|
-
const skipComment = (i) => {
|
|
87
|
-
if (s[i] !== "/") return -1;
|
|
88
|
-
let end;
|
|
89
|
-
if (s[i + 1] === "/") {
|
|
90
|
-
end = s.indexOf("\n", i);
|
|
91
|
-
if (end === -1) end = n;
|
|
92
|
-
} else if (s[i + 1] === "*") {
|
|
93
|
-
end = s.indexOf("*/", i + 2);
|
|
94
|
-
end = end === -1 ? n : end + 2;
|
|
95
|
-
} else {
|
|
96
|
-
return -1;
|
|
97
|
-
}
|
|
98
|
-
comments.push([i, end]);
|
|
99
|
-
return end;
|
|
100
|
-
};
|
|
101
|
-
|
|
102
|
-
const skipTrivia = (i) => {
|
|
103
|
-
for (;;) {
|
|
104
|
-
while (i < n && WHITESPACE.test(s[i])) i++;
|
|
105
|
-
const end = skipComment(i);
|
|
106
|
-
if (end === -1) return i;
|
|
107
|
-
i = end;
|
|
108
|
-
}
|
|
109
|
-
};
|
|
110
|
-
|
|
111
|
-
const skipString = (i) => {
|
|
112
|
-
const quote = s[i];
|
|
113
|
-
for (i++; i < n && s[i] !== quote && s[i] !== "\n"; i++) {
|
|
114
|
-
if (s[i] === "\\") i++;
|
|
115
|
-
}
|
|
116
|
-
return Math.min(i + 1, n);
|
|
117
|
-
};
|
|
118
|
-
|
|
119
|
-
const skipTemplate = (i) => {
|
|
120
|
-
for (i++; i < n; i++) {
|
|
121
|
-
if (s[i] === "\\") i++;
|
|
122
|
-
else if (s[i] === "`") return i + 1;
|
|
123
|
-
else if (s[i] === "$" && s[i + 1] === "{") {
|
|
124
|
-
const end = skipCode(i + 2, true);
|
|
125
|
-
if (end === -1) return -1;
|
|
126
|
-
i = end;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
return -1;
|
|
130
|
-
};
|
|
131
|
-
|
|
132
|
-
const skipRegex = (i) => {
|
|
133
|
-
let inClass = false;
|
|
134
|
-
for (let j = i + 1; j < n; j++) {
|
|
135
|
-
const c = s[j];
|
|
136
|
-
if (c === "\n") return -1;
|
|
137
|
-
if (c === "\\") j++;
|
|
138
|
-
else if (inClass) inClass = c !== "]";
|
|
139
|
-
else if (c === "[") inClass = true;
|
|
140
|
-
else if (c === "/") {
|
|
141
|
-
for (j++; j < n && ID_PART.test(s[j]); j++);
|
|
142
|
-
return j;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
return -1;
|
|
146
|
-
};
|
|
147
|
-
|
|
148
|
-
/** Skips code up to the closing `}` (returning its index) or the end of the file. -1 if a brace never closes. */
|
|
149
|
-
const skipCode = (i, inBraces) => {
|
|
150
|
-
const fail = inBraces ? -1 : n;
|
|
151
|
-
let prev = "";
|
|
152
|
-
while (i < n) {
|
|
153
|
-
const c = s[i];
|
|
154
|
-
if (WHITESPACE.test(c)) {
|
|
155
|
-
i++;
|
|
156
|
-
continue;
|
|
157
|
-
}
|
|
158
|
-
const commentEnd = skipComment(i);
|
|
159
|
-
if (commentEnd !== -1) {
|
|
160
|
-
i = commentEnd;
|
|
161
|
-
continue;
|
|
162
|
-
}
|
|
163
|
-
const expressionStart = prev === "" || prev === "keyword" || EXPRESSION_PUNCTUATION.has(prev);
|
|
164
|
-
if (c === "}") {
|
|
165
|
-
if (inBraces) return i;
|
|
166
|
-
prev = c;
|
|
167
|
-
i++;
|
|
168
|
-
} else if (c === "{") {
|
|
169
|
-
const end = skipCode(i + 1, true);
|
|
170
|
-
if (end === -1) return fail;
|
|
171
|
-
prev = "}";
|
|
172
|
-
i = end + 1;
|
|
173
|
-
} else if (c === '"' || c === "'") {
|
|
174
|
-
prev = "value";
|
|
175
|
-
const end = skipString(i);
|
|
176
|
-
literals.push([i, end]);
|
|
177
|
-
i = end;
|
|
178
|
-
} else if (c === "`") {
|
|
179
|
-
const end = skipTemplate(i);
|
|
180
|
-
if (end === -1) return fail;
|
|
181
|
-
literals.push([i, end]);
|
|
182
|
-
prev = "value";
|
|
183
|
-
i = end;
|
|
184
|
-
} else if (c === "/" && expressionStart && skipRegex(i) !== -1) {
|
|
185
|
-
prev = "value";
|
|
186
|
-
i = skipRegex(i);
|
|
187
|
-
} else if (c === "<" && jsx && expressionStart && (ID_START.test(s[i + 1] ?? "") || s[i + 1] === ">")) {
|
|
188
|
-
const end = parseElement(i);
|
|
189
|
-
prev = end === -1 ? c : "value";
|
|
190
|
-
i = end === -1 ? i + 1 : end;
|
|
191
|
-
} else if (ID_PART.test(c)) {
|
|
192
|
-
let j = i + 1;
|
|
193
|
-
while (j < n && ID_PART.test(s[j])) j++;
|
|
194
|
-
prev = EXPRESSION_KEYWORDS.has(s.slice(i, j)) ? "keyword" : "word";
|
|
195
|
-
i = j;
|
|
196
|
-
} else {
|
|
197
|
-
prev = c;
|
|
198
|
-
i++;
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
return fail;
|
|
202
|
-
};
|
|
203
|
-
|
|
204
|
-
/** Element, attribute, or closing-tag name: identifiers joined by `.`, `:`, or `-`. */
|
|
205
|
-
const readName = (i) => {
|
|
206
|
-
if (i >= n || !ID_START.test(s[i])) return i;
|
|
207
|
-
let j = i + 1;
|
|
208
|
-
while (j < n && (ID_PART.test(s[j]) || s[j] === "-" || s[j] === "." || s[j] === ":")) j++;
|
|
209
|
-
return j;
|
|
210
|
-
};
|
|
211
|
-
|
|
212
|
-
/** Parses a JSX element starting at `<`; returns the index after it, or -1 (discarding anything found inside). */
|
|
213
|
-
const parseElement = (start) => {
|
|
214
|
-
const elementMark = elements.length;
|
|
215
|
-
const allMark = all.length;
|
|
216
|
-
const commentMark = comments.length;
|
|
217
|
-
const literalMark = literals.length;
|
|
218
|
-
depth++;
|
|
219
|
-
const end = parseElementBody(start);
|
|
220
|
-
depth--;
|
|
221
|
-
if (end === -1) {
|
|
222
|
-
elements.length = elementMark;
|
|
223
|
-
all.length = allMark;
|
|
224
|
-
comments.length = commentMark;
|
|
225
|
-
literals.length = literalMark;
|
|
226
|
-
}
|
|
227
|
-
return end;
|
|
228
|
-
};
|
|
229
|
-
|
|
230
|
-
const parseElementBody = (start) => {
|
|
231
|
-
let i = skipTrivia(start + 1);
|
|
232
|
-
const nameStart = i;
|
|
233
|
-
const nameEnd = readName(i);
|
|
234
|
-
const name = s.slice(nameStart, nameEnd);
|
|
235
|
-
if (name === "" && s[i] !== ">") return -1;
|
|
236
|
-
i = nameEnd;
|
|
237
|
-
|
|
238
|
-
const attributes = [];
|
|
239
|
-
let spreadEnd = null;
|
|
240
|
-
let selfClosing = false;
|
|
241
|
-
for (;;) {
|
|
242
|
-
i = skipTrivia(i);
|
|
243
|
-
if (i >= n) return -1;
|
|
244
|
-
if (s[i] === "/") {
|
|
245
|
-
if (s[i + 1] !== ">") return -1;
|
|
246
|
-
selfClosing = true;
|
|
247
|
-
i += 2;
|
|
248
|
-
break;
|
|
249
|
-
}
|
|
250
|
-
if (s[i] === ">") {
|
|
251
|
-
i++;
|
|
252
|
-
break;
|
|
253
|
-
}
|
|
254
|
-
if (s[i] === "{") {
|
|
255
|
-
const end = skipCode(i + 1, true);
|
|
256
|
-
if (end === -1) return -1;
|
|
257
|
-
i = end + 1;
|
|
258
|
-
spreadEnd = i;
|
|
259
|
-
continue;
|
|
260
|
-
}
|
|
261
|
-
const attributeEnd = readName(i);
|
|
262
|
-
if (attributeEnd === i) return -1;
|
|
263
|
-
const attribute = { name: s.slice(i, attributeEnd), start: i, nameEnd: attributeEnd, value: null };
|
|
264
|
-
i = skipTrivia(attributeEnd);
|
|
265
|
-
if (s[i] === "=") {
|
|
266
|
-
i = skipTrivia(i + 1);
|
|
267
|
-
const valueStart = i;
|
|
268
|
-
if (s[i] === '"' || s[i] === "'") {
|
|
269
|
-
const close = s.indexOf(s[i], i + 1);
|
|
270
|
-
if (close === -1) return -1;
|
|
271
|
-
i = close + 1;
|
|
272
|
-
literals.push([valueStart, i]);
|
|
273
|
-
attribute.value = { kind: "string", start: valueStart, end: i };
|
|
274
|
-
} else if (s[i] === "{") {
|
|
275
|
-
const end = skipCode(i + 1, true);
|
|
276
|
-
if (end === -1) return -1;
|
|
277
|
-
i = end + 1;
|
|
278
|
-
attribute.value = { kind: "expression", start: valueStart, end: i };
|
|
279
|
-
} else if (s[i] === "<") {
|
|
280
|
-
const end = parseElement(i);
|
|
281
|
-
if (end === -1) return -1;
|
|
282
|
-
i = end;
|
|
283
|
-
attribute.value = { kind: "element", start: valueStart, end: i };
|
|
284
|
-
} else {
|
|
285
|
-
return -1;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
attributes.push(attribute);
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
if (name === tagName && nameStart === start + 1) {
|
|
292
|
-
elements.push({ start, nameEnd, end: i, line: lineAt(s, start), attributes, spreadEnd });
|
|
293
|
-
}
|
|
294
|
-
// Filled in once the closing tag is found; `close` stays null for `<X />`.
|
|
295
|
-
const record = { name, start, openEnd: i, end: i, depth: depth - 1, close: null };
|
|
296
|
-
all.push(record);
|
|
297
|
-
if (selfClosing) return i;
|
|
298
|
-
|
|
299
|
-
// Children: raw text, `{expressions}`, nested elements, then the matching closing tag.
|
|
300
|
-
for (;;) {
|
|
301
|
-
const textStart = i;
|
|
302
|
-
while (i < n && s[i] !== "<" && s[i] !== "{") i++;
|
|
303
|
-
if (i >= n) return -1;
|
|
304
|
-
// JSX text is content, not code, so an import written in it does not count.
|
|
305
|
-
if (i > textStart) literals.push([textStart, i]);
|
|
306
|
-
if (s[i] === "{") {
|
|
307
|
-
const end = skipCode(i + 1, true);
|
|
308
|
-
if (end === -1) return -1;
|
|
309
|
-
i = end + 1;
|
|
310
|
-
continue;
|
|
311
|
-
}
|
|
312
|
-
const afterOpen = skipTrivia(i + 1);
|
|
313
|
-
if (s[afterOpen] === "/") {
|
|
314
|
-
const closeStart = skipTrivia(afterOpen + 1);
|
|
315
|
-
const closeEnd = readName(closeStart);
|
|
316
|
-
if (s.slice(closeStart, closeEnd) !== name) return -1;
|
|
317
|
-
const gt = skipTrivia(closeEnd);
|
|
318
|
-
if (s[gt] !== ">") return -1;
|
|
319
|
-
record.close = { start: i, end: gt + 1 };
|
|
320
|
-
record.end = gt + 1;
|
|
321
|
-
return gt + 1;
|
|
322
|
-
}
|
|
323
|
-
const end = parseElement(i);
|
|
324
|
-
if (end === -1) return -1;
|
|
325
|
-
i = end;
|
|
326
|
-
}
|
|
327
|
-
};
|
|
328
|
-
|
|
329
|
-
skipCode(0, false);
|
|
330
|
-
return { elements, all, comments, literals };
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
/** 1-based line number of a character index. */
|
|
334
|
-
export function lineAt(source, index) {
|
|
335
|
-
let line = 1;
|
|
336
|
-
for (let i = source.indexOf("\n"); i !== -1 && i < index; i = source.indexOf("\n", i + 1)) line++;
|
|
337
|
-
return line;
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
const IMPORT_PATTERN =
|
|
341
|
-
/\bimport\s+(?:[\p{ID_Start}$_][\p{ID_Continue}$]*\s*,\s*)?\{([^}]*)\}\s*from\s*(["'])critiqs-react\2/gu;
|
|
342
|
-
|
|
343
|
-
/**
|
|
344
|
-
* Whether the source imports `Critiqs` by name from "critiqs-react": an import
|
|
345
|
-
* declaration starting its own line, outside comments and strings.
|
|
346
|
-
*/
|
|
347
|
-
export function importsCritiqs(source, excluded) {
|
|
348
|
-
if (excluded === undefined) {
|
|
349
|
-
const { comments, literals } = scanSource(source, { jsx: false });
|
|
350
|
-
excluded = [...comments, ...literals];
|
|
351
|
-
}
|
|
352
|
-
for (const match of source.matchAll(IMPORT_PATTERN)) {
|
|
353
|
-
const index = match.index ?? 0;
|
|
354
|
-
if (excluded.some(([start, end]) => index >= start && index < end)) continue;
|
|
355
|
-
if (!/(^|\n)[ \t\uFEFF]*$/.test(source.slice(Math.max(0, source.lastIndexOf("\n", index - 1)), index))) continue;
|
|
356
|
-
const names = (match[1] ?? "").split(",").map((specifier) => specifier.trim());
|
|
357
|
-
if (names.some((name) => name === "Critiqs" || /^Critiqs\s+as\s+Critiqs$/.test(name))) return true;
|
|
358
|
-
}
|
|
359
|
-
return false;
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
/** `<Critiqs>` elements in a file that imports Critiqs; empty otherwise. */
|
|
363
|
-
export function findCritiqsElements(source, { jsx = true } = {}) {
|
|
364
|
-
const { elements, comments, literals } = scanSource(source, { jsx });
|
|
365
|
-
return importsCritiqs(source, [...comments, ...literals]) ? elements : [];
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
const LITERAL_EXPRESSION = /^(\s*)(["'`])([^"'`\\\r\n]*)\2\s*$/;
|
|
369
|
-
|
|
370
|
-
/** The [start, end) range of a string literal's contents in a `projectId` value, or null for code. */
|
|
371
|
-
function literalRange(source, value) {
|
|
372
|
-
if (value.kind === "string") return [value.start + 1, value.end - 1];
|
|
373
|
-
if (value.kind !== "expression") return null;
|
|
374
|
-
const match = LITERAL_EXPRESSION.exec(source.slice(value.start + 1, value.end - 1));
|
|
375
|
-
if (match === null) return null;
|
|
376
|
-
const [, space = "", quote, text = ""] = match;
|
|
377
|
-
if (quote === "`" && text.includes("${")) return null;
|
|
378
|
-
const start = value.start + 1 + space.length + 1;
|
|
379
|
-
return [start, start + text.length];
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
/**
|
|
383
|
-
* A property's value as init writes it: a string literal, `{ expression }` for
|
|
384
|
-
* code such as `import.meta.env.VITE_CRITIQS_PROJECT_ID`, or `true` for a bare
|
|
385
|
-
* attribute such as `requireProjectId`.
|
|
386
|
-
*/
|
|
387
|
-
function propText(name, value) {
|
|
388
|
-
if (value === true) return ` ${name}`;
|
|
389
|
-
if (typeof value === "object" && value !== null) return ` ${name}={${value.expression}}`;
|
|
390
|
-
return ` ${name}="${value}"`;
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
/** The code inside an attribute's `{…}`, trimmed. */
|
|
394
|
-
const expressionText = (source, value) => source.slice(value.start + 1, value.end - 1).trim();
|
|
395
|
-
|
|
396
|
-
/**
|
|
397
|
-
* How to set a property, such as `projectId`, on one element:
|
|
398
|
-
* - insert: no such attribute; adds one right after the tag name.
|
|
399
|
-
* - replace: a string literal value; replaces only its contents.
|
|
400
|
-
* - unchanged: already this value. A bare attribute (`true`) that is present
|
|
401
|
-
* in any form is left as the author wrote it.
|
|
402
|
-
* - expression: the value comes from other code, which init does not edit.
|
|
403
|
-
* - spread: the property comes before spread props that could override it, so init does not edit.
|
|
404
|
-
* With spread props and no such property, it is inserted after the last spread, where it wins.
|
|
405
|
-
* `source` is the edited file for insert and replace; `line` is where the change is.
|
|
406
|
-
*/
|
|
407
|
-
export function planProp(source, element, name, value) {
|
|
408
|
-
const attribute = element.attributes.find((candidate) => candidate.name === name);
|
|
409
|
-
if (attribute !== undefined && element.spreadEnd !== null && attribute.start < element.spreadEnd) {
|
|
410
|
-
return { action: "spread", line: lineAt(source, attribute.start) };
|
|
411
|
-
}
|
|
412
|
-
const splice = (index, removeEnd, text) => ({
|
|
413
|
-
source: source.slice(0, index) + text + source.slice(removeEnd),
|
|
414
|
-
line: lineAt(source, index),
|
|
415
|
-
});
|
|
416
|
-
if (attribute === undefined) {
|
|
417
|
-
const at = element.spreadEnd ?? element.nameEnd;
|
|
418
|
-
return { action: "insert", ...splice(at, at, propText(name, value)) };
|
|
419
|
-
}
|
|
420
|
-
const line = lineAt(source, attribute.start);
|
|
421
|
-
if (value === true) return { action: "unchanged", line };
|
|
422
|
-
if (typeof value === "object" && value !== null) {
|
|
423
|
-
const same = attribute.value?.kind === "expression" && expressionText(source, attribute.value) === value.expression;
|
|
424
|
-
return { action: same ? "unchanged" : "expression", line };
|
|
425
|
-
}
|
|
426
|
-
if (attribute.value === null) {
|
|
427
|
-
return { action: "replace", ...splice(attribute.nameEnd, attribute.nameEnd, `="${value}"`) };
|
|
428
|
-
}
|
|
429
|
-
const range = literalRange(source, attribute.value);
|
|
430
|
-
if (range === null) return { action: "expression", line };
|
|
431
|
-
if (source.slice(range[0], range[1]) === value) return { action: "unchanged", line };
|
|
432
|
-
return { action: "replace", ...splice(range[0], range[1], value) };
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
/** Whether an element has a property with this value, in the sense of `planProp`'s "unchanged". */
|
|
436
|
-
function hasProp(source, element, name, value) {
|
|
437
|
-
const attribute = element.attributes.find((candidate) => candidate.name === name);
|
|
438
|
-
if (attribute === undefined) return false;
|
|
439
|
-
if (value === true) return true;
|
|
440
|
-
if (typeof value === "object" && value !== null) return attribute.value?.kind === "expression" && expressionText(source, attribute.value) === value.expression;
|
|
441
|
-
return readProp(source, element, name)?.value === value;
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
/** How to set `projectId` on one element; see `planProp`. */
|
|
445
|
-
export function planProjectId(source, element, projectId) {
|
|
446
|
-
return planProp(source, element, "projectId", projectId);
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
/**
|
|
450
|
-
* A string property's value on one element: a literal's text, `expression`
|
|
451
|
-
* (with its code as `text`) when code sets it, or null when it is absent.
|
|
452
|
-
*/
|
|
453
|
-
export function readProp(source, element, name) {
|
|
454
|
-
const attribute = element.attributes.find((candidate) => candidate.name === name);
|
|
455
|
-
if (attribute === undefined) return null;
|
|
456
|
-
if (attribute.value === null) return { kind: "literal", value: "" };
|
|
457
|
-
const range = literalRange(source, attribute.value);
|
|
458
|
-
if (range !== null) return { kind: "literal", value: source.slice(range[0], range[1]) };
|
|
459
|
-
return attribute.value.kind === "expression" ? { kind: "expression", text: expressionText(source, attribute.value) } : { kind: "expression" };
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
/** Every `<Critiqs>` element under `root`, with its file and source. */
|
|
463
|
-
export function findCritiqsUsages(root) {
|
|
464
|
-
const usages = [];
|
|
465
|
-
for (const file of findSourceFiles(root)) {
|
|
466
|
-
const source = readFileSync(file, "utf8");
|
|
467
|
-
if (!source.includes("critiqs-react")) continue;
|
|
468
|
-
const jsx = JSX_EXTENSIONS.has(extname(file));
|
|
469
|
-
for (const element of findCritiqsElements(source, { jsx })) usages.push({ file, source, element });
|
|
470
|
-
}
|
|
471
|
-
return usages;
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
// ---------------------------------------------------------------------------
|
|
476
|
-
// Adding <Critiqs /> where the app renders
|
|
477
|
-
|
|
478
|
-
/** A Next.js App Router root layout: Critiqs goes inside `<body>`. */
|
|
479
|
-
const NEXT_APP_LAYOUT = /^(src\/)?app\/layout\.(tsx|jsx|js)$/;
|
|
480
|
-
/** A Next.js Pages Router custom App: Critiqs goes beside `<Component {...pageProps} />`. */
|
|
481
|
-
const NEXT_PAGES_APP = /^(src\/)?pages\/_app\.(tsx|jsx|js)$/;
|
|
482
|
-
/** Tests, stories, and fixtures render React too, but they aren't the app. */
|
|
483
|
-
const NOT_APP_CODE = /(^|\/)(__tests__|__mocks__|__fixtures__|fixtures|tests?|e2e|cypress|playwright|stories|\.storybook)\/|\.(test|spec|stories|story)\.[a-z]+$/;
|
|
484
|
-
const REACT_DOM_IMPORT = /(?:\bfrom\s*|\brequire\s*\(\s*)(["'])react-dom(?:\/client)?\1/g;
|
|
485
|
-
/** Code right before the element React's root renders: `root.render(`, `ReactDOM.render(`, `hydrate(`. */
|
|
486
|
-
const RENDER_CALL = /(?:^|[^\w$])(?:render|hydrate)\s*\(\s*$/;
|
|
487
|
-
/** `hydrateRoot(container, ` right before the element. */
|
|
488
|
-
const HYDRATE_ROOT_CALL = /\bhydrateRoot\s*\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*,\s*$/;
|
|
489
|
-
/** Ways of using Critiqs that init can't follow: under another name, as a namespace, re-exported, or loaded at run time. */
|
|
490
|
-
const OTHER_CRITIQS_USE = [
|
|
491
|
-
/\bCritiqs\s+as\s+(?!Critiqs\b)[\p{ID_Start}$_]/gu,
|
|
492
|
-
/\*\s*as\s+[\p{ID_Start}$_][\p{ID_Continue}$]*\s+from\s*(["'])critiqs-react\1/gu,
|
|
493
|
-
/\bexport\s*\{[^}]*\bCritiqs\b[^}]*\}\s*from\s*(["'])critiqs-react\1/g,
|
|
494
|
-
/\b(?:require|import)\s*\(\s*(["'])critiqs-react\1\s*\)/g,
|
|
495
|
-
];
|
|
496
|
-
const IMPORT_DECLARATION = /^[ \t]*import\b(?!\s*[(.])[^"'`;]*?(["'])[^"'\n]*\1[ \t]*;?/gm;
|
|
497
|
-
const LEADING = /^?(?:#![^\n]*\n)?(?:\s*(?:\/\/[^\n]*|\/\*[\s\S]*?\*\/|(["'])use [\w ]+\1;?))*[ \t]*\n?/;
|
|
498
|
-
|
|
499
|
-
/** Where each kind of place is described to people. */
|
|
500
|
-
export const MOUNT_KINDS = {
|
|
501
|
-
"next-app": "Next.js root layout",
|
|
502
|
-
"next-pages": "Next.js custom App",
|
|
503
|
-
"react-root": "React root",
|
|
504
|
-
chosen: "chosen element",
|
|
505
|
-
};
|
|
506
|
-
|
|
507
|
-
const posix = (path) => path.split(sep).join("/");
|
|
508
|
-
const outside = (index, ranges) => !ranges.some(([start, end]) => index >= start && index < end);
|
|
509
|
-
const matchesOutside = (source, pattern, ranges) => [...source.matchAll(pattern)].some((match) => outside(match.index ?? 0, ranges));
|
|
510
|
-
|
|
511
|
-
/**
|
|
512
|
-
* Elements in one file that `<Critiqs />` can go beside, by what the file is:
|
|
513
|
-
* a Next.js root layout's `<body>`, a Next.js custom App's `<Component>`, or
|
|
514
|
-
* the element a React root renders (`createRoot(…).render(<App />)`,
|
|
515
|
-
* `ReactDOM.render`, `hydrateRoot`). `mount` names the element instead.
|
|
516
|
-
* `path` is relative to the app's folder, with `/`.
|
|
517
|
-
*/
|
|
518
|
-
export function mountPointsIn(source, path, { mount = null, explicit = false } = {}) {
|
|
519
|
-
if (!JSX_EXTENSIONS.has(extname(path))) return [];
|
|
520
|
-
const { all, comments, literals } = scanSource(source);
|
|
521
|
-
const point = (kind) => (element) => ({ kind, element, line: lineAt(source, element.start) });
|
|
522
|
-
if (mount !== null) return all.filter((element) => element.name === mount).map(point("chosen"));
|
|
523
|
-
if (NEXT_APP_LAYOUT.test(path)) return all.filter((element) => element.name === "body" && element.close !== null).map(point("next-app"));
|
|
524
|
-
if (NEXT_PAGES_APP.test(path)) return all.filter((element) => element.name === "Component").map(point("next-pages"));
|
|
525
|
-
if (!explicit && NOT_APP_CODE.test(path)) return [];
|
|
526
|
-
if (!matchesOutside(source, REACT_DOM_IMPORT, [...comments, ...literals])) return [];
|
|
527
|
-
return all
|
|
528
|
-
.filter((element) => {
|
|
529
|
-
if (element.depth !== 0) return false;
|
|
530
|
-
const before = source.slice(Math.max(0, element.start - 400), element.start);
|
|
531
|
-
return RENDER_CALL.test(before) || HYDRATE_ROOT_CALL.test(before);
|
|
532
|
-
})
|
|
533
|
-
.map(point("react-root"));
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
/** Places under `root` where `<Critiqs />` can go; `entry` limits the search to one file. */
|
|
537
|
-
export function findMountPoints(root, { entry = null, mount = null } = {}) {
|
|
538
|
-
const files = entry === null ? findSourceFiles(root) : [resolve(root, entry)];
|
|
539
|
-
const points = [];
|
|
540
|
-
for (const file of files) {
|
|
541
|
-
const source = readFileSync(file, "utf8");
|
|
542
|
-
for (const point of mountPointsIn(source, posix(relative(root, file)), { mount, explicit: entry !== null })) {
|
|
543
|
-
points.push({ file, source, ...point });
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
return points;
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
/** ` name="value"` (or `name={code}`, or a bare `name`) for each property, in order. */
|
|
550
|
-
export function propsText(props) {
|
|
551
|
-
return Object.entries(props)
|
|
552
|
-
.map(([name, value]) => propText(name, value))
|
|
553
|
-
.join("");
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
/** Add a sibling unless the chosen mount is a known container (the root body or a fragment). */
|
|
557
|
-
function placeElement(source, element, tag, container = false) {
|
|
558
|
-
if (element.close === null || (!container && element.name !== "")) {
|
|
559
|
-
const end = element.close?.end ?? element.end;
|
|
560
|
-
const original = source.slice(element.start, end);
|
|
561
|
-
return { source: `${source.slice(0, element.start)}<>${original}${tag}</>${source.slice(end)}`, at: element.start };
|
|
562
|
-
}
|
|
563
|
-
const closeAt = element.close.start;
|
|
564
|
-
const lineStart = source.lastIndexOf("\n", closeAt - 1) + 1;
|
|
565
|
-
const closeIndent = source.slice(lineStart, closeAt);
|
|
566
|
-
if (!/^[ \t]*$/.test(closeIndent)) return { source: source.slice(0, closeAt) + tag + source.slice(closeAt), at: closeAt };
|
|
567
|
-
// On its own line, indented like the other children.
|
|
568
|
-
const children = source.slice(element.openEnd, lineStart);
|
|
569
|
-
const childIndent = /\n([ \t]*)\S/.exec(children)?.[1] ?? `${closeIndent}${closeIndent.includes("\t") ? "\t" : " "}`;
|
|
570
|
-
return { source: `${source.slice(0, lineStart)}${childIndent}${tag}\n${source.slice(lineStart)}`, at: lineStart };
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
/** Insert before an existing import, leaving its attributes and complete declaration intact. */
|
|
574
|
-
function placeImport(source) {
|
|
575
|
-
const { comments, literals } = scanSource(source);
|
|
576
|
-
const excluded = [...comments, ...literals];
|
|
577
|
-
let last = null;
|
|
578
|
-
for (const match of source.matchAll(IMPORT_DECLARATION)) {
|
|
579
|
-
if (outside(match.index ?? 0, excluded)) last = match;
|
|
580
|
-
}
|
|
581
|
-
if (last !== null) {
|
|
582
|
-
const start = last.index ?? 0;
|
|
583
|
-
const semicolon = last[0].trimEnd().endsWith(";") ? ";" : "";
|
|
584
|
-
return source.slice(0, start) + `import { Critiqs } from ${last[1]}critiqs-react${last[1]}${semicolon}\n` + source.slice(start);
|
|
585
|
-
}
|
|
586
|
-
const end = LEADING.exec(source)?.[0].length ?? 0;
|
|
587
|
-
const lead = source.slice(0, end);
|
|
588
|
-
const rest = source.slice(end);
|
|
589
|
-
const separator = lead === "" || lead.endsWith("\n") ? "" : "\n";
|
|
590
|
-
return `${lead}${separator}import { Critiqs } from "critiqs-react";\n${rest.startsWith("\n") ? "" : "\n"}${rest}`;
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
/** The lines that differ between two versions of a file, with `-` and `+`, for a preview. */
|
|
594
|
-
export function changedLines(before, after) {
|
|
595
|
-
const a = before.split("\n");
|
|
596
|
-
const b = after.split("\n");
|
|
597
|
-
let start = 0;
|
|
598
|
-
while (start < a.length && start < b.length && a[start] === b[start]) start++;
|
|
599
|
-
let end = 0;
|
|
600
|
-
while (end < a.length - start && end < b.length - start && a[a.length - 1 - end] === b[b.length - 1 - end]) end++;
|
|
601
|
-
return [
|
|
602
|
-
...a.slice(start, a.length - end).map((line) => `- ${line}`),
|
|
603
|
-
...b.slice(start, b.length - end).map((line) => `+ ${line}`),
|
|
604
|
-
];
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
/**
|
|
608
|
-
* Plans adding `<Critiqs />` with `props` to the one place under `root` where
|
|
609
|
-
* the app renders, importing it from "critiqs-react". Writes nothing.
|
|
610
|
-
* Refuses, with a reason, when Critiqs is used in a way init can't follow,
|
|
611
|
-
* when there is no recognizable place or several, or when `Critiqs` already
|
|
612
|
-
* names something else in that file.
|
|
613
|
-
*/
|
|
614
|
-
export function planInstall(root, props, { entry = null, mount = null } = {}) {
|
|
615
|
-
for (const file of findSourceFiles(root)) {
|
|
616
|
-
const source = readFileSync(file, "utf8");
|
|
617
|
-
if (!source.includes("critiqs-react")) continue;
|
|
618
|
-
const { comments, literals } = scanSource(source, { jsx: JSX_EXTENSIONS.has(extname(file)) });
|
|
619
|
-
if (OTHER_CRITIQS_USE.some((pattern) => matchesOutside(source, pattern, [...comments, ...literals]))) {
|
|
620
|
-
return { ok: false, reason: "other-use", file };
|
|
621
|
-
}
|
|
622
|
-
}
|
|
623
|
-
if (entry !== null) {
|
|
624
|
-
let isFile = false;
|
|
625
|
-
try {
|
|
626
|
-
isFile = statSync(resolve(root, entry)).isFile();
|
|
627
|
-
} catch {}
|
|
628
|
-
if (!isFile) return { ok: false, reason: "no-entry", entry };
|
|
629
|
-
}
|
|
630
|
-
const points = findMountPoints(root, { entry, mount });
|
|
631
|
-
if (points.length === 0) return { ok: false, reason: "no-root", entry, mount };
|
|
632
|
-
if (points.length > 1) return { ok: false, reason: "several-roots", points };
|
|
633
|
-
const [point] = points;
|
|
634
|
-
const { comments, literals } = scanSource(point.source);
|
|
635
|
-
const imported = importsCritiqs(point.source, [...comments, ...literals]);
|
|
636
|
-
if (!imported && matchesOutside(point.source, /(?<![\p{ID_Continue}$.])Critiqs(?![\p{ID_Continue}$])/gu, [...comments, ...literals])) {
|
|
637
|
-
return { ok: false, reason: "name-taken", file: point.file, line: point.line };
|
|
638
|
-
}
|
|
639
|
-
const placed = placeElement(point.source, point.element, `<Critiqs${propsText(props)} />`, point.kind === "next-app");
|
|
640
|
-
const source = imported ? placed.source : placeImport(placed.source);
|
|
641
|
-
// The result must read back as exactly one Critiqs, with these settings.
|
|
642
|
-
const [added, ...extra] = findCritiqsElements(source);
|
|
643
|
-
if (added === undefined || extra.length > 0 || Object.entries(props).some(([name, value]) => !hasProp(source, added, name, value))) {
|
|
644
|
-
return { ok: false, reason: "unreadable", file: point.file, line: point.line };
|
|
645
|
-
}
|
|
646
|
-
// One preview per edit, so a reader sees exactly what each adds.
|
|
647
|
-
const preview = [...changedLines(point.source, placed.source), ...(imported ? [] : changedLines(placed.source, source))];
|
|
648
|
-
return { ok: true, file: point.file, original: point.source, source, kind: point.kind, line: added.line, imported: !imported, preview };
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
/**
|
|
652
|
-
* Plans setting string properties, such as `projectId` and `backend`, on the
|
|
653
|
-
* prototype's one `<Critiqs />`; with none, plans adding it where the app
|
|
654
|
-
* renders (`planInstall`). Writes nothing; `applyPlan` writes the one file.
|
|
655
|
-
* Every property is set, or the plan refuses with a reason.
|
|
656
|
-
*/
|
|
657
|
-
export function planComponent(root, props, { entry = null, mount = null } = {}) {
|
|
658
|
-
let isDirectory = false;
|
|
659
|
-
try {
|
|
660
|
-
isDirectory = statSync(root).isDirectory();
|
|
661
|
-
} catch {}
|
|
662
|
-
if (!isDirectory) return { ok: false, reason: "not-folder" };
|
|
663
|
-
const usages = findCritiqsUsages(root);
|
|
664
|
-
if (usages.length > 1) return { ok: false, reason: "several", usages };
|
|
665
|
-
if (usages.length === 0) {
|
|
666
|
-
const install = planInstall(root, props, { entry, mount });
|
|
667
|
-
return install.ok ? { ...install, action: "install", changed: Object.keys(props) } : install;
|
|
668
|
-
}
|
|
669
|
-
const [{ file, element }] = usages;
|
|
670
|
-
let source = usages[0].source;
|
|
671
|
-
let current = element;
|
|
672
|
-
const changed = [];
|
|
673
|
-
// Each new property goes right after the tag name, so add them last first to keep their order.
|
|
674
|
-
for (const [name, value] of Object.entries(props).reverse()) {
|
|
675
|
-
const plan = planProp(source, current, name, value);
|
|
676
|
-
if (plan.action === "expression" || plan.action === "spread") return { ok: false, reason: plan.action, file, line: plan.line, name, value };
|
|
677
|
-
if (plan.action === "unchanged") continue;
|
|
678
|
-
source = plan.source;
|
|
679
|
-
changed.push(name);
|
|
680
|
-
// Later properties are planned against the edited source.
|
|
681
|
-
const next = findCritiqsElements(source, { jsx: JSX_EXTENSIONS.has(extname(file)) });
|
|
682
|
-
if (next.length !== 1) return { ok: false, reason: "unreadable", file, line: element.line };
|
|
683
|
-
current = next[0];
|
|
684
|
-
}
|
|
685
|
-
changed.reverse();
|
|
686
|
-
return {
|
|
687
|
-
ok: true,
|
|
688
|
-
action: changed.length === 0 ? "unchanged" : "update",
|
|
689
|
-
file,
|
|
690
|
-
original: usages[0].source,
|
|
691
|
-
source,
|
|
692
|
-
line: element.line,
|
|
693
|
-
changed,
|
|
694
|
-
};
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
/** Writes a plan's file, if it changes anything. */
|
|
698
|
-
export function applyPlan(plan) {
|
|
699
|
-
if (plan.ok && plan.source !== plan.original) writeFileSync(plan.file, plan.source);
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
/** How to add Critiqs by hand, for when init can't. */
|
|
703
|
-
export function manualInstructions(props) {
|
|
704
|
-
return [
|
|
705
|
-
`Add it where the app renders, imported with import { Critiqs } from "critiqs-react":`,
|
|
706
|
-
"",
|
|
707
|
-
` <Critiqs${propsText(props)} />`,
|
|
708
|
-
"",
|
|
709
|
-
"- A single-page app (Vite, Create React App, and others): next to <App /> in the file that calls createRoot(…).render(…).",
|
|
710
|
-
"- Next.js App Router: inside <body> in app/layout.tsx.",
|
|
711
|
-
"- Next.js Pages Router: next to <Component {...pageProps} /> in pages/_app.tsx.",
|
|
712
|
-
"- Anything else: in the component every page renders.",
|
|
713
|
-
"Or name the file for init to edit: --entry <file>, and the element to add it beside: --mount <Element>.",
|
|
714
|
-
].join("\n");
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
/** Why a plan refused, as complete sentences with what to do. `where` shows a file and line. */
|
|
718
|
-
export function refusal(plan, props, where, folder) {
|
|
719
|
-
switch (plan.reason) {
|
|
720
|
-
case "not-folder":
|
|
721
|
-
return `${folder} is not a folder.`;
|
|
722
|
-
case "several":
|
|
723
|
-
return (
|
|
724
|
-
`Found ${plan.usages.length} <Critiqs /> components, so nothing was changed:\n` +
|
|
725
|
-
`${plan.usages.map(({ file, element }) => ` ${where(file, element.line)}`).join("\n")}\n\n` +
|
|
726
|
-
`Keep one, where the app renders, and set on it:${propsText(props)}`
|
|
727
|
-
);
|
|
728
|
-
case "expression":
|
|
729
|
-
return `${where(plan.file, plan.line)} sets ${plan.name} from code, so nothing was changed. Set it to: ${typeof plan.value === "object" ? `{${plan.value.expression}}` : plan.value}`;
|
|
730
|
-
case "spread":
|
|
731
|
-
return `${where(plan.file, plan.line)} sets ${plan.name} before spread props that could override it, so nothing was changed. Move${propText(plan.name, plan.value)} after the spread.`;
|
|
732
|
-
case "other-use":
|
|
733
|
-
return (
|
|
734
|
-
`${where(plan.file, 1).replace(/:1$/, "")} uses Critiqs under another name or loads it another way, so init didn't add a second one. ` +
|
|
735
|
-
`Set these properties on that component yourself:${propsText(props)}`
|
|
736
|
-
);
|
|
737
|
-
case "no-entry":
|
|
738
|
-
return `${plan.entry} is not a file in ${folder}. Name the file where the app renders, relative to that folder.`;
|
|
739
|
-
case "no-root":
|
|
740
|
-
return (
|
|
741
|
-
`No <Critiqs /> component found in ${folder}.\n` +
|
|
742
|
-
(plan.mount !== null
|
|
743
|
-
? `There is no <${plan.mount}> element ${plan.entry === null ? "there" : `in ${plan.entry}`}, so nothing was changed.\n`
|
|
744
|
-
: plan.entry !== null
|
|
745
|
-
? `${plan.entry} doesn't render a React root, Next.js layout, or custom App init recognizes, so nothing was changed. Name the element to add it beside with --mount <Element>.\n`
|
|
746
|
-
: "Init didn't find where the app renders, so nothing was changed.\n") +
|
|
747
|
-
manualInstructions(props)
|
|
748
|
-
);
|
|
749
|
-
case "several-roots":
|
|
750
|
-
return (
|
|
751
|
-
`Found ${plan.points.length} places the app could render Critiqs, so nothing was changed:\n` +
|
|
752
|
-
`${plan.points.map((point) => ` ${where(point.file, point.line)} (${MOUNT_KINDS[point.kind]}${point.kind === "chosen" ? `, <${point.element.name}>` : ""})`).join("\n")}\n\n` +
|
|
753
|
-
"Choose one with --entry <file> (and --mount <Element> if that file has several), or add it yourself:\n\n" +
|
|
754
|
-
` <Critiqs${propsText(props)} />`
|
|
755
|
-
);
|
|
756
|
-
case "name-taken":
|
|
757
|
-
return `${where(plan.file, plan.line)} already uses the name Critiqs for something else, so nothing was changed. ${manualInstructions(props)}`;
|
|
758
|
-
default:
|
|
759
|
-
return `Couldn't safely edit ${where(plan.file, plan.line)}, so nothing was changed. ${manualInstructions(props)}`;
|
|
760
|
-
}
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
// ---------------------------------------------------------------------------
|
|
764
|
-
// Connecting through the app's environment
|
|
765
|
-
|
|
766
|
-
/**
|
|
767
|
-
* How the code names the project:
|
|
768
|
-
* - "env": the component reads one public environment variable of the app's
|
|
769
|
-
* framework (Vite or Next.js), and init sets it in a `.env` file on this
|
|
770
|
-
* computer. Each deployment sets its own, so each can use its own project,
|
|
771
|
-
* and a copy without one shows nothing. `addFlag` adds `requireProjectId`
|
|
772
|
-
* when init writes the expression; existing wiring is kept as written.
|
|
773
|
-
* - "literal": init writes the ID into the component, as for components that
|
|
774
|
-
* already name one and builds whose public settings init doesn't know.
|
|
775
|
-
* `problem` says why init can't wire this app safely, and what to do.
|
|
776
|
-
*/
|
|
777
|
-
export function chooseWiring(root, { envFile = null } = {}) {
|
|
778
|
-
const app = describeApp(root, { envFile });
|
|
779
|
-
const literal = { mode: "literal", app };
|
|
780
|
-
let usages = [];
|
|
781
|
-
try {
|
|
782
|
-
usages = findCritiqsUsages(root);
|
|
783
|
-
} catch {}
|
|
784
|
-
if (usages.length > 1) return literal;
|
|
785
|
-
const current = usages.length === 1 ? readProp(usages[0].source, usages[0].element, "projectId") : null;
|
|
786
|
-
if (current?.kind === "literal") return literal;
|
|
787
|
-
if (current?.kind === "expression") {
|
|
788
|
-
const variable = envVariableOf(current.text, app);
|
|
789
|
-
return variable === null ? literal : { mode: "env", app, variable, addFlag: false, problem: app.problem };
|
|
790
|
-
}
|
|
791
|
-
if (app.framework === null) return literal;
|
|
792
|
-
if (app.customPrefix) {
|
|
793
|
-
return {
|
|
794
|
-
mode: "env",
|
|
795
|
-
app,
|
|
796
|
-
problem:
|
|
797
|
-
"This app's Vite config sets envPrefix, so init can't tell which variable names reach the browser, and nothing was changed. " +
|
|
798
|
-
"Give <Critiqs /> projectId={import.meta.env.<a name with your prefix>} requireProjectId, then run init again to set it.",
|
|
799
|
-
};
|
|
800
|
-
}
|
|
801
|
-
return { mode: "env", app, variable: app.variable, addFlag: true, problem: app.problem };
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
/** The component's properties for a connection: the ID, or the expression that reads it, then `backend` when given. */
|
|
805
|
-
export function connectionProps(wiring, projectId, backend) {
|
|
806
|
-
const withBackend = backend === undefined || backend === null ? {} : { backend };
|
|
807
|
-
if (wiring.mode !== "env") return { projectId, ...withBackend };
|
|
808
|
-
return { projectId: { expression: `${wiring.app.access}.${wiring.variable}` }, ...(wiring.addFlag ? { requireProjectId: true } : {}), ...withBackend };
|
|
809
|
-
}
|
|
810
|
-
|
|
811
|
-
/** What each deployment does with an environment-backed project ID. */
|
|
812
|
-
export function deploymentAdvice(wiring) {
|
|
813
|
-
const reads = wiring.app.framework === "next" ? "Next.js" : "Vite";
|
|
814
|
-
return (
|
|
815
|
-
`Set ${wiring.variable} in each deployment's build settings to that deployment's project ID (${reads} reads it when the app is built, so rebuild after changing it), ` +
|
|
816
|
-
"and leave it unset where Critiqs shouldn't appear."
|
|
817
|
-
);
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
/**
|
|
821
|
-
* When `root` declares a workspace: its packages where an app renders or
|
|
822
|
-
* already uses Critiqs, which each get their own project. null for a folder
|
|
823
|
-
* that declares no workspace.
|
|
824
|
-
*/
|
|
825
|
-
export function workspaceApps(root) {
|
|
826
|
-
const patterns = workspacePatterns(root);
|
|
827
|
-
if (patterns === null) return null;
|
|
828
|
-
return workspaceMembers(root, patterns).filter((dir) => {
|
|
829
|
-
try {
|
|
830
|
-
return findCritiqsUsages(dir).length > 0 || findMountPoints(dir).length > 0;
|
|
831
|
-
} catch {
|
|
832
|
-
return false;
|
|
833
|
-
}
|
|
834
|
-
});
|
|
835
|
-
}
|
|
836
|
-
|
|
837
|
-
/** Why init doesn't choose an app in a workspace, with the exact commands for each. */
|
|
838
|
-
export function workspaceRefusal(apps, folder, show, command) {
|
|
839
|
-
return (
|
|
840
|
-
`${folder.charAt(0).toUpperCase()}${folder.slice(1)} is a workspace with ${apps.length === 1 ? "an app" : `${apps.length} apps`}, so nothing was changed: each app gets its own Critiqs project and settings. ` +
|
|
841
|
-
`Run init for one app:\n${apps.map((dir) => ` ${command} --dir ${show(dir)}`).join("\n")}`
|
|
842
|
-
);
|
|
843
|
-
}
|
|
844
|
-
|
|
845
|
-
/** Parses `init <projectId> [--dir <path>] [--entry <file>] [--mount <Element>] [--project-env-file <file>] [--dry-run]`; returns options or an error message. */
|
|
846
|
-
export function parseArguments(argv) {
|
|
847
|
-
const options = { help: false, command: null, projectId: null, dir: ".", entry: null, mount: null, envFile: null, dryRun: false };
|
|
848
|
-
const positional = [];
|
|
849
|
-
const keys = { "--dir": "dir", "--entry": "entry", "--mount": "mount", "--project-env-file": "envFile", "--env-file": "envFile" };
|
|
850
|
-
for (let i = 0; i < argv.length; i++) {
|
|
851
|
-
const arg = argv[i] ?? "";
|
|
852
|
-
const flag = Object.keys(keys).find((name) => arg === name || arg.startsWith(`${name}=`));
|
|
853
|
-
if (arg === "-h" || arg === "--help") options.help = true;
|
|
854
|
-
else if (arg === "--dry-run") options.dryRun = true;
|
|
855
|
-
else if (flag !== undefined) {
|
|
856
|
-
const value = arg === flag ? argv[++i] : arg.slice(flag.length + 1);
|
|
857
|
-
if (value === undefined || value === "") return { error: flag === "--dir" ? "--dir needs a folder path." : `${flag} needs a value.` };
|
|
858
|
-
options[keys[flag]] = value;
|
|
859
|
-
} else if (arg.startsWith("-")) return { error: `Unknown option ${arg}.` };
|
|
860
|
-
else positional.push(arg);
|
|
861
|
-
}
|
|
862
|
-
options.command = positional[0] ?? null;
|
|
863
|
-
options.projectId = positional[1] ?? null;
|
|
864
|
-
if (options.help) return options;
|
|
865
|
-
if (options.command !== "init") {
|
|
866
|
-
return { error: options.command === null ? "Missing command." : `Unknown command ${options.command}.` };
|
|
867
|
-
}
|
|
868
|
-
if (options.projectId === null) return { error: "Missing project ID." };
|
|
869
|
-
if (positional.length > 2) return { error: `Unexpected argument ${positional[2]}.` };
|
|
870
|
-
if (options.mount !== null && !/^[\p{ID_Start}$_][\p{ID_Continue}$.\-:]*$/u.test(options.mount)) return { error: "--mount needs an element name, such as App." };
|
|
871
|
-
return options;
|
|
872
|
-
}
|
|
873
|
-
|
|
874
|
-
/**
|
|
875
|
-
* Runs the CLI and returns its exit code: 0 when the project ID is set, 1 when it
|
|
876
|
-
* could not be set automatically, 2 for usage errors. `print` receives each message.
|
|
877
|
-
* With no `<Critiqs />` yet, it adds one where the app renders.
|
|
878
|
-
*/
|
|
879
|
-
export function runInit(argv, { cwd = process.cwd(), print = console.log } = {}) {
|
|
880
|
-
const options = parseArguments(argv);
|
|
881
|
-
if ("error" in options) {
|
|
882
|
-
print(`${options.error}\n\n${HELP}`);
|
|
883
|
-
return 2;
|
|
884
|
-
}
|
|
885
|
-
if (options.help) {
|
|
886
|
-
print(HELP);
|
|
887
|
-
return 0;
|
|
888
|
-
}
|
|
889
|
-
|
|
890
|
-
const projectId = options.projectId;
|
|
891
|
-
if (!isValidProjectId(projectId)) {
|
|
892
|
-
print(
|
|
893
|
-
`"${projectId}" is not a Critiqs project ID. Copy it from project setup in the Critiqs sidebar: ` +
|
|
894
|
-
"16 to 64 lowercase letters and digits, or p_ and 32 for a self-hosted server.",
|
|
895
|
-
);
|
|
896
|
-
return 2;
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
const root = resolve(cwd, options.dir);
|
|
900
|
-
const where = (file, line) => `${relative(cwd, file) || file}:${line}`;
|
|
901
|
-
const show = (path) => relative(cwd, path) || ".";
|
|
902
|
-
const folder = relative(cwd, root) || "this folder";
|
|
903
|
-
const apps = workspaceApps(root);
|
|
904
|
-
if (apps !== null && apps.length > 0) {
|
|
905
|
-
print(workspaceRefusal(apps, folder, show, `npx critiqs-react init ${projectId}`));
|
|
906
|
-
return 1;
|
|
907
|
-
}
|
|
908
|
-
const wiring = chooseWiring(root, { envFile: options.envFile });
|
|
909
|
-
if (wiring.problem) {
|
|
910
|
-
print(wiring.problem);
|
|
911
|
-
return 1;
|
|
912
|
-
}
|
|
913
|
-
const props = connectionProps(wiring, projectId);
|
|
914
|
-
const plan = planComponent(root, props, { entry: options.entry, mount: options.mount });
|
|
915
|
-
if (!plan.ok) {
|
|
916
|
-
print(
|
|
917
|
-
plan.reason === "expression" && wiring.mode === "literal"
|
|
918
|
-
? `${where(plan.file, plan.line)} sets projectId from code, so it was not changed.\nSet it to the project ID: ${projectId}`
|
|
919
|
-
: plan.reason === "spread" && wiring.mode === "literal"
|
|
920
|
-
? `${where(plan.file, plan.line)} sets projectId before spread props that could override it, so it was not changed.\nMove projectId="${projectId}" after the spread.`
|
|
921
|
-
: refusal(plan, props, where, folder),
|
|
922
|
-
);
|
|
923
|
-
return plan.reason === "not-folder" || plan.reason === "no-entry" ? 2 : 1;
|
|
924
|
-
}
|
|
925
|
-
let env = null;
|
|
926
|
-
if (wiring.mode === "env") {
|
|
927
|
-
try {
|
|
928
|
-
env = planEnv(wiring.app, wiring.variable, projectId);
|
|
929
|
-
} catch {
|
|
930
|
-
print(`Couldn't read this app's .env files, so nothing was changed. Restore access, or set ${wiring.variable}=${projectId} in the .env.local file the app loads.`);
|
|
931
|
-
return 1;
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
const dry = options.dryRun ? " (dry run, nothing written)" : "";
|
|
935
|
-
if (plan.action === "unchanged" && (env === null || !env.changed)) {
|
|
936
|
-
print(`${where(plan.file, plan.line)} already uses this project ID${env === null ? "" : ` (${env.name} in ${show(env.file)})`}.`);
|
|
937
|
-
return 0;
|
|
938
|
-
}
|
|
939
|
-
if (plan.action === "install") {
|
|
940
|
-
const preview = plan.preview.map((line) => ` ${line}`).join("\n");
|
|
941
|
-
print(
|
|
942
|
-
`${options.dryRun ? "Would add" : "Added"} <Critiqs /> to ${where(plan.file, plan.line)} (${MOUNT_KINDS[plan.kind]})` +
|
|
943
|
-
`${plan.imported ? ", importing it from critiqs-react" : ""}${dry}:\n${preview}`,
|
|
944
|
-
);
|
|
945
|
-
} else if (plan.action === "update" && wiring.mode === "env") {
|
|
946
|
-
print(`${options.dryRun ? "Would connect" : "Connected"} <Critiqs /> in ${where(plan.file, plan.line)} to ${wiring.variable}${wiring.addFlag ? "; it stays hidden wherever that isn't set" : ""}${dry}.`);
|
|
947
|
-
} else if (plan.action === "update") {
|
|
948
|
-
print(`${options.dryRun ? "Would set" : "Set"} the project ID in ${where(plan.file, plan.line)}${dry}.`);
|
|
949
|
-
}
|
|
950
|
-
if (!options.dryRun) applyPlan(plan);
|
|
951
|
-
if (env === null) return 0;
|
|
952
|
-
if (env.changed) {
|
|
953
|
-
if (!options.dryRun) {
|
|
954
|
-
try {
|
|
955
|
-
applyEnv(env);
|
|
956
|
-
} catch {
|
|
957
|
-
print(`Couldn't write ${show(env.file)}. Add this line to it yourself:\n ${env.name}=${projectId}`);
|
|
958
|
-
return 1;
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
print(`${options.dryRun ? "Would set" : "Set"} ${env.name}=${projectId} in ${show(env.file)} for this computer${dry}.`);
|
|
962
|
-
}
|
|
963
|
-
print(deploymentAdvice(wiring));
|
|
964
|
-
return 0;
|
|
965
|
-
}
|