flagdoctor 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +102 -2
- package/dist/index.js +4234 -0
- package/package.json +24 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,4234 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
3
|
+
|
|
4
|
+
// packages/cli/dist/index.js
|
|
5
|
+
import { jsx as _jsx8 } from "react/jsx-runtime";
|
|
6
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
8
|
+
import { access as access2, writeFile as writeFile4 } from "node:fs/promises";
|
|
9
|
+
import path4 from "node:path";
|
|
10
|
+
import { pathToFileURL } from "node:url";
|
|
11
|
+
import { Command, CommanderError } from "commander";
|
|
12
|
+
|
|
13
|
+
// packages/core/src/source/LocalProvider.ts
|
|
14
|
+
import { open, readFile, readdir, realpath, stat } from "node:fs/promises";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
|
|
17
|
+
// packages/shared-types/src/index.ts
|
|
18
|
+
import { z } from "zod";
|
|
19
|
+
var severitySchema = z.enum(["error", "warning", "info"]);
|
|
20
|
+
var confidenceSchema = z.enum(["high", "medium", "low"]);
|
|
21
|
+
var expectedTypeSchema = z.enum(["boolean", "number", "string", "json", "unknown"]);
|
|
22
|
+
var referenceResolutionSchema = z.enum(["literal", "constant", "dynamic", "llm"]);
|
|
23
|
+
var findingOriginSchema = z.enum(["ast", "llm", "snapshot"]);
|
|
24
|
+
var flagReferenceSchema = z.object({
|
|
25
|
+
flagName: z.string().nullable(),
|
|
26
|
+
resolution: referenceResolutionSchema,
|
|
27
|
+
expectedType: expectedTypeSchema,
|
|
28
|
+
repository: z.string().nullable(),
|
|
29
|
+
filePath: z.string().min(1),
|
|
30
|
+
line: z.number().int().positive(),
|
|
31
|
+
column: z.number().int().positive(),
|
|
32
|
+
sdk: z.string().min(1),
|
|
33
|
+
method: z.string().min(1),
|
|
34
|
+
snippet: z.string(),
|
|
35
|
+
commit: z.string().nullable(),
|
|
36
|
+
/** Nearest enclosing class/interface/type name at the call site, if any. */
|
|
37
|
+
enclosingClass: z.string().nullable().default(null),
|
|
38
|
+
/** Nearest enclosing function/method name at the call site, if any. */
|
|
39
|
+
enclosingFunction: z.string().nullable().default(null)
|
|
40
|
+
});
|
|
41
|
+
var RESERVED_SDK_IDENTIFIERS = ["flagsmith-js-client", "flagsmith-java-client"];
|
|
42
|
+
var wrapperDefinitionSchema = z.object({
|
|
43
|
+
name: z.string().min(1),
|
|
44
|
+
argumentIndex: z.number().int().nonnegative(),
|
|
45
|
+
expectedType: expectedTypeSchema,
|
|
46
|
+
sdk: z.string().min(1).default("registered-wrapper")
|
|
47
|
+
}).strict().refine((wrapper) => !RESERVED_SDK_IDENTIFIERS.includes(wrapper.sdk), {
|
|
48
|
+
message: "registered wrappers may not use a reserved built-in SDK identity"
|
|
49
|
+
});
|
|
50
|
+
var DEFAULT_FLAGSMITH_BASE_URL = "https://api.flagsmith.com/api/v1";
|
|
51
|
+
var featureTypeSchema = z.enum(["STANDARD", "MULTIVARIATE", "unknown"]);
|
|
52
|
+
var sourceProviderOptionsSchema = z.object({
|
|
53
|
+
root: z.string().min(1).optional(),
|
|
54
|
+
include: z.array(z.string().min(1)).default([]),
|
|
55
|
+
exclude: z.array(z.string().min(1)).default([]),
|
|
56
|
+
maxFiles: z.number().int().positive().default(2e3),
|
|
57
|
+
maxFileBytes: z.number().int().positive().default(2e6),
|
|
58
|
+
respectGitignore: z.boolean().default(true)
|
|
59
|
+
}).strict();
|
|
60
|
+
var sourceFileSchema = z.object({
|
|
61
|
+
relativePath: z.string().min(1),
|
|
62
|
+
sizeBytes: z.number().int().nonnegative(),
|
|
63
|
+
extension: z.string(),
|
|
64
|
+
modifiedAt: z.string().nullable()
|
|
65
|
+
});
|
|
66
|
+
var flagsmithConfigSchema = z.object({
|
|
67
|
+
baseUrl: z.string().min(1).default(DEFAULT_FLAGSMITH_BASE_URL),
|
|
68
|
+
project: z.union([z.string().min(1), z.number().int().positive()]),
|
|
69
|
+
environment: z.string().min(1),
|
|
70
|
+
timeoutMs: z.number().int().positive().default(1e4),
|
|
71
|
+
maxRetries: z.number().int().min(0).max(5).default(2),
|
|
72
|
+
retryDelayMs: z.number().int().nonnegative().default(250)
|
|
73
|
+
}).strict();
|
|
74
|
+
var adapterErrorKindSchema = z.enum([
|
|
75
|
+
"configuration",
|
|
76
|
+
"authentication",
|
|
77
|
+
"authorization",
|
|
78
|
+
"not_found",
|
|
79
|
+
"rate_limited",
|
|
80
|
+
"timeout",
|
|
81
|
+
"network",
|
|
82
|
+
"invalid_response",
|
|
83
|
+
"server"
|
|
84
|
+
]);
|
|
85
|
+
var adapterErrorSchema = z.object({
|
|
86
|
+
kind: adapterErrorKindSchema,
|
|
87
|
+
status: z.number().int().nullable(),
|
|
88
|
+
message: z.string()
|
|
89
|
+
});
|
|
90
|
+
var featureEnvironmentStateSchema = z.object({
|
|
91
|
+
environmentId: z.number().int().nullable(),
|
|
92
|
+
enabled: z.boolean(),
|
|
93
|
+
value: z.unknown().optional(),
|
|
94
|
+
valueAvailable: z.boolean()
|
|
95
|
+
});
|
|
96
|
+
var normalizedFeatureSchema = z.object({
|
|
97
|
+
id: z.number().int(),
|
|
98
|
+
name: z.string(),
|
|
99
|
+
type: featureTypeSchema,
|
|
100
|
+
archived: z.boolean(),
|
|
101
|
+
defaultEnabled: z.boolean().nullable(),
|
|
102
|
+
environments: z.record(z.string(), featureEnvironmentStateSchema.nullable())
|
|
103
|
+
});
|
|
104
|
+
var flagSnapshotSchema = z.object({
|
|
105
|
+
project: z.object({
|
|
106
|
+
id: z.number().int(),
|
|
107
|
+
name: z.string(),
|
|
108
|
+
uuid: z.string().nullable()
|
|
109
|
+
}),
|
|
110
|
+
environment: z.object({
|
|
111
|
+
id: z.number().int(),
|
|
112
|
+
key: z.string(),
|
|
113
|
+
name: z.string()
|
|
114
|
+
}),
|
|
115
|
+
fetchedAt: z.string(),
|
|
116
|
+
features: z.record(z.string(), normalizedFeatureSchema)
|
|
117
|
+
});
|
|
118
|
+
var ruleIdSchema = z.enum(["FD001", "FD002", "FD004", "FD006", "FDLLM"]);
|
|
119
|
+
var findingSchema = z.object({
|
|
120
|
+
id: z.string().min(1),
|
|
121
|
+
ruleId: ruleIdSchema,
|
|
122
|
+
severity: severitySchema,
|
|
123
|
+
confidence: confidenceSchema,
|
|
124
|
+
flagName: z.string().nullable(),
|
|
125
|
+
environment: z.string(),
|
|
126
|
+
repository: z.string().nullable(),
|
|
127
|
+
filePath: z.string().nullable(),
|
|
128
|
+
line: z.number().int().positive().nullable(),
|
|
129
|
+
column: z.number().int().positive().nullable(),
|
|
130
|
+
message: z.string(),
|
|
131
|
+
suggestion: z.string().nullable(),
|
|
132
|
+
origin: findingOriginSchema
|
|
133
|
+
});
|
|
134
|
+
var layerSchema = z.enum([
|
|
135
|
+
"controller",
|
|
136
|
+
"service",
|
|
137
|
+
"repository",
|
|
138
|
+
"model",
|
|
139
|
+
"component",
|
|
140
|
+
"other"
|
|
141
|
+
]);
|
|
142
|
+
var impactNodeSchema = z.object({
|
|
143
|
+
filePath: z.string().min(1),
|
|
144
|
+
className: z.string().nullable(),
|
|
145
|
+
functionName: z.string().min(1),
|
|
146
|
+
layer: layerSchema,
|
|
147
|
+
depth: z.number().int().positive(),
|
|
148
|
+
/**
|
|
149
|
+
* Key (`file#class#function`) of the node this one was reached from: for callers, the
|
|
150
|
+
* function it calls; for callees, the function that calls it. Absent in older reports.
|
|
151
|
+
*/
|
|
152
|
+
via: z.string().nullable().optional()
|
|
153
|
+
});
|
|
154
|
+
var dependencySiteSchema = z.object({
|
|
155
|
+
repository: z.string().nullable(),
|
|
156
|
+
filePath: z.string().min(1),
|
|
157
|
+
enclosingClass: z.string().nullable(),
|
|
158
|
+
enclosingFunction: z.string().nullable(),
|
|
159
|
+
line: z.number().int().positive(),
|
|
160
|
+
column: z.number().int().positive(),
|
|
161
|
+
sdk: z.string().min(1),
|
|
162
|
+
method: z.string().min(1),
|
|
163
|
+
expectedType: expectedTypeSchema,
|
|
164
|
+
resolution: referenceResolutionSchema,
|
|
165
|
+
/** Functions that (transitively) call into this site, nearest first. */
|
|
166
|
+
callers: z.array(impactNodeSchema).default([]),
|
|
167
|
+
/** Functions this site's enclosing function (transitively) calls, nearest first. */
|
|
168
|
+
callees: z.array(impactNodeSchema).default([]),
|
|
169
|
+
/**
|
|
170
|
+
* What the direct callers go on to call besides this check — the
|
|
171
|
+
* services/repositories/models in the same flow the flag gates.
|
|
172
|
+
*/
|
|
173
|
+
flow: z.array(impactNodeSchema).default([])
|
|
174
|
+
});
|
|
175
|
+
var flagDependencyStatusSchema = z.enum([
|
|
176
|
+
"matched",
|
|
177
|
+
"missing",
|
|
178
|
+
"archived",
|
|
179
|
+
"dynamic",
|
|
180
|
+
"unknown"
|
|
181
|
+
]);
|
|
182
|
+
var relatedCodeSchema = z.object({
|
|
183
|
+
filePath: z.string().min(1),
|
|
184
|
+
className: z.string().nullable(),
|
|
185
|
+
layer: layerSchema,
|
|
186
|
+
matchedTerms: z.array(z.string()),
|
|
187
|
+
functions: z.array(z.string())
|
|
188
|
+
});
|
|
189
|
+
var flagDependencySchema = z.object({
|
|
190
|
+
flagKey: z.string().min(1),
|
|
191
|
+
flagName: z.string().nullable(),
|
|
192
|
+
status: flagDependencyStatusSchema,
|
|
193
|
+
sites: z.array(dependencySiteSchema),
|
|
194
|
+
files: z.array(z.string()),
|
|
195
|
+
classes: z.array(z.string()),
|
|
196
|
+
functions: z.array(z.string()),
|
|
197
|
+
/** Code the flag's name points to, ranked; inferred, not traced. */
|
|
198
|
+
relatedCode: z.array(relatedCodeSchema).default([])
|
|
199
|
+
});
|
|
200
|
+
var scanDiagnosticSchema = z.object({
|
|
201
|
+
filePath: z.string(),
|
|
202
|
+
line: z.number().int().positive(),
|
|
203
|
+
column: z.number().int().positive(),
|
|
204
|
+
kind: z.enum(["parse_error", "read_error", "unsupported_language"]),
|
|
205
|
+
message: z.string()
|
|
206
|
+
});
|
|
207
|
+
var scanReportSchema = z.object({
|
|
208
|
+
schemaVersion: z.literal(1),
|
|
209
|
+
status: z.enum(["completed", "partial", "failed"]),
|
|
210
|
+
project: z.object({ id: z.number().int(), name: z.string() }).nullable(),
|
|
211
|
+
environment: z.string(),
|
|
212
|
+
fetchedAt: z.string().nullable(),
|
|
213
|
+
repository: z.string().nullable(),
|
|
214
|
+
commit: z.string().nullable(),
|
|
215
|
+
summary: z.object({
|
|
216
|
+
errors: z.number().int().nonnegative(),
|
|
217
|
+
warnings: z.number().int().nonnegative(),
|
|
218
|
+
info: z.number().int().nonnegative(),
|
|
219
|
+
total: z.number().int().nonnegative(),
|
|
220
|
+
scannedFiles: z.number().int().nonnegative(),
|
|
221
|
+
skippedFiles: z.number().int().nonnegative()
|
|
222
|
+
}),
|
|
223
|
+
findings: z.array(findingSchema),
|
|
224
|
+
diagnostics: z.array(scanDiagnosticSchema),
|
|
225
|
+
error: z.object({ kind: adapterErrorKindSchema, message: z.string() }).nullable(),
|
|
226
|
+
/** Which files/classes/functions each flag affects. Empty for older reports. */
|
|
227
|
+
dependencies: z.array(flagDependencySchema).default([]),
|
|
228
|
+
/** Present when an LLM reviewed this report; its findings carry origin 'llm'. */
|
|
229
|
+
analysis: z.object({
|
|
230
|
+
provider: z.string(),
|
|
231
|
+
model: z.string(),
|
|
232
|
+
summary: z.string(),
|
|
233
|
+
analyzedAt: z.string()
|
|
234
|
+
}).nullable().optional()
|
|
235
|
+
});
|
|
236
|
+
var flagdoctorConfigSchema = z.object({
|
|
237
|
+
version: z.literal(1).optional(),
|
|
238
|
+
repository: z.object({
|
|
239
|
+
root: z.string().min(1).default("."),
|
|
240
|
+
include: z.array(z.string().min(1)).default([]),
|
|
241
|
+
exclude: z.array(z.string().min(1)).default([])
|
|
242
|
+
}).strict().default({ root: ".", include: [], exclude: [] }),
|
|
243
|
+
flagsmith: z.object({
|
|
244
|
+
baseUrl: z.string().min(1).optional(),
|
|
245
|
+
project: z.union([z.string().min(1), z.number().int().positive()]),
|
|
246
|
+
environment: z.string().min(1).optional(),
|
|
247
|
+
environments: z.record(z.string().min(1), z.string().min(1)).optional()
|
|
248
|
+
}).strict().refine(
|
|
249
|
+
(value) => value.environment !== void 0 || value.environments !== void 0 && Object.keys(value.environments).length > 0,
|
|
250
|
+
{ message: "flagsmith.environment or flagsmith.environments is required" }
|
|
251
|
+
)
|
|
252
|
+
}).strict();
|
|
253
|
+
|
|
254
|
+
// packages/core/src/source/gitignore.ts
|
|
255
|
+
import { createRequire } from "node:module";
|
|
256
|
+
var require2 = createRequire(import.meta.url);
|
|
257
|
+
var ignore = require2("ignore");
|
|
258
|
+
function toPosixPath(value) {
|
|
259
|
+
return value.split("\\").join("/");
|
|
260
|
+
}
|
|
261
|
+
function createIgnoreMatcher(patterns) {
|
|
262
|
+
const matcher = ignore().add([...patterns]);
|
|
263
|
+
return (relativePath) => matcher.ignores(toPosixPath(relativePath));
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// packages/core/src/source/LocalProvider.ts
|
|
267
|
+
var DEFAULT_EXCLUDED_DIRS = /* @__PURE__ */ new Set([
|
|
268
|
+
".git",
|
|
269
|
+
"node_modules",
|
|
270
|
+
"dist",
|
|
271
|
+
"build",
|
|
272
|
+
"out",
|
|
273
|
+
"coverage",
|
|
274
|
+
".next",
|
|
275
|
+
".nuxt",
|
|
276
|
+
".svelte-kit",
|
|
277
|
+
"vendor",
|
|
278
|
+
"target",
|
|
279
|
+
".venv",
|
|
280
|
+
"venv",
|
|
281
|
+
"__pycache__"
|
|
282
|
+
]);
|
|
283
|
+
var DEFAULT_EXCLUDE_PATTERNS = [
|
|
284
|
+
"**/.git/**",
|
|
285
|
+
"**/node_modules/**",
|
|
286
|
+
"**/dist/**",
|
|
287
|
+
"**/build/**",
|
|
288
|
+
"**/out/**",
|
|
289
|
+
"**/coverage/**",
|
|
290
|
+
"**/.next/**",
|
|
291
|
+
"**/vendor/**",
|
|
292
|
+
"**/target/**",
|
|
293
|
+
"**/.venv/**",
|
|
294
|
+
"**/venv/**",
|
|
295
|
+
"**/__pycache__/**",
|
|
296
|
+
"**/*.min.js",
|
|
297
|
+
"**/*.map",
|
|
298
|
+
"**/*.tsbuildinfo",
|
|
299
|
+
".gitignore",
|
|
300
|
+
"**/.gitignore",
|
|
301
|
+
".env",
|
|
302
|
+
"**/.env",
|
|
303
|
+
"**/.env.*"
|
|
304
|
+
];
|
|
305
|
+
var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
306
|
+
".png",
|
|
307
|
+
".jpg",
|
|
308
|
+
".jpeg",
|
|
309
|
+
".gif",
|
|
310
|
+
".bmp",
|
|
311
|
+
".webp",
|
|
312
|
+
".ico",
|
|
313
|
+
".svgz",
|
|
314
|
+
".pdf",
|
|
315
|
+
".zip",
|
|
316
|
+
".gz",
|
|
317
|
+
".tar",
|
|
318
|
+
".rar",
|
|
319
|
+
".7z",
|
|
320
|
+
".exe",
|
|
321
|
+
".dll",
|
|
322
|
+
".so",
|
|
323
|
+
".dylib",
|
|
324
|
+
".o",
|
|
325
|
+
".a",
|
|
326
|
+
".class",
|
|
327
|
+
".jar",
|
|
328
|
+
".pyc",
|
|
329
|
+
".woff",
|
|
330
|
+
".woff2",
|
|
331
|
+
".ttf",
|
|
332
|
+
".eot",
|
|
333
|
+
".otf",
|
|
334
|
+
".mp3",
|
|
335
|
+
".mp4",
|
|
336
|
+
".mov",
|
|
337
|
+
".avi",
|
|
338
|
+
".wasm",
|
|
339
|
+
".sqlite",
|
|
340
|
+
".db"
|
|
341
|
+
]);
|
|
342
|
+
async function readIgnoreFile(directory) {
|
|
343
|
+
let content;
|
|
344
|
+
try {
|
|
345
|
+
content = await readFile(path.join(directory, ".gitignore"), "utf8");
|
|
346
|
+
} catch {
|
|
347
|
+
return [];
|
|
348
|
+
}
|
|
349
|
+
return content.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
|
|
350
|
+
}
|
|
351
|
+
function prefixIgnorePatterns(baseDirectory, patterns) {
|
|
352
|
+
if (baseDirectory === "") return patterns;
|
|
353
|
+
return patterns.map((pattern) => {
|
|
354
|
+
const negated = pattern.startsWith("!");
|
|
355
|
+
const body = negated ? pattern.slice(1) : pattern;
|
|
356
|
+
const anchored = body.startsWith("/");
|
|
357
|
+
const bare = anchored ? body.slice(1) : body;
|
|
358
|
+
const prefixed = anchored || bare.includes("/") ? `${baseDirectory}/${bare}` : `${baseDirectory}/**/${bare}`;
|
|
359
|
+
return negated ? `!${prefixed}` : prefixed;
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
async function looksBinary(filePath) {
|
|
363
|
+
const handle = await open(filePath, "r");
|
|
364
|
+
try {
|
|
365
|
+
const buffer = Buffer.alloc(1024);
|
|
366
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
367
|
+
return buffer.subarray(0, bytesRead).includes(0);
|
|
368
|
+
} finally {
|
|
369
|
+
await handle.close();
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
var LocalProvider = class {
|
|
373
|
+
rootPath;
|
|
374
|
+
options;
|
|
375
|
+
isExcluded;
|
|
376
|
+
isIncluded;
|
|
377
|
+
constructor(options = {}) {
|
|
378
|
+
const parsed = sourceProviderOptionsSchema.parse(options);
|
|
379
|
+
this.options = parsed;
|
|
380
|
+
this.rootPath = path.resolve(parsed.root ?? process.cwd());
|
|
381
|
+
this.isExcluded = createIgnoreMatcher([...DEFAULT_EXCLUDE_PATTERNS, ...parsed.exclude]);
|
|
382
|
+
this.isIncluded = parsed.include.length > 0 ? createIgnoreMatcher(parsed.include) : () => true;
|
|
383
|
+
}
|
|
384
|
+
async listFiles() {
|
|
385
|
+
const files = [];
|
|
386
|
+
await this.walk(this.rootPath, [], files);
|
|
387
|
+
return files.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
|
|
388
|
+
}
|
|
389
|
+
async readFile(relativePath) {
|
|
390
|
+
const resolved = await this.resolveInsideRoot(relativePath);
|
|
391
|
+
return readFile(resolved, "utf8");
|
|
392
|
+
}
|
|
393
|
+
async walk(directory, inheritedIgnorePatterns, files) {
|
|
394
|
+
if (files.length >= this.options.maxFiles) return;
|
|
395
|
+
const directoryPath = toPosixPath(path.relative(this.rootPath, directory));
|
|
396
|
+
const localPatterns = this.options.respectGitignore ? await readIgnoreFile(directory) : [];
|
|
397
|
+
const ignorePatterns = [
|
|
398
|
+
...inheritedIgnorePatterns,
|
|
399
|
+
...prefixIgnorePatterns(directoryPath, localPatterns)
|
|
400
|
+
];
|
|
401
|
+
const isGitIgnored = createIgnoreMatcher(ignorePatterns);
|
|
402
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
403
|
+
for (const entry of entries) {
|
|
404
|
+
if (files.length >= this.options.maxFiles) return;
|
|
405
|
+
if (entry.isSymbolicLink()) continue;
|
|
406
|
+
const absolutePath = path.join(directory, entry.name);
|
|
407
|
+
const relativePath = toPosixPath(path.relative(this.rootPath, absolutePath));
|
|
408
|
+
if (relativePath.startsWith("../") || relativePath.startsWith("/")) continue;
|
|
409
|
+
if (entry.isDirectory()) {
|
|
410
|
+
if (DEFAULT_EXCLUDED_DIRS.has(entry.name.toLowerCase()) || this.isExcluded(relativePath) || isGitIgnored(relativePath) || isGitIgnored(`${relativePath}/`)) {
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
await this.walk(absolutePath, ignorePatterns, files);
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
if (!entry.isFile()) continue;
|
|
417
|
+
if (!this.isIncluded(relativePath) || this.isExcluded(relativePath) || isGitIgnored(relativePath)) {
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
const info = await stat(absolutePath);
|
|
421
|
+
if (info.size > this.options.maxFileBytes) continue;
|
|
422
|
+
const extension = path.extname(entry.name).toLowerCase();
|
|
423
|
+
if (BINARY_EXTENSIONS.has(extension)) continue;
|
|
424
|
+
if (await looksBinary(absolutePath)) continue;
|
|
425
|
+
files.push({
|
|
426
|
+
relativePath,
|
|
427
|
+
sizeBytes: info.size,
|
|
428
|
+
extension,
|
|
429
|
+
modifiedAt: info.mtime.toISOString()
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
async resolveInsideRoot(relativePath) {
|
|
434
|
+
if (typeof relativePath !== "string" || relativePath.trim() === "") {
|
|
435
|
+
throw new Error("Source path must be a non-empty relative path");
|
|
436
|
+
}
|
|
437
|
+
if (path.isAbsolute(relativePath) || relativePath.includes("\0")) {
|
|
438
|
+
throw new Error(`Source path escapes repository root: ${relativePath}`);
|
|
439
|
+
}
|
|
440
|
+
const resolved = path.resolve(this.rootPath, relativePath);
|
|
441
|
+
if (!this.isInsideRoot(resolved)) {
|
|
442
|
+
throw new Error(`Source path escapes repository root: ${relativePath}`);
|
|
443
|
+
}
|
|
444
|
+
const real = await realpath(resolved).catch(() => resolved);
|
|
445
|
+
if (!this.isInsideRoot(real)) {
|
|
446
|
+
throw new Error(`Source path escapes repository root: ${relativePath}`);
|
|
447
|
+
}
|
|
448
|
+
return resolved;
|
|
449
|
+
}
|
|
450
|
+
isInsideRoot(candidate) {
|
|
451
|
+
const withSeparator = this.rootPath.endsWith(path.sep) ? this.rootPath : `${this.rootPath}${path.sep}`;
|
|
452
|
+
return candidate === this.rootPath || candidate.startsWith(withSeparator);
|
|
453
|
+
}
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
// packages/core/src/scan/constants.ts
|
|
457
|
+
var SCOPE_TYPES = /* @__PURE__ */ new Set([
|
|
458
|
+
"program",
|
|
459
|
+
"function_declaration",
|
|
460
|
+
"function_expression",
|
|
461
|
+
"arrow_function",
|
|
462
|
+
"method_declaration",
|
|
463
|
+
"constructor_declaration",
|
|
464
|
+
"class_body",
|
|
465
|
+
"block"
|
|
466
|
+
]);
|
|
467
|
+
function nearestScope(node) {
|
|
468
|
+
let current = node.parent;
|
|
469
|
+
while (current && !SCOPE_TYPES.has(current.type)) current = current.parent;
|
|
470
|
+
return current ?? node;
|
|
471
|
+
}
|
|
472
|
+
function outerScope(node) {
|
|
473
|
+
let current = node.parent;
|
|
474
|
+
while (current) {
|
|
475
|
+
if (SCOPE_TYPES.has(current.type)) return current;
|
|
476
|
+
current = current.parent;
|
|
477
|
+
}
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
function scopeChain(node) {
|
|
481
|
+
const scopes = [];
|
|
482
|
+
let scope = nearestScope(node);
|
|
483
|
+
while (scope) {
|
|
484
|
+
scopes.push(scope);
|
|
485
|
+
if (scope.type === "program") break;
|
|
486
|
+
scope = outerScope(scope);
|
|
487
|
+
}
|
|
488
|
+
return scopes;
|
|
489
|
+
}
|
|
490
|
+
function literalString(input) {
|
|
491
|
+
if (!input) return null;
|
|
492
|
+
const node = input.type === "as_expression" || input.type === "parenthesized_expression" ? input.namedChildren[0] ?? null : input;
|
|
493
|
+
if (!node || node.type !== "string" && node.type !== "string_literal") return null;
|
|
494
|
+
const raw = node.text;
|
|
495
|
+
if (raw.length < 2) return null;
|
|
496
|
+
const quote = raw[0];
|
|
497
|
+
if (quote !== '"' && quote !== "'" || raw[raw.length - 1] !== quote) return null;
|
|
498
|
+
const inner = raw.slice(1, -1);
|
|
499
|
+
return inner.includes("\\") ? null : inner;
|
|
500
|
+
}
|
|
501
|
+
function isImmutableJsDeclarator(node) {
|
|
502
|
+
const parent = node.parent;
|
|
503
|
+
return parent?.type === "lexical_declaration" && parent.children.some((child) => child.type === "const");
|
|
504
|
+
}
|
|
505
|
+
function isImmutableJavaDeclarator(node) {
|
|
506
|
+
const parent = node.parent;
|
|
507
|
+
if (!parent || parent.type !== "field_declaration" && parent.type !== "local_variable_declaration") {
|
|
508
|
+
return false;
|
|
509
|
+
}
|
|
510
|
+
const modifiers = parent.namedChildren.find((child) => child.type === "modifiers");
|
|
511
|
+
return modifiers?.children.some((child) => child.type === "final") ?? false;
|
|
512
|
+
}
|
|
513
|
+
function buildConstantTable(root, language) {
|
|
514
|
+
const table = /* @__PURE__ */ new Map();
|
|
515
|
+
const bind = (name, scope, value) => {
|
|
516
|
+
const scoped = table.get(scope.id) ?? /* @__PURE__ */ new Map();
|
|
517
|
+
scoped.set(name, previousValue(scoped, name, value));
|
|
518
|
+
table.set(scope.id, scoped);
|
|
519
|
+
};
|
|
520
|
+
const visit = (node) => {
|
|
521
|
+
if (node.type === "variable_declarator") {
|
|
522
|
+
const name = node.childForFieldName("name");
|
|
523
|
+
if (name?.type === "identifier") {
|
|
524
|
+
const provablyImmutable = language === "js" ? isImmutableJsDeclarator(node) : isImmutableJavaDeclarator(node);
|
|
525
|
+
const value = provablyImmutable ? literalString(node.childForFieldName("value")) : null;
|
|
526
|
+
bind(name.text, nearestScope(node), value);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
if (language === "js" && node.type === "formal_parameters") {
|
|
530
|
+
for (const child of node.namedChildren) {
|
|
531
|
+
const pattern = child.type === "identifier" ? child : child.childForFieldName("pattern");
|
|
532
|
+
if (pattern?.type === "identifier") bind(pattern.text, nearestScope(node), null);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
if (language === "java" && node.type === "formal_parameter") {
|
|
536
|
+
const name = node.childForFieldName("name");
|
|
537
|
+
if (name?.type === "identifier") bind(name.text, nearestScope(node), null);
|
|
538
|
+
}
|
|
539
|
+
if (node.type === "assignment_expression") {
|
|
540
|
+
const left = node.childForFieldName("left") ?? node.namedChildren[0];
|
|
541
|
+
if (left?.type === "identifier") bind(left.text, nearestScope(node), null);
|
|
542
|
+
}
|
|
543
|
+
for (const child of node.namedChildren) visit(child);
|
|
544
|
+
};
|
|
545
|
+
visit(root);
|
|
546
|
+
return table;
|
|
547
|
+
}
|
|
548
|
+
function previousValue(scoped, name, value) {
|
|
549
|
+
if (!scoped.has(name)) return value;
|
|
550
|
+
const previous = scoped.get(name) ?? null;
|
|
551
|
+
return previous === value ? value : null;
|
|
552
|
+
}
|
|
553
|
+
function resolveName(node, table) {
|
|
554
|
+
const literal = literalString(node);
|
|
555
|
+
if (literal !== null && node.type !== "identifier") {
|
|
556
|
+
return { value: literal, resolution: "literal" };
|
|
557
|
+
}
|
|
558
|
+
if (node.type !== "identifier") return null;
|
|
559
|
+
for (const scope of scopeChain(node)) {
|
|
560
|
+
const scoped = table.get(scope.id);
|
|
561
|
+
if (scoped?.has(node.text)) {
|
|
562
|
+
const found = scoped.get(node.text);
|
|
563
|
+
return found === null || found === void 0 ? null : { value: found, resolution: "constant" };
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
return null;
|
|
567
|
+
}
|
|
568
|
+
function positionOf(node) {
|
|
569
|
+
return { line: node.startPosition.row + 1, column: node.startPosition.column + 1 };
|
|
570
|
+
}
|
|
571
|
+
function makeSnippet(text, maxLength = 160) {
|
|
572
|
+
const collapsed = text.replace(/\s+/g, " ").trim();
|
|
573
|
+
const redacted = collapsed.replace(/\b[A-Za-z0-9_-]{40,}\b/g, "[REDACTED]");
|
|
574
|
+
return redacted.length <= maxLength ? redacted : `${redacted.slice(0, maxLength - 1)}\u2026`;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// packages/core/src/scan/sdkPatterns.ts
|
|
578
|
+
var JS_SDK_METHODS = {
|
|
579
|
+
hasFeature: { sdk: "flagsmith-js-client", expectedType: "boolean" },
|
|
580
|
+
getValue: { sdk: "flagsmith-js-client", expectedType: "unknown" }
|
|
581
|
+
};
|
|
582
|
+
var JAVA_SDK_METHODS = {
|
|
583
|
+
isFeatureEnabled: { sdk: "flagsmith-java-client", expectedType: "boolean" },
|
|
584
|
+
getFeatureValue: { sdk: "flagsmith-java-client", expectedType: "unknown" },
|
|
585
|
+
getFlag: { sdk: "flagsmith-java-client", expectedType: "unknown" }
|
|
586
|
+
};
|
|
587
|
+
var JS_SDK_IMPORTS = [
|
|
588
|
+
"@flagsmith/flagsmith",
|
|
589
|
+
"@flagsmith/nodejs",
|
|
590
|
+
"@flagsmith/react-native"
|
|
591
|
+
];
|
|
592
|
+
|
|
593
|
+
// packages/core/src/scan/extractors/context.ts
|
|
594
|
+
function walk(node, visit) {
|
|
595
|
+
visit(node);
|
|
596
|
+
for (const child of node.namedChildren) walk(child, visit);
|
|
597
|
+
}
|
|
598
|
+
function nearestAncestor(node, types) {
|
|
599
|
+
let current = node.parent;
|
|
600
|
+
while (current) {
|
|
601
|
+
if (types.has(current.type)) return current;
|
|
602
|
+
current = current.parent;
|
|
603
|
+
}
|
|
604
|
+
return null;
|
|
605
|
+
}
|
|
606
|
+
var JS_FUNCTION_TYPES = /* @__PURE__ */ new Set([
|
|
607
|
+
"function_declaration",
|
|
608
|
+
"generator_function_declaration",
|
|
609
|
+
"function_expression",
|
|
610
|
+
"generator_function",
|
|
611
|
+
"arrow_function",
|
|
612
|
+
"method_definition"
|
|
613
|
+
]);
|
|
614
|
+
var JS_CLASS_TYPES = /* @__PURE__ */ new Set(["class_declaration", "class"]);
|
|
615
|
+
function jsFunctionName(node) {
|
|
616
|
+
const direct = node.childForFieldName("name");
|
|
617
|
+
if (direct) return direct.text;
|
|
618
|
+
const parent = node.parent;
|
|
619
|
+
if (parent?.type === "variable_declarator") {
|
|
620
|
+
const name = parent.childForFieldName("name");
|
|
621
|
+
if (name) return name.text;
|
|
622
|
+
}
|
|
623
|
+
if (parent?.type === "pair") {
|
|
624
|
+
const key = parent.childForFieldName("key");
|
|
625
|
+
if (key) return key.text.replace(/^['"]|['"]$/g, "");
|
|
626
|
+
}
|
|
627
|
+
if (parent?.type === "assignment_expression") {
|
|
628
|
+
const left = parent.childForFieldName("left");
|
|
629
|
+
if (left) return left.text;
|
|
630
|
+
}
|
|
631
|
+
if (parent?.type === "property_identifier") return parent.text;
|
|
632
|
+
return "(anonymous)";
|
|
633
|
+
}
|
|
634
|
+
function jsClassName(node) {
|
|
635
|
+
return node.childForFieldName("name")?.text ?? null;
|
|
636
|
+
}
|
|
637
|
+
function jsEnclosingScope(node) {
|
|
638
|
+
const functionNode = nearestAncestor(node, JS_FUNCTION_TYPES);
|
|
639
|
+
const classNode = nearestAncestor(node, JS_CLASS_TYPES);
|
|
640
|
+
return {
|
|
641
|
+
enclosingFunction: functionNode ? jsFunctionName(functionNode) : null,
|
|
642
|
+
enclosingClass: classNode ? jsClassName(classNode) : null
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
var JAVA_FUNCTION_TYPES = /* @__PURE__ */ new Set(["method_declaration", "constructor_declaration"]);
|
|
646
|
+
var JAVA_CLASS_TYPES = /* @__PURE__ */ new Set([
|
|
647
|
+
"class_declaration",
|
|
648
|
+
"interface_declaration",
|
|
649
|
+
"enum_declaration",
|
|
650
|
+
"record_declaration"
|
|
651
|
+
]);
|
|
652
|
+
function javaEnclosingScope(node) {
|
|
653
|
+
const functionNode = nearestAncestor(node, JAVA_FUNCTION_TYPES);
|
|
654
|
+
const classNode = nearestAncestor(node, JAVA_CLASS_TYPES);
|
|
655
|
+
return {
|
|
656
|
+
enclosingFunction: functionNode?.childForFieldName("name")?.text ?? null,
|
|
657
|
+
enclosingClass: classNode?.childForFieldName("name")?.text ?? null
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
function buildReference(nameNode, callNode, context, method, sdk, expectedType, flagName, resolution, scope = { enclosingClass: null, enclosingFunction: null }) {
|
|
661
|
+
const { line, column } = positionOf(nameNode);
|
|
662
|
+
return {
|
|
663
|
+
flagName,
|
|
664
|
+
resolution,
|
|
665
|
+
expectedType,
|
|
666
|
+
repository: context.repository,
|
|
667
|
+
filePath: context.filePath,
|
|
668
|
+
line,
|
|
669
|
+
column,
|
|
670
|
+
sdk,
|
|
671
|
+
method,
|
|
672
|
+
snippet: makeSnippet(callNode.text),
|
|
673
|
+
commit: context.commit,
|
|
674
|
+
enclosingClass: scope.enclosingClass,
|
|
675
|
+
enclosingFunction: scope.enclosingFunction
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
function wrapperByName(context) {
|
|
679
|
+
return new Map(context.wrappers.map((wrapper) => [wrapper.name, wrapper]));
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// packages/core/src/scan/extractors/java.ts
|
|
683
|
+
var FLAGS_FACTORIES = /* @__PURE__ */ new Set(["getEnvironmentFlags", "getIdentityFlags"]);
|
|
684
|
+
function invocationName(node) {
|
|
685
|
+
return node.type === "method_invocation" ? node.childForFieldName("name")?.text ?? null : null;
|
|
686
|
+
}
|
|
687
|
+
function importedSdkTypes(root) {
|
|
688
|
+
const result = { flagsType: null, clientType: null };
|
|
689
|
+
walk(root, (node) => {
|
|
690
|
+
if (node.type !== "import_declaration") return;
|
|
691
|
+
let fqn = node.text.trim();
|
|
692
|
+
if (fqn.startsWith("import ")) fqn = fqn.slice(7).trim();
|
|
693
|
+
if (fqn.startsWith("static ")) fqn = fqn.slice(7).trim();
|
|
694
|
+
if (fqn.endsWith(";")) fqn = fqn.slice(0, -1).trim();
|
|
695
|
+
if (fqn === "com.flagsmith.models.Flags") result.flagsType = "Flags";
|
|
696
|
+
if (fqn === "com.flagsmith.FlagsmithClient") result.clientType = "FlagsmithClient";
|
|
697
|
+
});
|
|
698
|
+
return result;
|
|
699
|
+
}
|
|
700
|
+
function buildSymbolTable(root) {
|
|
701
|
+
const table = /* @__PURE__ */ new Map();
|
|
702
|
+
const bind = (symbol2, scope) => {
|
|
703
|
+
const scoped = table.get(scope.id) ?? /* @__PURE__ */ new Map();
|
|
704
|
+
const existing = scoped.get(symbol2.name);
|
|
705
|
+
scoped.set(
|
|
706
|
+
symbol2.name,
|
|
707
|
+
existing && existing.typeText !== symbol2.typeText ? { ...symbol2, typeText: "" } : symbol2
|
|
708
|
+
);
|
|
709
|
+
table.set(scope.id, scoped);
|
|
710
|
+
};
|
|
711
|
+
walk(root, (node) => {
|
|
712
|
+
if (node.type === "variable_declarator") {
|
|
713
|
+
const name = node.childForFieldName("name");
|
|
714
|
+
const parent = node.parent;
|
|
715
|
+
if (name?.type !== "identifier" || !parent) return;
|
|
716
|
+
if (parent.type !== "field_declaration" && parent.type !== "local_variable_declaration") {
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
bind(
|
|
720
|
+
{
|
|
721
|
+
name: name.text,
|
|
722
|
+
typeText: parent.childForFieldName("type")?.text.trim() ?? "",
|
|
723
|
+
value: node.childForFieldName("value"),
|
|
724
|
+
kind: parent.type === "field_declaration" ? "field" : "local"
|
|
725
|
+
},
|
|
726
|
+
scopeChain(node)[0] ?? node
|
|
727
|
+
);
|
|
728
|
+
}
|
|
729
|
+
if (node.type === "formal_parameter") {
|
|
730
|
+
const name = node.childForFieldName("name");
|
|
731
|
+
if (name?.type !== "identifier") return;
|
|
732
|
+
bind(
|
|
733
|
+
{
|
|
734
|
+
name: name.text,
|
|
735
|
+
typeText: node.childForFieldName("type")?.text.trim() ?? "",
|
|
736
|
+
value: null,
|
|
737
|
+
kind: "parameter"
|
|
738
|
+
},
|
|
739
|
+
scopeChain(node)[0] ?? node
|
|
740
|
+
);
|
|
741
|
+
}
|
|
742
|
+
});
|
|
743
|
+
return table;
|
|
744
|
+
}
|
|
745
|
+
function resolveSymbol(nameNode, table) {
|
|
746
|
+
if (nameNode.type !== "identifier") return null;
|
|
747
|
+
for (const scope of scopeChain(nameNode)) {
|
|
748
|
+
const symbol2 = table.get(scope.id)?.get(nameNode.text);
|
|
749
|
+
if (symbol2) return symbol2;
|
|
750
|
+
}
|
|
751
|
+
return null;
|
|
752
|
+
}
|
|
753
|
+
function isClientSymbol(symbol2, imports) {
|
|
754
|
+
return imports.clientType !== null && symbol2.typeText === imports.clientType;
|
|
755
|
+
}
|
|
756
|
+
function isFlagsSymbol(symbol2, imports) {
|
|
757
|
+
return imports.flagsType !== null && symbol2.typeText === imports.flagsType;
|
|
758
|
+
}
|
|
759
|
+
function verifiedFactory(node, symbols, imports) {
|
|
760
|
+
if (!node || node.type !== "method_invocation") return false;
|
|
761
|
+
const name = invocationName(node);
|
|
762
|
+
if (!name || !FLAGS_FACTORIES.has(name)) return false;
|
|
763
|
+
const receiver = node.childForFieldName("object");
|
|
764
|
+
if (receiver?.type !== "identifier") return false;
|
|
765
|
+
const symbol2 = resolveSymbol(receiver, symbols);
|
|
766
|
+
return symbol2 !== null && isClientSymbol(symbol2, imports);
|
|
767
|
+
}
|
|
768
|
+
function isFlagsReceiver(receiver, symbols, imports) {
|
|
769
|
+
if (receiver?.type === "identifier") {
|
|
770
|
+
const symbol2 = resolveSymbol(receiver, symbols);
|
|
771
|
+
if (!symbol2) return false;
|
|
772
|
+
return isFlagsSymbol(symbol2, imports) || verifiedFactory(symbol2.value, symbols, imports);
|
|
773
|
+
}
|
|
774
|
+
return verifiedFactory(receiver, symbols, imports);
|
|
775
|
+
}
|
|
776
|
+
function declaredTypeOf(node) {
|
|
777
|
+
let current = node.parent;
|
|
778
|
+
while (current) {
|
|
779
|
+
if (current.type === "local_variable_declaration" || current.type === "field_declaration") {
|
|
780
|
+
return current.childForFieldName("type")?.text ?? "";
|
|
781
|
+
}
|
|
782
|
+
if (current.type === "method_declaration" || current.type === "class_body") break;
|
|
783
|
+
current = current.parent;
|
|
784
|
+
}
|
|
785
|
+
return "";
|
|
786
|
+
}
|
|
787
|
+
function inferExpectedType(node, method) {
|
|
788
|
+
if (method === "isFeatureEnabled") return "boolean";
|
|
789
|
+
if (method !== "getFeatureValue") return "unknown";
|
|
790
|
+
const declared = declaredTypeOf(node).trim();
|
|
791
|
+
if (/^String$/.test(declared)) return "string";
|
|
792
|
+
if (/^Boolean$|^boolean$/.test(declared)) return "boolean";
|
|
793
|
+
if (/^(Integer|int|Long|long|Double|double|Float|float|Number)$/.test(declared)) return "number";
|
|
794
|
+
return "unknown";
|
|
795
|
+
}
|
|
796
|
+
function extractJavaReferences(root, context) {
|
|
797
|
+
const imports = importedSdkTypes(root);
|
|
798
|
+
if (!imports.flagsType && !imports.clientType && context.wrappers.length === 0) return [];
|
|
799
|
+
const symbols = buildSymbolTable(root);
|
|
800
|
+
const table = buildConstantTable(root, "java");
|
|
801
|
+
const wrappers = wrapperByName(context);
|
|
802
|
+
const references = [];
|
|
803
|
+
walk(root, (node) => {
|
|
804
|
+
if (node.type !== "method_invocation") return;
|
|
805
|
+
const method = invocationName(node);
|
|
806
|
+
if (!method) return;
|
|
807
|
+
const wrapper = wrappers.get(method);
|
|
808
|
+
const pattern = JAVA_SDK_METHODS[method];
|
|
809
|
+
if (!wrapper && !pattern) return;
|
|
810
|
+
const receiver = node.childForFieldName("object");
|
|
811
|
+
if (!wrapper && !isFlagsReceiver(receiver, symbols, imports)) return;
|
|
812
|
+
const argumentIndex = wrapper?.argumentIndex ?? 0;
|
|
813
|
+
const nameNode = node.childForFieldName("arguments")?.namedChildren[argumentIndex] ?? null;
|
|
814
|
+
if (!nameNode) return;
|
|
815
|
+
const resolved = resolveName(nameNode, table);
|
|
816
|
+
const sdk = wrapper?.sdk ?? pattern?.sdk ?? "registered-wrapper";
|
|
817
|
+
references.push(
|
|
818
|
+
buildReference(
|
|
819
|
+
nameNode,
|
|
820
|
+
node,
|
|
821
|
+
context,
|
|
822
|
+
method,
|
|
823
|
+
sdk,
|
|
824
|
+
wrapper?.expectedType ?? inferExpectedType(node, method),
|
|
825
|
+
resolved?.value ?? null,
|
|
826
|
+
resolved ? resolved.resolution : "dynamic",
|
|
827
|
+
javaEnclosingScope(node)
|
|
828
|
+
)
|
|
829
|
+
);
|
|
830
|
+
});
|
|
831
|
+
return references.sort((a, b) => a.line - b.line || a.column - b.column);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// packages/core/src/scan/extractors/jsTs.ts
|
|
835
|
+
function collectIdentifiers(node, into) {
|
|
836
|
+
if (node.type === "identifier") into.add(node.text);
|
|
837
|
+
for (const child of node.namedChildren) collectIdentifiers(child, into);
|
|
838
|
+
}
|
|
839
|
+
function enclosingDeclarator(node) {
|
|
840
|
+
let current = node.parent;
|
|
841
|
+
while (current) {
|
|
842
|
+
if (current.type === "variable_declarator") return current;
|
|
843
|
+
if (current.type === "program" || current.type === "statement_block") return null;
|
|
844
|
+
current = current.parent;
|
|
845
|
+
}
|
|
846
|
+
return null;
|
|
847
|
+
}
|
|
848
|
+
function sdkBindings(root) {
|
|
849
|
+
const receivers = /* @__PURE__ */ new Set();
|
|
850
|
+
const factories = /* @__PURE__ */ new Set();
|
|
851
|
+
const identifiers = /* @__PURE__ */ new Set();
|
|
852
|
+
walk(root, (node) => {
|
|
853
|
+
if (node.type === "import_statement") {
|
|
854
|
+
const source = literalString(node.childForFieldName("source") ?? null);
|
|
855
|
+
if (source && JS_SDK_IMPORTS.includes(source)) {
|
|
856
|
+
identifiers.clear();
|
|
857
|
+
const clause = node.namedChildren.find((child) => child.type === "import_clause");
|
|
858
|
+
if (clause) collectIdentifiers(clause, identifiers);
|
|
859
|
+
for (const name of identifiers) {
|
|
860
|
+
if (name === "createFlagsmithInstance") factories.add(name);
|
|
861
|
+
else receivers.add(name);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
if (node.type === "call_expression") {
|
|
866
|
+
const fn = node.childForFieldName("function");
|
|
867
|
+
const firstArgument = node.childForFieldName("arguments")?.namedChildren[0] ?? null;
|
|
868
|
+
const source = literalString(firstArgument);
|
|
869
|
+
const isRequire = fn?.type === "identifier" && fn.text === "require" && source !== null && JS_SDK_IMPORTS.includes(source);
|
|
870
|
+
const isFactory = fn?.type === "identifier" && factories.has(fn.text);
|
|
871
|
+
if (isRequire || isFactory) {
|
|
872
|
+
const nameNode = enclosingDeclarator(node)?.childForFieldName("name");
|
|
873
|
+
if (nameNode?.type === "identifier") receivers.add(nameNode.text);
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
});
|
|
877
|
+
return { receivers, factories };
|
|
878
|
+
}
|
|
879
|
+
function inferExpectedType2(call, method, pattern, wrappers) {
|
|
880
|
+
const wrapper = wrappers.get(method);
|
|
881
|
+
if (wrapper) return wrapper.expectedType;
|
|
882
|
+
if (method === "hasFeature") return "boolean";
|
|
883
|
+
if (method !== "getValue") return pattern.expectedType;
|
|
884
|
+
const args = call.childForFieldName("arguments");
|
|
885
|
+
const options = args?.namedChildren[1];
|
|
886
|
+
if (options?.type === "object") {
|
|
887
|
+
const jsonTrue = options.namedChildren.some((pair) => {
|
|
888
|
+
const key = pair.childForFieldName("key")?.text.replace(/['"]/g, "");
|
|
889
|
+
return key === "json" && pair.childForFieldName("value")?.text === "true";
|
|
890
|
+
});
|
|
891
|
+
if (jsonTrue) return "json";
|
|
892
|
+
}
|
|
893
|
+
const annotation = enclosingDeclarator(call)?.childForFieldName("type")?.text ?? "";
|
|
894
|
+
const declared = annotation.replace(/^\s*:\s*/, "").trim();
|
|
895
|
+
if (/^(string|String)$/.test(declared)) return "string";
|
|
896
|
+
if (/^(number|Number)$/.test(declared)) return "number";
|
|
897
|
+
if (/^(boolean|Boolean)$/.test(declared)) return "boolean";
|
|
898
|
+
if (/json|record|object/i.test(declared)) return "json";
|
|
899
|
+
return pattern.expectedType;
|
|
900
|
+
}
|
|
901
|
+
function extractJsTsReferences(root, context) {
|
|
902
|
+
const { receivers } = sdkBindings(root);
|
|
903
|
+
if (receivers.size === 0 && context.wrappers.length === 0) return [];
|
|
904
|
+
const table = buildConstantTable(root, "js");
|
|
905
|
+
const wrappers = wrapperByName(context);
|
|
906
|
+
const references = [];
|
|
907
|
+
walk(root, (node) => {
|
|
908
|
+
if (node.type !== "call_expression") return;
|
|
909
|
+
const functionNode = node.childForFieldName("function");
|
|
910
|
+
if (!functionNode) return;
|
|
911
|
+
let method = null;
|
|
912
|
+
let receiver = null;
|
|
913
|
+
if (functionNode.type === "member_expression") {
|
|
914
|
+
method = functionNode.childForFieldName("property")?.text ?? null;
|
|
915
|
+
receiver = functionNode.childForFieldName("object") ?? null;
|
|
916
|
+
} else if (functionNode.type === "identifier") {
|
|
917
|
+
method = functionNode.text;
|
|
918
|
+
}
|
|
919
|
+
if (!method) return;
|
|
920
|
+
const wrapper = wrappers.get(method);
|
|
921
|
+
const pattern = JS_SDK_METHODS[method];
|
|
922
|
+
if (!wrapper && !pattern) return;
|
|
923
|
+
if (!wrapper && !(receiver?.type === "identifier" && receivers.has(receiver.text))) {
|
|
924
|
+
return;
|
|
925
|
+
}
|
|
926
|
+
const argumentIndex = wrapper?.argumentIndex ?? 0;
|
|
927
|
+
const nameNode = node.childForFieldName("arguments")?.namedChildren[argumentIndex] ?? null;
|
|
928
|
+
if (!nameNode) return;
|
|
929
|
+
const resolved = resolveName(nameNode, table);
|
|
930
|
+
const sdk = wrapper?.sdk ?? pattern?.sdk ?? "registered-wrapper";
|
|
931
|
+
const expectedType = inferExpectedType2(
|
|
932
|
+
node,
|
|
933
|
+
method,
|
|
934
|
+
pattern ?? { sdk, expectedType: wrapper?.expectedType ?? "unknown" },
|
|
935
|
+
wrappers
|
|
936
|
+
);
|
|
937
|
+
references.push(
|
|
938
|
+
buildReference(
|
|
939
|
+
nameNode,
|
|
940
|
+
node,
|
|
941
|
+
context,
|
|
942
|
+
method,
|
|
943
|
+
sdk,
|
|
944
|
+
expectedType,
|
|
945
|
+
resolved?.value ?? null,
|
|
946
|
+
resolved ? resolved.resolution : "dynamic",
|
|
947
|
+
jsEnclosingScope(node)
|
|
948
|
+
)
|
|
949
|
+
);
|
|
950
|
+
});
|
|
951
|
+
return references.sort((a, b) => a.line - b.line || a.column - b.column);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
// packages/core/src/scan/parser.ts
|
|
955
|
+
import { Language, Parser } from "web-tree-sitter";
|
|
956
|
+
import { getWasmPath } from "tree-sitter-wasm";
|
|
957
|
+
var initialisation = null;
|
|
958
|
+
var languages = /* @__PURE__ */ new Map();
|
|
959
|
+
async function loadLanguage(language) {
|
|
960
|
+
initialisation ??= Parser.init();
|
|
961
|
+
await initialisation;
|
|
962
|
+
const cached = languages.get(language);
|
|
963
|
+
if (cached) return cached;
|
|
964
|
+
const loaded = await Language.load(getWasmPath(language));
|
|
965
|
+
languages.set(language, loaded);
|
|
966
|
+
return loaded;
|
|
967
|
+
}
|
|
968
|
+
async function parseSource(language, source) {
|
|
969
|
+
const grammar = await loadLanguage(language);
|
|
970
|
+
const parser = new Parser();
|
|
971
|
+
parser.setLanguage(grammar);
|
|
972
|
+
const tree = parser.parse(source);
|
|
973
|
+
if (!tree) throw new Error("Tree-sitter returned no syntax tree");
|
|
974
|
+
return tree;
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// packages/core/src/scan/prefilter.ts
|
|
978
|
+
var LANGUAGE_BY_EXTENSION = {
|
|
979
|
+
".js": "javascript",
|
|
980
|
+
".jsx": "javascript",
|
|
981
|
+
".mjs": "javascript",
|
|
982
|
+
".cjs": "javascript",
|
|
983
|
+
".ts": "typescript",
|
|
984
|
+
".tsx": "typescript",
|
|
985
|
+
".java": "java"
|
|
986
|
+
};
|
|
987
|
+
var BASE_KEYWORDS = [
|
|
988
|
+
"flagsmith",
|
|
989
|
+
"hasfeature",
|
|
990
|
+
"getvalue",
|
|
991
|
+
"isfeatureenabled",
|
|
992
|
+
"getfeaturevalue",
|
|
993
|
+
"createflagsmithinstance"
|
|
994
|
+
];
|
|
995
|
+
function languageForFile(relativePath) {
|
|
996
|
+
const dot = relativePath.lastIndexOf(".");
|
|
997
|
+
if (dot < 0) return null;
|
|
998
|
+
return LANGUAGE_BY_EXTENSION[relativePath.slice(dot).toLowerCase()] ?? null;
|
|
999
|
+
}
|
|
1000
|
+
function passesPrefilter(content, wrapperNames) {
|
|
1001
|
+
const lower = content.toLowerCase();
|
|
1002
|
+
if (BASE_KEYWORDS.some((keyword) => lower.includes(keyword))) return true;
|
|
1003
|
+
return wrapperNames.some((name) => lower.includes(name.toLowerCase()));
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
// packages/core/src/scan/Scanner.ts
|
|
1007
|
+
function messageOf(error) {
|
|
1008
|
+
return error instanceof Error ? error.message : String(error);
|
|
1009
|
+
}
|
|
1010
|
+
async function scanSources(options) {
|
|
1011
|
+
const wrappers = (options.wrappers ?? []).map(
|
|
1012
|
+
(wrapper) => wrapperDefinitionSchema.parse(wrapper)
|
|
1013
|
+
);
|
|
1014
|
+
const maxFiles = options.maxFiles ?? 2e3;
|
|
1015
|
+
const maxFileBytes = options.maxFileBytes ?? 2e6;
|
|
1016
|
+
const wrapperNames = wrappers.map((wrapper) => wrapper.name);
|
|
1017
|
+
const references = [];
|
|
1018
|
+
const diagnostics = [];
|
|
1019
|
+
let scannedFiles = 0;
|
|
1020
|
+
let skippedFiles = 0;
|
|
1021
|
+
const files = await options.provider.listFiles();
|
|
1022
|
+
for (const file of files) {
|
|
1023
|
+
if (options.signal?.aborted) break;
|
|
1024
|
+
if (scannedFiles >= maxFiles || file.sizeBytes > maxFileBytes) {
|
|
1025
|
+
skippedFiles += 1;
|
|
1026
|
+
continue;
|
|
1027
|
+
}
|
|
1028
|
+
const language = languageForFile(file.relativePath);
|
|
1029
|
+
if (!language) {
|
|
1030
|
+
skippedFiles += 1;
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
let content;
|
|
1034
|
+
try {
|
|
1035
|
+
content = await options.provider.readFile(file.relativePath);
|
|
1036
|
+
} catch (error) {
|
|
1037
|
+
diagnostics.push({
|
|
1038
|
+
filePath: file.relativePath,
|
|
1039
|
+
line: 1,
|
|
1040
|
+
column: 1,
|
|
1041
|
+
kind: "read_error",
|
|
1042
|
+
message: messageOf(error)
|
|
1043
|
+
});
|
|
1044
|
+
skippedFiles += 1;
|
|
1045
|
+
continue;
|
|
1046
|
+
}
|
|
1047
|
+
if (!passesPrefilter(content, wrapperNames)) {
|
|
1048
|
+
skippedFiles += 1;
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
try {
|
|
1052
|
+
const tree = await parseSource(language, content);
|
|
1053
|
+
if (tree.rootNode.hasError) {
|
|
1054
|
+
diagnostics.push({
|
|
1055
|
+
filePath: file.relativePath,
|
|
1056
|
+
line: 1,
|
|
1057
|
+
column: 1,
|
|
1058
|
+
kind: "parse_error",
|
|
1059
|
+
message: "Tree-sitter reported syntax errors; extraction continued for parsed nodes"
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
1062
|
+
const context = {
|
|
1063
|
+
repository: options.repository ?? null,
|
|
1064
|
+
filePath: file.relativePath,
|
|
1065
|
+
commit: options.commit ?? null,
|
|
1066
|
+
wrappers
|
|
1067
|
+
};
|
|
1068
|
+
const extracted = language === "java" ? extractJavaReferences(tree.rootNode, context) : extractJsTsReferences(tree.rootNode, context);
|
|
1069
|
+
references.push(...extracted);
|
|
1070
|
+
scannedFiles += 1;
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
diagnostics.push({
|
|
1073
|
+
filePath: file.relativePath,
|
|
1074
|
+
line: 1,
|
|
1075
|
+
column: 1,
|
|
1076
|
+
kind: "parse_error",
|
|
1077
|
+
message: messageOf(error)
|
|
1078
|
+
});
|
|
1079
|
+
skippedFiles += 1;
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
references.sort(
|
|
1083
|
+
(a, b) => a.filePath.localeCompare(b.filePath) || a.line - b.line || a.column - b.column
|
|
1084
|
+
);
|
|
1085
|
+
return { references, diagnostics, scannedFiles, skippedFiles };
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
// packages/core/src/flagsmith/FlagsmithAdapter.ts
|
|
1089
|
+
import { z as z4 } from "zod";
|
|
1090
|
+
|
|
1091
|
+
// packages/core/src/flagsmith/client.ts
|
|
1092
|
+
import { z as z2 } from "zod";
|
|
1093
|
+
|
|
1094
|
+
// packages/core/src/flagsmith/errors.ts
|
|
1095
|
+
var FlagsmithAdapterError = class extends Error {
|
|
1096
|
+
kind;
|
|
1097
|
+
status;
|
|
1098
|
+
constructor(kind, message, status = null) {
|
|
1099
|
+
super(message);
|
|
1100
|
+
this.name = "FlagsmithAdapterError";
|
|
1101
|
+
this.kind = kind;
|
|
1102
|
+
this.status = status;
|
|
1103
|
+
}
|
|
1104
|
+
toJSON() {
|
|
1105
|
+
return { kind: this.kind, status: this.status, message: this.message };
|
|
1106
|
+
}
|
|
1107
|
+
};
|
|
1108
|
+
function redact(value, secrets) {
|
|
1109
|
+
let result = value;
|
|
1110
|
+
for (const secret of secrets) {
|
|
1111
|
+
if (secret.length > 0) result = result.split(secret).join("[REDACTED]");
|
|
1112
|
+
}
|
|
1113
|
+
return result;
|
|
1114
|
+
}
|
|
1115
|
+
function errorMessage(error) {
|
|
1116
|
+
return error instanceof Error ? error.message : String(error);
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
// packages/core/src/flagsmith/client.ts
|
|
1120
|
+
var MAX_PAGES = 50;
|
|
1121
|
+
function normalizeBaseUrl(input = DEFAULT_FLAGSMITH_BASE_URL) {
|
|
1122
|
+
const raw = input.trim();
|
|
1123
|
+
if (raw === "") {
|
|
1124
|
+
throw new FlagsmithAdapterError("configuration", "Flagsmith base URL must not be empty");
|
|
1125
|
+
}
|
|
1126
|
+
let url;
|
|
1127
|
+
try {
|
|
1128
|
+
url = new URL(raw);
|
|
1129
|
+
} catch {
|
|
1130
|
+
throw new FlagsmithAdapterError("configuration", "Flagsmith base URL must be an absolute URL");
|
|
1131
|
+
}
|
|
1132
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
1133
|
+
throw new FlagsmithAdapterError("configuration", "Flagsmith base URL must use http or https");
|
|
1134
|
+
}
|
|
1135
|
+
if (url.username !== "" || url.password !== "") {
|
|
1136
|
+
throw new FlagsmithAdapterError(
|
|
1137
|
+
"configuration",
|
|
1138
|
+
"Flagsmith base URL must not contain credentials"
|
|
1139
|
+
);
|
|
1140
|
+
}
|
|
1141
|
+
let path5 = url.pathname.replace(/\/+$/, "");
|
|
1142
|
+
const versionedIndex = path5.lastIndexOf("/api/v1");
|
|
1143
|
+
if (versionedIndex >= 0) {
|
|
1144
|
+
path5 = path5.slice(0, versionedIndex + "/api/v1".length);
|
|
1145
|
+
} else if (path5 === "/api" || path5.endsWith("/api")) {
|
|
1146
|
+
path5 = `${path5}/v1`;
|
|
1147
|
+
} else {
|
|
1148
|
+
path5 = `${path5}/api/v1`;
|
|
1149
|
+
}
|
|
1150
|
+
url.pathname = path5;
|
|
1151
|
+
url.search = "";
|
|
1152
|
+
url.hash = "";
|
|
1153
|
+
return url.toString().replace(/\/+$/, "");
|
|
1154
|
+
}
|
|
1155
|
+
function readTokenFromEnv(env = process.env) {
|
|
1156
|
+
const token = env.FLAGSMITH_TOKEN?.trim() ?? "";
|
|
1157
|
+
if (token === "") {
|
|
1158
|
+
throw new FlagsmithAdapterError(
|
|
1159
|
+
"configuration",
|
|
1160
|
+
"FLAGSMITH_TOKEN is required for Flagsmith Management API access"
|
|
1161
|
+
);
|
|
1162
|
+
}
|
|
1163
|
+
return token;
|
|
1164
|
+
}
|
|
1165
|
+
function statusError(status, url, body, token) {
|
|
1166
|
+
const path5 = (() => {
|
|
1167
|
+
try {
|
|
1168
|
+
return new URL(url).pathname;
|
|
1169
|
+
} catch {
|
|
1170
|
+
return "request";
|
|
1171
|
+
}
|
|
1172
|
+
})();
|
|
1173
|
+
const detail = redact(body.slice(0, 200), [token]);
|
|
1174
|
+
const message = `Flagsmith API returned HTTP ${status} for ${path5}${detail ? `: ${detail}` : ""}`;
|
|
1175
|
+
if (status === 401) return new FlagsmithAdapterError("authentication", message, status);
|
|
1176
|
+
if (status === 403) return new FlagsmithAdapterError("authorization", message, status);
|
|
1177
|
+
if (status === 404) return new FlagsmithAdapterError("not_found", message, status);
|
|
1178
|
+
if (status === 429) return new FlagsmithAdapterError("rate_limited", message, status);
|
|
1179
|
+
if (status >= 500) return new FlagsmithAdapterError("server", message, status);
|
|
1180
|
+
return new FlagsmithAdapterError("invalid_response", message, status);
|
|
1181
|
+
}
|
|
1182
|
+
function shouldRetry(error) {
|
|
1183
|
+
return error.kind === "rate_limited" || error.kind === "timeout" || error.kind === "network" || error.kind === "server";
|
|
1184
|
+
}
|
|
1185
|
+
async function delay(milliseconds) {
|
|
1186
|
+
if (milliseconds <= 0) return;
|
|
1187
|
+
await new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
1188
|
+
}
|
|
1189
|
+
var FlagsmithHttpClient = class {
|
|
1190
|
+
baseUrl;
|
|
1191
|
+
token;
|
|
1192
|
+
timeoutMs;
|
|
1193
|
+
maxRetries;
|
|
1194
|
+
retryDelayMs;
|
|
1195
|
+
fetchImpl;
|
|
1196
|
+
constructor(options) {
|
|
1197
|
+
this.baseUrl = normalizeBaseUrl(options.baseUrl);
|
|
1198
|
+
this.token = options.token;
|
|
1199
|
+
this.timeoutMs = options.timeoutMs;
|
|
1200
|
+
this.maxRetries = options.maxRetries;
|
|
1201
|
+
this.retryDelayMs = options.retryDelayMs;
|
|
1202
|
+
this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
1203
|
+
}
|
|
1204
|
+
buildUrl(path5, params = {}) {
|
|
1205
|
+
const url = new URL(`${this.baseUrl}/${path5.replace(/^\/+/, "")}`);
|
|
1206
|
+
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, String(value));
|
|
1207
|
+
return url.toString();
|
|
1208
|
+
}
|
|
1209
|
+
async getJson(url, parse) {
|
|
1210
|
+
const target = url.startsWith("http://") || url.startsWith("https://") ? url : this.buildUrl(url);
|
|
1211
|
+
let lastError = null;
|
|
1212
|
+
for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
|
|
1213
|
+
try {
|
|
1214
|
+
const response = await this.fetchJson(target);
|
|
1215
|
+
return parse(response);
|
|
1216
|
+
} catch (error) {
|
|
1217
|
+
const typed = error instanceof FlagsmithAdapterError ? error : new FlagsmithAdapterError(
|
|
1218
|
+
"invalid_response",
|
|
1219
|
+
redact(errorMessage(error), [this.token])
|
|
1220
|
+
);
|
|
1221
|
+
lastError = typed;
|
|
1222
|
+
if (!shouldRetry(typed) || attempt === this.maxRetries) throw typed;
|
|
1223
|
+
await delay(this.retryDelayMs * 2 ** attempt);
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
throw lastError ?? new FlagsmithAdapterError("network", "Flagsmith request failed");
|
|
1227
|
+
}
|
|
1228
|
+
async getAllPages(path5, params, parseItem) {
|
|
1229
|
+
let nextUrl = this.buildUrl(path5, params);
|
|
1230
|
+
const results = [];
|
|
1231
|
+
let pages = 0;
|
|
1232
|
+
while (nextUrl !== null && pages < MAX_PAGES) {
|
|
1233
|
+
if (!this.isAllowedUrl(nextUrl)) {
|
|
1234
|
+
throw new FlagsmithAdapterError(
|
|
1235
|
+
"invalid_response",
|
|
1236
|
+
"Flagsmith pagination URL is outside the configured API base"
|
|
1237
|
+
);
|
|
1238
|
+
}
|
|
1239
|
+
const currentUrl = nextUrl;
|
|
1240
|
+
const page = await this.getJson(
|
|
1241
|
+
currentUrl,
|
|
1242
|
+
(raw) => parsePaginated(raw, parseItem)
|
|
1243
|
+
);
|
|
1244
|
+
results.push(...page.results);
|
|
1245
|
+
pages += 1;
|
|
1246
|
+
nextUrl = page.next;
|
|
1247
|
+
}
|
|
1248
|
+
if (nextUrl !== null) {
|
|
1249
|
+
throw new FlagsmithAdapterError(
|
|
1250
|
+
"invalid_response",
|
|
1251
|
+
"Flagsmith pagination exceeded the page limit"
|
|
1252
|
+
);
|
|
1253
|
+
}
|
|
1254
|
+
return results;
|
|
1255
|
+
}
|
|
1256
|
+
isAllowedUrl(url) {
|
|
1257
|
+
let parsed;
|
|
1258
|
+
try {
|
|
1259
|
+
parsed = new URL(url);
|
|
1260
|
+
} catch {
|
|
1261
|
+
return false;
|
|
1262
|
+
}
|
|
1263
|
+
const base = new URL(this.baseUrl);
|
|
1264
|
+
return parsed.origin === base.origin && parsed.username === "" && parsed.password === "" && (parsed.pathname === base.pathname || parsed.pathname.startsWith(`${base.pathname}/`));
|
|
1265
|
+
}
|
|
1266
|
+
async fetchJson(url) {
|
|
1267
|
+
let response;
|
|
1268
|
+
try {
|
|
1269
|
+
response = await this.fetchImpl(url, {
|
|
1270
|
+
method: "GET",
|
|
1271
|
+
headers: {
|
|
1272
|
+
Accept: "application/json",
|
|
1273
|
+
Authorization: `Api-Key ${this.token}`
|
|
1274
|
+
},
|
|
1275
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
1276
|
+
});
|
|
1277
|
+
} catch (error) {
|
|
1278
|
+
const name = error instanceof Error ? error.name : "";
|
|
1279
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
1280
|
+
throw new FlagsmithAdapterError("timeout", "Flagsmith request timed out");
|
|
1281
|
+
}
|
|
1282
|
+
throw new FlagsmithAdapterError(
|
|
1283
|
+
"network",
|
|
1284
|
+
redact(`Flagsmith request failed: ${errorMessage(error)}`, [this.token])
|
|
1285
|
+
);
|
|
1286
|
+
}
|
|
1287
|
+
if (!response.ok) {
|
|
1288
|
+
const body = await response.text().catch(() => "");
|
|
1289
|
+
throw statusError(response.status, url, body, this.token);
|
|
1290
|
+
}
|
|
1291
|
+
try {
|
|
1292
|
+
return await response.json();
|
|
1293
|
+
} catch {
|
|
1294
|
+
throw new FlagsmithAdapterError("invalid_response", "Flagsmith response was not valid JSON");
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
};
|
|
1298
|
+
function parsePaginated(raw, parseItem) {
|
|
1299
|
+
const envelope = z2.object({
|
|
1300
|
+
count: z2.number().int(),
|
|
1301
|
+
next: z2.string().nullable().optional(),
|
|
1302
|
+
results: z2.array(z2.unknown())
|
|
1303
|
+
}).parse(raw);
|
|
1304
|
+
return {
|
|
1305
|
+
count: envelope.count,
|
|
1306
|
+
next: envelope.next ?? null,
|
|
1307
|
+
results: envelope.results.map(parseItem)
|
|
1308
|
+
};
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
// packages/core/src/flagsmith/dto.ts
|
|
1312
|
+
import { z as z3 } from "zod";
|
|
1313
|
+
var projectDtoSchema = z3.object({
|
|
1314
|
+
id: z3.number().int(),
|
|
1315
|
+
uuid: z3.string().nullish(),
|
|
1316
|
+
name: z3.string(),
|
|
1317
|
+
organisation: z3.number().int().nullish()
|
|
1318
|
+
});
|
|
1319
|
+
var environmentDtoSchema = z3.object({
|
|
1320
|
+
id: z3.number().int(),
|
|
1321
|
+
uuid: z3.string().nullish(),
|
|
1322
|
+
name: z3.string(),
|
|
1323
|
+
api_key: z3.string(),
|
|
1324
|
+
project: z3.number().int()
|
|
1325
|
+
});
|
|
1326
|
+
var featureDtoSchema = z3.object({
|
|
1327
|
+
id: z3.number().int(),
|
|
1328
|
+
name: z3.string(),
|
|
1329
|
+
type: z3.string().nullish(),
|
|
1330
|
+
default_enabled: z3.boolean().nullish(),
|
|
1331
|
+
initial_value: z3.unknown().nullish(),
|
|
1332
|
+
is_archived: z3.boolean().nullish()
|
|
1333
|
+
});
|
|
1334
|
+
var featureStateDtoSchema = z3.object({
|
|
1335
|
+
id: z3.number().int().nullish(),
|
|
1336
|
+
feature: z3.number().int(),
|
|
1337
|
+
enabled: z3.boolean(),
|
|
1338
|
+
feature_state_value: z3.unknown().nullish(),
|
|
1339
|
+
identity: z3.unknown().nullish(),
|
|
1340
|
+
feature_segment: z3.unknown().nullish(),
|
|
1341
|
+
environment: z3.union([z3.number().int(), z3.string(), z3.null()]).nullish()
|
|
1342
|
+
});
|
|
1343
|
+
|
|
1344
|
+
// packages/core/src/flagsmith/normalize.ts
|
|
1345
|
+
function normalizeFeatureType(type) {
|
|
1346
|
+
return type === "STANDARD" || type === "MULTIVARIATE" ? type : "unknown";
|
|
1347
|
+
}
|
|
1348
|
+
function toEnvironmentState(state, environmentId) {
|
|
1349
|
+
if (!state) return null;
|
|
1350
|
+
return {
|
|
1351
|
+
environmentId: state.environment === environmentId ? environmentId : null,
|
|
1352
|
+
enabled: state.enabled,
|
|
1353
|
+
value: state.feature_state_value,
|
|
1354
|
+
valueAvailable: state.feature_state_value !== void 0
|
|
1355
|
+
};
|
|
1356
|
+
}
|
|
1357
|
+
function buildFlagSnapshot(input) {
|
|
1358
|
+
const environmentDefaults = /* @__PURE__ */ new Map();
|
|
1359
|
+
for (const state of input.states) {
|
|
1360
|
+
if (state.identity != null || state.feature_segment != null) continue;
|
|
1361
|
+
if (state.environment != null && String(state.environment) !== String(input.environment.id)) {
|
|
1362
|
+
continue;
|
|
1363
|
+
}
|
|
1364
|
+
if (!environmentDefaults.has(state.feature)) environmentDefaults.set(state.feature, state);
|
|
1365
|
+
}
|
|
1366
|
+
const features = {};
|
|
1367
|
+
for (const feature of input.features) {
|
|
1368
|
+
features[feature.name] = {
|
|
1369
|
+
id: feature.id,
|
|
1370
|
+
name: feature.name,
|
|
1371
|
+
type: normalizeFeatureType(feature.type),
|
|
1372
|
+
archived: feature.is_archived === true,
|
|
1373
|
+
defaultEnabled: feature.default_enabled ?? null,
|
|
1374
|
+
environments: {
|
|
1375
|
+
[input.environment.api_key]: toEnvironmentState(
|
|
1376
|
+
environmentDefaults.get(feature.id),
|
|
1377
|
+
input.environment.id
|
|
1378
|
+
)
|
|
1379
|
+
}
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
return {
|
|
1383
|
+
project: {
|
|
1384
|
+
id: input.project.id,
|
|
1385
|
+
name: input.project.name,
|
|
1386
|
+
uuid: input.project.uuid ?? null
|
|
1387
|
+
},
|
|
1388
|
+
environment: {
|
|
1389
|
+
id: input.environment.id,
|
|
1390
|
+
key: input.environment.api_key,
|
|
1391
|
+
name: input.environment.name
|
|
1392
|
+
},
|
|
1393
|
+
fetchedAt: (input.fetchedAt ?? /* @__PURE__ */ new Date()).toISOString(),
|
|
1394
|
+
features
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
// packages/core/src/flagsmith/FlagsmithAdapter.ts
|
|
1399
|
+
function matchesProject(project, identifier) {
|
|
1400
|
+
if (typeof identifier === "number") return project.id === identifier;
|
|
1401
|
+
if (/^\d+$/.test(identifier)) return project.id === Number(identifier);
|
|
1402
|
+
return project.name === identifier;
|
|
1403
|
+
}
|
|
1404
|
+
var FlagsmithAdapter = class {
|
|
1405
|
+
config;
|
|
1406
|
+
client;
|
|
1407
|
+
constructor(options) {
|
|
1408
|
+
const { token, fetchImpl, ...configInput } = options;
|
|
1409
|
+
this.config = flagsmithConfigSchema.parse(configInput);
|
|
1410
|
+
if (token.trim() === "") {
|
|
1411
|
+
throw new FlagsmithAdapterError(
|
|
1412
|
+
"configuration",
|
|
1413
|
+
"Flagsmith Organisation API token must not be empty"
|
|
1414
|
+
);
|
|
1415
|
+
}
|
|
1416
|
+
this.client = new FlagsmithHttpClient({
|
|
1417
|
+
baseUrl: this.config.baseUrl,
|
|
1418
|
+
token,
|
|
1419
|
+
timeoutMs: this.config.timeoutMs,
|
|
1420
|
+
maxRetries: this.config.maxRetries,
|
|
1421
|
+
retryDelayMs: this.config.retryDelayMs,
|
|
1422
|
+
fetchImpl
|
|
1423
|
+
});
|
|
1424
|
+
}
|
|
1425
|
+
async fetchSnapshot() {
|
|
1426
|
+
const projects = await this.client.getJson(
|
|
1427
|
+
"/projects/",
|
|
1428
|
+
(raw) => z4.array(projectDtoSchema).parse(raw)
|
|
1429
|
+
);
|
|
1430
|
+
const project = projects.find((candidate) => matchesProject(candidate, this.config.project));
|
|
1431
|
+
if (!project) {
|
|
1432
|
+
throw new FlagsmithAdapterError("not_found", "Flagsmith project was not found");
|
|
1433
|
+
}
|
|
1434
|
+
const environments = await this.client.getAllPages(
|
|
1435
|
+
"/environments/",
|
|
1436
|
+
{ project: project.id },
|
|
1437
|
+
(raw) => environmentDtoSchema.parse(raw)
|
|
1438
|
+
);
|
|
1439
|
+
const environment = environments.find(
|
|
1440
|
+
(candidate) => candidate.project === project.id && (candidate.name === this.config.environment || candidate.api_key === this.config.environment)
|
|
1441
|
+
);
|
|
1442
|
+
if (!environment) {
|
|
1443
|
+
throw new FlagsmithAdapterError("not_found", "Flagsmith environment was not found");
|
|
1444
|
+
}
|
|
1445
|
+
const features = await this.client.getAllPages(
|
|
1446
|
+
`/projects/${project.id}/features/`,
|
|
1447
|
+
{ page_size: 100 },
|
|
1448
|
+
(raw) => featureDtoSchema.parse(raw)
|
|
1449
|
+
);
|
|
1450
|
+
const states = await this.client.getAllPages(
|
|
1451
|
+
`/environments/${encodeURIComponent(environment.api_key)}/featurestates/`,
|
|
1452
|
+
{},
|
|
1453
|
+
(raw) => featureStateDtoSchema.parse(raw)
|
|
1454
|
+
);
|
|
1455
|
+
return buildFlagSnapshot({ project, environment, features, states });
|
|
1456
|
+
}
|
|
1457
|
+
};
|
|
1458
|
+
|
|
1459
|
+
// packages/core/src/config/loadConfig.ts
|
|
1460
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
1461
|
+
import { parse as parseYaml } from "yaml";
|
|
1462
|
+
var SECRET_KEY_PATTERN = /(?:token|secret|password|api[_-]?key|credential)/i;
|
|
1463
|
+
var FlagdoctorConfigError = class extends Error {
|
|
1464
|
+
constructor(message) {
|
|
1465
|
+
super(message);
|
|
1466
|
+
this.name = "FlagdoctorConfigError";
|
|
1467
|
+
}
|
|
1468
|
+
};
|
|
1469
|
+
function parseFlagdoctorConfig(text) {
|
|
1470
|
+
let raw;
|
|
1471
|
+
try {
|
|
1472
|
+
raw = parseYaml(text);
|
|
1473
|
+
} catch {
|
|
1474
|
+
throw new FlagdoctorConfigError("flagdoctor.yaml is not valid YAML");
|
|
1475
|
+
}
|
|
1476
|
+
if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
|
|
1477
|
+
for (const key of Object.keys(raw)) {
|
|
1478
|
+
if (SECRET_KEY_PATTERN.test(key)) {
|
|
1479
|
+
throw new FlagdoctorConfigError(`flagdoctor.yaml must not contain secret field '${key}'`);
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
const result = flagdoctorConfigSchema.safeParse(raw ?? {});
|
|
1484
|
+
if (!result.success) {
|
|
1485
|
+
const fields = result.error.issues.map((issue) => issue.path.join(".")).join(", ");
|
|
1486
|
+
throw new FlagdoctorConfigError(`flagdoctor.yaml contains invalid configuration: ${fields}`);
|
|
1487
|
+
}
|
|
1488
|
+
return result.data;
|
|
1489
|
+
}
|
|
1490
|
+
async function loadFlagdoctorConfig(filePath = "flagdoctor.yaml") {
|
|
1491
|
+
let text;
|
|
1492
|
+
try {
|
|
1493
|
+
text = await readFile2(filePath, "utf8");
|
|
1494
|
+
} catch {
|
|
1495
|
+
throw new FlagdoctorConfigError(`Unable to read configuration file: ${filePath}`);
|
|
1496
|
+
}
|
|
1497
|
+
return parseFlagdoctorConfig(text);
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
// packages/core/src/config/env.ts
|
|
1501
|
+
import { readFile as readFile3, writeFile } from "node:fs/promises";
|
|
1502
|
+
var ENV_KEY_PATTERN = /^[A-Z][A-Z0-9_]*$/;
|
|
1503
|
+
var ENV_LINE_PATTERN = /^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=\s*(.*?)\s*$/;
|
|
1504
|
+
function unquote(value) {
|
|
1505
|
+
if (value.length >= 2 && (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'"))) {
|
|
1506
|
+
return value.slice(1, -1);
|
|
1507
|
+
}
|
|
1508
|
+
const commentIndex = value.search(/\s+#/);
|
|
1509
|
+
return commentIndex === -1 ? value : value.slice(0, commentIndex);
|
|
1510
|
+
}
|
|
1511
|
+
async function loadEnvFile(filePath, env = process.env) {
|
|
1512
|
+
let text;
|
|
1513
|
+
try {
|
|
1514
|
+
text = await readFile3(filePath, "utf8");
|
|
1515
|
+
} catch {
|
|
1516
|
+
return;
|
|
1517
|
+
}
|
|
1518
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1519
|
+
const match = ENV_LINE_PATTERN.exec(line);
|
|
1520
|
+
if (!match) continue;
|
|
1521
|
+
const key = match[1];
|
|
1522
|
+
const rawValue = match[2];
|
|
1523
|
+
if (key === void 0 || rawValue === void 0 || env[key]) continue;
|
|
1524
|
+
env[key] = unquote(rawValue);
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
function serializeEnvValue(value) {
|
|
1528
|
+
return /[\s#"']/.test(value) ? JSON.stringify(value) : value;
|
|
1529
|
+
}
|
|
1530
|
+
async function upsertEnvVar(filePath, key, value) {
|
|
1531
|
+
if (!ENV_KEY_PATTERN.test(key)) {
|
|
1532
|
+
throw new Error(`Invalid environment variable name: ${key}`);
|
|
1533
|
+
}
|
|
1534
|
+
if (value.trim() === "") {
|
|
1535
|
+
throw new Error(`Environment variable ${key} must not be empty`);
|
|
1536
|
+
}
|
|
1537
|
+
let text = "";
|
|
1538
|
+
try {
|
|
1539
|
+
text = await readFile3(filePath, "utf8");
|
|
1540
|
+
} catch (error) {
|
|
1541
|
+
if (error.code !== "ENOENT") throw error;
|
|
1542
|
+
}
|
|
1543
|
+
const lines = text.split(/\r?\n/);
|
|
1544
|
+
const target = new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`);
|
|
1545
|
+
const index = lines.findIndex((line) => target.test(line));
|
|
1546
|
+
const serialized = `${key}=${serializeEnvValue(value)}`;
|
|
1547
|
+
if (index >= 0) {
|
|
1548
|
+
lines[index] = serialized;
|
|
1549
|
+
} else {
|
|
1550
|
+
if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
|
|
1551
|
+
lines.push(serialized, "");
|
|
1552
|
+
}
|
|
1553
|
+
await writeFile(filePath, lines.join("\n"), "utf8");
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
// packages/core/src/config/formatConfig.ts
|
|
1557
|
+
import { stringify } from "yaml";
|
|
1558
|
+
function formatFlagdoctorConfig(config) {
|
|
1559
|
+
const parsed = flagdoctorConfigSchema.parse(config);
|
|
1560
|
+
return stringify(parsed, { lineWidth: 0 });
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
// packages/core/src/flagsmith/discovery.ts
|
|
1564
|
+
import { z as z5 } from "zod";
|
|
1565
|
+
var FlagsmithDiscovery = class {
|
|
1566
|
+
client;
|
|
1567
|
+
constructor(options) {
|
|
1568
|
+
if (options.token.trim() === "") {
|
|
1569
|
+
throw new FlagsmithAdapterError("configuration", "Flagsmith token must not be empty");
|
|
1570
|
+
}
|
|
1571
|
+
this.client = new FlagsmithHttpClient({
|
|
1572
|
+
baseUrl: options.baseUrl,
|
|
1573
|
+
token: options.token,
|
|
1574
|
+
timeoutMs: options.timeoutMs ?? 1e4,
|
|
1575
|
+
maxRetries: options.maxRetries ?? 2,
|
|
1576
|
+
retryDelayMs: options.retryDelayMs ?? 250,
|
|
1577
|
+
fetchImpl: options.fetchImpl
|
|
1578
|
+
});
|
|
1579
|
+
}
|
|
1580
|
+
async listProjects() {
|
|
1581
|
+
const projects = await this.client.getJson(
|
|
1582
|
+
"/projects/",
|
|
1583
|
+
(raw) => z5.array(projectDtoSchema).parse(raw)
|
|
1584
|
+
);
|
|
1585
|
+
return projects.map((project) => ({
|
|
1586
|
+
id: project.id,
|
|
1587
|
+
name: project.name,
|
|
1588
|
+
uuid: project.uuid ?? null
|
|
1589
|
+
}));
|
|
1590
|
+
}
|
|
1591
|
+
async listEnvironments(projectId) {
|
|
1592
|
+
const environments = await this.client.getAllPages(
|
|
1593
|
+
"/environments/",
|
|
1594
|
+
{ project: projectId },
|
|
1595
|
+
(raw) => environmentDtoSchema.parse(raw)
|
|
1596
|
+
);
|
|
1597
|
+
return environments.filter((environment) => environment.project === projectId).map((environment) => ({
|
|
1598
|
+
id: environment.id,
|
|
1599
|
+
name: environment.name,
|
|
1600
|
+
apiKey: environment.api_key,
|
|
1601
|
+
project: environment.project
|
|
1602
|
+
}));
|
|
1603
|
+
}
|
|
1604
|
+
};
|
|
1605
|
+
|
|
1606
|
+
// packages/core/src/rules/evaluate.ts
|
|
1607
|
+
import { createHash } from "node:crypto";
|
|
1608
|
+
function findingId(ruleId, reference) {
|
|
1609
|
+
const material = [
|
|
1610
|
+
ruleId,
|
|
1611
|
+
reference.flagName ?? "",
|
|
1612
|
+
reference.filePath,
|
|
1613
|
+
reference.line,
|
|
1614
|
+
reference.column,
|
|
1615
|
+
reference.method
|
|
1616
|
+
].join("|");
|
|
1617
|
+
return `fd-${createHash("sha256").update(material).digest("hex").slice(0, 12)}`;
|
|
1618
|
+
}
|
|
1619
|
+
function toFinding(reference, ruleId, severity, confidence, message, suggestion, origin, environment, repository) {
|
|
1620
|
+
return {
|
|
1621
|
+
id: findingId(ruleId, reference),
|
|
1622
|
+
ruleId,
|
|
1623
|
+
severity,
|
|
1624
|
+
confidence,
|
|
1625
|
+
flagName: reference.flagName,
|
|
1626
|
+
environment,
|
|
1627
|
+
repository: repository ?? reference.repository,
|
|
1628
|
+
filePath: reference.filePath,
|
|
1629
|
+
line: reference.line,
|
|
1630
|
+
column: reference.column,
|
|
1631
|
+
message,
|
|
1632
|
+
suggestion,
|
|
1633
|
+
origin
|
|
1634
|
+
};
|
|
1635
|
+
}
|
|
1636
|
+
function editDistance(left, right) {
|
|
1637
|
+
const rows = left.length + 1;
|
|
1638
|
+
const columns = right.length + 1;
|
|
1639
|
+
const previous = Array.from({ length: columns }, (_, index) => index);
|
|
1640
|
+
const current = new Array(columns).fill(0);
|
|
1641
|
+
for (let row = 1; row < rows; row += 1) {
|
|
1642
|
+
current[0] = row;
|
|
1643
|
+
for (let column = 1; column < columns; column += 1) {
|
|
1644
|
+
const cost = left[row - 1] === right[column - 1] ? 0 : 1;
|
|
1645
|
+
current[column] = Math.min(
|
|
1646
|
+
(current[column - 1] ?? 0) + 1,
|
|
1647
|
+
(previous[column] ?? 0) + 1,
|
|
1648
|
+
(previous[column - 1] ?? 0) + cost
|
|
1649
|
+
);
|
|
1650
|
+
}
|
|
1651
|
+
for (let column = 0; column < columns; column += 1) previous[column] = current[column] ?? 0;
|
|
1652
|
+
}
|
|
1653
|
+
return previous[columns - 1] ?? 0;
|
|
1654
|
+
}
|
|
1655
|
+
function closeName(flagName, snapshot) {
|
|
1656
|
+
const names = Object.keys(snapshot.features).sort();
|
|
1657
|
+
let best = null;
|
|
1658
|
+
let bestDistance = Number.POSITIVE_INFINITY;
|
|
1659
|
+
for (const name of names) {
|
|
1660
|
+
const distance = editDistance(flagName.toLowerCase(), name.toLowerCase());
|
|
1661
|
+
if (distance < bestDistance) {
|
|
1662
|
+
best = name;
|
|
1663
|
+
bestDistance = distance;
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
const threshold = Math.max(1, Math.floor(flagName.length / 3));
|
|
1667
|
+
return best !== null && bestDistance <= threshold ? best : null;
|
|
1668
|
+
}
|
|
1669
|
+
var [JS_SDK, JAVA_SDK] = RESERVED_SDK_IDENTIFIERS;
|
|
1670
|
+
var VALUE_READING_PAIRS = /* @__PURE__ */ new Set([`${JS_SDK}|getValue`, `${JAVA_SDK}|getFeatureValue`]);
|
|
1671
|
+
function readsRemoteValue(reference) {
|
|
1672
|
+
return VALUE_READING_PAIRS.has(`${reference.sdk}|${reference.method}`);
|
|
1673
|
+
}
|
|
1674
|
+
function demonstrablyIncompatible(expected, value) {
|
|
1675
|
+
const valueType = typeof value;
|
|
1676
|
+
switch (expected) {
|
|
1677
|
+
case "boolean":
|
|
1678
|
+
return valueType === "number" || valueType === "object";
|
|
1679
|
+
case "number":
|
|
1680
|
+
return valueType === "boolean" || valueType === "object";
|
|
1681
|
+
case "string":
|
|
1682
|
+
return valueType === "boolean" || valueType === "number";
|
|
1683
|
+
case "json":
|
|
1684
|
+
return valueType === "boolean" || valueType === "number";
|
|
1685
|
+
default:
|
|
1686
|
+
return false;
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
function evaluateFindings(options) {
|
|
1690
|
+
const findings = [];
|
|
1691
|
+
const environmentKey = options.snapshot.environment.key;
|
|
1692
|
+
for (const reference of options.references) {
|
|
1693
|
+
if (reference.resolution === "dynamic" || reference.flagName === null) {
|
|
1694
|
+
findings.push(
|
|
1695
|
+
toFinding(
|
|
1696
|
+
reference,
|
|
1697
|
+
"FD006",
|
|
1698
|
+
"info",
|
|
1699
|
+
"low",
|
|
1700
|
+
"Flag name could not be resolved statically; no name was guessed.",
|
|
1701
|
+
"Use a string literal or a safe same-file constant as the flag name.",
|
|
1702
|
+
"ast",
|
|
1703
|
+
options.environment,
|
|
1704
|
+
options.repository ?? null
|
|
1705
|
+
)
|
|
1706
|
+
);
|
|
1707
|
+
continue;
|
|
1708
|
+
}
|
|
1709
|
+
const flagName = reference.flagName;
|
|
1710
|
+
const feature = options.snapshot.features[flagName];
|
|
1711
|
+
if (!feature) {
|
|
1712
|
+
const suggestionName = closeName(flagName, options.snapshot);
|
|
1713
|
+
findings.push(
|
|
1714
|
+
toFinding(
|
|
1715
|
+
reference,
|
|
1716
|
+
"FD001",
|
|
1717
|
+
"error",
|
|
1718
|
+
"high",
|
|
1719
|
+
`Flag '${flagName}' is referenced in code but is absent from the selected snapshot.`,
|
|
1720
|
+
suggestionName ? `Possible close name: '${suggestionName}'. Confirm before changing code.` : null,
|
|
1721
|
+
"snapshot",
|
|
1722
|
+
options.environment,
|
|
1723
|
+
options.repository ?? null
|
|
1724
|
+
)
|
|
1725
|
+
);
|
|
1726
|
+
continue;
|
|
1727
|
+
}
|
|
1728
|
+
if (feature.archived) {
|
|
1729
|
+
findings.push(
|
|
1730
|
+
toFinding(
|
|
1731
|
+
reference,
|
|
1732
|
+
"FD002",
|
|
1733
|
+
"error",
|
|
1734
|
+
"high",
|
|
1735
|
+
`Flag '${flagName}' is archived but is still referenced in code.`,
|
|
1736
|
+
"Choose an active flag or retire the code reference.",
|
|
1737
|
+
"snapshot",
|
|
1738
|
+
options.environment,
|
|
1739
|
+
options.repository ?? null
|
|
1740
|
+
)
|
|
1741
|
+
);
|
|
1742
|
+
}
|
|
1743
|
+
if (reference.expectedType !== "unknown" && readsRemoteValue(reference)) {
|
|
1744
|
+
const state = feature.environments[environmentKey] ?? null;
|
|
1745
|
+
if (state && state.valueAvailable && state.value !== null && state.value !== void 0 && demonstrablyIncompatible(reference.expectedType, state.value)) {
|
|
1746
|
+
const actual = typeof state.value;
|
|
1747
|
+
findings.push(
|
|
1748
|
+
toFinding(
|
|
1749
|
+
reference,
|
|
1750
|
+
"FD004",
|
|
1751
|
+
"warning",
|
|
1752
|
+
"high",
|
|
1753
|
+
`Code expects ${reference.expectedType}, but ${reference.method} would read a ${actual} value.`,
|
|
1754
|
+
"Confirm the SDK conversion semantics or update the configured value.",
|
|
1755
|
+
"snapshot",
|
|
1756
|
+
options.environment,
|
|
1757
|
+
options.repository ?? null
|
|
1758
|
+
)
|
|
1759
|
+
);
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
return findings.sort(
|
|
1764
|
+
(a, b) => (a.filePath ?? "").localeCompare(b.filePath ?? "") || (a.line ?? 0) - (b.line ?? 0) || (a.column ?? 0) - (b.column ?? 0) || a.ruleId.localeCompare(b.ruleId)
|
|
1765
|
+
);
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
// packages/core/src/callgraph/buildCallGraph.ts
|
|
1769
|
+
import { posix } from "node:path";
|
|
1770
|
+
|
|
1771
|
+
// packages/core/src/callgraph/classifyLayer.ts
|
|
1772
|
+
var CONTROLLER_ANNOTATIONS = /* @__PURE__ */ new Set(["Controller", "RestController"]);
|
|
1773
|
+
var SERVICE_ANNOTATIONS = /* @__PURE__ */ new Set(["Service"]);
|
|
1774
|
+
var REPOSITORY_ANNOTATIONS = /* @__PURE__ */ new Set(["Repository"]);
|
|
1775
|
+
var MODEL_ANNOTATIONS = /* @__PURE__ */ new Set(["Entity", "Document", "Table"]);
|
|
1776
|
+
var COMPONENT_ANNOTATIONS = /* @__PURE__ */ new Set(["Component", "Configuration", "Injectable", "Bean"]);
|
|
1777
|
+
var NAME_PATTERNS = [
|
|
1778
|
+
[/Controller$/, "controller"],
|
|
1779
|
+
[/(ServiceImpl|Service)$/, "service"],
|
|
1780
|
+
[/(Repository|Dao)$/, "repository"],
|
|
1781
|
+
[/(Entity|Model)$/, "model"]
|
|
1782
|
+
];
|
|
1783
|
+
var PATH_PATTERNS = [
|
|
1784
|
+
[/\bcontrollers?\b/, "controller"],
|
|
1785
|
+
[/\bservices?\b/, "service"],
|
|
1786
|
+
[/\b(repositories|repository|dao)\b/, "repository"],
|
|
1787
|
+
[/\b(models?|entities|entity)\b/, "model"]
|
|
1788
|
+
];
|
|
1789
|
+
function classifyLayer(className, annotations, filePath) {
|
|
1790
|
+
if (annotations.some((name) => CONTROLLER_ANNOTATIONS.has(name))) return "controller";
|
|
1791
|
+
if (annotations.some((name) => SERVICE_ANNOTATIONS.has(name))) return "service";
|
|
1792
|
+
if (annotations.some((name) => REPOSITORY_ANNOTATIONS.has(name))) return "repository";
|
|
1793
|
+
if (annotations.some((name) => MODEL_ANNOTATIONS.has(name))) return "model";
|
|
1794
|
+
if (annotations.some((name) => COMPONENT_ANNOTATIONS.has(name))) return "component";
|
|
1795
|
+
if (className) {
|
|
1796
|
+
for (const [pattern, layer] of NAME_PATTERNS) {
|
|
1797
|
+
if (pattern.test(className)) return layer;
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
const lowerPath = filePath.toLowerCase();
|
|
1801
|
+
for (const [pattern, layer] of PATH_PATTERNS) {
|
|
1802
|
+
if (pattern.test(lowerPath)) return layer;
|
|
1803
|
+
}
|
|
1804
|
+
return "other";
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
// packages/core/src/callgraph/javaCallGraph.ts
|
|
1808
|
+
function annotationNames(node) {
|
|
1809
|
+
const modifiers = node.namedChildren.find((child) => child.type === "modifiers");
|
|
1810
|
+
if (!modifiers) return [];
|
|
1811
|
+
return modifiers.namedChildren.filter((child) => child.type === "marker_annotation" || child.type === "annotation").map((annotation) => annotation.childForFieldName("name")?.text).filter((name) => typeof name === "string");
|
|
1812
|
+
}
|
|
1813
|
+
function memberContainer(classNode) {
|
|
1814
|
+
const body = classNode.namedChildren.find(
|
|
1815
|
+
(child) => child.type === "class_body" || child.type === "interface_body" || child.type === "enum_body"
|
|
1816
|
+
);
|
|
1817
|
+
if (!body) return null;
|
|
1818
|
+
if (body.type === "enum_body") {
|
|
1819
|
+
return body.namedChildren.find((child) => child.type === "enum_body_declarations") ?? null;
|
|
1820
|
+
}
|
|
1821
|
+
return body;
|
|
1822
|
+
}
|
|
1823
|
+
function fieldDeclarations(classBody) {
|
|
1824
|
+
const fields = /* @__PURE__ */ new Map();
|
|
1825
|
+
for (const member of classBody.namedChildren) {
|
|
1826
|
+
if (member.type !== "field_declaration") continue;
|
|
1827
|
+
const typeText = member.childForFieldName("type")?.text.trim() ?? "";
|
|
1828
|
+
for (const declarator of member.namedChildren) {
|
|
1829
|
+
if (declarator.type !== "variable_declarator") continue;
|
|
1830
|
+
const name = declarator.childForFieldName("name");
|
|
1831
|
+
if (name?.type === "identifier") fields.set(name.text, typeText);
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
return fields;
|
|
1835
|
+
}
|
|
1836
|
+
function localDeclarations(methodNode) {
|
|
1837
|
+
const locals = /* @__PURE__ */ new Map();
|
|
1838
|
+
walk(methodNode, (node) => {
|
|
1839
|
+
if (node.type === "formal_parameter") {
|
|
1840
|
+
const name = node.childForFieldName("name");
|
|
1841
|
+
const typeText = node.childForFieldName("type")?.text.trim() ?? "";
|
|
1842
|
+
if (name?.type === "identifier") locals.set(name.text, typeText);
|
|
1843
|
+
}
|
|
1844
|
+
if (node.type === "variable_declarator" && node.parent?.type === "local_variable_declaration") {
|
|
1845
|
+
const name = node.childForFieldName("name");
|
|
1846
|
+
const typeText = node.parent.childForFieldName("type")?.text.trim() ?? "";
|
|
1847
|
+
if (name?.type === "identifier") locals.set(name.text, typeText);
|
|
1848
|
+
}
|
|
1849
|
+
});
|
|
1850
|
+
return locals;
|
|
1851
|
+
}
|
|
1852
|
+
function directInvocations(bodyLike) {
|
|
1853
|
+
const result = [];
|
|
1854
|
+
const visit = (node) => {
|
|
1855
|
+
if (node.type === "method_invocation") result.push(node);
|
|
1856
|
+
for (const child of node.namedChildren) {
|
|
1857
|
+
if (JAVA_FUNCTION_TYPES.has(child.type) || JAVA_CLASS_TYPES.has(child.type)) continue;
|
|
1858
|
+
visit(child);
|
|
1859
|
+
}
|
|
1860
|
+
};
|
|
1861
|
+
visit(bodyLike);
|
|
1862
|
+
return result;
|
|
1863
|
+
}
|
|
1864
|
+
function simpleTypeName(typeText) {
|
|
1865
|
+
if (!typeText) return null;
|
|
1866
|
+
const withoutGenerics = typeText.replace(/<.*>$/, "").trim();
|
|
1867
|
+
const segments = withoutGenerics.split(".");
|
|
1868
|
+
return segments[segments.length - 1] || null;
|
|
1869
|
+
}
|
|
1870
|
+
function extractJavaSymbols(root, filePath) {
|
|
1871
|
+
const classes = [];
|
|
1872
|
+
const callSites = [];
|
|
1873
|
+
walk(root, (classNode) => {
|
|
1874
|
+
if (!JAVA_CLASS_TYPES.has(classNode.type)) return;
|
|
1875
|
+
const className = classNode.childForFieldName("name")?.text;
|
|
1876
|
+
if (!className) return;
|
|
1877
|
+
const classBody = memberContainer(classNode);
|
|
1878
|
+
const fields = classBody ? fieldDeclarations(classBody) : /* @__PURE__ */ new Map();
|
|
1879
|
+
const methods = classBody ? classBody.namedChildren.filter((member) => JAVA_FUNCTION_TYPES.has(member.type)).map((member) => member.childForFieldName("name")?.text ?? "(constructor)") : [];
|
|
1880
|
+
classes.push({ className, annotations: annotationNames(classNode), fields, methods });
|
|
1881
|
+
if (!classBody) return;
|
|
1882
|
+
for (const member of classBody.namedChildren) {
|
|
1883
|
+
if (!JAVA_FUNCTION_TYPES.has(member.type)) continue;
|
|
1884
|
+
const functionName = member.childForFieldName("name")?.text ?? "(constructor)";
|
|
1885
|
+
const caller = { filePath, className, functionName };
|
|
1886
|
+
const locals = localDeclarations(member);
|
|
1887
|
+
for (const invocation of directInvocations(member)) {
|
|
1888
|
+
const calleeName = invocation.childForFieldName("name")?.text;
|
|
1889
|
+
if (!calleeName) continue;
|
|
1890
|
+
const receiver = invocation.childForFieldName("object") ?? null;
|
|
1891
|
+
if (receiver === null || receiver.type === "this") {
|
|
1892
|
+
callSites.push({ caller, calleeName, receiverType: null, sameClass: true });
|
|
1893
|
+
continue;
|
|
1894
|
+
}
|
|
1895
|
+
if (receiver.type === "identifier") {
|
|
1896
|
+
const declaredType = locals.get(receiver.text) ?? fields.get(receiver.text) ?? null;
|
|
1897
|
+
callSites.push({
|
|
1898
|
+
caller,
|
|
1899
|
+
calleeName,
|
|
1900
|
+
receiverType: simpleTypeName(declaredType ?? ""),
|
|
1901
|
+
sameClass: false
|
|
1902
|
+
});
|
|
1903
|
+
continue;
|
|
1904
|
+
}
|
|
1905
|
+
callSites.push({ caller, calleeName, receiverType: null, sameClass: false });
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
});
|
|
1909
|
+
return { classes, callSites };
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
// packages/core/src/callgraph/jsTsCallGraph.ts
|
|
1913
|
+
function typeAnnotationName(node) {
|
|
1914
|
+
if (!node) return null;
|
|
1915
|
+
const annotation = node.type === "type_annotation" ? node : node.childForFieldName("type");
|
|
1916
|
+
const inner = annotation?.namedChildren[0];
|
|
1917
|
+
return inner?.text.replace(/<.*>$/, "").trim() ?? null;
|
|
1918
|
+
}
|
|
1919
|
+
function decoratorsOf(classNode) {
|
|
1920
|
+
const host = classNode.parent;
|
|
1921
|
+
if (!host) return [];
|
|
1922
|
+
const siblings = host.namedChildren;
|
|
1923
|
+
const index = siblings.findIndex((sibling) => sibling.id === classNode.id);
|
|
1924
|
+
if (index === -1) return [];
|
|
1925
|
+
const decorators = [];
|
|
1926
|
+
for (let i = index - 1; i >= 0; i -= 1) {
|
|
1927
|
+
const sibling = siblings[i];
|
|
1928
|
+
if (sibling.type !== "decorator") break;
|
|
1929
|
+
const inner = sibling.namedChildren[0];
|
|
1930
|
+
const name = inner?.type === "call_expression" ? inner.childForFieldName("function")?.text : inner?.text;
|
|
1931
|
+
if (name) decorators.unshift(name);
|
|
1932
|
+
}
|
|
1933
|
+
return decorators;
|
|
1934
|
+
}
|
|
1935
|
+
function classFields(classNode) {
|
|
1936
|
+
const fields = /* @__PURE__ */ new Map();
|
|
1937
|
+
const body = classNode.namedChildren.find((child) => child.type === "class_body");
|
|
1938
|
+
if (!body) return fields;
|
|
1939
|
+
for (const member of body.namedChildren) {
|
|
1940
|
+
if (member.type === "public_field_definition" || member.type === "field_definition") {
|
|
1941
|
+
const name = member.childForFieldName("name")?.text;
|
|
1942
|
+
const type = typeAnnotationName(member);
|
|
1943
|
+
if (name && type) fields.set(name, type);
|
|
1944
|
+
}
|
|
1945
|
+
if (member.type === "method_definition" && member.childForFieldName("name")?.text === "constructor") {
|
|
1946
|
+
const parameters = member.childForFieldName("parameters");
|
|
1947
|
+
for (const parameter of parameters?.namedChildren ?? []) {
|
|
1948
|
+
const isProperty = parameter.namedChildren.some(
|
|
1949
|
+
(child) => child.type === "accessibility_modifier"
|
|
1950
|
+
);
|
|
1951
|
+
if (!isProperty) continue;
|
|
1952
|
+
const name = parameter.childForFieldName("pattern")?.text;
|
|
1953
|
+
const type = typeAnnotationName(parameter);
|
|
1954
|
+
if (name && type) fields.set(name, type);
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
return fields;
|
|
1959
|
+
}
|
|
1960
|
+
function parameterTypes(functionNode) {
|
|
1961
|
+
const types = /* @__PURE__ */ new Map();
|
|
1962
|
+
const parameters = functionNode.childForFieldName("parameters");
|
|
1963
|
+
for (const parameter of parameters?.namedChildren ?? []) {
|
|
1964
|
+
if (parameter.type !== "required_parameter" && parameter.type !== "optional_parameter") continue;
|
|
1965
|
+
const name = parameter.childForFieldName("pattern")?.text;
|
|
1966
|
+
const type = typeAnnotationName(parameter);
|
|
1967
|
+
if (name && type) types.set(name, type);
|
|
1968
|
+
}
|
|
1969
|
+
return types;
|
|
1970
|
+
}
|
|
1971
|
+
function directCalls(functionNode) {
|
|
1972
|
+
const body = functionNode.childForFieldName("body") ?? functionNode;
|
|
1973
|
+
const result = [];
|
|
1974
|
+
const visit = (node) => {
|
|
1975
|
+
if (node.type === "call_expression") result.push(node);
|
|
1976
|
+
for (const child of node.namedChildren) {
|
|
1977
|
+
if (JS_FUNCTION_TYPES.has(child.type) || JS_CLASS_TYPES.has(child.type)) continue;
|
|
1978
|
+
visit(child);
|
|
1979
|
+
}
|
|
1980
|
+
};
|
|
1981
|
+
visit(body);
|
|
1982
|
+
return result;
|
|
1983
|
+
}
|
|
1984
|
+
function importBindings(root) {
|
|
1985
|
+
const bindings = [];
|
|
1986
|
+
walk(root, (node) => {
|
|
1987
|
+
if (node.type !== "import_statement") return;
|
|
1988
|
+
const source = literalString(node.childForFieldName("source") ?? null);
|
|
1989
|
+
const clause = node.namedChildren.find((child) => child.type === "import_clause");
|
|
1990
|
+
if (!source || !clause) return;
|
|
1991
|
+
for (const part of clause.namedChildren) {
|
|
1992
|
+
if (part.type === "identifier") {
|
|
1993
|
+
bindings.push({ localName: part.text, importedName: "default", source });
|
|
1994
|
+
}
|
|
1995
|
+
if (part.type === "named_imports") {
|
|
1996
|
+
for (const specifier of part.namedChildren) {
|
|
1997
|
+
if (specifier.type !== "import_specifier") continue;
|
|
1998
|
+
const name = specifier.childForFieldName("name")?.text ?? specifier.namedChildren[0]?.text;
|
|
1999
|
+
const alias = specifier.childForFieldName("alias")?.text;
|
|
2000
|
+
if (name) bindings.push({ localName: alias ?? name, importedName: name, source });
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
});
|
|
2005
|
+
return bindings;
|
|
2006
|
+
}
|
|
2007
|
+
function extractJsTsSymbols(root, filePath) {
|
|
2008
|
+
const classes = [];
|
|
2009
|
+
const classFieldsByName = /* @__PURE__ */ new Map();
|
|
2010
|
+
walk(root, (node) => {
|
|
2011
|
+
if (!JS_CLASS_TYPES.has(node.type)) return;
|
|
2012
|
+
const className = jsClassName(node);
|
|
2013
|
+
if (!className) return;
|
|
2014
|
+
const fields = classFields(node);
|
|
2015
|
+
classFieldsByName.set(className, fields);
|
|
2016
|
+
classes.push({ className, decorators: decoratorsOf(node), fields });
|
|
2017
|
+
});
|
|
2018
|
+
const topLevelFunctions = /* @__PURE__ */ new Set();
|
|
2019
|
+
const functions = [];
|
|
2020
|
+
const callSites = [];
|
|
2021
|
+
walk(root, (node) => {
|
|
2022
|
+
if (!JS_FUNCTION_TYPES.has(node.type)) return;
|
|
2023
|
+
const classNode = nearestAncestor(node, JS_CLASS_TYPES);
|
|
2024
|
+
const className = classNode ? jsClassName(classNode) : null;
|
|
2025
|
+
const functionName = jsFunctionName(node);
|
|
2026
|
+
if (!functionName) return;
|
|
2027
|
+
if (className === null) topLevelFunctions.add(functionName);
|
|
2028
|
+
const caller = { filePath, className, functionName };
|
|
2029
|
+
functions.push(caller);
|
|
2030
|
+
const fields = className ? classFieldsByName.get(className) ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map();
|
|
2031
|
+
const params = parameterTypes(node);
|
|
2032
|
+
for (const call of directCalls(node)) {
|
|
2033
|
+
const fn = call.childForFieldName("function");
|
|
2034
|
+
if (!fn) continue;
|
|
2035
|
+
if (fn.type === "identifier") {
|
|
2036
|
+
callSites.push({
|
|
2037
|
+
caller,
|
|
2038
|
+
calleeName: fn.text,
|
|
2039
|
+
receiverType: null,
|
|
2040
|
+
sameClass: false,
|
|
2041
|
+
bareIdentifier: true
|
|
2042
|
+
});
|
|
2043
|
+
continue;
|
|
2044
|
+
}
|
|
2045
|
+
if (fn.type !== "member_expression") continue;
|
|
2046
|
+
const calleeName = fn.childForFieldName("property")?.text;
|
|
2047
|
+
if (!calleeName) continue;
|
|
2048
|
+
const object = fn.childForFieldName("object");
|
|
2049
|
+
if (object?.type === "this") {
|
|
2050
|
+
callSites.push({ caller, calleeName, receiverType: null, sameClass: true, bareIdentifier: false });
|
|
2051
|
+
continue;
|
|
2052
|
+
}
|
|
2053
|
+
if (object?.type === "member_expression" && object.childForFieldName("object")?.type === "this") {
|
|
2054
|
+
const fieldName = object.childForFieldName("property")?.text;
|
|
2055
|
+
const receiverType = fieldName ? fields.get(fieldName) ?? null : null;
|
|
2056
|
+
callSites.push({ caller, calleeName, receiverType, sameClass: false, bareIdentifier: false });
|
|
2057
|
+
continue;
|
|
2058
|
+
}
|
|
2059
|
+
if (object?.type === "identifier") {
|
|
2060
|
+
const receiverType = params.get(object.text) ?? fields.get(object.text) ?? null;
|
|
2061
|
+
callSites.push({ caller, calleeName, receiverType, sameClass: false, bareIdentifier: false });
|
|
2062
|
+
continue;
|
|
2063
|
+
}
|
|
2064
|
+
callSites.push({ caller, calleeName, receiverType: null, sameClass: false, bareIdentifier: false });
|
|
2065
|
+
}
|
|
2066
|
+
});
|
|
2067
|
+
return {
|
|
2068
|
+
classes,
|
|
2069
|
+
functions,
|
|
2070
|
+
topLevelFunctions: Array.from(topLevelFunctions),
|
|
2071
|
+
imports: importBindings(root),
|
|
2072
|
+
callSites
|
|
2073
|
+
};
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
// packages/core/src/callgraph/types.ts
|
|
2077
|
+
function symbolKey(ref) {
|
|
2078
|
+
return `${ref.filePath}#${ref.className ?? ""}#${ref.functionName}`;
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
// packages/core/src/callgraph/buildCallGraph.ts
|
|
2082
|
+
var JS_EXTENSION_CANDIDATES = ["", ".ts", ".tsx", ".js", ".jsx"];
|
|
2083
|
+
var JS_INDEX_CANDIDATES = ["/index.ts", "/index.tsx", "/index.js", "/index.jsx"];
|
|
2084
|
+
function resolveJsImportPath(fromFilePath, specifier, known) {
|
|
2085
|
+
if (!specifier.startsWith("./") && !specifier.startsWith("../")) return null;
|
|
2086
|
+
const base = posix.normalize(posix.join(posix.dirname(fromFilePath), specifier));
|
|
2087
|
+
for (const suffix of JS_EXTENSION_CANDIDATES) {
|
|
2088
|
+
const candidate = `${base}${suffix}`;
|
|
2089
|
+
if (known.has(candidate)) return candidate;
|
|
2090
|
+
}
|
|
2091
|
+
for (const suffix of JS_INDEX_CANDIDATES) {
|
|
2092
|
+
const candidate = `${base}${suffix}`;
|
|
2093
|
+
if (known.has(candidate)) return candidate;
|
|
2094
|
+
}
|
|
2095
|
+
return null;
|
|
2096
|
+
}
|
|
2097
|
+
function addEdge(map, from, to) {
|
|
2098
|
+
const existing = map.get(from);
|
|
2099
|
+
if (existing) existing.add(to);
|
|
2100
|
+
else map.set(from, /* @__PURE__ */ new Set([to]));
|
|
2101
|
+
}
|
|
2102
|
+
async function buildCallGraph(options) {
|
|
2103
|
+
const maxFiles = options.maxFiles ?? 2e3;
|
|
2104
|
+
const maxFileBytes = options.maxFileBytes ?? 2e6;
|
|
2105
|
+
const files = await options.provider.listFiles();
|
|
2106
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
2107
|
+
const methodsByClassName = /* @__PURE__ */ new Map();
|
|
2108
|
+
const topLevelFunctionsByFile = /* @__PURE__ */ new Map();
|
|
2109
|
+
const importsByFile = /* @__PURE__ */ new Map();
|
|
2110
|
+
const rawCallSites = [];
|
|
2111
|
+
const registerNode = (ref, layer) => {
|
|
2112
|
+
const key = symbolKey(ref);
|
|
2113
|
+
if (!nodes.has(key)) nodes.set(key, { ...ref, layer });
|
|
2114
|
+
if (ref.className) {
|
|
2115
|
+
const list = methodsByClassName.get(ref.className) ?? [];
|
|
2116
|
+
list.push(ref);
|
|
2117
|
+
methodsByClassName.set(ref.className, list);
|
|
2118
|
+
}
|
|
2119
|
+
};
|
|
2120
|
+
let scanned = 0;
|
|
2121
|
+
for (const file of files) {
|
|
2122
|
+
if (options.signal?.aborted) break;
|
|
2123
|
+
if (scanned >= maxFiles || file.sizeBytes > maxFileBytes) continue;
|
|
2124
|
+
const language = languageForFile(file.relativePath);
|
|
2125
|
+
if (!language) continue;
|
|
2126
|
+
let content;
|
|
2127
|
+
try {
|
|
2128
|
+
content = await options.provider.readFile(file.relativePath);
|
|
2129
|
+
} catch {
|
|
2130
|
+
continue;
|
|
2131
|
+
}
|
|
2132
|
+
try {
|
|
2133
|
+
const tree = await parseSource(language, content);
|
|
2134
|
+
if (language === "java") {
|
|
2135
|
+
const symbols = extractJavaSymbols(tree.rootNode, file.relativePath);
|
|
2136
|
+
for (const classInfo of symbols.classes) {
|
|
2137
|
+
const layer = classifyLayer(classInfo.className, classInfo.annotations, file.relativePath);
|
|
2138
|
+
for (const methodName of classInfo.methods) {
|
|
2139
|
+
registerNode({ filePath: file.relativePath, className: classInfo.className, functionName: methodName }, layer);
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
for (const site of symbols.callSites) rawCallSites.push({ ...site, bareIdentifier: false });
|
|
2143
|
+
} else {
|
|
2144
|
+
const symbols = extractJsTsSymbols(tree.rootNode, file.relativePath);
|
|
2145
|
+
const layerByClass = new Map(
|
|
2146
|
+
symbols.classes.map((info) => [
|
|
2147
|
+
info.className,
|
|
2148
|
+
classifyLayer(info.className, info.decorators, file.relativePath)
|
|
2149
|
+
])
|
|
2150
|
+
);
|
|
2151
|
+
for (const ref of symbols.functions) {
|
|
2152
|
+
const layer = ref.className ? layerByClass.get(ref.className) ?? "other" : "other";
|
|
2153
|
+
registerNode(ref, layer);
|
|
2154
|
+
}
|
|
2155
|
+
topLevelFunctionsByFile.set(file.relativePath, new Set(symbols.topLevelFunctions));
|
|
2156
|
+
importsByFile.set(file.relativePath, symbols.imports);
|
|
2157
|
+
for (const site of symbols.callSites) rawCallSites.push(site);
|
|
2158
|
+
}
|
|
2159
|
+
scanned += 1;
|
|
2160
|
+
} catch {
|
|
2161
|
+
continue;
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
const knownFiles = new Set(files.map((file) => file.relativePath));
|
|
2165
|
+
const callersOf = /* @__PURE__ */ new Map();
|
|
2166
|
+
const calleesOf = /* @__PURE__ */ new Map();
|
|
2167
|
+
for (const site of rawCallSites) {
|
|
2168
|
+
const callerKey = symbolKey(site.caller);
|
|
2169
|
+
let calleeKey = null;
|
|
2170
|
+
if (site.sameClass) {
|
|
2171
|
+
const candidate = { ...site.caller, functionName: site.calleeName };
|
|
2172
|
+
if (nodes.has(symbolKey(candidate))) calleeKey = symbolKey(candidate);
|
|
2173
|
+
} else if (site.receiverType !== null) {
|
|
2174
|
+
const matches2 = (methodsByClassName.get(site.receiverType) ?? []).filter(
|
|
2175
|
+
(ref) => ref.functionName === site.calleeName
|
|
2176
|
+
);
|
|
2177
|
+
if (matches2.length === 1) calleeKey = symbolKey(matches2[0]);
|
|
2178
|
+
} else if (site.bareIdentifier) {
|
|
2179
|
+
const sameFile = topLevelFunctionsByFile.get(site.caller.filePath);
|
|
2180
|
+
if (sameFile?.has(site.calleeName)) {
|
|
2181
|
+
calleeKey = symbolKey({
|
|
2182
|
+
filePath: site.caller.filePath,
|
|
2183
|
+
className: null,
|
|
2184
|
+
functionName: site.calleeName
|
|
2185
|
+
});
|
|
2186
|
+
} else {
|
|
2187
|
+
const binding = (importsByFile.get(site.caller.filePath) ?? []).find(
|
|
2188
|
+
(candidate) => candidate.localName === site.calleeName && candidate.importedName !== "default"
|
|
2189
|
+
);
|
|
2190
|
+
const resolvedFile = binding ? resolveJsImportPath(site.caller.filePath, binding.source, knownFiles) : null;
|
|
2191
|
+
if (resolvedFile && binding) {
|
|
2192
|
+
const target = {
|
|
2193
|
+
filePath: resolvedFile,
|
|
2194
|
+
className: null,
|
|
2195
|
+
functionName: binding.importedName
|
|
2196
|
+
};
|
|
2197
|
+
if (nodes.has(symbolKey(target))) calleeKey = symbolKey(target);
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
if (calleeKey) {
|
|
2202
|
+
addEdge(calleesOf, callerKey, calleeKey);
|
|
2203
|
+
addEdge(callersOf, calleeKey, callerKey);
|
|
2204
|
+
}
|
|
2205
|
+
}
|
|
2206
|
+
return { nodes, callersOf, calleesOf };
|
|
2207
|
+
}
|
|
2208
|
+
function bfs(graph, startRef, adjacency, maxDepth, maxNodes) {
|
|
2209
|
+
const startKey = symbolKey(startRef);
|
|
2210
|
+
const visited = /* @__PURE__ */ new Set([startKey]);
|
|
2211
|
+
const result = [];
|
|
2212
|
+
let frontier = [startKey];
|
|
2213
|
+
let depth = 0;
|
|
2214
|
+
while (frontier.length > 0 && depth < maxDepth && result.length < maxNodes) {
|
|
2215
|
+
const next = [];
|
|
2216
|
+
for (const key of frontier) {
|
|
2217
|
+
for (const neighborKey of adjacency.get(key) ?? []) {
|
|
2218
|
+
if (visited.has(neighborKey)) continue;
|
|
2219
|
+
visited.add(neighborKey);
|
|
2220
|
+
const node = graph.nodes.get(neighborKey);
|
|
2221
|
+
if (node) {
|
|
2222
|
+
result.push({ ...node, depth: depth + 1, via: key });
|
|
2223
|
+
if (result.length >= maxNodes) break;
|
|
2224
|
+
}
|
|
2225
|
+
next.push(neighborKey);
|
|
2226
|
+
}
|
|
2227
|
+
if (result.length >= maxNodes) break;
|
|
2228
|
+
}
|
|
2229
|
+
frontier = next;
|
|
2230
|
+
depth += 1;
|
|
2231
|
+
}
|
|
2232
|
+
return result;
|
|
2233
|
+
}
|
|
2234
|
+
var DEFAULT_IMPACT_DEPTH = 3;
|
|
2235
|
+
var DEFAULT_IMPACT_MAX_NODES = 20;
|
|
2236
|
+
function findCallers(graph, ref, maxDepth = DEFAULT_IMPACT_DEPTH, maxNodes = DEFAULT_IMPACT_MAX_NODES) {
|
|
2237
|
+
return bfs(graph, ref, graph.callersOf, maxDepth, maxNodes);
|
|
2238
|
+
}
|
|
2239
|
+
function findCallees(graph, ref, maxDepth = DEFAULT_IMPACT_DEPTH, maxNodes = DEFAULT_IMPACT_MAX_NODES) {
|
|
2240
|
+
return bfs(graph, ref, graph.calleesOf, maxDepth, maxNodes);
|
|
2241
|
+
}
|
|
2242
|
+
|
|
2243
|
+
// packages/core/src/dependency/relatedCode.ts
|
|
2244
|
+
var STOP_WORDS = /* @__PURE__ */ new Set([
|
|
2245
|
+
"enabled",
|
|
2246
|
+
"enable",
|
|
2247
|
+
"disabled",
|
|
2248
|
+
"disable",
|
|
2249
|
+
"is",
|
|
2250
|
+
"flag",
|
|
2251
|
+
"flags",
|
|
2252
|
+
"feature",
|
|
2253
|
+
"features",
|
|
2254
|
+
"beta",
|
|
2255
|
+
"alpha",
|
|
2256
|
+
"new",
|
|
2257
|
+
"old",
|
|
2258
|
+
"legacy",
|
|
2259
|
+
"max",
|
|
2260
|
+
"min",
|
|
2261
|
+
"size",
|
|
2262
|
+
"text",
|
|
2263
|
+
"value",
|
|
2264
|
+
"config",
|
|
2265
|
+
"mode",
|
|
2266
|
+
"use",
|
|
2267
|
+
"get",
|
|
2268
|
+
"set",
|
|
2269
|
+
"has",
|
|
2270
|
+
"the",
|
|
2271
|
+
"and",
|
|
2272
|
+
"of",
|
|
2273
|
+
"for",
|
|
2274
|
+
"to",
|
|
2275
|
+
"on",
|
|
2276
|
+
"off",
|
|
2277
|
+
"show",
|
|
2278
|
+
"allow",
|
|
2279
|
+
"experiment",
|
|
2280
|
+
"test",
|
|
2281
|
+
"temp",
|
|
2282
|
+
"kill",
|
|
2283
|
+
"switch",
|
|
2284
|
+
"toggle",
|
|
2285
|
+
"rollout"
|
|
2286
|
+
]);
|
|
2287
|
+
var LAYER_RANK = {
|
|
2288
|
+
controller: 0,
|
|
2289
|
+
service: 1,
|
|
2290
|
+
repository: 2,
|
|
2291
|
+
model: 3,
|
|
2292
|
+
component: 4,
|
|
2293
|
+
other: 5
|
|
2294
|
+
};
|
|
2295
|
+
var MAX_RELATED = 8;
|
|
2296
|
+
var MAX_FUNCTIONS = 5;
|
|
2297
|
+
var MIN_SUBSTRING_TERM = 5;
|
|
2298
|
+
function stem(word) {
|
|
2299
|
+
if (word.length > 4 && word.endsWith("ies")) return `${word.slice(0, -3)}y`;
|
|
2300
|
+
if (word.length > 3 && word.endsWith("s") && !word.endsWith("ss")) return word.slice(0, -1);
|
|
2301
|
+
return word;
|
|
2302
|
+
}
|
|
2303
|
+
function splitWords(text) {
|
|
2304
|
+
return text.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[^A-Za-z0-9]+/).map((word) => word.toLowerCase()).filter((word) => word.length > 0);
|
|
2305
|
+
}
|
|
2306
|
+
function flagTerms(flagName) {
|
|
2307
|
+
const terms = splitWords(flagName).filter((word) => word.length >= 2 && !/^v?\d+$/.test(word) && !STOP_WORDS.has(word)).map(stem);
|
|
2308
|
+
return Array.from(new Set(terms));
|
|
2309
|
+
}
|
|
2310
|
+
function matches(terms, identifier) {
|
|
2311
|
+
const words = new Set(splitWords(identifier).map(stem));
|
|
2312
|
+
const joined = identifier.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
2313
|
+
return terms.filter(
|
|
2314
|
+
(term) => words.has(term) || term.length >= MIN_SUBSTRING_TERM && joined.includes(term)
|
|
2315
|
+
);
|
|
2316
|
+
}
|
|
2317
|
+
function findRelatedCode(flagName, excludeFiles, callGraph) {
|
|
2318
|
+
if (flagName === null || !callGraph) return [];
|
|
2319
|
+
const terms = flagTerms(flagName);
|
|
2320
|
+
if (terms.length === 0) return [];
|
|
2321
|
+
const excluded = new Set(excludeFiles);
|
|
2322
|
+
const units = /* @__PURE__ */ new Map();
|
|
2323
|
+
for (const node of callGraph.nodes.values()) {
|
|
2324
|
+
if (excluded.has(node.filePath)) continue;
|
|
2325
|
+
const key = `${node.filePath}#${node.className ?? ""}`;
|
|
2326
|
+
const unit = units.get(key) ?? {
|
|
2327
|
+
filePath: node.filePath,
|
|
2328
|
+
className: node.className,
|
|
2329
|
+
layer: node.layer,
|
|
2330
|
+
functions: []
|
|
2331
|
+
};
|
|
2332
|
+
unit.functions.push(node.functionName);
|
|
2333
|
+
units.set(key, unit);
|
|
2334
|
+
}
|
|
2335
|
+
const related = [];
|
|
2336
|
+
for (const unit of units.values()) {
|
|
2337
|
+
const localPath = unit.filePath.replace(/\.[^./]+$/, "").split("/").slice(-2).join("/");
|
|
2338
|
+
const matched = /* @__PURE__ */ new Set([
|
|
2339
|
+
...matches(terms, localPath),
|
|
2340
|
+
...unit.className ? matches(terms, unit.className) : []
|
|
2341
|
+
]);
|
|
2342
|
+
const byName = matched.size > 0;
|
|
2343
|
+
const matchedFunctions = unit.functions.filter((name) => {
|
|
2344
|
+
const hits = matches(terms, name);
|
|
2345
|
+
for (const hit of hits) matched.add(hit);
|
|
2346
|
+
return hits.length > 0;
|
|
2347
|
+
});
|
|
2348
|
+
if (matched.size === 0) continue;
|
|
2349
|
+
related.push({
|
|
2350
|
+
filePath: unit.filePath,
|
|
2351
|
+
className: unit.className,
|
|
2352
|
+
layer: unit.layer,
|
|
2353
|
+
matchedTerms: terms.filter((term) => matched.has(term)),
|
|
2354
|
+
functions: Array.from(new Set(matchedFunctions)).slice(0, MAX_FUNCTIONS),
|
|
2355
|
+
byName
|
|
2356
|
+
});
|
|
2357
|
+
}
|
|
2358
|
+
const primary = terms[0];
|
|
2359
|
+
const anchored = related.some((entry) => entry.matchedTerms.includes(primary)) ? related.filter((entry) => entry.matchedTerms.includes(primary)) : related;
|
|
2360
|
+
return anchored.sort(
|
|
2361
|
+
(a, b) => Number(b.byName) - Number(a.byName) || b.matchedTerms.length - a.matchedTerms.length || b.functions.length - a.functions.length || LAYER_RANK[a.layer] - LAYER_RANK[b.layer] || a.filePath.localeCompare(b.filePath)
|
|
2362
|
+
).slice(0, MAX_RELATED).map((entry) => ({
|
|
2363
|
+
filePath: entry.filePath,
|
|
2364
|
+
className: entry.className,
|
|
2365
|
+
layer: entry.layer,
|
|
2366
|
+
matchedTerms: entry.matchedTerms,
|
|
2367
|
+
functions: entry.functions
|
|
2368
|
+
}));
|
|
2369
|
+
}
|
|
2370
|
+
|
|
2371
|
+
// packages/core/src/dependency/buildDependencyGraph.ts
|
|
2372
|
+
function statusFor(flagName, snapshot) {
|
|
2373
|
+
if (flagName === null) return "dynamic";
|
|
2374
|
+
if (!snapshot) return "unknown";
|
|
2375
|
+
const feature = snapshot.features[flagName];
|
|
2376
|
+
if (!feature) return "missing";
|
|
2377
|
+
return feature.archived ? "archived" : "matched";
|
|
2378
|
+
}
|
|
2379
|
+
function toSite(reference, callGraph) {
|
|
2380
|
+
const ref = reference.enclosingFunction !== null ? {
|
|
2381
|
+
filePath: reference.filePath,
|
|
2382
|
+
className: reference.enclosingClass,
|
|
2383
|
+
functionName: reference.enclosingFunction
|
|
2384
|
+
} : null;
|
|
2385
|
+
const callers = ref && callGraph ? findCallers(callGraph, ref) : [];
|
|
2386
|
+
return {
|
|
2387
|
+
repository: reference.repository,
|
|
2388
|
+
filePath: reference.filePath,
|
|
2389
|
+
enclosingClass: reference.enclosingClass,
|
|
2390
|
+
enclosingFunction: reference.enclosingFunction,
|
|
2391
|
+
line: reference.line,
|
|
2392
|
+
column: reference.column,
|
|
2393
|
+
sdk: reference.sdk,
|
|
2394
|
+
method: reference.method,
|
|
2395
|
+
expectedType: reference.expectedType,
|
|
2396
|
+
resolution: reference.resolution,
|
|
2397
|
+
callers,
|
|
2398
|
+
callees: ref && callGraph ? findCallees(callGraph, ref) : [],
|
|
2399
|
+
flow: ref && callGraph ? flowOf(callGraph, ref, callers) : []
|
|
2400
|
+
};
|
|
2401
|
+
}
|
|
2402
|
+
var MAX_FLOW_NODES = 20;
|
|
2403
|
+
function flowOf(callGraph, ref, callers) {
|
|
2404
|
+
const own = symbolKey(ref);
|
|
2405
|
+
const seen = /* @__PURE__ */ new Set([own]);
|
|
2406
|
+
const flow = [];
|
|
2407
|
+
for (const caller of callers) {
|
|
2408
|
+
if (caller.depth !== 1) continue;
|
|
2409
|
+
seen.add(symbolKey(caller));
|
|
2410
|
+
for (const node of findCallees(callGraph, caller, 2)) {
|
|
2411
|
+
const key = symbolKey(node);
|
|
2412
|
+
if (seen.has(key)) continue;
|
|
2413
|
+
seen.add(key);
|
|
2414
|
+
flow.push(node);
|
|
2415
|
+
if (flow.length >= MAX_FLOW_NODES) return flow;
|
|
2416
|
+
}
|
|
2417
|
+
}
|
|
2418
|
+
return flow;
|
|
2419
|
+
}
|
|
2420
|
+
function unique(values) {
|
|
2421
|
+
return Array.from(new Set(values.filter((value) => value !== null))).sort();
|
|
2422
|
+
}
|
|
2423
|
+
function dependencyKey(reference) {
|
|
2424
|
+
if (reference.flagName !== null) return reference.flagName;
|
|
2425
|
+
return `dynamic:${reference.filePath}:${reference.line}:${reference.column}`;
|
|
2426
|
+
}
|
|
2427
|
+
function buildDependencyGraph(options) {
|
|
2428
|
+
const groups = /* @__PURE__ */ new Map();
|
|
2429
|
+
for (const reference of options.references) {
|
|
2430
|
+
const key = dependencyKey(reference);
|
|
2431
|
+
const existing = groups.get(key);
|
|
2432
|
+
if (existing) existing.push(reference);
|
|
2433
|
+
else groups.set(key, [reference]);
|
|
2434
|
+
}
|
|
2435
|
+
const dependencies = [];
|
|
2436
|
+
for (const [flagKey, references] of groups) {
|
|
2437
|
+
const flagName = references[0].flagName;
|
|
2438
|
+
const sites = references.map((reference) => toSite(reference, options.callGraph)).sort((a, b) => a.filePath.localeCompare(b.filePath) || a.line - b.line);
|
|
2439
|
+
const files = unique(sites.map((site) => site.filePath));
|
|
2440
|
+
dependencies.push({
|
|
2441
|
+
flagKey,
|
|
2442
|
+
flagName,
|
|
2443
|
+
status: statusFor(flagName, options.snapshot),
|
|
2444
|
+
sites,
|
|
2445
|
+
files,
|
|
2446
|
+
classes: unique(sites.map((site) => site.enclosingClass)),
|
|
2447
|
+
functions: unique(sites.map((site) => site.enclosingFunction)),
|
|
2448
|
+
relatedCode: findRelatedCode(flagName, files, options.callGraph)
|
|
2449
|
+
});
|
|
2450
|
+
}
|
|
2451
|
+
return dependencies.sort(
|
|
2452
|
+
(a, b) => (a.flagName ?? "\uFFFF").localeCompare(b.flagName ?? "\uFFFF") || a.flagKey.localeCompare(b.flagKey)
|
|
2453
|
+
);
|
|
2454
|
+
}
|
|
2455
|
+
|
|
2456
|
+
// packages/core/src/engine/runScan.ts
|
|
2457
|
+
async function runDiagnosticScan(options) {
|
|
2458
|
+
const scan = await scanSources({
|
|
2459
|
+
provider: options.provider,
|
|
2460
|
+
wrappers: options.wrappers,
|
|
2461
|
+
signal: options.signal
|
|
2462
|
+
});
|
|
2463
|
+
let snapshot = null;
|
|
2464
|
+
let scanError = null;
|
|
2465
|
+
try {
|
|
2466
|
+
const adapter = new FlagsmithAdapter({
|
|
2467
|
+
token: options.token,
|
|
2468
|
+
baseUrl: options.config.flagsmith.baseUrl ?? DEFAULT_FLAGSMITH_BASE_URL,
|
|
2469
|
+
project: options.config.flagsmith.project,
|
|
2470
|
+
environment: options.environmentKey,
|
|
2471
|
+
fetchImpl: options.fetchImpl
|
|
2472
|
+
});
|
|
2473
|
+
const raw = await adapter.fetchSnapshot();
|
|
2474
|
+
snapshot = flagSnapshotSchema.parse(raw);
|
|
2475
|
+
} catch (error) {
|
|
2476
|
+
if (error instanceof FlagsmithAdapterError) {
|
|
2477
|
+
scanError = { kind: error.kind, message: error.message };
|
|
2478
|
+
} else {
|
|
2479
|
+
scanError = {
|
|
2480
|
+
kind: "invalid_response",
|
|
2481
|
+
message: redact(errorMessage(error), [options.token])
|
|
2482
|
+
};
|
|
2483
|
+
}
|
|
2484
|
+
}
|
|
2485
|
+
const findings = snapshot && !scanError ? evaluateFindings({
|
|
2486
|
+
references: scan.references,
|
|
2487
|
+
snapshot,
|
|
2488
|
+
environment: options.environment,
|
|
2489
|
+
repository: options.repository
|
|
2490
|
+
}) : [];
|
|
2491
|
+
const incompleteScan = scan.diagnostics.some(
|
|
2492
|
+
(diagnostic) => diagnostic.kind === "parse_error" || diagnostic.kind === "read_error"
|
|
2493
|
+
);
|
|
2494
|
+
const status = scanError ? "failed" : incompleteScan ? "partial" : "completed";
|
|
2495
|
+
const errors = findings.filter((finding) => finding.severity === "error").length;
|
|
2496
|
+
const warnings = findings.filter((finding) => finding.severity === "warning").length;
|
|
2497
|
+
const info = findings.filter((finding) => finding.severity === "info").length;
|
|
2498
|
+
let callGraph = null;
|
|
2499
|
+
if (scan.references.length > 0) {
|
|
2500
|
+
try {
|
|
2501
|
+
callGraph = await buildCallGraph({ provider: options.provider, signal: options.signal });
|
|
2502
|
+
} catch {
|
|
2503
|
+
callGraph = null;
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
const dependencies = buildDependencyGraph({ references: scan.references, snapshot, callGraph });
|
|
2507
|
+
return {
|
|
2508
|
+
schemaVersion: 1,
|
|
2509
|
+
status,
|
|
2510
|
+
project: snapshot ? { id: snapshot.project.id, name: snapshot.project.name } : null,
|
|
2511
|
+
environment: options.environment,
|
|
2512
|
+
fetchedAt: snapshot?.fetchedAt ?? null,
|
|
2513
|
+
repository: options.repository ?? null,
|
|
2514
|
+
commit: options.commit ?? null,
|
|
2515
|
+
summary: {
|
|
2516
|
+
errors,
|
|
2517
|
+
warnings,
|
|
2518
|
+
info,
|
|
2519
|
+
total: findings.length,
|
|
2520
|
+
scannedFiles: scan.scannedFiles,
|
|
2521
|
+
skippedFiles: scan.skippedFiles
|
|
2522
|
+
},
|
|
2523
|
+
findings,
|
|
2524
|
+
diagnostics: scan.diagnostics,
|
|
2525
|
+
error: scanError,
|
|
2526
|
+
dependencies
|
|
2527
|
+
};
|
|
2528
|
+
}
|
|
2529
|
+
|
|
2530
|
+
// packages/core/src/report/json.ts
|
|
2531
|
+
function formatJsonReport(report) {
|
|
2532
|
+
return JSON.stringify(report, null, 2);
|
|
2533
|
+
}
|
|
2534
|
+
|
|
2535
|
+
// packages/core/src/report/terminal.ts
|
|
2536
|
+
function formatTerminalReport(report) {
|
|
2537
|
+
const lines = [];
|
|
2538
|
+
const project = report.project ? `${report.project.name} (#${report.project.id})` : "n/a";
|
|
2539
|
+
lines.push(`FlagDoctor scan \u2014 environment: ${report.environment} | status: ${report.status}`);
|
|
2540
|
+
lines.push(
|
|
2541
|
+
`Project: ${project} | fetched: ${report.fetchedAt ?? "n/a"} | repository: ${report.repository ?? "n/a"} | commit: ${report.commit ?? "n/a"}`
|
|
2542
|
+
);
|
|
2543
|
+
lines.push(
|
|
2544
|
+
`Files: ${report.summary.scannedFiles} scanned, ${report.summary.skippedFiles} skipped | Findings: ${report.summary.errors} errors, ${report.summary.warnings} warnings, ${report.summary.info} info`
|
|
2545
|
+
);
|
|
2546
|
+
if (report.status === "partial") {
|
|
2547
|
+
lines.push("");
|
|
2548
|
+
lines.push(
|
|
2549
|
+
`Scan incomplete: ${report.diagnostics.length} source diagnostic(s); findings may be incomplete.`
|
|
2550
|
+
);
|
|
2551
|
+
}
|
|
2552
|
+
if (report.error) {
|
|
2553
|
+
lines.push("");
|
|
2554
|
+
lines.push(`Scan failed (${report.error.kind}): ${report.error.message}`);
|
|
2555
|
+
}
|
|
2556
|
+
if (report.findings.length > 0) {
|
|
2557
|
+
lines.push("");
|
|
2558
|
+
for (const finding of report.findings) {
|
|
2559
|
+
const location = finding.filePath ? finding.line ? `${finding.filePath}:${finding.line}:${finding.column ?? 1}` : finding.filePath : "no source location";
|
|
2560
|
+
lines.push(
|
|
2561
|
+
`[${finding.ruleId}] ${finding.id} ${finding.severity}/${finding.confidence} ${finding.flagName ?? "(dynamic)"} \u2014 ${location}`
|
|
2562
|
+
);
|
|
2563
|
+
lines.push(` ${finding.message}`);
|
|
2564
|
+
if (finding.suggestion) lines.push(` Suggestion: ${finding.suggestion}`);
|
|
2565
|
+
}
|
|
2566
|
+
}
|
|
2567
|
+
if (report.diagnostics.length > 0) {
|
|
2568
|
+
lines.push("");
|
|
2569
|
+
lines.push(`Diagnostics (${report.diagnostics.length}):`);
|
|
2570
|
+
for (const diagnostic of report.diagnostics) {
|
|
2571
|
+
lines.push(
|
|
2572
|
+
` ${diagnostic.filePath}:${diagnostic.line}:${diagnostic.column} ${diagnostic.kind}: ${diagnostic.message}`
|
|
2573
|
+
);
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
return lines.join("\n");
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
// packages/core/src/report/dependencyTree.ts
|
|
2580
|
+
var STATUS_MARKER = {
|
|
2581
|
+
matched: "\u2714",
|
|
2582
|
+
missing: "\u2716",
|
|
2583
|
+
archived: "\u26A0",
|
|
2584
|
+
dynamic: "?",
|
|
2585
|
+
unknown: "\xB7"
|
|
2586
|
+
};
|
|
2587
|
+
function groupBy(items, key) {
|
|
2588
|
+
const map = /* @__PURE__ */ new Map();
|
|
2589
|
+
for (const item of items) {
|
|
2590
|
+
const existing = map.get(key(item));
|
|
2591
|
+
if (existing) existing.push(item);
|
|
2592
|
+
else map.set(key(item), [item]);
|
|
2593
|
+
}
|
|
2594
|
+
return map;
|
|
2595
|
+
}
|
|
2596
|
+
function siteLabel(site) {
|
|
2597
|
+
const scope = site.enclosingFunction ? `function ${site.enclosingFunction}()` : "(module scope)";
|
|
2598
|
+
return `${scope} \u2014 ${site.method} \u2192 ${site.expectedType} [${site.resolution}] L${site.line}`;
|
|
2599
|
+
}
|
|
2600
|
+
function impactLabel(node) {
|
|
2601
|
+
const scope = node.className ? `${node.className}.${node.functionName}()` : `${node.functionName}()`;
|
|
2602
|
+
return `${scope} [${node.layer}] \u2014 ${node.filePath}`;
|
|
2603
|
+
}
|
|
2604
|
+
function impactLines(site, indent) {
|
|
2605
|
+
const lines = [];
|
|
2606
|
+
if (site.enclosingFunction !== null && site.callers.length === 0) {
|
|
2607
|
+
lines.push(`${indent}called by: none found \u2014 nothing in the scanned code calls ${site.enclosingFunction}()`);
|
|
2608
|
+
}
|
|
2609
|
+
if (site.callers.length > 0) {
|
|
2610
|
+
lines.push(`${indent}called by:`);
|
|
2611
|
+
for (const node of site.callers) lines.push(`${indent} ${" ".repeat(node.depth - 1)}\u2191 ${impactLabel(node)}`);
|
|
2612
|
+
}
|
|
2613
|
+
if (site.flow.length > 0) {
|
|
2614
|
+
lines.push(`${indent}in that flow, the caller also uses:`);
|
|
2615
|
+
for (const node of site.flow) lines.push(`${indent} ${" ".repeat(node.depth - 1)}\u2192 ${impactLabel(node)}`);
|
|
2616
|
+
}
|
|
2617
|
+
if (site.callees.length > 0) {
|
|
2618
|
+
lines.push(`${indent}calls:`);
|
|
2619
|
+
for (const node of site.callees) lines.push(`${indent} ${" ".repeat(node.depth - 1)}\u2193 ${impactLabel(node)}`);
|
|
2620
|
+
}
|
|
2621
|
+
return lines;
|
|
2622
|
+
}
|
|
2623
|
+
function formatDependencyTree(dependencies) {
|
|
2624
|
+
if (dependencies.length === 0) return "No flag dependencies were found in the scanned sources.";
|
|
2625
|
+
const totalSites = dependencies.reduce((sum, dependency) => sum + dependency.sites.length, 0);
|
|
2626
|
+
const lines = [
|
|
2627
|
+
`Flag dependency map (${dependencies.length} flag${dependencies.length === 1 ? "" : "s"} \xB7 ${totalSites} usage site${totalSites === 1 ? "" : "s"})`,
|
|
2628
|
+
""
|
|
2629
|
+
];
|
|
2630
|
+
for (const dependency of dependencies) {
|
|
2631
|
+
const marker = STATUS_MARKER[dependency.status];
|
|
2632
|
+
const label = dependency.flagName ?? "unresolved dynamic reference";
|
|
2633
|
+
lines.push(`${marker} ${label} (${dependency.status})`);
|
|
2634
|
+
const byFile = groupBy(dependency.sites, (site) => site.filePath);
|
|
2635
|
+
for (const [filePath, fileSites] of byFile) {
|
|
2636
|
+
lines.push(` \u2514\u2500 ${filePath}`);
|
|
2637
|
+
const byClass = groupBy(fileSites, (site) => site.enclosingClass);
|
|
2638
|
+
for (const [className, classSites] of byClass) {
|
|
2639
|
+
if (className !== null) {
|
|
2640
|
+
lines.push(` \u2514\u2500 class ${className}`);
|
|
2641
|
+
for (const site of classSites) {
|
|
2642
|
+
lines.push(` \u2514\u2500 ${siteLabel(site)}`);
|
|
2643
|
+
lines.push(...impactLines(site, " "));
|
|
2644
|
+
}
|
|
2645
|
+
} else {
|
|
2646
|
+
for (const site of classSites) {
|
|
2647
|
+
lines.push(` \u2514\u2500 ${siteLabel(site)}`);
|
|
2648
|
+
lines.push(...impactLines(site, " "));
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2653
|
+
if (dependency.relatedCode.length > 0) {
|
|
2654
|
+
lines.push(" related code (inferred from the flag name, not from calls):");
|
|
2655
|
+
for (const related of dependency.relatedCode) {
|
|
2656
|
+
const name = related.className ?? related.filePath;
|
|
2657
|
+
lines.push(
|
|
2658
|
+
` ~ ${name} [${related.layer}] \u2014 ${related.filePath} (matched: ${related.matchedTerms.join(", ")})`
|
|
2659
|
+
);
|
|
2660
|
+
if (related.functions.length > 0) {
|
|
2661
|
+
lines.push(` functions: ${related.functions.map((fn) => `${fn}()`).join(", ")}`);
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
}
|
|
2665
|
+
lines.push("");
|
|
2666
|
+
}
|
|
2667
|
+
return lines.join("\n").trimEnd();
|
|
2668
|
+
}
|
|
2669
|
+
|
|
2670
|
+
// packages/core/src/llm/buildAnalysisContext.ts
|
|
2671
|
+
var MAX_EXAMPLE_IMPACT_NODES = 8;
|
|
2672
|
+
var MAX_CONTEXT_SITES = 6;
|
|
2673
|
+
function toContextImpactNode(node) {
|
|
2674
|
+
return { className: node.className, functionName: node.functionName, layer: node.layer };
|
|
2675
|
+
}
|
|
2676
|
+
function buildAnalysisContext(report) {
|
|
2677
|
+
return {
|
|
2678
|
+
project: report.project?.name ?? null,
|
|
2679
|
+
environment: report.environment,
|
|
2680
|
+
repository: report.repository,
|
|
2681
|
+
scanStatus: report.status,
|
|
2682
|
+
coverage: {
|
|
2683
|
+
scannedFiles: report.summary.scannedFiles,
|
|
2684
|
+
skippedFiles: report.summary.skippedFiles,
|
|
2685
|
+
diagnostics: report.diagnostics.length
|
|
2686
|
+
},
|
|
2687
|
+
flags: report.dependencies.map((dependency) => {
|
|
2688
|
+
const sampleSite = dependency.sites.find(
|
|
2689
|
+
(site) => site.callers.length > 0 || site.callees.length > 0
|
|
2690
|
+
);
|
|
2691
|
+
return {
|
|
2692
|
+
flagName: dependency.flagName,
|
|
2693
|
+
status: dependency.status,
|
|
2694
|
+
files: dependency.files,
|
|
2695
|
+
classes: dependency.classes,
|
|
2696
|
+
functions: dependency.functions,
|
|
2697
|
+
siteCount: dependency.sites.length,
|
|
2698
|
+
sites: dependency.sites.slice(0, MAX_CONTEXT_SITES).map((site) => ({
|
|
2699
|
+
filePath: site.filePath,
|
|
2700
|
+
className: site.enclosingClass,
|
|
2701
|
+
functionName: site.enclosingFunction,
|
|
2702
|
+
line: site.line,
|
|
2703
|
+
method: site.method,
|
|
2704
|
+
expectedType: site.expectedType,
|
|
2705
|
+
resolution: site.resolution
|
|
2706
|
+
})),
|
|
2707
|
+
exampleCallers: (sampleSite?.callers ?? []).slice(0, MAX_EXAMPLE_IMPACT_NODES).map(toContextImpactNode),
|
|
2708
|
+
exampleCallees: (sampleSite?.callees ?? []).slice(0, MAX_EXAMPLE_IMPACT_NODES).map(toContextImpactNode),
|
|
2709
|
+
exampleFlow: (sampleSite?.flow ?? []).slice(0, MAX_EXAMPLE_IMPACT_NODES).map(toContextImpactNode),
|
|
2710
|
+
relatedByName: dependency.relatedCode.map((related) => ({
|
|
2711
|
+
className: related.className,
|
|
2712
|
+
layer: related.layer,
|
|
2713
|
+
filePath: related.filePath
|
|
2714
|
+
}))
|
|
2715
|
+
};
|
|
2716
|
+
}),
|
|
2717
|
+
findings: report.findings.filter((finding) => finding.origin !== "llm").map((finding) => ({
|
|
2718
|
+
ruleId: finding.ruleId,
|
|
2719
|
+
severity: finding.severity,
|
|
2720
|
+
flagName: finding.flagName,
|
|
2721
|
+
filePath: finding.filePath,
|
|
2722
|
+
line: finding.line,
|
|
2723
|
+
message: finding.message
|
|
2724
|
+
}))
|
|
2725
|
+
};
|
|
2726
|
+
}
|
|
2727
|
+
var DEFAULT_CONTEXT_MAX_CHARS = 14e3;
|
|
2728
|
+
var size = (context) => JSON.stringify(context).length;
|
|
2729
|
+
function priority(flag) {
|
|
2730
|
+
return flag.status === "matched" ? 1 : 0;
|
|
2731
|
+
}
|
|
2732
|
+
function fitAnalysisContext(context, maxChars = DEFAULT_CONTEXT_MAX_CHARS) {
|
|
2733
|
+
if (size(context) <= maxChars) return context;
|
|
2734
|
+
const steps = [
|
|
2735
|
+
["related-by-name hints", (flag) => ({ ...flag, relatedByName: [] })],
|
|
2736
|
+
["callee samples", (flag) => ({ ...flag, exampleCallees: [] })],
|
|
2737
|
+
["extra call sites", (flag) => ({ ...flag, sites: flag.sites.slice(0, 2) })],
|
|
2738
|
+
["flow samples", (flag) => ({ ...flag, exampleFlow: flag.exampleFlow.slice(0, 3) })],
|
|
2739
|
+
["caller samples", (flag) => ({ ...flag, exampleCallers: flag.exampleCallers.slice(0, 3) })]
|
|
2740
|
+
];
|
|
2741
|
+
let current = context;
|
|
2742
|
+
const applied = [];
|
|
2743
|
+
for (const [label, shrink] of steps) {
|
|
2744
|
+
current = { ...current, flags: current.flags.map(shrink) };
|
|
2745
|
+
applied.push(label);
|
|
2746
|
+
if (size({ ...current, omitted: { flags: 0, detail: applied.join(", ") } }) <= maxChars) {
|
|
2747
|
+
return { ...current, omitted: { flags: 0, detail: `dropped ${applied.join(", ")}` } };
|
|
2748
|
+
}
|
|
2749
|
+
}
|
|
2750
|
+
const ranked = [...current.flags].sort((a, b) => priority(a) - priority(b));
|
|
2751
|
+
const kept = [];
|
|
2752
|
+
for (const flag of ranked) {
|
|
2753
|
+
const candidate = {
|
|
2754
|
+
...current,
|
|
2755
|
+
flags: [...kept, flag],
|
|
2756
|
+
omitted: { flags: ranked.length, detail: "" }
|
|
2757
|
+
};
|
|
2758
|
+
if (size(candidate) > maxChars) break;
|
|
2759
|
+
kept.push(flag);
|
|
2760
|
+
}
|
|
2761
|
+
const omittedFlags = ranked.length - kept.length;
|
|
2762
|
+
return {
|
|
2763
|
+
...current,
|
|
2764
|
+
flags: kept,
|
|
2765
|
+
omitted: {
|
|
2766
|
+
flags: omittedFlags,
|
|
2767
|
+
detail: `dropped ${applied.join(", ")}; ${omittedFlags} healthy-first flag(s) omitted to fit the token limit`
|
|
2768
|
+
}
|
|
2769
|
+
};
|
|
2770
|
+
}
|
|
2771
|
+
|
|
2772
|
+
// packages/core/src/llm/groqClient.ts
|
|
2773
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
2774
|
+
|
|
2775
|
+
// packages/core/src/llm/errors.ts
|
|
2776
|
+
var GroqAdapterError = class extends Error {
|
|
2777
|
+
kind;
|
|
2778
|
+
status;
|
|
2779
|
+
constructor(kind, message, status = null) {
|
|
2780
|
+
super(message);
|
|
2781
|
+
this.name = "GroqAdapterError";
|
|
2782
|
+
this.kind = kind;
|
|
2783
|
+
this.status = status;
|
|
2784
|
+
}
|
|
2785
|
+
};
|
|
2786
|
+
|
|
2787
|
+
// packages/core/src/llm/prompt.ts
|
|
2788
|
+
var ANALYSIS_SYSTEM_PROMPT = `You are FlagDoctor's feature-flag misconfiguration reviewer and debugging assistant.
|
|
2789
|
+
You receive a compiled, static description of one codebase scan against one Flagsmith environment:
|
|
2790
|
+
- "coverage": files scanned/skipped and source problems, i.e. how complete the data is.
|
|
2791
|
+
- "flags": every Flagsmith flag referenced in code, with its status against the live environment
|
|
2792
|
+
snapshot ("matched", "missing", "archived", "dynamic" for an unresolved name, "unknown" when no snapshot
|
|
2793
|
+
was available); "sites" (file, class, function, line, SDK method, expected type) where it is read;
|
|
2794
|
+
"exampleCallers" (who calls the flag check, nearest first), "exampleCallees" (what the check calls) and
|
|
2795
|
+
"exampleFlow" (what the flag's direct caller also uses: the services, repositories and models the flag
|
|
2796
|
+
gates), each tagged with a best-effort layer (controller, service, repository, model, component, other);
|
|
2797
|
+
and "relatedByName" (classes whose names share terms with the flag name \u2014 a naming heuristic only).
|
|
2798
|
+
- "omitted" (only when present): detail or whole flags were dropped to fit a token limit. Say so in your
|
|
2799
|
+
summary if it limits what you can conclude, and never treat an omitted flag as absent from the code.
|
|
2800
|
+
- "findings": the deterministic findings already raised by AST rules (FD001 missing, FD002 archived,
|
|
2801
|
+
FD004 type mismatch, FD006 dynamic reference).
|
|
2802
|
+
|
|
2803
|
+
Your job is to find problems those rules cannot catch, and to help the developer debug the ones they did:
|
|
2804
|
+
- Flags checked in the wrong place: a check inside a repository/model layer with no controller or service
|
|
2805
|
+
above it; a flag whose name points at one feature (for example questions) but whose callers or gated flow
|
|
2806
|
+
sit in an unrelated feature (for example users).
|
|
2807
|
+
- Flags defined but never wired in: related code exists by name but "exampleCallers" is empty.
|
|
2808
|
+
- Near-duplicate flag names (typos), and the likely intended name when a flag is missing.
|
|
2809
|
+
- Status that contradicts usage (for example "archived" but read from many functions).
|
|
2810
|
+
- Type problems implied by the expected type and the code that consumes the value.
|
|
2811
|
+
- For notable deterministic findings, the likely root cause and how to confirm it. Do not just restate the
|
|
2812
|
+
finding; add information.
|
|
2813
|
+
|
|
2814
|
+
Rules:
|
|
2815
|
+
- Only report what the data supports. Never invent flag names, files, classes or functions that are not in
|
|
2816
|
+
the input. Layers come from a heuristic and unresolved calls are simply absent, so a short or empty chain
|
|
2817
|
+
means "no evidence", not proof of a bug \u2014 say so when you rely on it.
|
|
2818
|
+
- Each finding's "message" states what is wrong and cites the evidence (flag, file, function names).
|
|
2819
|
+
Its "suggestion" is a concrete debugging or fix step: what to check or change and where.
|
|
2820
|
+
- Use severity "warning" for likely real problems and "info" for observations. Do not use "error".
|
|
2821
|
+
- If nothing looks wrong, return an empty findings array. Do not pad the answer.
|
|
2822
|
+
- "summary" is one short paragraph: overall health, the most important risk, and what to do first.
|
|
2823
|
+
|
|
2824
|
+
Respond with ONLY a single JSON object matching this shape, no prose and no markdown fences:
|
|
2825
|
+
{
|
|
2826
|
+
"summary": "one short paragraph",
|
|
2827
|
+
"findings": [
|
|
2828
|
+
{
|
|
2829
|
+
"flagName": "string or null",
|
|
2830
|
+
"filePath": "string or null",
|
|
2831
|
+
"severity": "warning" | "info",
|
|
2832
|
+
"message": "string",
|
|
2833
|
+
"suggestion": "string or null"
|
|
2834
|
+
}
|
|
2835
|
+
]
|
|
2836
|
+
}`;
|
|
2837
|
+
function buildUserMessage(context) {
|
|
2838
|
+
return JSON.stringify(context);
|
|
2839
|
+
}
|
|
2840
|
+
|
|
2841
|
+
// packages/core/src/llm/schema.ts
|
|
2842
|
+
import { z as z6 } from "zod";
|
|
2843
|
+
var llmFindingSchema = z6.object({
|
|
2844
|
+
flagName: z6.string().nullable().default(null),
|
|
2845
|
+
filePath: z6.string().nullable().default(null),
|
|
2846
|
+
severity: severitySchema.default("info"),
|
|
2847
|
+
message: z6.string().min(1),
|
|
2848
|
+
suggestion: z6.string().nullable().default(null)
|
|
2849
|
+
});
|
|
2850
|
+
var llmAnalysisResponseSchema = z6.object({
|
|
2851
|
+
summary: z6.string().default(""),
|
|
2852
|
+
findings: z6.array(llmFindingSchema).default([])
|
|
2853
|
+
});
|
|
2854
|
+
|
|
2855
|
+
// packages/core/src/llm/groqClient.ts
|
|
2856
|
+
var DEFAULT_GROQ_BASE_URL = "https://api.groq.com/openai/v1";
|
|
2857
|
+
var DEFAULT_GROQ_MODEL = "qwen/qwen3.8-27b";
|
|
2858
|
+
function readGroqApiKeyFromEnv(env = process.env) {
|
|
2859
|
+
const key = env.GROQ_API_KEY?.trim() ?? "";
|
|
2860
|
+
if (key === "") {
|
|
2861
|
+
throw new GroqAdapterError(
|
|
2862
|
+
"configuration",
|
|
2863
|
+
"GROQ_API_KEY is required for AI analysis. Set it in your environment or .env file."
|
|
2864
|
+
);
|
|
2865
|
+
}
|
|
2866
|
+
return key;
|
|
2867
|
+
}
|
|
2868
|
+
function findingId2(flagName, filePath, message) {
|
|
2869
|
+
const material = ["FDLLM", flagName ?? "", filePath ?? "", message].join("|");
|
|
2870
|
+
return `fd-${createHash2("sha256").update(material).digest("hex").slice(0, 12)}`;
|
|
2871
|
+
}
|
|
2872
|
+
function toFindings(response, environment) {
|
|
2873
|
+
return response.findings.map((finding) => ({
|
|
2874
|
+
id: findingId2(finding.flagName, finding.filePath, finding.message),
|
|
2875
|
+
ruleId: "FDLLM",
|
|
2876
|
+
// AI findings are low-confidence by definition and must never fail a build, so "error" is capped.
|
|
2877
|
+
severity: finding.severity === "error" ? "warning" : finding.severity,
|
|
2878
|
+
confidence: "low",
|
|
2879
|
+
flagName: finding.flagName,
|
|
2880
|
+
environment,
|
|
2881
|
+
repository: null,
|
|
2882
|
+
filePath: finding.filePath,
|
|
2883
|
+
line: null,
|
|
2884
|
+
column: null,
|
|
2885
|
+
message: finding.message,
|
|
2886
|
+
suggestion: finding.suggestion,
|
|
2887
|
+
origin: "llm"
|
|
2888
|
+
}));
|
|
2889
|
+
}
|
|
2890
|
+
function statusError2(status, body, apiKey) {
|
|
2891
|
+
const detail = redact(body.slice(0, 300), [apiKey]);
|
|
2892
|
+
const message = `Groq API returned HTTP ${status}${detail ? `: ${detail}` : ""}`;
|
|
2893
|
+
if (status === 401 || status === 403) {
|
|
2894
|
+
return new GroqAdapterError("authentication", message, status);
|
|
2895
|
+
}
|
|
2896
|
+
if (status === 429) return new GroqAdapterError("rate_limited", message, status);
|
|
2897
|
+
if (status >= 500) return new GroqAdapterError("server", message, status);
|
|
2898
|
+
return new GroqAdapterError("invalid_response", message, status);
|
|
2899
|
+
}
|
|
2900
|
+
function stripReasoning(content) {
|
|
2901
|
+
return content.replace(/<think>[\s\S]*?<\/think>/gi, "").replace(/<think>[\s\S]*$/i, "").trim();
|
|
2902
|
+
}
|
|
2903
|
+
function extractJsonObject(content) {
|
|
2904
|
+
const cleaned = stripReasoning(content).replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
|
|
2905
|
+
try {
|
|
2906
|
+
return JSON.parse(cleaned);
|
|
2907
|
+
} catch {
|
|
2908
|
+
const start = cleaned.indexOf("{");
|
|
2909
|
+
const end = cleaned.lastIndexOf("}");
|
|
2910
|
+
if (start === -1 || end <= start) throw new Error("no JSON object found");
|
|
2911
|
+
return JSON.parse(cleaned.slice(start, end + 1));
|
|
2912
|
+
}
|
|
2913
|
+
}
|
|
2914
|
+
var GroqClient = class {
|
|
2915
|
+
apiKey;
|
|
2916
|
+
model;
|
|
2917
|
+
/** True when the caller named a model; we never swap a model the user chose. */
|
|
2918
|
+
explicitModel;
|
|
2919
|
+
baseUrl;
|
|
2920
|
+
timeoutMs;
|
|
2921
|
+
fetchImpl;
|
|
2922
|
+
constructor(options) {
|
|
2923
|
+
this.apiKey = options.apiKey;
|
|
2924
|
+
this.model = options.model ?? DEFAULT_GROQ_MODEL;
|
|
2925
|
+
this.explicitModel = options.model !== void 0;
|
|
2926
|
+
this.baseUrl = (options.baseUrl ?? DEFAULT_GROQ_BASE_URL).replace(/\/+$/, "");
|
|
2927
|
+
this.timeoutMs = options.timeoutMs ?? 9e4;
|
|
2928
|
+
this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
2929
|
+
}
|
|
2930
|
+
async send(context, features) {
|
|
2931
|
+
try {
|
|
2932
|
+
return await this.fetchImpl(`${this.baseUrl}/chat/completions`, {
|
|
2933
|
+
method: "POST",
|
|
2934
|
+
headers: {
|
|
2935
|
+
"Content-Type": "application/json",
|
|
2936
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
2937
|
+
},
|
|
2938
|
+
body: JSON.stringify({
|
|
2939
|
+
model: this.model,
|
|
2940
|
+
temperature: 0.2,
|
|
2941
|
+
// Bounds the answer so request + answer stay inside the per-minute token limit.
|
|
2942
|
+
max_completion_tokens: 3500,
|
|
2943
|
+
...features.json ? { response_format: { type: "json_object" } } : {},
|
|
2944
|
+
...features.hideReasoning ? { reasoning_format: "hidden" } : {},
|
|
2945
|
+
messages: [
|
|
2946
|
+
{ role: "system", content: ANALYSIS_SYSTEM_PROMPT },
|
|
2947
|
+
{ role: "user", content: buildUserMessage(context) }
|
|
2948
|
+
]
|
|
2949
|
+
}),
|
|
2950
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
2951
|
+
});
|
|
2952
|
+
} catch (error) {
|
|
2953
|
+
const name = error instanceof Error ? error.name : "";
|
|
2954
|
+
if (name === "TimeoutError" || name === "AbortError") {
|
|
2955
|
+
throw new GroqAdapterError("timeout", "Groq request timed out");
|
|
2956
|
+
}
|
|
2957
|
+
throw new GroqAdapterError(
|
|
2958
|
+
"network",
|
|
2959
|
+
redact(`Groq request failed: ${errorMessage(error)}`, [this.apiKey])
|
|
2960
|
+
);
|
|
2961
|
+
}
|
|
2962
|
+
}
|
|
2963
|
+
/**
|
|
2964
|
+
* Groq retires and renames models often. When the built-in default is gone, pick another
|
|
2965
|
+
* Qwen model the key can use instead of failing; returns whether the model changed.
|
|
2966
|
+
*/
|
|
2967
|
+
async fallbackToAvailableQwen() {
|
|
2968
|
+
try {
|
|
2969
|
+
const response = await this.fetchImpl(`${this.baseUrl}/models`, {
|
|
2970
|
+
headers: { Authorization: `Bearer ${this.apiKey}` },
|
|
2971
|
+
signal: AbortSignal.timeout(15e3)
|
|
2972
|
+
});
|
|
2973
|
+
if (!response.ok) return false;
|
|
2974
|
+
const payload = await response.json();
|
|
2975
|
+
const candidates = (payload.data ?? []).map((model) => model.id).filter((id) => typeof id === "string" && /^qwen/i.test(id) && id !== this.model).sort().reverse();
|
|
2976
|
+
const chosen = candidates[0];
|
|
2977
|
+
if (!chosen) return false;
|
|
2978
|
+
this.model = chosen;
|
|
2979
|
+
return true;
|
|
2980
|
+
} catch {
|
|
2981
|
+
return false;
|
|
2982
|
+
}
|
|
2983
|
+
}
|
|
2984
|
+
/** Sends the compiled context to Groq and returns the mapped misconfiguration findings. */
|
|
2985
|
+
async analyze(context) {
|
|
2986
|
+
const features = {
|
|
2987
|
+
json: true,
|
|
2988
|
+
hideReasoning: /qwen3|qwq|deepseek-r1/i.test(this.model)
|
|
2989
|
+
};
|
|
2990
|
+
let response = await this.send(context, features);
|
|
2991
|
+
if (response.status === 404 && !this.explicitModel) {
|
|
2992
|
+
const body = await response.clone().text().catch(() => "");
|
|
2993
|
+
if (/model_not_found|does not exist/i.test(body) && await this.fallbackToAvailableQwen()) {
|
|
2994
|
+
features.hideReasoning = /qwen3|qwq|deepseek-r1/i.test(this.model);
|
|
2995
|
+
response = await this.send(context, features);
|
|
2996
|
+
}
|
|
2997
|
+
}
|
|
2998
|
+
for (let attempt = 0; attempt < 2 && response.status === 400; attempt += 1) {
|
|
2999
|
+
const body = await response.clone().text().catch(() => "");
|
|
3000
|
+
if (features.hideReasoning && /reasoning/i.test(body)) features.hideReasoning = false;
|
|
3001
|
+
else if (features.json && /response_format|json/i.test(body)) features.json = false;
|
|
3002
|
+
else break;
|
|
3003
|
+
response = await this.send(context, features);
|
|
3004
|
+
}
|
|
3005
|
+
if (!response.ok) {
|
|
3006
|
+
const body = await response.text().catch(() => "");
|
|
3007
|
+
throw statusError2(response.status, body, this.apiKey);
|
|
3008
|
+
}
|
|
3009
|
+
let payload;
|
|
3010
|
+
try {
|
|
3011
|
+
payload = await response.json();
|
|
3012
|
+
} catch {
|
|
3013
|
+
throw new GroqAdapterError("invalid_response", "Groq response was not valid JSON");
|
|
3014
|
+
}
|
|
3015
|
+
const content = extractMessageContent(payload);
|
|
3016
|
+
if (content === null) {
|
|
3017
|
+
throw new GroqAdapterError("invalid_response", "Groq response had no message content");
|
|
3018
|
+
}
|
|
3019
|
+
let parsedContent;
|
|
3020
|
+
try {
|
|
3021
|
+
parsedContent = extractJsonObject(content);
|
|
3022
|
+
} catch {
|
|
3023
|
+
throw new GroqAdapterError("invalid_response", "Groq message content was not valid JSON");
|
|
3024
|
+
}
|
|
3025
|
+
const result = llmAnalysisResponseSchema.safeParse(parsedContent);
|
|
3026
|
+
if (!result.success) {
|
|
3027
|
+
throw new GroqAdapterError(
|
|
3028
|
+
"invalid_response",
|
|
3029
|
+
"Groq message content did not match the expected analysis shape"
|
|
3030
|
+
);
|
|
3031
|
+
}
|
|
3032
|
+
return {
|
|
3033
|
+
summary: result.data.summary,
|
|
3034
|
+
findings: toFindings(result.data, context.environment),
|
|
3035
|
+
model: this.model
|
|
3036
|
+
};
|
|
3037
|
+
}
|
|
3038
|
+
};
|
|
3039
|
+
function extractMessageContent(payload) {
|
|
3040
|
+
if (typeof payload !== "object" || payload === null) return null;
|
|
3041
|
+
const choices = payload.choices;
|
|
3042
|
+
if (!Array.isArray(choices) || choices.length === 0) return null;
|
|
3043
|
+
const message = choices[0].message;
|
|
3044
|
+
if (typeof message !== "object" || message === null) return null;
|
|
3045
|
+
const content = message.content;
|
|
3046
|
+
return typeof content === "string" ? content : null;
|
|
3047
|
+
}
|
|
3048
|
+
|
|
3049
|
+
// packages/core/src/llm/analyzeReport.ts
|
|
3050
|
+
function tally(findings) {
|
|
3051
|
+
const count = (severity) => findings.filter((finding) => finding.severity === severity).length;
|
|
3052
|
+
return { errors: count("error"), warnings: count("warning"), info: count("info"), total: findings.length };
|
|
3053
|
+
}
|
|
3054
|
+
async function analyzeReport(report, client, now = () => /* @__PURE__ */ new Date()) {
|
|
3055
|
+
const analysis = await client.analyze(fitAnalysisContext(buildAnalysisContext(report)));
|
|
3056
|
+
const deterministic = report.findings.filter((finding) => finding.origin !== "llm");
|
|
3057
|
+
const seen = new Set(deterministic.map((finding) => finding.id));
|
|
3058
|
+
const aiFindings = analysis.findings.filter((finding) => {
|
|
3059
|
+
if (seen.has(finding.id)) return false;
|
|
3060
|
+
seen.add(finding.id);
|
|
3061
|
+
return true;
|
|
3062
|
+
});
|
|
3063
|
+
const findings = [...deterministic, ...aiFindings];
|
|
3064
|
+
return {
|
|
3065
|
+
report: {
|
|
3066
|
+
...report,
|
|
3067
|
+
findings,
|
|
3068
|
+
summary: { ...report.summary, ...tally(findings) },
|
|
3069
|
+
analysis: {
|
|
3070
|
+
provider: "groq",
|
|
3071
|
+
model: analysis.model,
|
|
3072
|
+
summary: analysis.summary,
|
|
3073
|
+
analyzedAt: now().toISOString()
|
|
3074
|
+
}
|
|
3075
|
+
},
|
|
3076
|
+
aiFindings,
|
|
3077
|
+
model: analysis.model,
|
|
3078
|
+
summary: analysis.summary
|
|
3079
|
+
};
|
|
3080
|
+
}
|
|
3081
|
+
|
|
3082
|
+
// packages/cli/dist/credentials.js
|
|
3083
|
+
import { mkdir, readFile as readFile4, writeFile as writeFile2 } from "node:fs/promises";
|
|
3084
|
+
import { homedir } from "node:os";
|
|
3085
|
+
import path2 from "node:path";
|
|
3086
|
+
function credentialFilePath(env) {
|
|
3087
|
+
const directory = env.FLAGDOCTOR_CONFIG_DIR ?? path2.join(homedir(), ".flagdoctor");
|
|
3088
|
+
return path2.join(directory, "credentials.json");
|
|
3089
|
+
}
|
|
3090
|
+
async function saveCliCredential(credential, env) {
|
|
3091
|
+
const target = credentialFilePath(env);
|
|
3092
|
+
await mkdir(path2.dirname(target), { recursive: true });
|
|
3093
|
+
await writeFile2(target, `${JSON.stringify(credential, null, 2)}
|
|
3094
|
+
`, {
|
|
3095
|
+
mode: 384,
|
|
3096
|
+
encoding: "utf8"
|
|
3097
|
+
});
|
|
3098
|
+
}
|
|
3099
|
+
async function readCliCredential(env) {
|
|
3100
|
+
try {
|
|
3101
|
+
const parsed = JSON.parse(await readFile4(credentialFilePath(env), "utf8"));
|
|
3102
|
+
if (typeof parsed.token !== "string" || typeof parsed.apiUrl !== "string")
|
|
3103
|
+
return null;
|
|
3104
|
+
return {
|
|
3105
|
+
token: parsed.token,
|
|
3106
|
+
apiUrl: parsed.apiUrl.replace(/\/+$/, ""),
|
|
3107
|
+
workspaceId: parsed.workspaceId ?? "",
|
|
3108
|
+
projectId: parsed.projectId ?? "",
|
|
3109
|
+
obtainedAt: parsed.obtainedAt ?? ""
|
|
3110
|
+
};
|
|
3111
|
+
} catch {
|
|
3112
|
+
return null;
|
|
3113
|
+
}
|
|
3114
|
+
}
|
|
3115
|
+
function apiBaseUrl(env) {
|
|
3116
|
+
return (env.FLAGDOCTOR_API_URL ?? "http://localhost:3001").replace(/\/+$/, "");
|
|
3117
|
+
}
|
|
3118
|
+
|
|
3119
|
+
// packages/cli/dist/setup.js
|
|
3120
|
+
import { spawn } from "node:child_process";
|
|
3121
|
+
import { access, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
|
|
3122
|
+
import path3 from "node:path";
|
|
3123
|
+
var SetupAbortedError = class extends Error {
|
|
3124
|
+
constructor() {
|
|
3125
|
+
super("Setup cancelled");
|
|
3126
|
+
this.name = "SetupAbortedError";
|
|
3127
|
+
}
|
|
3128
|
+
};
|
|
3129
|
+
function createTerminalPrompt(input, output) {
|
|
3130
|
+
const stream = input;
|
|
3131
|
+
return (question, options = {}) => {
|
|
3132
|
+
const label = options.default ? `${question} [${options.default}]: ` : question;
|
|
3133
|
+
output.write(label);
|
|
3134
|
+
return new Promise((resolve, reject) => {
|
|
3135
|
+
let value = "";
|
|
3136
|
+
const wasRaw = stream.isRaw === true;
|
|
3137
|
+
const cleanup = () => {
|
|
3138
|
+
stream.off("data", onData);
|
|
3139
|
+
stream.setRawMode?.(wasRaw);
|
|
3140
|
+
stream.pause();
|
|
3141
|
+
};
|
|
3142
|
+
const onData = (chunk) => {
|
|
3143
|
+
const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
3144
|
+
for (const character of text) {
|
|
3145
|
+
if (character === "\r" || character === "\n") {
|
|
3146
|
+
cleanup();
|
|
3147
|
+
output.write("\n");
|
|
3148
|
+
resolve(value.trim() === "" && options.default ? options.default : value.trim());
|
|
3149
|
+
return;
|
|
3150
|
+
}
|
|
3151
|
+
if (character === "" || character === "") {
|
|
3152
|
+
cleanup();
|
|
3153
|
+
output.write("\n");
|
|
3154
|
+
reject(new SetupAbortedError());
|
|
3155
|
+
return;
|
|
3156
|
+
}
|
|
3157
|
+
if (character === "\b" || character === "\x7F") {
|
|
3158
|
+
if (value.length > 0) {
|
|
3159
|
+
value = value.slice(0, -1);
|
|
3160
|
+
if (options.secret !== true)
|
|
3161
|
+
output.write("\b \b");
|
|
3162
|
+
}
|
|
3163
|
+
continue;
|
|
3164
|
+
}
|
|
3165
|
+
value += character;
|
|
3166
|
+
output.write(options.secret === true ? "*" : character);
|
|
3167
|
+
}
|
|
3168
|
+
};
|
|
3169
|
+
stream.on("data", onData);
|
|
3170
|
+
stream.setRawMode?.(true);
|
|
3171
|
+
stream.resume();
|
|
3172
|
+
});
|
|
3173
|
+
};
|
|
3174
|
+
}
|
|
3175
|
+
function isInteractiveSetup(forcePlain, input) {
|
|
3176
|
+
return forcePlain !== true && (input?.isTTY === true || process.stdin.isTTY === true) && process.stdout.isTTY === true;
|
|
3177
|
+
}
|
|
3178
|
+
async function fileExists(filePath) {
|
|
3179
|
+
try {
|
|
3180
|
+
await access(filePath);
|
|
3181
|
+
return true;
|
|
3182
|
+
} catch {
|
|
3183
|
+
return false;
|
|
3184
|
+
}
|
|
3185
|
+
}
|
|
3186
|
+
function parseList(value) {
|
|
3187
|
+
return value.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
|
|
3188
|
+
}
|
|
3189
|
+
function titleCase(value) {
|
|
3190
|
+
return value.split(/[\s_-]+/).filter((part) => part.length > 0).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
|
|
3191
|
+
}
|
|
3192
|
+
function parseMapping(value) {
|
|
3193
|
+
const mapping = {};
|
|
3194
|
+
for (const entry of parseList(value)) {
|
|
3195
|
+
const separator = entry.indexOf("=");
|
|
3196
|
+
if (separator <= 0) {
|
|
3197
|
+
const alias2 = entry.trim();
|
|
3198
|
+
if (alias2 !== "")
|
|
3199
|
+
mapping[alias2] = titleCase(alias2);
|
|
3200
|
+
continue;
|
|
3201
|
+
}
|
|
3202
|
+
const alias = entry.slice(0, separator).trim();
|
|
3203
|
+
const target = entry.slice(separator + 1).trim();
|
|
3204
|
+
if (alias !== "" && target !== "")
|
|
3205
|
+
mapping[alias] = target;
|
|
3206
|
+
}
|
|
3207
|
+
return mapping;
|
|
3208
|
+
}
|
|
3209
|
+
function suggestedAlias(name) {
|
|
3210
|
+
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "environment";
|
|
3211
|
+
}
|
|
3212
|
+
function buildGitUrl(baseUrl, repository, token) {
|
|
3213
|
+
const base = (baseUrl.trim() || "https://github.com").replace(/\/+$/, "");
|
|
3214
|
+
const raw = repository.trim().replace(/^\/+|\/+$/g, "");
|
|
3215
|
+
const url = /^https?:\/\//i.test(raw) ? raw : `${base}/${raw.replace(/\.git$/, "")}.git`;
|
|
3216
|
+
if (token.trim() === "")
|
|
3217
|
+
return url;
|
|
3218
|
+
const parsed = new URL(url);
|
|
3219
|
+
parsed.username = "oauth2";
|
|
3220
|
+
parsed.password = token.trim();
|
|
3221
|
+
return parsed.toString();
|
|
3222
|
+
}
|
|
3223
|
+
function resolveDestination(cwd, value, repoName) {
|
|
3224
|
+
const relative = value.trim() || path3.join("repos", repoName);
|
|
3225
|
+
const absolute = path3.resolve(cwd, relative);
|
|
3226
|
+
const root = path3.resolve(cwd);
|
|
3227
|
+
if (absolute === root || !absolute.startsWith(`${root}${path3.sep}`)) {
|
|
3228
|
+
throw new Error("Destination must be a folder inside the current workspace");
|
|
3229
|
+
}
|
|
3230
|
+
return relative.split(path3.sep).join("/");
|
|
3231
|
+
}
|
|
3232
|
+
async function defaultExecGit(args, cwd, secrets) {
|
|
3233
|
+
return new Promise((resolve, reject) => {
|
|
3234
|
+
const child = spawn("git", [...args], {
|
|
3235
|
+
cwd,
|
|
3236
|
+
windowsHide: true,
|
|
3237
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
3238
|
+
});
|
|
3239
|
+
let stdout = "";
|
|
3240
|
+
let stderr = "";
|
|
3241
|
+
child.stdout?.on("data", (chunk) => {
|
|
3242
|
+
stdout += chunk.toString("utf8");
|
|
3243
|
+
});
|
|
3244
|
+
child.stderr?.on("data", (chunk) => {
|
|
3245
|
+
stderr += chunk.toString("utf8");
|
|
3246
|
+
});
|
|
3247
|
+
child.on("error", (error) => reject(new Error(redact(errorMessage(error), secrets))));
|
|
3248
|
+
child.on("close", (code) => {
|
|
3249
|
+
if (code === 0) {
|
|
3250
|
+
resolve({ stdout, stderr });
|
|
3251
|
+
} else {
|
|
3252
|
+
const detail = stderr.trim() || stdout.trim();
|
|
3253
|
+
reject(new Error(redact(`git exited with code ${code ?? "unknown"}: ${detail}`, secrets)));
|
|
3254
|
+
}
|
|
3255
|
+
});
|
|
3256
|
+
});
|
|
3257
|
+
}
|
|
3258
|
+
async function runSetupWizard(options, deps) {
|
|
3259
|
+
const { stdout, stderr, cwd, env } = deps;
|
|
3260
|
+
const prompt = deps.prompt ?? (deps.input ? createTerminalPrompt(deps.input, { write: stdout }) : void 0);
|
|
3261
|
+
if (!prompt) {
|
|
3262
|
+
stderr("Interactive setup requires a terminal.\n");
|
|
3263
|
+
return 2;
|
|
3264
|
+
}
|
|
3265
|
+
const configPath = path3.resolve(cwd, options.config ?? "flagdoctor.yaml");
|
|
3266
|
+
if (options.force !== true && await fileExists(configPath)) {
|
|
3267
|
+
stderr(`${path3.relative(cwd, configPath)} already exists; use --force to overwrite it.
|
|
3268
|
+
`);
|
|
3269
|
+
return 2;
|
|
3270
|
+
}
|
|
3271
|
+
stdout("FlagDoctor guided setup\n=======================\n\n");
|
|
3272
|
+
const source = (await prompt("Repository source (local/github/gitlab) [local]: ", {
|
|
3273
|
+
default: "local"
|
|
3274
|
+
})).toLowerCase();
|
|
3275
|
+
if (!["local", "github", "gitlab"].includes(source)) {
|
|
3276
|
+
stderr(`Unsupported repository source: ${source}
|
|
3277
|
+
`);
|
|
3278
|
+
return 2;
|
|
3279
|
+
}
|
|
3280
|
+
let root = ".";
|
|
3281
|
+
if (source === "local") {
|
|
3282
|
+
root = (await prompt("Local repository path [.]: ", { default: "." })).trim() || ".";
|
|
3283
|
+
try {
|
|
3284
|
+
const info = await stat2(path3.resolve(cwd, root));
|
|
3285
|
+
if (!info.isDirectory())
|
|
3286
|
+
throw new Error("not a directory");
|
|
3287
|
+
} catch {
|
|
3288
|
+
stderr(`Local repository path is not a directory: ${root}
|
|
3289
|
+
`);
|
|
3290
|
+
return 2;
|
|
3291
|
+
}
|
|
3292
|
+
} else {
|
|
3293
|
+
const defaultBase = source === "github" ? "https://github.com" : "https://gitlab.com";
|
|
3294
|
+
const base = await prompt(`Git ${source} base URL [${defaultBase}]: `, {
|
|
3295
|
+
default: defaultBase
|
|
3296
|
+
});
|
|
3297
|
+
const pat = await prompt(`Git ${source} personal access token (optional, hidden): `, {
|
|
3298
|
+
secret: true
|
|
3299
|
+
});
|
|
3300
|
+
const repository = (await prompt("Repository (owner/repo or full URL): ")).trim();
|
|
3301
|
+
if (repository === "") {
|
|
3302
|
+
stderr("A repository is required for import.\n");
|
|
3303
|
+
return 2;
|
|
3304
|
+
}
|
|
3305
|
+
const repoName = repository.replace(/\.git$/, "").split("/").filter(Boolean).pop() ?? "repository";
|
|
3306
|
+
const destination = resolveDestination(cwd, await prompt(`Local destination folder [repos/${repoName}]: `, {
|
|
3307
|
+
default: path3.join("repos", repoName)
|
|
3308
|
+
}), repoName);
|
|
3309
|
+
const execGit = deps.execGit ?? ((args, gitCwd) => defaultExecGit(args, gitCwd, pat.trim() === "" ? [] : [pat.trim()]));
|
|
3310
|
+
const gitUrl = buildGitUrl(base, repository, pat.trim());
|
|
3311
|
+
stdout(`Importing ${source} repository into ${destination} ...
|
|
3312
|
+
`);
|
|
3313
|
+
try {
|
|
3314
|
+
await execGit(["clone", "--depth", "1", gitUrl, destination], cwd);
|
|
3315
|
+
} catch (error) {
|
|
3316
|
+
stderr(`Import failed: ${redact(errorMessage(error), [pat.trim()])}
|
|
3317
|
+
`);
|
|
3318
|
+
return 2;
|
|
3319
|
+
}
|
|
3320
|
+
root = destination;
|
|
3321
|
+
}
|
|
3322
|
+
const include = parseList(await prompt("Include globs (comma-separated, optional): "));
|
|
3323
|
+
const exclude = parseList(await prompt("Exclude globs (comma-separated, optional): "));
|
|
3324
|
+
const baseUrl = (await prompt(`Flagsmith Management API base URL [${DEFAULT_FLAGSMITH_BASE_URL}]: `, {
|
|
3325
|
+
default: DEFAULT_FLAGSMITH_BASE_URL
|
|
3326
|
+
})).trim() || DEFAULT_FLAGSMITH_BASE_URL;
|
|
3327
|
+
let token = env.FLAGSMITH_TOKEN?.trim() ?? "";
|
|
3328
|
+
if (token !== "") {
|
|
3329
|
+
const reuse = (await prompt("Use the FLAGSMITH_TOKEN already in the environment? [Y/n]: ", {
|
|
3330
|
+
default: "Y"
|
|
3331
|
+
})).toLowerCase();
|
|
3332
|
+
if (reuse === "n" || reuse === "no")
|
|
3333
|
+
token = "";
|
|
3334
|
+
}
|
|
3335
|
+
if (token === "") {
|
|
3336
|
+
token = await prompt("Flagsmith Organisation API token (hidden): ", { secret: true });
|
|
3337
|
+
}
|
|
3338
|
+
token = token.trim();
|
|
3339
|
+
if (token === "") {
|
|
3340
|
+
stderr("A Flagsmith Organisation API token is required.\n");
|
|
3341
|
+
return 2;
|
|
3342
|
+
}
|
|
3343
|
+
const saveToken = (await prompt("Save the token to local .env (gitignored)? [Y/n]: ", { default: "Y" })).toLowerCase();
|
|
3344
|
+
if (saveToken !== "n" && saveToken !== "no") {
|
|
3345
|
+
try {
|
|
3346
|
+
await upsertEnvVar(path3.join(cwd, ".env"), "FLAGSMITH_TOKEN", token);
|
|
3347
|
+
env.FLAGSMITH_TOKEN = token;
|
|
3348
|
+
stdout("Token saved to .env only; it is never written to flagdoctor.yaml.\n");
|
|
3349
|
+
} catch (error) {
|
|
3350
|
+
stderr(`Could not update .env: ${errorMessage(error)}
|
|
3351
|
+
`);
|
|
3352
|
+
return 2;
|
|
3353
|
+
}
|
|
3354
|
+
}
|
|
3355
|
+
const defaultMapping = "development=Development,production=Production";
|
|
3356
|
+
let project;
|
|
3357
|
+
let environments;
|
|
3358
|
+
let knownTargets = [];
|
|
3359
|
+
const sync = (await prompt("Fetch projects and environments from Flagsmith now? [Y/n]: ", { default: "Y" })).toLowerCase();
|
|
3360
|
+
if (sync !== "n" && sync !== "no") {
|
|
3361
|
+
try {
|
|
3362
|
+
const discovery = new FlagsmithDiscovery({ baseUrl, token, fetchImpl: deps.fetchImpl });
|
|
3363
|
+
const projects = await discovery.listProjects();
|
|
3364
|
+
if (projects.length === 0)
|
|
3365
|
+
throw new Error("No projects available for this token");
|
|
3366
|
+
stdout("\nProjects:\n");
|
|
3367
|
+
projects.forEach((candidate, index) => {
|
|
3368
|
+
stdout(` ${index + 1}. ${candidate.name} (id ${candidate.id})
|
|
3369
|
+
`);
|
|
3370
|
+
});
|
|
3371
|
+
const choice = (await prompt("Select a project number or enter its name [1]: ", { default: "1" })).trim();
|
|
3372
|
+
const selected = projects[Number(choice) - 1] ?? projects.find((candidate) => candidate.name === choice || String(candidate.id) === choice);
|
|
3373
|
+
if (!selected) {
|
|
3374
|
+
stderr(`Unknown Flagsmith project: ${choice}
|
|
3375
|
+
`);
|
|
3376
|
+
return 2;
|
|
3377
|
+
}
|
|
3378
|
+
project = selected.id;
|
|
3379
|
+
const discovered = await discovery.listEnvironments(selected.id);
|
|
3380
|
+
if (discovered.length === 0) {
|
|
3381
|
+
throw new Error("No environments found for the selected project");
|
|
3382
|
+
}
|
|
3383
|
+
stdout("\nEnvironments:\n");
|
|
3384
|
+
discovered.forEach((environment) => {
|
|
3385
|
+
stdout(` ${environment.name} (key ${environment.apiKey})
|
|
3386
|
+
`);
|
|
3387
|
+
});
|
|
3388
|
+
knownTargets = discovered.flatMap((environment) => [environment.name, environment.apiKey]);
|
|
3389
|
+
const suggested = discovered.map((environment) => `${suggestedAlias(environment.name)}=${environment.name}`).join(", ");
|
|
3390
|
+
environments = parseMapping(await prompt(`Environment aliases (alias=Flagsmith name; bare names use title case) [${suggested}]: `, { default: suggested }));
|
|
3391
|
+
} catch (error) {
|
|
3392
|
+
stderr(`Flagsmith sync failed: ${redact(errorMessage(error), [token])}
|
|
3393
|
+
`);
|
|
3394
|
+
stderr("Enter the project and environments manually.\n");
|
|
3395
|
+
project = await prompt("Flagsmith project (id or name): ");
|
|
3396
|
+
environments = parseMapping(await prompt(`Environment aliases (e.g. ${defaultMapping}; bare names use title case) [${defaultMapping}]: `, { default: defaultMapping }));
|
|
3397
|
+
}
|
|
3398
|
+
} else {
|
|
3399
|
+
project = await prompt("Flagsmith project (id or name): ");
|
|
3400
|
+
environments = parseMapping(await prompt(`Environment aliases (e.g. ${defaultMapping}; bare names use title case) [${defaultMapping}]: `, { default: defaultMapping }));
|
|
3401
|
+
}
|
|
3402
|
+
const projectValue = String(project).trim();
|
|
3403
|
+
if (projectValue === "") {
|
|
3404
|
+
stderr("A Flagsmith project is required.\n");
|
|
3405
|
+
return 2;
|
|
3406
|
+
}
|
|
3407
|
+
if (Object.keys(environments).length === 0) {
|
|
3408
|
+
stderr("At least one environment alias is required (e.g. development=Development).\n");
|
|
3409
|
+
return 2;
|
|
3410
|
+
}
|
|
3411
|
+
for (const [alias, target] of Object.entries(environments)) {
|
|
3412
|
+
if (knownTargets.length > 0 && !knownTargets.includes(target)) {
|
|
3413
|
+
stdout(`Warning: '${alias}' maps to '${target}', which was not returned by Flagsmith.
|
|
3414
|
+
Use the exact environment name or client key shown above.
|
|
3415
|
+
`);
|
|
3416
|
+
}
|
|
3417
|
+
}
|
|
3418
|
+
stdout(`
|
|
3419
|
+
Environment aliases: ${Object.entries(environments).map(([alias, target]) => `${alias} -> ${target}`).join(", ")}
|
|
3420
|
+
`);
|
|
3421
|
+
const config = {
|
|
3422
|
+
version: 1,
|
|
3423
|
+
repository: { root, include, exclude },
|
|
3424
|
+
flagsmith: { baseUrl, project: projectValue, environments }
|
|
3425
|
+
};
|
|
3426
|
+
try {
|
|
3427
|
+
await writeFile3(configPath, formatFlagdoctorConfig(config), "utf8");
|
|
3428
|
+
} catch (error) {
|
|
3429
|
+
stderr(`Could not write configuration: ${errorMessage(error)}
|
|
3430
|
+
`);
|
|
3431
|
+
return 2;
|
|
3432
|
+
}
|
|
3433
|
+
stdout(`
|
|
3434
|
+
Configuration written to ${path3.relative(cwd, configPath)}.
|
|
3435
|
+
`);
|
|
3436
|
+
stdout(`Next: run.bat scan --env ${Object.keys(environments)[0] ?? "development"}
|
|
3437
|
+
`);
|
|
3438
|
+
return 0;
|
|
3439
|
+
}
|
|
3440
|
+
|
|
3441
|
+
// packages/cli/dist/sync.js
|
|
3442
|
+
async function authorizedFetch(credential, path5, init, deps) {
|
|
3443
|
+
const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
|
|
3444
|
+
return fetchImpl(`${credential.apiUrl}${path5}`, {
|
|
3445
|
+
...init,
|
|
3446
|
+
headers: {
|
|
3447
|
+
"Content-Type": "application/json",
|
|
3448
|
+
...init.headers,
|
|
3449
|
+
Authorization: `Bearer ${credential.token}`
|
|
3450
|
+
},
|
|
3451
|
+
signal: AbortSignal.timeout(15e3)
|
|
3452
|
+
});
|
|
3453
|
+
}
|
|
3454
|
+
async function failureReason(response) {
|
|
3455
|
+
const body = await response.json().catch(() => null);
|
|
3456
|
+
if (response.status === 401)
|
|
3457
|
+
return "login expired \u2014 run `flagdoctor login`";
|
|
3458
|
+
return body?.error?.message ?? `HTTP ${response.status}`;
|
|
3459
|
+
}
|
|
3460
|
+
async function syncReport(kind, report, deps) {
|
|
3461
|
+
if (deps.enabled === false)
|
|
3462
|
+
return { kind: "skipped", reason: "disabled with --no-sync" };
|
|
3463
|
+
const credential = await readCliCredential(deps.env);
|
|
3464
|
+
if (!credential)
|
|
3465
|
+
return { kind: "skipped", reason: "run `flagdoctor login` to sync reports to the dashboard" };
|
|
3466
|
+
try {
|
|
3467
|
+
const response = await authorizedFetch(credential, "/api/v1/cli/scans", { method: "POST", body: JSON.stringify({ kind, report }) }, deps);
|
|
3468
|
+
if (!response.ok)
|
|
3469
|
+
return { kind: "failed", reason: await failureReason(response) };
|
|
3470
|
+
const payload = await response.json();
|
|
3471
|
+
const web = webBaseUrl(deps.env, credential.apiUrl);
|
|
3472
|
+
return { kind: "synced", scanId: payload.scan.id, url: `${web}/scans/${payload.scan.id}` };
|
|
3473
|
+
} catch (error) {
|
|
3474
|
+
return {
|
|
3475
|
+
kind: "failed",
|
|
3476
|
+
reason: redact(errorMessage(error), [credential.token])
|
|
3477
|
+
};
|
|
3478
|
+
}
|
|
3479
|
+
}
|
|
3480
|
+
async function fetchProjectConfig(deps) {
|
|
3481
|
+
const credential = await readCliCredential(deps.env);
|
|
3482
|
+
if (!credential)
|
|
3483
|
+
return null;
|
|
3484
|
+
try {
|
|
3485
|
+
const response = await authorizedFetch(credential, "/api/v1/cli/project-config", { method: "GET" }, deps);
|
|
3486
|
+
return response.ok ? await response.json() : null;
|
|
3487
|
+
} catch {
|
|
3488
|
+
return null;
|
|
3489
|
+
}
|
|
3490
|
+
}
|
|
3491
|
+
async function pushProjectConfig(input, deps) {
|
|
3492
|
+
const credential = await readCliCredential(deps.env);
|
|
3493
|
+
if (!credential)
|
|
3494
|
+
return { kind: "skipped", reason: "run `flagdoctor login` to save this setup to your project" };
|
|
3495
|
+
try {
|
|
3496
|
+
const response = await authorizedFetch(credential, "/api/v1/cli/project-config", { method: "PUT", body: JSON.stringify({ environments: input.environments }) }, deps);
|
|
3497
|
+
if (!response.ok)
|
|
3498
|
+
return { kind: "failed", reason: await failureReason(response) };
|
|
3499
|
+
return { kind: "synced", scanId: "config", url: "" };
|
|
3500
|
+
} catch (error) {
|
|
3501
|
+
return { kind: "failed", reason: redact(errorMessage(error), [credential.token]) };
|
|
3502
|
+
}
|
|
3503
|
+
}
|
|
3504
|
+
function webBaseUrl(env, apiUrl) {
|
|
3505
|
+
const explicit = env.FLAGDOCTOR_WEB_URL?.trim();
|
|
3506
|
+
if (explicit)
|
|
3507
|
+
return explicit.replace(/\/+$/, "");
|
|
3508
|
+
const local = /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(apiUrl);
|
|
3509
|
+
return local ? "http://localhost:5173" : apiUrl.replace(/\/+$/, "");
|
|
3510
|
+
}
|
|
3511
|
+
|
|
3512
|
+
// packages/cli/dist/ui/components.js
|
|
3513
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3514
|
+
import { useEffect, useState } from "react";
|
|
3515
|
+
import { Box, Text } from "ink";
|
|
3516
|
+
var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
3517
|
+
function Spinner({ label }) {
|
|
3518
|
+
const [frame, setFrame] = useState(0);
|
|
3519
|
+
const [seconds, setSeconds] = useState(0);
|
|
3520
|
+
useEffect(() => {
|
|
3521
|
+
const started = Date.now();
|
|
3522
|
+
const timer = setInterval(() => {
|
|
3523
|
+
setFrame((current) => (current + 1) % FRAMES.length);
|
|
3524
|
+
setSeconds(Math.floor((Date.now() - started) / 1e3));
|
|
3525
|
+
}, 80);
|
|
3526
|
+
return () => clearInterval(timer);
|
|
3527
|
+
}, []);
|
|
3528
|
+
return _jsxs(Text, { children: [_jsx(Text, { color: "cyan", children: FRAMES[frame] }), " ", label, seconds >= 2 ? _jsxs(Text, { dimColor: true, children: [" (", seconds, "s)"] }) : null] });
|
|
3529
|
+
}
|
|
3530
|
+
function Banner({ title, subtitle }) {
|
|
3531
|
+
return _jsxs(Box, { marginBottom: 1, children: [_jsx(Text, { bold: true, color: "green", children: "\u25C9 FlagDoctor" }), _jsxs(Text, { bold: true, children: [" ", title] }), subtitle ? _jsxs(Text, { dimColor: true, children: [" \xB7 ", subtitle] }) : null] });
|
|
3532
|
+
}
|
|
3533
|
+
function Badge({ color, children }) {
|
|
3534
|
+
return _jsx(Text, { color, bold: true, children });
|
|
3535
|
+
}
|
|
3536
|
+
function Panel({ title, color = "gray", children }) {
|
|
3537
|
+
return _jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: color, paddingX: 1, marginBottom: 1, children: [title ? _jsx(Text, { bold: true, color: color === "gray" ? void 0 : color, children: title }) : null, children] });
|
|
3538
|
+
}
|
|
3539
|
+
function KeyValue({ label, children }) {
|
|
3540
|
+
return _jsxs(Box, { children: [_jsx(Box, { width: 13, children: _jsx(Text, { dimColor: true, children: label }) }), _jsx(Text, { children })] });
|
|
3541
|
+
}
|
|
3542
|
+
function Stat({ label, value, color }) {
|
|
3543
|
+
return _jsxs(Box, { marginRight: 3, children: [_jsx(Text, { color, bold: true, children: value }), _jsxs(Text, { dimColor: true, children: [" ", label] })] });
|
|
3544
|
+
}
|
|
3545
|
+
function SyncNote({ state }) {
|
|
3546
|
+
if (state.kind === "synced") {
|
|
3547
|
+
return _jsxs(Text, { children: [_jsx(Text, { color: "green", children: "\u2714" }), " Synced to FlagDoctor ", _jsxs(Text, { dimColor: true, children: ["(", state.scanId.slice(0, 8), ")"] }), "\n", _jsxs(Text, { dimColor: true, children: [" View it in the dashboard: ", state.url] })] });
|
|
3548
|
+
}
|
|
3549
|
+
if (state.kind === "failed") {
|
|
3550
|
+
return _jsxs(Text, { children: [_jsx(Text, { color: "yellow", children: "\u25B2" }), " Not synced: ", state.reason] });
|
|
3551
|
+
}
|
|
3552
|
+
return _jsxs(Text, { dimColor: true, children: ["\u25CB Not synced: ", state.reason] });
|
|
3553
|
+
}
|
|
3554
|
+
|
|
3555
|
+
// packages/cli/dist/ui/DependencyTreeView.js
|
|
3556
|
+
import { jsx as _jsx2, jsxs as _jsxs2, Fragment as _Fragment } from "react/jsx-runtime";
|
|
3557
|
+
import { Box as Box2, Text as Text2 } from "ink";
|
|
3558
|
+
|
|
3559
|
+
// packages/cli/dist/ui/theme.js
|
|
3560
|
+
var SEVERITY_COLOR = {
|
|
3561
|
+
error: "red",
|
|
3562
|
+
warning: "yellow",
|
|
3563
|
+
info: "cyan"
|
|
3564
|
+
};
|
|
3565
|
+
var SEVERITY_ICON = {
|
|
3566
|
+
error: "\u2716",
|
|
3567
|
+
warning: "\u25B2",
|
|
3568
|
+
info: "\u25CF"
|
|
3569
|
+
};
|
|
3570
|
+
var STATUS_COLOR = {
|
|
3571
|
+
matched: "green",
|
|
3572
|
+
missing: "red",
|
|
3573
|
+
archived: "yellow",
|
|
3574
|
+
dynamic: "cyan",
|
|
3575
|
+
unknown: "gray"
|
|
3576
|
+
};
|
|
3577
|
+
var STATUS_ICON = {
|
|
3578
|
+
matched: "\u2714",
|
|
3579
|
+
missing: "\u2716",
|
|
3580
|
+
archived: "\u25B2",
|
|
3581
|
+
dynamic: "?",
|
|
3582
|
+
unknown: "\xB7"
|
|
3583
|
+
};
|
|
3584
|
+
var LAYER_COLOR = {
|
|
3585
|
+
controller: "cyan",
|
|
3586
|
+
service: "green",
|
|
3587
|
+
repository: "magenta",
|
|
3588
|
+
model: "yellow",
|
|
3589
|
+
component: "blue",
|
|
3590
|
+
other: "gray"
|
|
3591
|
+
};
|
|
3592
|
+
var SCAN_STATUS_COLOR = {
|
|
3593
|
+
completed: "green",
|
|
3594
|
+
partial: "yellow",
|
|
3595
|
+
failed: "red"
|
|
3596
|
+
};
|
|
3597
|
+
function terminalColumns(stream = process.stdout) {
|
|
3598
|
+
return Math.max(60, Math.min(stream.columns ?? 100, 140));
|
|
3599
|
+
}
|
|
3600
|
+
|
|
3601
|
+
// packages/cli/dist/ui/DependencyTreeView.js
|
|
3602
|
+
function groupBy2(items, key) {
|
|
3603
|
+
const map = /* @__PURE__ */ new Map();
|
|
3604
|
+
for (const item of items) {
|
|
3605
|
+
const existing = map.get(key(item));
|
|
3606
|
+
if (existing)
|
|
3607
|
+
existing.push(item);
|
|
3608
|
+
else
|
|
3609
|
+
map.set(key(item), [item]);
|
|
3610
|
+
}
|
|
3611
|
+
return Array.from(map.entries());
|
|
3612
|
+
}
|
|
3613
|
+
function symbol(node) {
|
|
3614
|
+
return node.className ? `${node.className}.${node.functionName}()` : `${node.functionName}()`;
|
|
3615
|
+
}
|
|
3616
|
+
function ImpactLine({ node, arrow }) {
|
|
3617
|
+
return _jsxs2(Text2, { children: [" ".repeat(node.depth - 1), _jsx2(Text2, { dimColor: true, children: arrow }), " ", _jsx2(Badge, { color: LAYER_COLOR[node.layer], children: node.layer }), " ", symbol(node), _jsxs2(Text2, { dimColor: true, children: [" ", node.filePath] })] });
|
|
3618
|
+
}
|
|
3619
|
+
function ImpactBlock({ title, arrow, nodes, emptyText }) {
|
|
3620
|
+
if (nodes.length === 0 && !emptyText)
|
|
3621
|
+
return null;
|
|
3622
|
+
return _jsxs2(Box2, { flexDirection: "column", marginLeft: 2, children: [_jsx2(Text2, { dimColor: true, children: title }), nodes.length === 0 ? _jsxs2(Text2, { color: "yellow", children: [" ", emptyText] }) : nodes.map((node, index) => _jsx2(ImpactLine, { node, arrow }, index))] });
|
|
3623
|
+
}
|
|
3624
|
+
function SiteView({ site }) {
|
|
3625
|
+
return _jsxs2(Box2, { flexDirection: "column", marginLeft: 2, children: [_jsxs2(Text2, { children: [_jsx2(Text2, { dimColor: true, children: "\u2514\u2500 " }), site.enclosingFunction ? _jsxs2(Text2, { bold: true, children: [site.enclosingFunction, "()"] }) : _jsx2(Text2, { dimColor: true, children: "module scope" }), _jsxs2(Text2, { dimColor: true, children: [" ", site.method, " \u2192 ", site.expectedType, " [", site.resolution, "] L", site.line] })] }), _jsx2(ImpactBlock, { title: "called by", arrow: "\u2191", nodes: site.callers, emptyText: site.enclosingFunction ? `none found \u2014 nothing in the scanned code calls ${site.enclosingFunction}()` : void 0 }), _jsx2(ImpactBlock, { title: "in that flow, the caller also uses", arrow: "\u2192", nodes: site.flow }), _jsx2(ImpactBlock, { title: "calls", arrow: "\u2193", nodes: site.callees })] });
|
|
3626
|
+
}
|
|
3627
|
+
function FlagView({ dependency }) {
|
|
3628
|
+
const color = STATUS_COLOR[dependency.status];
|
|
3629
|
+
return _jsxs2(Box2, { flexDirection: "column", marginBottom: 1, children: [_jsxs2(Text2, { children: [_jsx2(Badge, { color, children: STATUS_ICON[dependency.status] }), " ", _jsx2(Text2, { bold: true, children: dependency.flagName ?? "unresolved dynamic reference" }), _jsxs2(Text2, { color, children: [" ", dependency.status] })] }), groupBy2(dependency.sites, (site) => site.filePath).map(([file, sites]) => _jsxs2(Box2, { flexDirection: "column", marginLeft: 2, children: [_jsx2(Text2, { color: "blue", children: file }), groupBy2(sites, (site) => site.enclosingClass).map(([className, classSites]) => _jsxs2(Box2, { flexDirection: "column", marginLeft: 2, children: [className ? _jsxs2(Text2, { children: [_jsx2(Text2, { dimColor: true, children: "class " }), _jsx2(Text2, { bold: true, color: "magenta", children: className })] }) : null, classSites.map((site, index) => _jsx2(SiteView, { site }, index))] }, className ?? "(module)"))] }, file)), dependency.relatedCode.length > 0 ? _jsxs2(Box2, { flexDirection: "column", marginLeft: 2, children: [_jsx2(Text2, { dimColor: true, children: "related code \u2014 inferred from the flag name, not from calls" }), dependency.relatedCode.map((related) => _jsxs2(Text2, { children: [_jsx2(Text2, { dimColor: true, children: "~ " }), _jsx2(Badge, { color: LAYER_COLOR[related.layer], children: related.layer }), " ", related.className ?? related.filePath, _jsxs2(Text2, { dimColor: true, children: [related.functions.length > 0 ? ` ${related.functions.map((fn) => `${fn}()`).join(", ")}` : "", " ", "(", related.matchedTerms.join(", "), ")"] })] }, `${related.filePath}#${related.className ?? ""}`))] }) : null] });
|
|
3630
|
+
}
|
|
3631
|
+
function DependencyTreeView({ dependencies, environment }) {
|
|
3632
|
+
const sites = dependencies.reduce((sum, dependency) => sum + dependency.sites.length, 0);
|
|
3633
|
+
const count = (status) => dependencies.filter((dependency) => dependency.status === status).length;
|
|
3634
|
+
return _jsxs2(Box2, { flexDirection: "column", children: [_jsx2(Banner, { title: "flag dependency map", subtitle: environment }), dependencies.length === 0 ? _jsx2(Text2, { color: "yellow", children: "No flag dependencies were found in the scanned sources." }) : _jsxs2(_Fragment, { children: [_jsxs2(Box2, { marginBottom: 1, children: [_jsx2(Stat, { label: "flags", value: dependencies.length, color: "white" }), _jsx2(Stat, { label: "usage sites", value: sites, color: "white" }), _jsx2(Stat, { label: "matched", value: count("matched"), color: "green" }), _jsx2(Stat, { label: "missing", value: count("missing"), color: count("missing") > 0 ? "red" : "gray" }), _jsx2(Stat, { label: "archived", value: count("archived"), color: count("archived") > 0 ? "yellow" : "gray" }), _jsx2(Stat, { label: "dynamic", value: count("dynamic"), color: "cyan" })] }), dependencies.map((dependency) => _jsx2(FlagView, { dependency }, dependency.flagKey))] })] });
|
|
3635
|
+
}
|
|
3636
|
+
|
|
3637
|
+
// packages/cli/dist/ui/render.js
|
|
3638
|
+
import { jsx as _jsx3 } from "react/jsx-runtime";
|
|
3639
|
+
import { render, renderToString } from "ink";
|
|
3640
|
+
function liveOptions(output) {
|
|
3641
|
+
return { patchConsole: false, ...output.stream ? { stdout: output.stream } : {} };
|
|
3642
|
+
}
|
|
3643
|
+
function present(element, output) {
|
|
3644
|
+
const text = renderToString(element, { columns: terminalColumns(output.stream) });
|
|
3645
|
+
output.stdout(`${text}
|
|
3646
|
+
`);
|
|
3647
|
+
}
|
|
3648
|
+
async function withSpinner(label, task, output) {
|
|
3649
|
+
if (!output.interactive)
|
|
3650
|
+
return task();
|
|
3651
|
+
const instance = render(_jsx3(Spinner, { label }), liveOptions(output));
|
|
3652
|
+
try {
|
|
3653
|
+
return await task();
|
|
3654
|
+
} finally {
|
|
3655
|
+
instance.unmount();
|
|
3656
|
+
await instance.waitUntilExit().catch(() => void 0);
|
|
3657
|
+
}
|
|
3658
|
+
}
|
|
3659
|
+
function liveScreen(initial, output) {
|
|
3660
|
+
if (!output.interactive) {
|
|
3661
|
+
return {
|
|
3662
|
+
update() {
|
|
3663
|
+
},
|
|
3664
|
+
close(final) {
|
|
3665
|
+
present(final, output);
|
|
3666
|
+
}
|
|
3667
|
+
};
|
|
3668
|
+
}
|
|
3669
|
+
const instance = render(initial, liveOptions(output));
|
|
3670
|
+
return {
|
|
3671
|
+
update(next) {
|
|
3672
|
+
instance.rerender(next);
|
|
3673
|
+
},
|
|
3674
|
+
close(final) {
|
|
3675
|
+
instance.rerender(final);
|
|
3676
|
+
instance.unmount();
|
|
3677
|
+
}
|
|
3678
|
+
};
|
|
3679
|
+
}
|
|
3680
|
+
|
|
3681
|
+
// packages/cli/dist/ui/ScanReportView.js
|
|
3682
|
+
import { jsxs as _jsxs3, jsx as _jsx4 } from "react/jsx-runtime";
|
|
3683
|
+
import { Box as Box3, Text as Text3 } from "ink";
|
|
3684
|
+
function groupByFile(findings) {
|
|
3685
|
+
const groups = /* @__PURE__ */ new Map();
|
|
3686
|
+
for (const finding of findings) {
|
|
3687
|
+
const key = finding.filePath ?? "(no source location)";
|
|
3688
|
+
const existing = groups.get(key);
|
|
3689
|
+
if (existing)
|
|
3690
|
+
existing.push(finding);
|
|
3691
|
+
else
|
|
3692
|
+
groups.set(key, [finding]);
|
|
3693
|
+
}
|
|
3694
|
+
return Array.from(groups.entries()).sort(([a], [b]) => a.localeCompare(b));
|
|
3695
|
+
}
|
|
3696
|
+
function FindingRow({ finding }) {
|
|
3697
|
+
const color = SEVERITY_COLOR[finding.severity];
|
|
3698
|
+
const location = finding.line ? `:${finding.line}${finding.column ? `:${finding.column}` : ""}` : "";
|
|
3699
|
+
return _jsxs3(Box3, { flexDirection: "column", marginLeft: 2, marginBottom: 1, children: [_jsxs3(Text3, { children: [_jsxs3(Badge, { color, children: [SEVERITY_ICON[finding.severity], " ", finding.ruleId] }), " ", _jsx4(Text3, { bold: true, children: finding.flagName ?? "(dynamic reference)" }), _jsxs3(Text3, { dimColor: true, children: [location, " \xB7 ", finding.severity, "/", finding.confidence, finding.origin === "llm" ? " \xB7 AI-assisted" : ""] })] }), _jsxs3(Box3, { marginLeft: 2, flexDirection: "column", children: [_jsx4(Text3, { children: finding.message }), finding.suggestion ? _jsxs3(Text3, { color: "green", children: ["\u2192 ", finding.suggestion] }) : null, _jsxs3(Text3, { dimColor: true, children: ["id ", finding.id] })] })] });
|
|
3700
|
+
}
|
|
3701
|
+
function ScanReportView({ report, aiSummary }) {
|
|
3702
|
+
const statusColor = SCAN_STATUS_COLOR[report.status];
|
|
3703
|
+
const { summary } = report;
|
|
3704
|
+
return _jsxs3(Box3, { flexDirection: "column", children: [_jsx4(Banner, { title: "scan", subtitle: report.environment }), _jsxs3(Panel, { color: statusColor, children: [_jsx4(KeyValue, { label: "Status", children: _jsx4(Badge, { color: statusColor, children: report.status.toUpperCase() }) }), _jsx4(KeyValue, { label: "Project", children: report.project ? `${report.project.name} (#${report.project.id})` : "n/a" }), _jsx4(KeyValue, { label: "Repository", children: report.repository ?? "n/a" }), _jsx4(KeyValue, { label: "Commit", children: report.commit ?? "n/a" }), _jsxs3(KeyValue, { label: "Files", children: [summary.scannedFiles, " scanned \xB7 ", summary.skippedFiles, " skipped"] }), _jsx4(KeyValue, { label: "Flags found", children: report.dependencies.length }), _jsxs3(Box3, { marginTop: 1, children: [_jsx4(Stat, { label: "errors", value: summary.errors, color: summary.errors > 0 ? "red" : "green" }), _jsx4(Stat, { label: "warnings", value: summary.warnings, color: summary.warnings > 0 ? "yellow" : "green" }), _jsx4(Stat, { label: "info", value: summary.info, color: "cyan" })] })] }), report.status === "partial" ? _jsxs3(Text3, { color: "yellow", children: ["\u25B2 Scan incomplete: ", report.diagnostics.length, " source diagnostic(s); findings may be incomplete.", "\n"] }) : null, report.error ? _jsxs3(Text3, { color: "red", children: ["\u2716 Scan failed (", report.error.kind, "): ", report.error.message, "\n"] }) : null, aiSummary ? _jsx4(Panel, { title: `AI review \xB7 ${aiSummary.model}`, color: "magenta", children: _jsx4(Text3, { children: aiSummary.text || "The model returned no summary." }) }) : null, report.findings.length === 0 && report.status === "completed" ? _jsx4(Text3, { color: "green", children: "\u2714 No findings \u2014 code and Flagsmith configuration agree." }) : null, groupByFile(report.findings).map(([file, findings]) => _jsxs3(Box3, { flexDirection: "column", marginBottom: 1, children: [_jsx4(Text3, { bold: true, underline: true, children: file }), findings.map((finding) => _jsx4(FindingRow, { finding }, finding.id))] }, file)), report.diagnostics.length > 0 ? _jsxs3(Box3, { flexDirection: "column", children: [_jsxs3(Text3, { bold: true, children: ["Diagnostics (", report.diagnostics.length, ")"] }), report.diagnostics.map((diagnostic, index) => _jsxs3(Text3, { dimColor: true, children: [diagnostic.filePath, ":", diagnostic.line, ":", diagnostic.column, " ", diagnostic.kind, ": ", diagnostic.message] }, index))] }) : null] });
|
|
3705
|
+
}
|
|
3706
|
+
|
|
3707
|
+
// packages/cli/dist/ui/showSplash.js
|
|
3708
|
+
import { jsx as _jsx6 } from "react/jsx-runtime";
|
|
3709
|
+
import { render as render2 } from "ink";
|
|
3710
|
+
|
|
3711
|
+
// packages/cli/dist/ui/Splash.js
|
|
3712
|
+
import { jsx as _jsx5, jsxs as _jsxs4 } from "react/jsx-runtime";
|
|
3713
|
+
import { useEffect as useEffect2, useState as useState2 } from "react";
|
|
3714
|
+
import { Box as Box4, Text as Text4 } from "ink";
|
|
3715
|
+
var TITLE = "FlagDoctor";
|
|
3716
|
+
var TAGLINE = "Does your code agree with your Flagsmith configuration?";
|
|
3717
|
+
var PALETTE = ["green", "greenBright", "cyan", "cyanBright", "greenBright"];
|
|
3718
|
+
var TAGLINE_AT = TITLE.length;
|
|
3719
|
+
var PANEL_AT = TITLE.length + 3;
|
|
3720
|
+
var SPLASH_FINAL_TICK = PANEL_AT + 4;
|
|
3721
|
+
var SPLASH_TICK_MS = 70;
|
|
3722
|
+
var COMMANDS = [
|
|
3723
|
+
["login", "sign in through your browser"],
|
|
3724
|
+
["init", "create flagdoctor.yaml for this repository"],
|
|
3725
|
+
["scan --env <name>", "compare code with Flagsmith"],
|
|
3726
|
+
["graph --env <name>", "which code each flag affects"],
|
|
3727
|
+
["analyze --env <name>", "AI review for misconfigurations"],
|
|
3728
|
+
["whoami", "show the connected project"]
|
|
3729
|
+
];
|
|
3730
|
+
function flagRows(tick) {
|
|
3731
|
+
const wave = tick % 4;
|
|
3732
|
+
const top = ["\u259B\u2580\u2580\u2580\u259C", "\u259B\u2580\u2580\u2580\u2580", "\u259C\u2580\u2580\u2580\u259B", "\u2580\u2580\u2580\u2580\u259C"][wave];
|
|
3733
|
+
const bottom = ["\u2599\u2584\u2584\u2584\u259F", "\u2599\u2584\u2584\u2584\u2584", "\u259F\u2584\u2584\u2584\u2599", "\u2584\u2584\u2584\u2584\u259F"][wave];
|
|
3734
|
+
return [`\u2503${top}`, `\u2503${bottom}`, "\u2503"];
|
|
3735
|
+
}
|
|
3736
|
+
function Splash({ info, animated = true, onDone }) {
|
|
3737
|
+
const [tick, setTick] = useState2(animated ? 0 : SPLASH_FINAL_TICK);
|
|
3738
|
+
useEffect2(() => {
|
|
3739
|
+
if (!animated)
|
|
3740
|
+
return;
|
|
3741
|
+
const timer = setInterval(() => {
|
|
3742
|
+
setTick((current) => Math.min(current + 1, SPLASH_FINAL_TICK));
|
|
3743
|
+
}, SPLASH_TICK_MS);
|
|
3744
|
+
return () => clearInterval(timer);
|
|
3745
|
+
}, [animated]);
|
|
3746
|
+
useEffect2(() => {
|
|
3747
|
+
if (tick >= SPLASH_FINAL_TICK)
|
|
3748
|
+
onDone?.();
|
|
3749
|
+
}, [tick, onDone]);
|
|
3750
|
+
const settled = tick >= SPLASH_FINAL_TICK;
|
|
3751
|
+
const color = settled ? "green" : PALETTE[tick % PALETTE.length];
|
|
3752
|
+
const [rowOne, rowTwo, rowThree] = flagRows(settled ? 0 : tick);
|
|
3753
|
+
const typed = TITLE.slice(0, Math.min(tick, TITLE.length));
|
|
3754
|
+
return _jsxs4(Box4, { flexDirection: "column", marginBottom: 1, children: [_jsxs4(Box4, { children: [_jsxs4(Box4, { flexDirection: "column", marginRight: 2, children: [_jsx5(Text4, { color, bold: true, children: rowOne }), _jsx5(Text4, { color, bold: true, children: rowTwo }), _jsx5(Text4, { color, children: rowThree }), _jsx5(Text4, { color, children: rowThree })] }), _jsxs4(Box4, { flexDirection: "column", justifyContent: "center", children: [_jsxs4(Text4, { bold: true, children: [typed, !settled && typed.length < TITLE.length ? _jsx5(Text4, { color: "green", children: "\u258C" }) : null] }), tick >= TAGLINE_AT ? _jsx5(Text4, { dimColor: true, children: TAGLINE }) : null, tick >= TAGLINE_AT ? _jsxs4(Text4, { dimColor: true, children: ["v", info.version] }) : null] })] }), tick >= PANEL_AT ? _jsxs4(Box4, { flexDirection: "column", borderStyle: "round", borderColor: "green", paddingX: 1, marginTop: 1, children: [_jsxs4(Text4, { children: [_jsx5(Text4, { dimColor: true, children: "folder " }), info.cwd] }), _jsxs4(Text4, { children: [_jsx5(Text4, { dimColor: true, children: "api " }), info.apiUrl, " \xB7", " ", info.loggedIn ? _jsx5(Text4, { color: "green", children: "logged in" }) : _jsx5(Text4, { color: "yellow", children: "not logged in" })] }), _jsxs4(Box4, { flexDirection: "column", marginTop: 1, children: [_jsx5(Text4, { bold: true, children: info.commands ? "Commands" : "Next steps" }), (info.commands ? COMMANDS : COMMANDS.slice(0, 4)).map(([command, summary]) => _jsxs4(Text4, { children: [_jsxs4(Text4, { color: "cyan", children: ["flagdoctor ", command] }), _jsxs4(Text4, { dimColor: true, children: [" \u2014 ", summary] })] }, command)), !info.loggedIn ? _jsx5(Text4, { color: "yellow", children: "Tip: run flagdoctor login so scans sync to your dashboard." }) : null] })] }) : null] });
|
|
3755
|
+
}
|
|
3756
|
+
|
|
3757
|
+
// packages/cli/dist/ui/showSplash.js
|
|
3758
|
+
async function showSplash(info, output, env = process.env) {
|
|
3759
|
+
if (!output.interactive || env.FLAGDOCTOR_NO_SPLASH)
|
|
3760
|
+
return false;
|
|
3761
|
+
let finished = () => void 0;
|
|
3762
|
+
const done = new Promise((resolve) => {
|
|
3763
|
+
finished = resolve;
|
|
3764
|
+
});
|
|
3765
|
+
const instance = render2(_jsx6(Splash, { info, onDone: finished }), {
|
|
3766
|
+
patchConsole: false,
|
|
3767
|
+
...output.stream ? { stdout: output.stream } : {}
|
|
3768
|
+
});
|
|
3769
|
+
const guard = setTimeout(finished, (SPLASH_FINAL_TICK + 10) * SPLASH_TICK_MS);
|
|
3770
|
+
await done;
|
|
3771
|
+
clearTimeout(guard);
|
|
3772
|
+
await new Promise((resolve) => setTimeout(resolve, SPLASH_TICK_MS));
|
|
3773
|
+
instance.unmount();
|
|
3774
|
+
await instance.waitUntilExit().catch(() => void 0);
|
|
3775
|
+
return true;
|
|
3776
|
+
}
|
|
3777
|
+
|
|
3778
|
+
// packages/cli/dist/ui/screens.js
|
|
3779
|
+
import { jsx as _jsx7, jsxs as _jsxs5, Fragment as _Fragment2 } from "react/jsx-runtime";
|
|
3780
|
+
import { Box as Box5, Text as Text5 } from "ink";
|
|
3781
|
+
function LoginView({ phase }) {
|
|
3782
|
+
return _jsxs5(Box5, { flexDirection: "column", children: [_jsx7(Banner, { title: "login" }), phase.kind === "starting" ? _jsx7(Spinner, { label: "Requesting a device code\u2026" }) : null, phase.kind === "waiting" ? _jsxs5(_Fragment2, { children: [_jsxs5(Panel, { title: "Approve this device", color: "cyan", children: [_jsxs5(Text5, { children: ["1. Open ", _jsx7(Text5, { color: "cyan", underline: true, children: phase.url })] }), _jsx7(Text5, { children: "2. Choose the project and enter this code:" }), _jsx7(Box5, { marginY: 1, marginLeft: 3, children: _jsx7(Text5, { bold: true, color: "green", children: phase.code }) })] }), _jsx7(Spinner, { label: "Waiting for browser approval\u2026" })] }) : null, phase.kind === "done" ? _jsxs5(Text5, { color: "green", children: ["\u2714 Logged in. Credential saved outside the repository.", "\n", _jsxs5(Text5, { dimColor: true, children: [" API: ", phase.apiUrl, " \u2014 reports from scan, graph and analyze now sync automatically."] })] }) : null, phase.kind === "error" ? _jsxs5(Text5, { color: "red", children: ["\u2716 Login failed: ", phase.message] }) : null] });
|
|
3783
|
+
}
|
|
3784
|
+
function WhoamiView({ email, project, apiUrl, flagsmith, codebases }) {
|
|
3785
|
+
return _jsxs5(Box5, { flexDirection: "column", children: [_jsx7(Banner, { title: "whoami" }), _jsxs5(Panel, { color: "green", children: [_jsx7(KeyValue, { label: "User", children: email }), _jsx7(KeyValue, { label: "Project", children: project }), _jsx7(KeyValue, { label: "API", children: apiUrl }), _jsx7(KeyValue, { label: "Flagsmith", children: _jsx7(Text5, { color: flagsmith ? "green" : "yellow", children: flagsmith ? "connected" : "not connected" }) }), _jsx7(KeyValue, { label: "Codebases", children: codebases })] })] });
|
|
3786
|
+
}
|
|
3787
|
+
function InitView({ configPath, fromProject, environments, sync }) {
|
|
3788
|
+
return _jsxs5(Box5, { flexDirection: "column", children: [_jsx7(Banner, { title: "init" }), _jsxs5(Panel, { color: "green", children: [_jsx7(KeyValue, { label: "Created", children: configPath }), _jsx7(KeyValue, { label: "Source", children: fromProject ? `project \u201C${fromProject}\u201D (from your FlagDoctor account)` : "starter template" }), _jsx7(KeyValue, { label: "Environments", children: environments.length > 0 ? environments.join(", ") : "none" })] }), _jsx7(SyncNote, { state: sync }), _jsxs5(Box5, { flexDirection: "column", marginTop: 1, children: [_jsx7(Text5, { bold: true, children: "Next steps" }), _jsxs5(Text5, { children: [_jsx7(Text5, { dimColor: true, children: "1." }), " Set ", _jsx7(Text5, { color: "cyan", children: "FLAGSMITH_TOKEN" }), " in your environment (never in flagdoctor.yaml)"] }), _jsxs5(Text5, { children: [_jsx7(Text5, { dimColor: true, children: "2." }), " ", _jsxs5(Text5, { color: "cyan", children: ["flagdoctor scan --env ", environments[0] ?? "production"] })] }), _jsxs5(Text5, { children: [_jsx7(Text5, { dimColor: true, children: "3." }), " ", _jsxs5(Text5, { color: "cyan", children: ["flagdoctor graph --env ", environments[0] ?? "production"] })] })] })] });
|
|
3789
|
+
}
|
|
3790
|
+
|
|
3791
|
+
// packages/cli/dist/index.js
|
|
3792
|
+
var CLI_PHASE = "phase-1c";
|
|
3793
|
+
function describeCli() {
|
|
3794
|
+
return `@flagdoctor/cli (${CLI_PHASE}: init and scan)`;
|
|
3795
|
+
}
|
|
3796
|
+
var INIT_YAML = `# FlagDoctor configuration (no secrets belong in this file)
|
|
3797
|
+
version: 1
|
|
3798
|
+
repository:
|
|
3799
|
+
root: .
|
|
3800
|
+
include: []
|
|
3801
|
+
exclude: []
|
|
3802
|
+
flagsmith:
|
|
3803
|
+
baseUrl: https://api.flagsmith.com/api/v1
|
|
3804
|
+
project: your-project-id-or-name
|
|
3805
|
+
environments:
|
|
3806
|
+
development: Development
|
|
3807
|
+
production: Production
|
|
3808
|
+
`;
|
|
3809
|
+
function buildInitYaml(project) {
|
|
3810
|
+
if (!project?.flagsmith)
|
|
3811
|
+
return INIT_YAML;
|
|
3812
|
+
const environments = Object.entries(project.environments);
|
|
3813
|
+
const lines = environments.length ? environments.map(([alias, name]) => ` ${alias}: ${name}`) : [" development: Development", " production: Production"];
|
|
3814
|
+
return `# FlagDoctor configuration (no secrets belong in this file)
|
|
3815
|
+
# Prefilled from your FlagDoctor project${project.projectName ? ` \u201C${project.projectName}\u201D` : ""}.
|
|
3816
|
+
version: 1
|
|
3817
|
+
repository:
|
|
3818
|
+
root: .
|
|
3819
|
+
include: []
|
|
3820
|
+
exclude: []
|
|
3821
|
+
flagsmith:
|
|
3822
|
+
baseUrl: ${project.flagsmith.baseUrl}
|
|
3823
|
+
project: ${project.flagsmith.projectRef}
|
|
3824
|
+
environments:
|
|
3825
|
+
${lines.join("\n")}
|
|
3826
|
+
`;
|
|
3827
|
+
}
|
|
3828
|
+
function cliVersion() {
|
|
3829
|
+
try {
|
|
3830
|
+
const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
3831
|
+
return typeof manifest.version === "string" ? manifest.version : "dev";
|
|
3832
|
+
} catch {
|
|
3833
|
+
return "dev";
|
|
3834
|
+
}
|
|
3835
|
+
}
|
|
3836
|
+
async function wait(milliseconds) {
|
|
3837
|
+
await new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
3838
|
+
}
|
|
3839
|
+
function uiFor(deps, stdout, plainRequested = false) {
|
|
3840
|
+
return {
|
|
3841
|
+
stdout,
|
|
3842
|
+
interactive: deps.plain !== true && !plainRequested && Boolean(process.stdout.isTTY) && Boolean(process.stdin.isTTY)
|
|
3843
|
+
};
|
|
3844
|
+
}
|
|
3845
|
+
async function runDeviceLogin(deps = {}) {
|
|
3846
|
+
const stdout = deps.stdout ?? ((text) => process.stdout.write(text));
|
|
3847
|
+
const stderr = deps.stderr ?? ((text) => process.stderr.write(text));
|
|
3848
|
+
const env = deps.env ?? process.env;
|
|
3849
|
+
const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
|
|
3850
|
+
const apiUrl = apiBaseUrl(env);
|
|
3851
|
+
const output = uiFor(deps, stdout);
|
|
3852
|
+
const screen = liveScreen(_jsx8(LoginView, { phase: { kind: "starting" } }), output);
|
|
3853
|
+
const finish = (phase) => {
|
|
3854
|
+
if (output.interactive)
|
|
3855
|
+
screen.close(_jsx8(LoginView, { phase }));
|
|
3856
|
+
else if (phase.kind === "done")
|
|
3857
|
+
stdout("Device authorized. Credential saved outside the repository.\n");
|
|
3858
|
+
};
|
|
3859
|
+
try {
|
|
3860
|
+
const response = await fetchImpl(`${apiUrl}/api/v1/cli/device/authorize`, { method: "POST" });
|
|
3861
|
+
if (!response.ok)
|
|
3862
|
+
throw new Error(`Device authorization failed with HTTP ${response.status}`);
|
|
3863
|
+
const device = await response.json();
|
|
3864
|
+
if (output.interactive) {
|
|
3865
|
+
screen.update(_jsx8(LoginView, { phase: { kind: "waiting", code: device.code, url: device.verificationUri } }));
|
|
3866
|
+
} else {
|
|
3867
|
+
stdout(`Open ${device.verificationUri} and approve this device code:
|
|
3868
|
+
|
|
3869
|
+
${device.code}
|
|
3870
|
+
|
|
3871
|
+
`);
|
|
3872
|
+
}
|
|
3873
|
+
if (process.platform === "win32" && deps.plain !== true) {
|
|
3874
|
+
const target = device.verificationUriComplete ?? device.verificationUri;
|
|
3875
|
+
spawn2("cmd", ["/c", "start", "", target], { detached: true, stdio: "ignore" }).unref();
|
|
3876
|
+
}
|
|
3877
|
+
const deadline = Date.now() + (device.expiresIn ?? 600) * 1e3;
|
|
3878
|
+
const interval = Math.max(1, device.interval ?? 5) * 1e3;
|
|
3879
|
+
while (Date.now() < deadline) {
|
|
3880
|
+
await wait(interval);
|
|
3881
|
+
const poll = await fetchImpl(`${apiUrl}/api/v1/cli/device/token`, {
|
|
3882
|
+
method: "POST",
|
|
3883
|
+
headers: { "Content-Type": "application/json" },
|
|
3884
|
+
body: JSON.stringify({ code: device.code })
|
|
3885
|
+
});
|
|
3886
|
+
if (poll.status === 400)
|
|
3887
|
+
throw new Error("Device code expired or was already used");
|
|
3888
|
+
if (!poll.ok)
|
|
3889
|
+
continue;
|
|
3890
|
+
const result = await poll.json();
|
|
3891
|
+
if (result.status === "complete" && result.token) {
|
|
3892
|
+
await saveCliCredential({
|
|
3893
|
+
token: result.token,
|
|
3894
|
+
apiUrl,
|
|
3895
|
+
workspaceId: result.workspaceId ?? "",
|
|
3896
|
+
projectId: result.projectId ?? "",
|
|
3897
|
+
obtainedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3898
|
+
}, env);
|
|
3899
|
+
finish({ kind: "done", apiUrl });
|
|
3900
|
+
return 0;
|
|
3901
|
+
}
|
|
3902
|
+
if (!output.interactive)
|
|
3903
|
+
stdout("Waiting for browser authorization\u2026\n");
|
|
3904
|
+
}
|
|
3905
|
+
finish({ kind: "error", message: "Device authorization timed out." });
|
|
3906
|
+
if (!output.interactive)
|
|
3907
|
+
stderr("Device authorization timed out.\n");
|
|
3908
|
+
return 2;
|
|
3909
|
+
} catch (error) {
|
|
3910
|
+
const message = errorMessage(error);
|
|
3911
|
+
finish({ kind: "error", message });
|
|
3912
|
+
if (!output.interactive)
|
|
3913
|
+
stderr(`Login failed: ${message}
|
|
3914
|
+
`);
|
|
3915
|
+
return 2;
|
|
3916
|
+
}
|
|
3917
|
+
}
|
|
3918
|
+
async function runScanForCommand(options, cwd, env, fetchImpl) {
|
|
3919
|
+
await loadEnvFile(path4.resolve(cwd, ".env"), env);
|
|
3920
|
+
const configPath = path4.resolve(cwd, options.config ?? "flagdoctor.yaml");
|
|
3921
|
+
const config = await loadFlagdoctorConfig(configPath);
|
|
3922
|
+
const environmentKey = resolveEnvironmentKey(config, options.env);
|
|
3923
|
+
const token = readTokenFromEnv(env);
|
|
3924
|
+
const root = options.root ? path4.resolve(cwd, options.root) : path4.resolve(path4.dirname(configPath), config.repository.root);
|
|
3925
|
+
const provider = new LocalProvider({
|
|
3926
|
+
root,
|
|
3927
|
+
include: config.repository.include,
|
|
3928
|
+
exclude: config.repository.exclude
|
|
3929
|
+
});
|
|
3930
|
+
return runDiagnosticScan({
|
|
3931
|
+
provider,
|
|
3932
|
+
config,
|
|
3933
|
+
token,
|
|
3934
|
+
environment: options.env,
|
|
3935
|
+
environmentKey,
|
|
3936
|
+
fetchImpl
|
|
3937
|
+
});
|
|
3938
|
+
}
|
|
3939
|
+
function resolveEnvironmentKey(config, alias) {
|
|
3940
|
+
const mapping = config.flagsmith.environments;
|
|
3941
|
+
if (mapping && mapping[alias])
|
|
3942
|
+
return mapping[alias];
|
|
3943
|
+
if (config.flagsmith.environment)
|
|
3944
|
+
return config.flagsmith.environment;
|
|
3945
|
+
throw new Error(`No Flagsmith environment mapping configured for '${alias}'`);
|
|
3946
|
+
}
|
|
3947
|
+
async function runCli(argv, dependencies = {}) {
|
|
3948
|
+
const stdout = dependencies.stdout ?? ((text) => process.stdout.write(text));
|
|
3949
|
+
const stderr = dependencies.stderr ?? ((text) => process.stderr.write(text));
|
|
3950
|
+
const cwd = dependencies.cwd ?? process.cwd();
|
|
3951
|
+
const env = dependencies.env ?? process.env;
|
|
3952
|
+
let exitCode = 0;
|
|
3953
|
+
const syncAndReport = async (kind, report, options, output) => {
|
|
3954
|
+
const state = await withSpinner("Syncing report to FlagDoctor\u2026", () => syncReport(kind, report, { env, fetchImpl: dependencies.fetchImpl, enabled: options.sync }), output);
|
|
3955
|
+
reportSync(state, output);
|
|
3956
|
+
};
|
|
3957
|
+
const reportSync = (state, output) => {
|
|
3958
|
+
if (output.interactive) {
|
|
3959
|
+
present(_jsx8(SyncNote, { state }), output);
|
|
3960
|
+
} else if (state.kind === "synced") {
|
|
3961
|
+
stderr(`Synced to FlagDoctor (${state.scanId}).
|
|
3962
|
+
`);
|
|
3963
|
+
} else if (state.kind === "failed") {
|
|
3964
|
+
stderr(`Not synced: ${state.reason}
|
|
3965
|
+
`);
|
|
3966
|
+
}
|
|
3967
|
+
};
|
|
3968
|
+
const splash = async (commands = false, plainRequested = false) => {
|
|
3969
|
+
const credential = await readCliCredential(env);
|
|
3970
|
+
return showSplash({
|
|
3971
|
+
version: cliVersion(),
|
|
3972
|
+
cwd,
|
|
3973
|
+
apiUrl: credential?.apiUrl ?? apiBaseUrl(env),
|
|
3974
|
+
loggedIn: credential !== null,
|
|
3975
|
+
commands
|
|
3976
|
+
}, uiFor(dependencies, stdout, plainRequested), env);
|
|
3977
|
+
};
|
|
3978
|
+
const program = new Command();
|
|
3979
|
+
program.name("flagdoctor").description("Diagnose feature-flag references against a Flagsmith environment").configureOutput({ writeOut: stdout, writeErr: stderr }).exitOverride();
|
|
3980
|
+
program.command("login").description("Authorize this CLI through the browser using a device code").option("--api-url <url>", "FlagDoctor server to sign in to (default: FLAGDOCTOR_API_URL)").action(async (options) => {
|
|
3981
|
+
await splash();
|
|
3982
|
+
const target = options.apiUrl?.trim();
|
|
3983
|
+
exitCode = await runDeviceLogin(target ? {
|
|
3984
|
+
...dependencies,
|
|
3985
|
+
env: { ...dependencies.env ?? process.env, FLAGDOCTOR_API_URL: target }
|
|
3986
|
+
} : dependencies);
|
|
3987
|
+
});
|
|
3988
|
+
program.command("whoami").description("Show the active CLI credential and connected project").action(async () => {
|
|
3989
|
+
try {
|
|
3990
|
+
const credential = await readCliCredential(env);
|
|
3991
|
+
if (!credential)
|
|
3992
|
+
throw new Error("not logged in");
|
|
3993
|
+
const fetchImpl = dependencies.fetchImpl ?? globalThis.fetch;
|
|
3994
|
+
const response = await fetchImpl(`${credential.apiUrl}/api/v1/cli/me`, {
|
|
3995
|
+
headers: { Authorization: `Bearer ${credential.token}` }
|
|
3996
|
+
});
|
|
3997
|
+
if (!response.ok)
|
|
3998
|
+
throw new Error(`CLI credential rejected (HTTP ${response.status})`);
|
|
3999
|
+
const info = await response.json();
|
|
4000
|
+
const output = uiFor(dependencies, stdout);
|
|
4001
|
+
if (output.interactive) {
|
|
4002
|
+
present(_jsx8(WhoamiView, { email: info.user?.email ?? "unknown user", project: info.projectName ?? "unknown project", apiUrl: credential.apiUrl, flagsmith: info.flagsmith?.connected === true, codebases: info.codebases?.length ?? 0 }), output);
|
|
4003
|
+
} else {
|
|
4004
|
+
stdout(`${info.user?.email ?? "unknown user"} \u2014 ${info.projectName ?? "unknown project"}
|
|
4005
|
+
`);
|
|
4006
|
+
}
|
|
4007
|
+
exitCode = 0;
|
|
4008
|
+
} catch (error) {
|
|
4009
|
+
stderr(`whoami failed: ${errorMessage(error)}. Run 'flagdoctor login' first.
|
|
4010
|
+
`);
|
|
4011
|
+
exitCode = 2;
|
|
4012
|
+
}
|
|
4013
|
+
});
|
|
4014
|
+
program.command("init").description("Guided setup; with --ci, write a safe starter config without prompts").option("-c, --config <path>", "configuration file path", "flagdoctor.yaml").option("-f, --force", "overwrite an existing configuration file").option("--ci", "write a starter config without interactive prompts").action(async (options) => {
|
|
4015
|
+
const target = path4.resolve(cwd, options.config ?? "flagdoctor.yaml");
|
|
4016
|
+
if (!options.force) {
|
|
4017
|
+
try {
|
|
4018
|
+
await access2(target);
|
|
4019
|
+
stderr(`${path4.relative(cwd, target)} already exists; use --force to overwrite it.
|
|
4020
|
+
`);
|
|
4021
|
+
exitCode = 2;
|
|
4022
|
+
return;
|
|
4023
|
+
} catch {
|
|
4024
|
+
}
|
|
4025
|
+
}
|
|
4026
|
+
const finishInit = async (fromProject) => {
|
|
4027
|
+
const output = uiFor(dependencies, stdout, options.ci === true);
|
|
4028
|
+
let environments = {};
|
|
4029
|
+
try {
|
|
4030
|
+
const config = await loadFlagdoctorConfig(target);
|
|
4031
|
+
environments = config.flagsmith.environments ?? {};
|
|
4032
|
+
if (config.flagsmith.environment && Object.keys(environments).length === 0) {
|
|
4033
|
+
environments = { default: config.flagsmith.environment };
|
|
4034
|
+
}
|
|
4035
|
+
} catch {
|
|
4036
|
+
}
|
|
4037
|
+
const sync = await pushProjectConfig({ environments }, { env, fetchImpl: dependencies.fetchImpl });
|
|
4038
|
+
if (output.interactive) {
|
|
4039
|
+
present(_jsx8(InitView, { configPath: path4.relative(cwd, target), fromProject, environments: Object.keys(environments), sync }), output);
|
|
4040
|
+
} else {
|
|
4041
|
+
stdout(`Created ${path4.relative(cwd, target)}
|
|
4042
|
+
Set FLAGSMITH_TOKEN in your environment before scanning. Never put tokens in flagdoctor.yaml.
|
|
4043
|
+
`);
|
|
4044
|
+
reportSync(sync, output);
|
|
4045
|
+
}
|
|
4046
|
+
};
|
|
4047
|
+
if (isInteractiveSetup(options.ci === true ? true : dependencies.plain, process.stdin)) {
|
|
4048
|
+
await splash();
|
|
4049
|
+
try {
|
|
4050
|
+
exitCode = await runSetupWizard(options, {
|
|
4051
|
+
stdout,
|
|
4052
|
+
stderr,
|
|
4053
|
+
cwd,
|
|
4054
|
+
env,
|
|
4055
|
+
input: process.stdin,
|
|
4056
|
+
fetchImpl: dependencies.fetchImpl
|
|
4057
|
+
});
|
|
4058
|
+
if (exitCode === 0)
|
|
4059
|
+
await finishInit(null);
|
|
4060
|
+
} catch (error) {
|
|
4061
|
+
if (error instanceof SetupAbortedError) {
|
|
4062
|
+
stderr("Setup cancelled.\n");
|
|
4063
|
+
exitCode = 2;
|
|
4064
|
+
return;
|
|
4065
|
+
}
|
|
4066
|
+
throw error;
|
|
4067
|
+
}
|
|
4068
|
+
return;
|
|
4069
|
+
}
|
|
4070
|
+
const project = await fetchProjectConfig({ env, fetchImpl: dependencies.fetchImpl });
|
|
4071
|
+
await writeFile4(target, buildInitYaml(project), "utf8");
|
|
4072
|
+
await finishInit(project?.flagsmith ? project.projectName ?? "project" : null);
|
|
4073
|
+
exitCode = 0;
|
|
4074
|
+
});
|
|
4075
|
+
program.command("scan").description("Scan local sources and evaluate deterministic diagnostics").requiredOption("--env <name>", "configured environment alias, e.g. production").option("--format <format>", "terminal or json", "terminal").option("-c, --config <path>", "configuration file path", "flagdoctor.yaml").option("--root <path>", "override the repository root").option("--ci", "plain non-interactive output").option("--no-sync", "do not upload the report to FlagDoctor").action(async (options) => {
|
|
4076
|
+
const format = options.format ?? "terminal";
|
|
4077
|
+
if (format !== "terminal" && format !== "json") {
|
|
4078
|
+
stderr(`Unsupported format '${format}'. Use terminal or json.
|
|
4079
|
+
`);
|
|
4080
|
+
exitCode = 2;
|
|
4081
|
+
return;
|
|
4082
|
+
}
|
|
4083
|
+
await loadEnvFile(path4.resolve(cwd, ".env"), env);
|
|
4084
|
+
const configPath = path4.resolve(cwd, options.config ?? "flagdoctor.yaml");
|
|
4085
|
+
if (isInteractiveSetup(options.ci === true ? true : dependencies.plain, process.stdin)) {
|
|
4086
|
+
let configExists = true;
|
|
4087
|
+
try {
|
|
4088
|
+
await access2(configPath);
|
|
4089
|
+
} catch {
|
|
4090
|
+
configExists = false;
|
|
4091
|
+
}
|
|
4092
|
+
if (!configExists) {
|
|
4093
|
+
try {
|
|
4094
|
+
const answer = await createTerminalPrompt(process.stdin, { write: stdout })(`No configuration at ${path4.relative(cwd, configPath)}. Run guided setup now? [Y/n]: `, { default: "Y" });
|
|
4095
|
+
if (answer.toLowerCase() !== "n" && answer.toLowerCase() !== "no") {
|
|
4096
|
+
exitCode = await runSetupWizard({}, {
|
|
4097
|
+
stdout,
|
|
4098
|
+
stderr,
|
|
4099
|
+
cwd,
|
|
4100
|
+
env,
|
|
4101
|
+
input: process.stdin,
|
|
4102
|
+
fetchImpl: dependencies.fetchImpl
|
|
4103
|
+
});
|
|
4104
|
+
if (exitCode !== 0)
|
|
4105
|
+
return;
|
|
4106
|
+
}
|
|
4107
|
+
} catch (error) {
|
|
4108
|
+
if (error instanceof SetupAbortedError) {
|
|
4109
|
+
stderr("Setup cancelled.\n");
|
|
4110
|
+
exitCode = 2;
|
|
4111
|
+
return;
|
|
4112
|
+
}
|
|
4113
|
+
throw error;
|
|
4114
|
+
}
|
|
4115
|
+
}
|
|
4116
|
+
}
|
|
4117
|
+
try {
|
|
4118
|
+
const asJson = format === "json";
|
|
4119
|
+
const output = uiFor(dependencies, stdout, options.ci === true || asJson);
|
|
4120
|
+
const report = await withSpinner(`Scanning and comparing with Flagsmith (${options.env})\u2026`, () => runScanForCommand(options, cwd, env, dependencies.fetchImpl), output);
|
|
4121
|
+
if (asJson)
|
|
4122
|
+
stdout(`${formatJsonReport(report)}
|
|
4123
|
+
`);
|
|
4124
|
+
else if (output.interactive)
|
|
4125
|
+
present(_jsx8(ScanReportView, { report }), output);
|
|
4126
|
+
else
|
|
4127
|
+
stdout(`${formatTerminalReport(report)}
|
|
4128
|
+
`);
|
|
4129
|
+
await syncAndReport("scan", report, options, output);
|
|
4130
|
+
exitCode = report.status !== "completed" ? 2 : report.summary.errors > 0 ? 1 : 0;
|
|
4131
|
+
} catch (error) {
|
|
4132
|
+
stderr(`FlagDoctor: ${redact(errorMessage(error), [env.FLAGSMITH_TOKEN ?? ""])}
|
|
4133
|
+
`);
|
|
4134
|
+
exitCode = 2;
|
|
4135
|
+
}
|
|
4136
|
+
});
|
|
4137
|
+
program.command("graph").description("Show which files, classes and functions each flag affects").requiredOption("--env <name>", "configured environment alias, e.g. production").option("--flag <name>", "show only this flag").option("--format <format>", "terminal or json", "terminal").option("-c, --config <path>", "configuration file path", "flagdoctor.yaml").option("--root <path>", "override the repository root").option("--no-sync", "do not upload the report to FlagDoctor").action(async (options) => {
|
|
4138
|
+
const format = options.format ?? "terminal";
|
|
4139
|
+
if (format !== "terminal" && format !== "json") {
|
|
4140
|
+
stderr(`Unsupported format '${format}'. Use terminal or json.
|
|
4141
|
+
`);
|
|
4142
|
+
exitCode = 2;
|
|
4143
|
+
return;
|
|
4144
|
+
}
|
|
4145
|
+
try {
|
|
4146
|
+
const output = uiFor(dependencies, stdout, format === "json");
|
|
4147
|
+
const report = await withSpinner(`Building the flag dependency map (${options.env})\u2026`, () => runScanForCommand(options, cwd, env, dependencies.fetchImpl), output);
|
|
4148
|
+
const dependenciesGraph = options.flag ? report.dependencies.filter((dependency) => dependency.flagName === options.flag) : report.dependencies;
|
|
4149
|
+
if (format === "json")
|
|
4150
|
+
stdout(`${JSON.stringify(dependenciesGraph, null, 2)}
|
|
4151
|
+
`);
|
|
4152
|
+
else if (output.interactive) {
|
|
4153
|
+
present(_jsx8(DependencyTreeView, { dependencies: dependenciesGraph, environment: options.env }), output);
|
|
4154
|
+
} else
|
|
4155
|
+
stdout(`${formatDependencyTree(dependenciesGraph)}
|
|
4156
|
+
`);
|
|
4157
|
+
await syncAndReport("graph", report, options, output);
|
|
4158
|
+
exitCode = report.status === "failed" ? 2 : 0;
|
|
4159
|
+
} catch (error) {
|
|
4160
|
+
stderr(`FlagDoctor: ${redact(errorMessage(error), [env.FLAGSMITH_TOKEN ?? ""])}
|
|
4161
|
+
`);
|
|
4162
|
+
exitCode = 2;
|
|
4163
|
+
}
|
|
4164
|
+
});
|
|
4165
|
+
program.command("analyze").description("Ask an LLM (Groq) to review the dependency map and findings for misconfigurations").requiredOption("--env <name>", "configured environment alias, e.g. production").option("--format <format>", "terminal or json", "terminal").option("-c, --config <path>", "configuration file path", "flagdoctor.yaml").option("--root <path>", "override the repository root").option("--model <name>", "Groq model to use").option("--no-sync", "do not upload the report to FlagDoctor").action(async (options) => {
|
|
4166
|
+
const format = options.format ?? "terminal";
|
|
4167
|
+
if (format !== "terminal" && format !== "json") {
|
|
4168
|
+
stderr(`Unsupported format '${format}'. Use terminal or json.
|
|
4169
|
+
`);
|
|
4170
|
+
exitCode = 2;
|
|
4171
|
+
return;
|
|
4172
|
+
}
|
|
4173
|
+
try {
|
|
4174
|
+
const output = uiFor(dependencies, stdout, format === "json");
|
|
4175
|
+
await loadEnvFile(path4.resolve(cwd, ".env"), env);
|
|
4176
|
+
const apiKey = readGroqApiKeyFromEnv(env);
|
|
4177
|
+
const report = await withSpinner(`Scanning (${options.env})\u2026`, () => runScanForCommand(options, cwd, env, dependencies.fetchImpl), output);
|
|
4178
|
+
const client = new GroqClient({
|
|
4179
|
+
apiKey,
|
|
4180
|
+
model: options.model ?? env.GROQ_MODEL?.trim() ?? void 0,
|
|
4181
|
+
fetchImpl: dependencies.fetchImpl
|
|
4182
|
+
});
|
|
4183
|
+
const analysis = await withSpinner("Sending the scan and dependency map to the AI model\u2026", () => analyzeReport(report, client), output);
|
|
4184
|
+
const enriched = analysis.report;
|
|
4185
|
+
if (format === "json")
|
|
4186
|
+
stdout(`${formatJsonReport(enriched)}
|
|
4187
|
+
`);
|
|
4188
|
+
else if (output.interactive) {
|
|
4189
|
+
present(_jsx8(ScanReportView, { report: enriched, aiSummary: { model: analysis.model, text: analysis.summary } }), output);
|
|
4190
|
+
} else {
|
|
4191
|
+
stdout(`AI summary (${analysis.model}): ${analysis.summary || "no summary returned"}
|
|
4192
|
+
|
|
4193
|
+
${formatTerminalReport(enriched)}
|
|
4194
|
+
`);
|
|
4195
|
+
}
|
|
4196
|
+
await syncAndReport("analyze", enriched, options, output);
|
|
4197
|
+
exitCode = enriched.status !== "completed" ? 2 : enriched.summary.errors > 0 ? 1 : 0;
|
|
4198
|
+
} catch (error) {
|
|
4199
|
+
stderr(`FlagDoctor: ${redact(errorMessage(error), [env.FLAGSMITH_TOKEN ?? "", env.GROQ_API_KEY ?? ""])}
|
|
4200
|
+
`);
|
|
4201
|
+
exitCode = 2;
|
|
4202
|
+
}
|
|
4203
|
+
});
|
|
4204
|
+
if (argv.length === 0 && await splash(true))
|
|
4205
|
+
return 0;
|
|
4206
|
+
try {
|
|
4207
|
+
await program.parseAsync(argv, { from: "user" });
|
|
4208
|
+
return exitCode;
|
|
4209
|
+
} catch (error) {
|
|
4210
|
+
if (error instanceof CommanderError) {
|
|
4211
|
+
if (error.code.startsWith("commander.help") || error.code === "commander.version")
|
|
4212
|
+
return 0;
|
|
4213
|
+
stderr(`${error.message}
|
|
4214
|
+
`);
|
|
4215
|
+
return 2;
|
|
4216
|
+
}
|
|
4217
|
+
stderr(`FlagDoctor: ${redact(errorMessage(error), [env.FLAGSMITH_TOKEN ?? ""])}
|
|
4218
|
+
`);
|
|
4219
|
+
return 2;
|
|
4220
|
+
}
|
|
4221
|
+
}
|
|
4222
|
+
var invokedDirectly = process.argv[1] !== void 0 && import.meta.url === pathToFileURL(process.argv[1]).href;
|
|
4223
|
+
if (invokedDirectly) {
|
|
4224
|
+
runCli(process.argv.slice(2)).then((code) => {
|
|
4225
|
+
process.exitCode = code;
|
|
4226
|
+
});
|
|
4227
|
+
}
|
|
4228
|
+
export {
|
|
4229
|
+
CLI_PHASE,
|
|
4230
|
+
describeCli,
|
|
4231
|
+
resolveEnvironmentKey,
|
|
4232
|
+
runCli,
|
|
4233
|
+
runDeviceLogin
|
|
4234
|
+
};
|