-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathinit.ts
More file actions
454 lines (416 loc) · 15.3 KB
/
Copy pathinit.ts
File metadata and controls
454 lines (416 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/**
* sentry init
*
* Initialize Sentry in a project using the remote wizard workflow.
* Communicates with the Mastra API via suspend/resume to perform
* local filesystem operations and interactive prompts.
*
* Supports two optional positionals with smart disambiguation:
* sentry init — auto-detect everything, dir = cwd
* sentry init . — dir = cwd, auto-detect org
* sentry init ./subdir — dir = subdir, auto-detect org
* sentry init acme/ — explicit org, dir = cwd
* sentry init acme/my-app — explicit org + project, dir = cwd
* sentry init my-app — use existing or create new project
* sentry init acme/ ./subdir — explicit org, dir = subdir
* sentry init acme/my-app ./subdir — explicit org + project, dir = subdir
* sentry init ./subdir acme/ — swapped, auto-correct with warning
*/
import path from "node:path";
import { setTag } from "@sentry/node-core/light";
import type { SentryContext } from "../context.js";
import { findProjectsBySlug } from "../lib/api/projects.js";
import { looksLikePath, parseOrgProjectArg } from "../lib/arg-parsing.js";
import { buildCommand } from "../lib/command.js";
import { ContextError, ValidationError } from "../lib/errors.js";
import { warmOrgDetection } from "../lib/init/org-prefetch.js";
import { runWizard } from "../lib/init/wizard-runner.js";
import { validateResourceId } from "../lib/input-validation.js";
import { logger } from "../lib/logger.js";
import {
DRY_RUN_ALIASES,
DRY_RUN_FLAG,
YES_ALIASES,
YES_FLAG,
} from "../lib/mutate-command.js";
const log = logger.withTag("init");
const FEATURE_DELIMITER = /[,+ ]+/;
const NON_INTERACTIVE_USAGE_HINT =
"sentry init --yes --features errors,tracing,replay [target] [directory]";
const USAGE_HINT = "sentry init <org>/<project> [directory]";
const FEATURE_ALIASES = {
errors: "errorMonitoring",
errorMonitoring: "errorMonitoring",
tracing: "performanceMonitoring",
performanceMonitoring: "performanceMonitoring",
logs: "logs",
replay: "sessionReplay",
sessionReplay: "sessionReplay",
metrics: "metrics",
profiling: "profiling",
sourcemaps: "sourceMaps",
sourceMaps: "sourceMaps",
crons: "crons",
"ai-monitoring": "aiMonitoring",
aiMonitoring: "aiMonitoring",
"user-feedback": "userFeedback",
userFeedback: "userFeedback",
} as const;
const SUPPORTED_FEATURE_NAMES = [
"errors",
"tracing",
"logs",
"replay",
"metrics",
"profiling",
"sourcemaps",
"crons",
"ai-monitoring",
"user-feedback",
] as const;
const SUPPORTED_FEATURE_TEXT = SUPPORTED_FEATURE_NAMES.join(", ");
type InitFlags = {
readonly yes: boolean;
readonly "dry-run": boolean;
readonly features?: string[];
readonly team?: string;
readonly app?: string;
/**
* Default `true` — Ink is the default UI on both the Bun binary
* and the npm/Node distribution. Stricli auto-generates a negated
* `--no-tui` flag that flips this to `false` — that's the escape
* hatch users invoke when the Ink path misbehaves (e.g. on unusual
* terminal emulators).
*/
readonly tui: boolean;
};
/**
* Classify and separate two optional positional args into a target and a directory.
*
* Uses {@link looksLikePath} to distinguish filesystem paths from org/project targets.
* Detects swapped arguments and emits a warning when auto-correcting.
*
* @returns Resolved target string (or undefined) and directory string (or undefined)
*/
function classifyArgs(
first?: string,
second?: string
): { target: string | undefined; directory: string | undefined } {
// No args — auto-detect everything
if (!first) {
return { target: undefined, directory: undefined };
}
const firstIsPath = looksLikePath(first);
// Single arg
if (!second) {
return firstIsPath
? { target: undefined, directory: first }
: { target: first, directory: undefined };
}
const secondIsPath = looksLikePath(second);
// Two paths → error
if (firstIsPath && secondIsPath) {
throw new ContextError("Arguments", USAGE_HINT, [
"Two directory paths provided. Only one directory is allowed.",
]);
}
// Two targets → error
if (!(firstIsPath || secondIsPath)) {
throw new ContextError("Arguments", USAGE_HINT, [
"Two targets provided. Use <org>/<project> for the target and a path (e.g., ./dir) for the directory.",
]);
}
// (TARGET, PATH) — correct order
if (!firstIsPath && secondIsPath) {
return { target: first, directory: second };
}
// (PATH, TARGET) — swapped, auto-correct with warning
log.warn(`Arguments appear reversed. Interpreting as: ${second} ${first}`);
return { target: second, directory: first };
}
function parseFeatures(
features: readonly string[] | undefined
): string[] | undefined {
const requested = features
?.flatMap((feature) => feature.split(FEATURE_DELIMITER))
.map((feature) => feature.trim())
.filter(Boolean);
if (!requested || requested.length === 0) {
return;
}
return requested.map(normalizeFeature);
}
function normalizeFeature(feature: string): string {
const normalized = FEATURE_ALIASES[feature as keyof typeof FEATURE_ALIASES];
if (!normalized) {
throw new ValidationError(
`Unknown init feature "${feature}". Supported features: ${SUPPORTED_FEATURE_TEXT}`,
"features"
);
}
return normalized;
}
function isNonInteractiveContext(context: unknown): boolean {
const { stdin, stdout } = context as {
stdin?: { isTTY?: boolean };
stdout?: { isTTY?: boolean };
};
return stdin?.isTTY !== true || stdout?.isTTY !== true;
}
function validateNonInteractiveInit(
context: unknown,
flags: InitFlags,
features: readonly string[] | undefined
): void {
if (!isNonInteractiveContext(context)) {
return;
}
// --dry-run implies non-interactive mode and forces yes=true in the
// wizard runner, so it doesn't need explicit --yes or --features.
if (flags["dry-run"]) {
return;
}
if (flags.yes && features && features.length > 0) {
return;
}
throw new ContextError("Yes flag and features", NON_INTERACTIVE_USAGE_HINT, [
"Agent/CI mode cannot ask interactive setup questions.",
"Pass --yes to accept non-interactive prompts.",
`Pass --features with one or more supported features: ${SUPPORTED_FEATURE_TEXT}.`,
"Run sentry init from an interactive terminal to use the wizard UI.",
]);
}
/**
* Resolve the parsed org/project target into explicit org and project values.
*
* For `project-search` (bare slug), searches for an existing project first.
* If not found, treats the slug as a **new project name** to create —
* org will be resolved later by init preflight before the workflow starts.
* If the slug matches an org name, treats it as org-only (like `slug/`).
*/
async function resolveTarget(targetArg: string | undefined): Promise<{
org: string | undefined;
project: string | undefined;
}> {
const parsed = parseOrgProjectArg(targetArg);
switch (parsed.type) {
case "explicit":
// Validate user-provided slugs before they reach API calls
validateResourceId(parsed.org, "organization slug");
validateResourceId(parsed.project, "project name");
return { org: parsed.org, project: parsed.project };
case "org-all":
validateResourceId(parsed.org, "organization slug");
return { org: parsed.org, project: undefined };
case "project-search": {
// Bare slug — could be an existing project name or a new project name.
// Search for an existing project first, then fall back to treating as
// the name for a new project to create.
const { projects, orgs } = await findProjectsBySlug(parsed.projectSlug);
// Multiple matches — disambiguation error
if (projects.length > 1) {
const first = projects[0];
const orgList = projects
.map((p) => ` ${p.orgSlug}/${p.slug}`)
.join("\n");
throw new ValidationError(
`Project "${parsed.projectSlug}" exists in multiple organizations.\n\n` +
`Specify the organization:\n${orgList}\n\n` +
`Example: sentry init ${first?.orgSlug ?? "<org>"}/${parsed.projectSlug}`
);
}
// Exactly one match — use it (wizard handles existing-project flow)
const [match] = projects;
if (match) {
return { org: match.orgSlug, project: match.slug };
}
// No project found — is the slug an org name?
const isOrg = orgs.some((o) => o.slug === parsed.projectSlug);
if (isOrg) {
return { org: parsed.projectSlug, project: undefined };
}
// Truly not found — treat as the name for a new project to create.
// Org will be resolved later by init preflight before the workflow starts.
log.info(
`No existing project "${parsed.projectSlug}" found — will create a new project with this name.`
);
return { org: undefined, project: parsed.projectSlug };
}
case "auto-detect":
return { org: undefined, project: undefined };
default: {
const _exhaustive: never = parsed;
throw new ContextError("Target", String(_exhaustive), []);
}
}
}
export const initCommand = buildCommand<
InitFlags,
[string?, string?],
SentryContext
>({
docs: {
brief: "Initialize Sentry in your project (experimental)",
fullDescription:
"EXPERIMENTAL: This command may modify your source files.\n\n" +
"Runs the Sentry setup wizard to detect your project's framework, " +
"install the SDK, and configure Sentry.\n\n" +
"Supports org/project syntax and a directory positional. Path-like\n" +
"arguments (starting with . / ~) are treated as the directory;\n" +
"everything else is treated as the target.\n\n" +
"Examples:\n" +
" sentry init\n" +
" sentry init acme/\n" +
" sentry init acme/my-app\n" +
" sentry init my-app\n" +
" sentry init acme/my-app ./my-project\n" +
" sentry init ./my-project",
},
parameters: {
positional: {
kind: "tuple",
parameters: [
{
placeholder: "target",
brief: "<org>/<project>, <org>/, <project>, or a directory path",
parse: String,
optional: true,
},
{
placeholder: "directory",
brief: "Project directory (default: current directory)",
parse: String,
optional: true,
},
],
},
flags: {
yes: {
...YES_FLAG,
brief:
"Accept non-interactive defaults (requires --features outside a TTY)",
},
"dry-run": DRY_RUN_FLAG,
features: {
kind: "parsed",
parse: String,
brief:
"Features to enable: errors,tracing,logs,replay,metrics,profiling,sourcemaps,crons,ai-monitoring,user-feedback",
variadic: true,
optional: true,
},
team: {
kind: "parsed",
parse: String,
brief: "Team slug to create the project under",
optional: true,
},
app: {
kind: "parsed",
parse: String,
brief:
"App to initialize in a monorepo (required with --yes when multiple apps are detected)",
optional: true,
},
tui: {
kind: "boolean",
brief:
"Use the Ink-based interactive UI (default). Pass --no-tui to fall back to plain log output.",
default: true,
},
},
aliases: {
...DRY_RUN_ALIASES,
...YES_ALIASES,
t: "team",
},
},
async *func(
this: SentryContext,
flags: InitFlags,
first?: string,
second?: string
) {
// 1. Classify positionals into target vs directory
const { target: targetArg, directory: dirArg } = classifyArgs(
first,
second
);
// 2. Resolve directory
const targetDir = dirArg ? path.resolve(this.cwd, dirArg) : this.cwd;
// 3. Parse and validate features before any network or wizard work.
const featuresList = parseFeatures(flags.features);
// Non-TTY callers (CI/agents) must provide every interactive choice
// needed to start setup. Fail before project lookup, org prefetch, or
// UI creation so the error is deterministic and actionable.
try {
validateNonInteractiveInit(this, flags, featuresList);
} catch (err) {
setTag("wizard.outcome", "context_error");
throw err;
}
// 4. Resolve target → org + project
// Validation of user-provided slugs happens inside resolveTarget.
// For bare slugs, if no existing project is found, the slug becomes
// the name for a new project (org resolved later by the wizard).
const { org: explicitOrg, project: explicitProject } =
await resolveTarget(targetArg);
// 5. Start background org detection when org is not yet known.
// The prefetch runs concurrently with the preamble, the wizard startup,
// and all early suspend/resume rounds — by the time the wizard needs the
// org (inside createSentryProject), the result is already cached.
if (!explicitOrg) {
warmOrgDetection(targetDir);
}
// 6. Run the wizard.
//
// Wrapped in try/finally so the macOS force-exit safety net (step 7)
// is scheduled on every exit path: success, WizardError, user cancel,
// and any other thrown error. Without finally, a thrown WizardError
// would skip the timer and the process would hang on the error
// display — exactly what Cursor Bugbot flagged on an earlier revision.
try {
await runWizard({
directory: targetDir,
yes: flags.yes,
dryRun: flags["dry-run"],
features: featuresList,
team: flags.team,
app: flags.app,
org: explicitOrg,
project: explicitProject,
// `flags.tui` defaults to `true`. `--no-tui` (auto-generated
// by stricli's flag negation) flips it to `false` — that's the
// signal we forward to the factory as `forceLegacyUi`.
forceLegacyUi: flags.tui === false,
});
} finally {
// 7. macOS-only force-exit safety net.
//
// On Darwin, `InkUI` opens a fresh `/dev/tty` `tty.ReadStream`
// (so Ink's `useInput` actually receives keystrokes — Bun's
// `process.stdin` doesn't deliver `readable` events properly,
// see oven-sh/bun#6862 / vadimdemedes/ink#636). The fresh
// stream is destroyed in the InkUI dispose path, but Bun's
// libuv handle for it can linger past `destroy()` on Darwin
// (oven-sh/bun#29126), keeping the event loop ref'd so the
// process hangs until the user presses a key.
//
// The .unref() timer doesn't hold the loop itself, so it's a no-op
// in the happy path (Linux: handle drains naturally; `--yes`
// on Darwin: LoggingUI doesn't open /dev/tty, may still drain
// naturally). On the Darwin hang path, it force-exits after a
// 100ms grace window — imperceptible to the user and enough
// for Sentry telemetry + stdio flushes to complete first.
//
// Skipped under `bun test` (which sets NODE_ENV=test automatically)
// because the test runner calls `initCommand.func` directly; an
// unref'd timer would still fire and terminate the runner mid-suite.
if (process.platform === "darwin" && process.env.NODE_ENV !== "test") {
setTimeout(() => {
process.exit(process.exitCode ?? 0);
}, 100).unref();
}
}
},
});