@dataparade/cli 0.0.28 → 0.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +4 -1
  2. package/dist/package.json +2 -2
  3. package/dist/src/ai-enrichment/providers/platform-proxy-provider.js +6 -1
  4. package/dist/src/cli/scan-interrupt-handlers.d.ts +34 -0
  5. package/dist/src/cli/scan-interrupt-handlers.js +105 -0
  6. package/dist/src/cli.d.ts +3 -0
  7. package/dist/src/cli.js +163 -58
  8. package/dist/src/config/scan-env.d.ts +5 -2
  9. package/dist/src/config/scan-env.js +8 -2
  10. package/dist/src/platform-api/fetch-failure.d.ts +5 -0
  11. package/dist/src/platform-api/fetch-failure.js +13 -0
  12. package/dist/src/platform-api/scan-quota-client.d.ts +3 -1
  13. package/dist/src/platform-api/scan-quota-client.js +41 -28
  14. package/dist/src/platform-api/upload-client.d.ts +5 -0
  15. package/dist/src/platform-api/upload-client.js +11 -1
  16. package/dist/src/ui/scan-progress-renderer.d.ts +38 -0
  17. package/dist/src/ui/scan-progress-renderer.js +110 -3
  18. package/dist/src/ui/types.d.ts +5 -0
  19. package/dist/tests/unit/ai-enrichment/platform-proxy-provider.spec.js +26 -0
  20. package/dist/tests/unit/cli/scan-ai-session-fallback.spec.d.ts +1 -0
  21. package/dist/tests/unit/cli/scan-ai-session-fallback.spec.js +156 -0
  22. package/dist/tests/unit/cli/scan-interrupt-handlers.spec.d.ts +1 -0
  23. package/dist/tests/unit/cli/scan-interrupt-handlers.spec.js +154 -0
  24. package/dist/tests/unit/cli/scan-quota-flow.spec.js +2 -2
  25. package/dist/tests/unit/platform-api/read-cli-api-error-message.spec.js +2 -2
  26. package/dist/tests/unit/ui/scan-progress-renderer.spec.js +155 -0
  27. package/dist/vendor/scanner/dist/src/pii-signals/match-pii-signals.d.ts +24 -0
  28. package/dist/vendor/scanner/dist/src/pii-signals/match-pii-signals.js +19 -6
  29. package/dist/vendor/scanner/dist/src/pii-signals/occurrence-group.js +5 -2
  30. package/dist/vendor/scanner/dist/src/pii-signals/pii-signal-aliases.js +5 -2
  31. package/package.json +2 -2
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const fs_1 = __importDefault(require("fs"));
7
+ const os_1 = __importDefault(require("os"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const cli_1 = require("../../../src/cli");
10
+ function jsonResponse(body, status = 200) {
11
+ return {
12
+ ok: status >= 200 && status < 300,
13
+ status,
14
+ statusText: status === 200 ? 'OK' : 'Error',
15
+ json: async () => body,
16
+ };
17
+ }
18
+ const IP_CAP_MESSAGE = 'Too many anonymous CLI scans from this IP (max 3). Create an account or use a workspace API key.';
19
+ describe('scan keeps going when AI enrichment or upload is unavailable', () => {
20
+ let tempRoot;
21
+ let projectDir;
22
+ let outputPath;
23
+ let fetchMock;
24
+ let logSpy;
25
+ let warnSpy;
26
+ let errorSpy;
27
+ const printed = () => [logSpy, warnSpy, errorSpy]
28
+ .flatMap((spy) => spy.mock.calls.map((call) => call.join(' ')))
29
+ .join('\n');
30
+ beforeEach(() => {
31
+ tempRoot = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'dp-scan-fallback-'));
32
+ projectDir = path_1.default.join(tempRoot, 'project');
33
+ fs_1.default.mkdirSync(projectDir);
34
+ fs_1.default.writeFileSync(path_1.default.join(projectDir, 'index.ts'), "export const handler = () => fetch('https://api.stripe.com/v1/charges');\n");
35
+ outputPath = path_1.default.join(tempRoot, 'out', 'dataflow.json');
36
+ fetchMock = jest.fn();
37
+ global.fetch = fetchMock;
38
+ logSpy = jest.spyOn(console, 'log').mockImplementation(() => { });
39
+ warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => { });
40
+ errorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });
41
+ delete process.env.DATAPARADE_WORKSPACE_API_KEY;
42
+ delete process.env.SCAN_HOSTED_INFER_PROXY_URL;
43
+ process.exitCode = 0;
44
+ });
45
+ afterEach(() => {
46
+ logSpy.mockRestore();
47
+ warnSpy.mockRestore();
48
+ errorSpy.mockRestore();
49
+ fs_1.default.rmSync(tempRoot, { recursive: true, force: true });
50
+ delete process.env.DATAPARADE_SKIP_AUTO_UPLOAD;
51
+ process.exitCode = 0;
52
+ });
53
+ it('runs a structural scan when the anonymous AI session cannot reach the API', async () => {
54
+ process.env.DATAPARADE_SKIP_AUTO_UPLOAD = 'true';
55
+ fetchMock.mockRejectedValue(Object.assign(new TypeError('fetch failed'), {
56
+ cause: { code: 'ECONNREFUSED', message: 'connect ECONNREFUSED' },
57
+ }));
58
+ await (0, cli_1.run)([
59
+ 'node',
60
+ 'cli',
61
+ 'scan',
62
+ projectDir,
63
+ '--ai-inference',
64
+ '--output',
65
+ outputPath,
66
+ ]);
67
+ expect(String(fetchMock.mock.calls[0][0])).toContain('/api/scans/cli/ai/anonymous-session');
68
+ expect(process.exitCode ?? 0).toBe(0);
69
+ expect(fs_1.default.existsSync(outputPath)).toBe(true);
70
+ expect(fs_1.default.existsSync(path_1.default.join(tempRoot, 'out', 'facts.json'))).toBe(true);
71
+ const output = printed();
72
+ expect(output).toContain('AI enrichment unavailable (could not reach the DataParade API: ECONNREFUSED: connect ECONNREFUSED); continuing with a structural scan. Use --no-ai-inference to skip this step.');
73
+ expect(output).not.toContain('Scan failed');
74
+ });
75
+ it('runs a structural scan when the anonymous per-IP cap is reached', async () => {
76
+ process.env.DATAPARADE_SKIP_AUTO_UPLOAD = 'true';
77
+ fetchMock.mockResolvedValue(jsonResponse({ statusCode: 429, message: IP_CAP_MESSAGE }, 429));
78
+ await (0, cli_1.run)([
79
+ 'node',
80
+ 'cli',
81
+ 'scan',
82
+ projectDir,
83
+ '--ai-inference',
84
+ '--output',
85
+ outputPath,
86
+ ]);
87
+ expect(fetchMock).toHaveBeenCalledTimes(1);
88
+ expect(process.exitCode ?? 0).toBe(0);
89
+ expect(fs_1.default.existsSync(outputPath)).toBe(true);
90
+ expect(printed()).toContain(`AI enrichment unavailable (${IP_CAP_MESSAGE.replace(/\.$/, '')}); continuing with a structural scan.`);
91
+ });
92
+ it('runs a structural scan when the workspace preflight cannot reach the API', async () => {
93
+ process.env.DATAPARADE_WORKSPACE_API_KEY = 'dp_live_test';
94
+ process.env.DATAPARADE_SKIP_AUTO_UPLOAD = 'true';
95
+ fetchMock.mockRejectedValue(new TypeError('fetch failed'));
96
+ await (0, cli_1.run)([
97
+ 'node',
98
+ 'cli',
99
+ 'scan',
100
+ projectDir,
101
+ '--ai-inference',
102
+ '--output',
103
+ outputPath,
104
+ ]);
105
+ expect(String(fetchMock.mock.calls[0][0])).toContain('/api/scans/cli/preflight');
106
+ expect(process.exitCode ?? 0).toBe(0);
107
+ expect(fs_1.default.existsSync(outputPath)).toBe(true);
108
+ expect(printed()).toContain('AI enrichment unavailable (');
109
+ });
110
+ it('says the upload did not complete and how to retry when it is refused', async () => {
111
+ fetchMock.mockImplementation(async (url) => {
112
+ if (String(url).includes('/api/scans/cli/preview')) {
113
+ return jsonResponse({ statusCode: 429, message: IP_CAP_MESSAGE }, 429);
114
+ }
115
+ throw new Error(`unexpected fetch ${String(url)}`);
116
+ });
117
+ await (0, cli_1.run)([
118
+ 'node',
119
+ 'cli',
120
+ 'scan',
121
+ projectDir,
122
+ '--no-ai-inference',
123
+ '--output',
124
+ outputPath,
125
+ ]);
126
+ expect(process.exitCode ?? 0).toBe(0);
127
+ expect(fs_1.default.existsSync(outputPath)).toBe(true);
128
+ const output = printed();
129
+ expect(output).toContain(`[scan] Auto-upload failed: ${IP_CAP_MESSAGE}`);
130
+ expect(output).toContain('The upload did not complete:');
131
+ const relative = path_1.default.relative(process.cwd(), outputPath);
132
+ const expectedTarget = relative.startsWith('..') ? outputPath : relative;
133
+ expect(output).toContain(`dataparade upload ${expectedTarget}`);
134
+ expect(output).toContain('DATAPARADE_WORKSPACE_API_KEY');
135
+ expect(output).toContain('Scan finished. The upload did not complete.');
136
+ expect(output).not.toContain('All done — nice work.');
137
+ });
138
+ it('gives the retry command without the API key hint on a network failure', async () => {
139
+ fetchMock.mockRejectedValue(new TypeError('fetch failed'));
140
+ await (0, cli_1.run)([
141
+ 'node',
142
+ 'cli',
143
+ 'scan',
144
+ projectDir,
145
+ '--no-ai-inference',
146
+ '--output',
147
+ outputPath,
148
+ ]);
149
+ expect(process.exitCode ?? 0).toBe(0);
150
+ const output = printed();
151
+ expect(output).toContain('The upload did not complete: could not reach the DataParade API');
152
+ expect(output).toContain('dataparade upload ');
153
+ expect(output).not.toContain('DATAPARADE_WORKSPACE_API_KEY');
154
+ expect(output).not.toContain('All done — nice work.');
155
+ });
156
+ });
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const node_events_1 = require("node:events");
4
+ const scan_interrupt_handlers_1 = require("../../../src/cli/scan-interrupt-handlers");
5
+ describe('installCliScanInterruptHandlers', () => {
6
+ function setup(options) {
7
+ const proc = new node_events_1.EventEmitter();
8
+ const exits = [];
9
+ const abortUi = jest.fn();
10
+ const reportFailed = jest.fn().mockResolvedValue(undefined);
11
+ let completionStatus = options?.completionStatus ?? 'none';
12
+ const uninstall = (0, scan_interrupt_handlers_1.installCliScanInterruptHandlers)({
13
+ proc,
14
+ exit: (code) => {
15
+ exits.push(code);
16
+ },
17
+ getState: () => ({
18
+ apiKey: options?.apiKey ?? 'dp_live_test',
19
+ jobId: options?.jobId ?? 'job-1',
20
+ completionStatus,
21
+ inFlight: options?.inFlight,
22
+ }),
23
+ setCompletionStatus: (status) => {
24
+ completionStatus = status;
25
+ },
26
+ onAbortUi: abortUi,
27
+ reportFailed,
28
+ });
29
+ return {
30
+ proc,
31
+ exits,
32
+ abortUi,
33
+ reportFailed,
34
+ uninstall,
35
+ setCompletionStatus: (status) => {
36
+ completionStatus = status;
37
+ },
38
+ getCompletionStatus: () => completionStatus,
39
+ };
40
+ }
41
+ afterEach(() => {
42
+ jest.useRealTimers();
43
+ });
44
+ it('reports scan_interrupted once on SIGINT and exits 130', async () => {
45
+ const { proc, exits, abortUi, reportFailed, uninstall } = setup();
46
+ proc.emit('SIGINT');
47
+ await Promise.resolve();
48
+ await Promise.resolve();
49
+ expect(abortUi).toHaveBeenCalledTimes(1);
50
+ expect(reportFailed).toHaveBeenCalledTimes(1);
51
+ const [reportInput] = reportFailed.mock.calls[0];
52
+ expect(reportInput.apiKey).toBe('dp_live_test');
53
+ expect(reportInput.jobId).toBe('job-1');
54
+ expect(reportInput.timeoutMs).toBeGreaterThan(0);
55
+ expect(reportInput.timeoutMs).toBeLessThanOrEqual(scan_interrupt_handlers_1.CLI_SCAN_INTERRUPT_COMPLETE_TIMEOUT_MS);
56
+ expect(exits).toEqual([scan_interrupt_handlers_1.CLI_SCAN_INTERRUPT_EXIT_CODES.SIGINT]);
57
+ uninstall();
58
+ });
59
+ it('exits immediately on a second signal without reporting again', async () => {
60
+ const { proc, exits, reportFailed, uninstall } = setup();
61
+ let resolveReport;
62
+ reportFailed.mockImplementation(() => new Promise((resolve) => {
63
+ resolveReport = resolve;
64
+ }));
65
+ proc.emit('SIGINT');
66
+ await Promise.resolve();
67
+ expect(reportFailed).toHaveBeenCalledTimes(1);
68
+ proc.emit('SIGINT');
69
+ expect(exits).toEqual([scan_interrupt_handlers_1.CLI_SCAN_INTERRUPT_EXIT_CODES.SIGINT]);
70
+ expect(reportFailed).toHaveBeenCalledTimes(1);
71
+ resolveReport?.();
72
+ await Promise.resolve();
73
+ await Promise.resolve();
74
+ expect(exits).toEqual([
75
+ scan_interrupt_handlers_1.CLI_SCAN_INTERRUPT_EXIT_CODES.SIGINT,
76
+ scan_interrupt_handlers_1.CLI_SCAN_INTERRUPT_EXIT_CODES.SIGINT,
77
+ ]);
78
+ uninstall();
79
+ });
80
+ it('waits for an in-flight complete instead of reporting again', async () => {
81
+ let resolveInFlight;
82
+ const inFlight = new Promise((resolve) => {
83
+ resolveInFlight = resolve;
84
+ });
85
+ const { proc, exits, reportFailed, uninstall, setCompletionStatus } = setup({ completionStatus: 'in_flight', inFlight });
86
+ proc.emit('SIGTERM');
87
+ await Promise.resolve();
88
+ expect(exits).toEqual([]);
89
+ // The scan's own complete lands.
90
+ setCompletionStatus('done');
91
+ resolveInFlight?.();
92
+ await new Promise((resolve) => setImmediate(resolve));
93
+ expect(reportFailed).not.toHaveBeenCalled();
94
+ expect(exits).toEqual([scan_interrupt_handlers_1.CLI_SCAN_INTERRUPT_EXIT_CODES.SIGTERM]);
95
+ uninstall();
96
+ });
97
+ it('reports scan_interrupted when the in-flight complete fails', async () => {
98
+ let rejectInFlight;
99
+ const inFlight = new Promise((_resolve, reject) => {
100
+ rejectInFlight = reject;
101
+ });
102
+ const { proc, exits, reportFailed, uninstall, setCompletionStatus } = setup({ completionStatus: 'in_flight', inFlight });
103
+ proc.emit('SIGINT');
104
+ await Promise.resolve();
105
+ // The scan path resets the status when its complete throws.
106
+ setCompletionStatus('none');
107
+ rejectInFlight?.(new Error('network down'));
108
+ await new Promise((resolve) => setImmediate(resolve));
109
+ expect(reportFailed).toHaveBeenCalledTimes(1);
110
+ expect(exits).toEqual([scan_interrupt_handlers_1.CLI_SCAN_INTERRUPT_EXIT_CODES.SIGINT]);
111
+ uninstall();
112
+ });
113
+ it('claims the completion so the scan path does not report again', async () => {
114
+ const { proc, reportFailed, uninstall, getCompletionStatus } = setup();
115
+ let statusDuringReport;
116
+ reportFailed.mockImplementation(() => {
117
+ statusDuringReport = getCompletionStatus();
118
+ return Promise.resolve();
119
+ });
120
+ proc.emit('SIGINT');
121
+ await new Promise((resolve) => setImmediate(resolve));
122
+ expect(statusDuringReport).toBe('in_flight');
123
+ expect(getCompletionStatus()).toBe('done');
124
+ uninstall();
125
+ });
126
+ it('does not block exit when the complete API hangs past the timeout', async () => {
127
+ jest.useFakeTimers();
128
+ const { proc, exits, reportFailed, uninstall } = setup();
129
+ reportFailed.mockImplementation(({ timeoutMs }) => new Promise((_resolve, reject) => {
130
+ setTimeout(() => {
131
+ reject(new Error('aborted'));
132
+ }, timeoutMs);
133
+ }));
134
+ proc.emit('SIGHUP');
135
+ await Promise.resolve();
136
+ expect(reportFailed).toHaveBeenCalledTimes(1);
137
+ expect(exits).toEqual([]);
138
+ await jest.advanceTimersByTimeAsync(scan_interrupt_handlers_1.CLI_SCAN_INTERRUPT_COMPLETE_TIMEOUT_MS);
139
+ await Promise.resolve();
140
+ await Promise.resolve();
141
+ expect(exits).toEqual([scan_interrupt_handlers_1.CLI_SCAN_INTERRUPT_EXIT_CODES.SIGHUP]);
142
+ uninstall();
143
+ });
144
+ it('uses exit codes 130, 143, and 129 for SIGINT, SIGTERM, and SIGHUP', async () => {
145
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
146
+ const { proc, exits, uninstall } = setup();
147
+ proc.emit(signal);
148
+ await Promise.resolve();
149
+ await Promise.resolve();
150
+ expect(exits).toEqual([scan_interrupt_handlers_1.CLI_SCAN_INTERRUPT_EXIT_CODES[signal]]);
151
+ uninstall();
152
+ }
153
+ });
154
+ });
@@ -64,11 +64,11 @@ describe('scan quota flow', () => {
64
64
  statusCode: 409,
65
65
  message: {
66
66
  code: 'scan_already_running',
67
- message: 'Scan in progress — start a new scan after the current one completes.',
67
+ message: 'Another scan is already running in this workspace. Wait for it to finish, if it was stopped, it is released automatically after 60 minutes of inactivity.',
68
68
  },
69
69
  }, 409));
70
70
  await (0, cli_1.run)(['node', 'cli', 'scan', tempRoot, '--ai-inference']);
71
- expect(errorSpy).toHaveBeenCalledWith('[scan] scan in progress: Scan in progress — start a new scan after the current one completes.');
71
+ expect(errorSpy).toHaveBeenCalledWith('[scan] scan in progress: Another scan is already running in this workspace. Wait for it to finish, if it was stopped, it is released automatically after 60 minutes of inactivity.');
72
72
  errorSpy.mockRestore();
73
73
  });
74
74
  it('reports failed completion when preflight succeeds but config validation fails', async () => {
@@ -16,11 +16,11 @@ describe("readCliApiErrorMessage", () => {
16
16
  statusCode: 409,
17
17
  message: {
18
18
  code: "scan_already_running",
19
- message: "Scan in progress — start a new scan after the current one completes.",
19
+ message: "Another scan is already running in this workspace. Wait for it to finish, if it was stopped, it is released automatically after 60 minutes of inactivity.",
20
20
  },
21
21
  }, "fallback")).toEqual({
22
22
  code: "scan_already_running",
23
- message: "Scan in progress — start a new scan after the current one completes.",
23
+ message: "Another scan is already running in this workspace. Wait for it to finish, if it was stopped, it is released automatically after 60 minutes of inactivity.",
24
24
  });
25
25
  });
26
26
  it("joins validation message arrays", () => {
@@ -37,6 +37,8 @@ jest.mock('@clack/prompts', () => {
37
37
  const spin = {
38
38
  start: jest.fn(),
39
39
  stop: jest.fn(),
40
+ cancel: jest.fn(),
41
+ error: jest.fn(),
40
42
  message: jest.fn(),
41
43
  };
42
44
  return {
@@ -49,6 +51,7 @@ jest.mock('@clack/prompts', () => {
49
51
  success: jest.fn(),
50
52
  step: jest.fn(),
51
53
  warn: jest.fn(),
54
+ error: jest.fn(),
52
55
  },
53
56
  };
54
57
  });
@@ -129,6 +132,27 @@ describe('ScanProgressRenderer', () => {
129
132
  expect(joined).not.toContain('Your preview is ready whenever you are');
130
133
  expect(ui.usesClackChrome).toBe(false);
131
134
  });
135
+ it('plain finish reports a failed upload instead of the success line', async () => {
136
+ const { lines, writeLine } = captureLines();
137
+ const ui = await (0, scan_progress_renderer_1.createScanProgressRenderer)({
138
+ isTTY: false,
139
+ noColor: true,
140
+ writeLine,
141
+ });
142
+ ui.onUploadFailed({
143
+ reason: 'Too many anonymous CLI scans from this IP (max 3)',
144
+ retryCommand: 'dataparade upload .dataparade/dataflow.json',
145
+ hint: 'Set DATAPARADE_WORKSPACE_API_KEY.',
146
+ });
147
+ ui.finish();
148
+ const joined = lines.join('\n');
149
+ expect(joined).toContain('The upload did not complete: Too many anonymous CLI scans from this IP (max 3).');
150
+ expect(joined).toContain('dataparade upload .dataparade/dataflow.json');
151
+ expect(joined).toContain('Set DATAPARADE_WORKSPACE_API_KEY.');
152
+ expect(joined).toContain('Scan finished. The upload did not complete.');
153
+ expect(joined).not.toContain('All done — nice work.');
154
+ expect(joined).not.toContain('Jump into DataParade');
155
+ });
132
156
  it('formats the preview link with ANSI when color is on', () => {
133
157
  const plain = (0, scan_progress_renderer_1.formatPreviewLink)('https://example.test/preview', false);
134
158
  expect(plain).toBe('https://example.test/preview');
@@ -272,4 +296,135 @@ describe('ScanProgressRenderer', () => {
272
296
  '[scan] ai-usage: provider_calls=1 tokens_total=10',
273
297
  ]);
274
298
  });
299
+ it('abort cancels the active spinner and skips the finish outro', async () => {
300
+ const { lines, writeLine } = captureLines();
301
+ const ui = await (0, scan_progress_renderer_1.createScanProgressRenderer)({
302
+ isTTY: true,
303
+ noColor: false,
304
+ writeLine,
305
+ prompts,
306
+ });
307
+ const spin = prompts.spinner();
308
+ prompts.spinner.mockClear();
309
+ ui.onProgress({
310
+ phase: 'ingest',
311
+ filesProcessed: 0,
312
+ totalFiles: 0,
313
+ progress: 0.05,
314
+ });
315
+ expect(prompts.spinner).toHaveBeenCalledTimes(1);
316
+ ui.abort('Scan cancelled');
317
+ expect(spin.cancel).toHaveBeenCalledWith('Scan cancelled');
318
+ expect(spin.stop).not.toHaveBeenCalled();
319
+ expect(prompts.outro).not.toHaveBeenCalled();
320
+ expect(lines.some((line) => line.includes('All done'))).toBe(false);
321
+ });
322
+ it('hands Ctrl+C back to the terminal after starting a spinner', async () => {
323
+ const { writeLine } = captureLines();
324
+ const stdin = { isTTY: true, setRawMode: jest.fn() };
325
+ const ui = await (0, scan_progress_renderer_1.createScanProgressRenderer)({
326
+ isTTY: true,
327
+ noColor: false,
328
+ writeLine,
329
+ prompts,
330
+ stdin,
331
+ });
332
+ ui.onProgress({
333
+ phase: 'ingest',
334
+ filesProcessed: 0,
335
+ totalFiles: 0,
336
+ progress: 0.05,
337
+ });
338
+ expect(stdin.setRawMode).toHaveBeenLastCalledWith(false);
339
+ });
340
+ it('abort between steps uses a Clack log line, not a raw write', async () => {
341
+ const { lines, writeLine } = captureLines();
342
+ const ui = await (0, scan_progress_renderer_1.createScanProgressRenderer)({
343
+ isTTY: true,
344
+ noColor: false,
345
+ writeLine,
346
+ prompts,
347
+ });
348
+ ui.abort('Scan cancelled');
349
+ expect(prompts.log.warn).toHaveBeenCalledWith('Scan cancelled');
350
+ expect(lines).not.toContain('Scan cancelled');
351
+ expect(prompts.outro).not.toHaveBeenCalled();
352
+ });
353
+ it('fail closes the active spinner with the error mark', async () => {
354
+ const { writeLine } = captureLines();
355
+ const ui = await (0, scan_progress_renderer_1.createScanProgressRenderer)({
356
+ isTTY: true,
357
+ noColor: false,
358
+ writeLine,
359
+ prompts,
360
+ });
361
+ const spin = prompts.spinner();
362
+ prompts.spinner.mockClear();
363
+ ui.onProgress({
364
+ phase: 'ingest',
365
+ filesProcessed: 0,
366
+ totalFiles: 0,
367
+ progress: 0.05,
368
+ });
369
+ ui.fail('Scan failed: API unreachable');
370
+ expect(spin.error).toHaveBeenCalledWith('Scan failed: API unreachable');
371
+ expect(prompts.outro).not.toHaveBeenCalled();
372
+ });
373
+ it('fail between steps logs a Clack error line', async () => {
374
+ const { lines, writeLine } = captureLines();
375
+ const ui = await (0, scan_progress_renderer_1.createScanProgressRenderer)({
376
+ isTTY: true,
377
+ noColor: false,
378
+ writeLine,
379
+ prompts,
380
+ });
381
+ ui.fail('Another scan is already running in this workspace.');
382
+ expect(prompts.log.error).toHaveBeenCalledWith('Another scan is already running in this workspace.');
383
+ expect(lines).toHaveLength(0);
384
+ });
385
+ it('ignores progress that arrives after the scan was cancelled', async () => {
386
+ const { lines, writeLine } = captureLines();
387
+ const ui = await (0, scan_progress_renderer_1.createScanProgressRenderer)({
388
+ isTTY: false,
389
+ noColor: true,
390
+ writeLine,
391
+ });
392
+ ui.onProgress({
393
+ phase: 'ingest',
394
+ filesProcessed: 0,
395
+ totalFiles: 0,
396
+ progress: 0.05,
397
+ });
398
+ ui.abort('Scan cancelled');
399
+ const linesAtAbort = lines.length;
400
+ // Work queued behind a blocking phase lands after Ctrl+C.
401
+ ui.onProgress({
402
+ phase: 'ai_enrichment',
403
+ filesProcessed: 0,
404
+ totalFiles: 0,
405
+ progress: 0.6,
406
+ });
407
+ ui.warn('late warning');
408
+ ui.fail('Scan failed: late');
409
+ ui.finish();
410
+ expect(lines).toHaveLength(linesAtAbort);
411
+ expect(lines[lines.length - 1]).toBe('Scan cancelled');
412
+ });
413
+ it('abort prints a plain cancellation line when Clack is off', async () => {
414
+ const { lines, writeLine } = captureLines();
415
+ const ui = await (0, scan_progress_renderer_1.createScanProgressRenderer)({
416
+ isTTY: false,
417
+ noColor: false,
418
+ writeLine,
419
+ });
420
+ ui.onProgress({
421
+ phase: 'ingest',
422
+ filesProcessed: 0,
423
+ totalFiles: 0,
424
+ progress: 0.05,
425
+ });
426
+ ui.abort('Scan cancelled');
427
+ expect(lines).toContain('Scan cancelled');
428
+ expect(lines.some((line) => line.includes('All done'))).toBe(false);
429
+ });
275
430
  });
@@ -102,5 +102,29 @@ export { piiSignalIdentity, rawHitIdentity, occurrenceIdentity, dataItemIdentity
102
102
  * field declaration a few lines below; span evidence through the annotation block.
103
103
  */
104
104
  export declare function javaAnnotationBlockStartLine(lines: readonly string[], fieldLineIndex: number): number;
105
+ /**
106
+ * A module path or URL path (`'../../services/email-service'`) or a prose message
107
+ * (`'Email not found.'`): it names a file or tells a person something, not a value.
108
+ * SQL, other strings and messages that interpolate a value (`"Logout failed for
109
+ * #{channel.email}."`) keep matching.
110
+ *
111
+ * A prose message starts with a capital, holds at least two whitespace characters and
112
+ * ends in `.`, `!` or `?`. The first two runs exclude whitespace, so the two `\s` are
113
+ * always the first two whitespace characters and each run has one way to match. Runs
114
+ * that also matched whitespace backtracked O(n^3) on a long capitalised string that is
115
+ * not prose (an inline SVG path `d="M1.5 2.5 ..."`). Matches on a single line are the
116
+ * same as before.
117
+ */
118
+ export declare const PATH_OR_PROSE_STRING: RegExp;
119
+ /**
120
+ * A whole import statement (`const mail = require('../mail');`, `import { isEmail } from
121
+ * 'validator';`, `from email.mime.text import MIMEText`, `require 'mail'`): its names are
122
+ * modules and bindings, not values.
123
+ *
124
+ * Whitespace runs never sit next to another run that also takes whitespace (`\s[^=]+`,
125
+ * `(?:\s*;)?`, `import\s(?:...)`): `from a import` followed by a long run of spaces
126
+ * backtracked O(n^3). Same matches as before.
127
+ */
128
+ export declare const IMPORT_LINE: RegExp;
105
129
  export declare function matchPiiSignalsInFile(input: MatchPiiSignalsFileInput, rules?: PiiSignalRule[]): PiiSignalHit[];
106
130
  export declare function matchPiiSignalsInFiles(files: MatchPiiSignalsFileInput[], rules?: PiiSignalRule[]): PiiSignalHit[];
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.dataItemIdentity = exports.occurrenceIdentity = exports.rawHitIdentity = exports.piiSignalIdentity = void 0;
3
+ exports.IMPORT_LINE = exports.PATH_OR_PROSE_STRING = exports.dataItemIdentity = exports.occurrenceIdentity = exports.rawHitIdentity = exports.piiSignalIdentity = void 0;
4
4
  exports.javaAnnotationBlockStartLine = javaAnnotationBlockStartLine;
5
5
  exports.matchPiiSignalsInFile = matchPiiSignalsInFile;
6
6
  exports.matchPiiSignalsInFiles = matchPiiSignalsInFiles;
@@ -15,7 +15,9 @@ function ruleById(rules) {
15
15
  return new Map(rules.map((rule) => [rule.id, rule]));
16
16
  }
17
17
  function isJavaFieldDeclarationLine(line) {
18
- return /\b(?:private|protected)\s+[\w<>,\s\[\]]+\s+\w+\s*;/.test(line);
18
+ // Single `\s` around the type: the type class takes whitespace too, and `\s+` there
19
+ // backtracked O(n^3) on `private` followed by a long run of spaces. Same matches.
20
+ return /\b(?:private|protected)\s[\w<>,\s\[\]]+\s\w+\s*;/.test(line);
19
21
  }
20
22
  /**
21
23
  * Gold often anchors on the leading @Column line while token matching fires on the
@@ -98,8 +100,15 @@ const TRANSLATION_KEY = /(\b(?:I18n\.t|i18n\.t|translate|t|__|\$t)\(\s*)(['"`])[
98
100
  * (`'Email not found.'`): it names a file or tells a person something, not a value.
99
101
  * SQL, other strings and messages that interpolate a value (`"Logout failed for
100
102
  * #{channel.email}."`) keep matching.
103
+ *
104
+ * A prose message starts with a capital, holds at least two whitespace characters and
105
+ * ends in `.`, `!` or `?`. The first two runs exclude whitespace, so the two `\s` are
106
+ * always the first two whitespace characters and each run has one way to match. Runs
107
+ * that also matched whitespace backtracked O(n^3) on a long capitalised string that is
108
+ * not prose (an inline SVG path `d="M1.5 2.5 ..."`). Matches on a single line are the
109
+ * same as before.
101
110
  */
102
- const PATH_OR_PROSE_STRING = /(['"`])(?:[\w.@-]*\/[\w./@-]*|[A-Z](?:(?![$#]\{)[^'"`\n])*\s(?:(?![$#]\{)[^'"`\n])*\s(?:(?![$#]\{)[^'"`\n])*[.!?])\1/g;
111
+ exports.PATH_OR_PROSE_STRING = /(['"`])(?:[\w.@-]*\/[\w./@-]*|[A-Z](?:(?![$#]\{)[^'"`\s])*\s(?:(?![$#]\{)[^'"`\s])*\s(?:(?![$#]\{)[^'"`\n])*[.!?])\1/g;
103
112
  /**
104
113
  * A capitalized Email or Mail class reference (`Channel::Email`, `models.Email.findOne`,
105
114
  * `Email::Cleaner`): a model or module, not an address. Lowercase members (`user.email`)
@@ -111,8 +120,12 @@ const EMAIL_NAMESPACE = /\b(?:Email|Mail)(?=::)/g;
111
120
  * A whole import statement (`const mail = require('../mail');`, `import { isEmail } from
112
121
  * 'validator';`, `from email.mime.text import MIMEText`, `require 'mail'`): its names are
113
122
  * modules and bindings, not values.
123
+ *
124
+ * Whitespace runs never sit next to another run that also takes whitespace (`\s[^=]+`,
125
+ * `(?:\s*;)?`, `import\s(?:...)`): `from a import` followed by a long run of spaces
126
+ * backtracked O(n^3). Same matches as before.
114
127
  */
115
- const IMPORT_LINE = /^\s*(?:(?:const|let|var)\s+[^=]+=\s*require\(\s*(['"`])[^'"`]*\1\s*\)(?:\(\s*(['"`])[^'"`]*\2\s*\))?(?:\.\w+)*\s*;?|import\b[^'"`]*\bfrom\s*(['"`])[^'"`]*\3\s*;?|import\s*(['"`])[^'"`]*\4\s*;?|from\s+[\w.]+\s+import\s+[\w\s,()*]+|import\s+[\w.]+(?:\s+as\s+\w+)?|require(?:_relative)?\s+(['"])[^'"]*\5)\s*$/;
128
+ exports.IMPORT_LINE = /^\s*(?:(?:const|let|var)\s[^=]+=\s*require\(\s*(['"`])[^'"`]*\1\s*\)(?:\(\s*(['"`])[^'"`]*\2\s*\))?(?:\.\w+)*(?:\s*;)?|import\b[^'"`]*\bfrom\s*(['"`])[^'"`]*\3(?:\s*;)?|import\s*(['"`])[^'"`]*\4(?:\s*;)?|from\s+[\w.]+\s+import\s(?:[\w\s,()*]*[\w,()*]|\s)|import\s+[\w.]+(?:\s+as\s+\w+)?|require(?:_relative)?\s+(['"])[^'"]*\5)\s*$/;
116
129
  const NEVER = /(?!)/g;
117
130
  /** A Ruby predicate (`inbox.email?`, `mail?`) asks a yes/no question; it is not an address. */
118
131
  const EMAIL_PREDICATE = /(\.|\b)e?mails?\?(?!\?)/g;
@@ -125,9 +138,9 @@ function matchPiiSignalsInFile(input, rules = (0, pii_signal_rules_1.loadPiiSign
125
138
  for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {
126
139
  // A translation key names a message, not a value: it is blanked before matching.
127
140
  const raw = lines[lineIndex] ?? "";
128
- const line = (IMPORT_LINE.test(raw) ? "" : raw)
141
+ const line = (exports.IMPORT_LINE.test(raw) ? "" : raw)
129
142
  .replace(TRANSLATION_KEY, '$1""')
130
- .replace(PATH_OR_PROSE_STRING, '""')
143
+ .replace(exports.PATH_OR_PROSE_STRING, '""')
131
144
  .replace(EMAIL_CLASS_REFERENCE, "$1Klass")
132
145
  .replace(EMAIL_NAMESPACE, "Klass")
133
146
  .replace(rubyFile ? EMAIL_PREDICATE : NEVER, "$1kind?");
@@ -89,7 +89,8 @@ function qualify(line, signalId) {
89
89
  // Also a function defined by assignment: `findOneByEmail = async (email) => ...`,
90
90
  // `sendEmail: async (to) => ...`, `x = function (...)`.
91
91
  const isFunctionName = (/^\s*(\(|:\s*(async\s+)?function\b)/.test(after) ||
92
- /^\s*[:=]\s*(async\s+)?(function\b|\([^)]*\)\s*(:\s*[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)/.test(after)) &&
92
+ // `:[^=]+` matches what `:\s*[^=]+` did (`[^=]` takes whitespace) in linear time.
93
+ /^\s*[:=]\s*(async\s+)?(function\b|\([^)]*\)\s*(:[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)/.test(after)) &&
93
94
  !assignsConcept;
94
95
  const words = identifierWords(identifier);
95
96
  // A getter named for whose value it returns keeps its qualifier:
@@ -130,7 +131,9 @@ function qualify(line, signalId) {
130
131
  // `const verificationEmail = user?.email ?? input.email` -> user. Only true locals;
131
132
  // `gift_card.used_by_email = user.email` stores a copy in another entity and keeps
132
133
  // its own name.
133
- const localCopy = new RegExp(`^\\s*(?:(?:const|let|var)\\s+)?([A-Za-z_]\\w*)\\s*(?::\\s*[\\w<>\\[\\]| ]+)?\\s*=\\s*(?:await\\s+)?(?:[\\w.]+\\s*\\?\\?\\s*)?([A-Za-z_]\\w*)\\s*(?:\\?\\.|\\.|\\[\\s*['"]|\\.get\\(\\s*['"])${conceptWords.map(escapeRegExp).join("_?")}\\b`, "i").exec(line);
134
+ // The type annotation's runs never meet another run that takes the same whitespace
135
+ // (`: ` followed by a long run of spaces backtracked O(n^3)); same matches and groups.
136
+ const localCopy = new RegExp(`^\\s*(?:(?:const|let|var)\\s+)?([A-Za-z_]\\w*)\\s*(?::(?:\\s*[\\w<>\\[\\]|](?:[\\w<>\\[\\]| ]*[\\w<>\\[\\]|])?|[^\\S ]* )\\s*)?=\\s*(?:await\\s+)?(?:[\\w.]+\\s*\\?\\?\\s*)?([A-Za-z_]\\w*)\\s*(?:\\?\\.|\\.|\\[\\s*['"]|\\.get\\(\\s*['"])${conceptWords.map(escapeRegExp).join("_?")}\\b`, "i").exec(line);
134
137
  if (localCopy && conceptWords.every((word) => identifierWords(localCopy[1]).includes(word))) {
135
138
  const source = /^users?$/i.test(localCopy[2])
136
139
  ? "user"
@@ -117,7 +117,9 @@ function isBareAddressFieldDeclaration(line, tokenStartIndex) {
117
117
  /\b(?:String|CharField|TextField|varchar|text)\s+address\b/i.test(line) ||
118
118
  /\baddress\s*=\s*models\./i.test(line) ||
119
119
  /\bprivate\s+\w+\s+address\s*;/.test(line) ||
120
- /\bvalidates(?:_\w+)*\s+:\w*address\b/i.test(line));
120
+ // `(?:_\w+)?` matches what `(?:_\w+)*` did (`_` is a word character) without
121
+ // exponential backtracking on `validates_a_a_a...`.
122
+ /\bvalidates(?:_\w+)?\s+:\w*address\b/i.test(line));
121
123
  }
122
124
  /** Extract identifier tokens from a source line (supports optional `$` prefix). */
123
125
  function extractLineIdentifierTokens(line) {
@@ -230,7 +232,8 @@ function resolveAliasRuleIdsForToken(token, line, tokenStartIndex, filePath) {
230
232
  // class, never a phone value; ALL_CAPS constants (`ATTENDEE_PHONE_NUMBER_FIELD`) still count.
231
233
  if (ruleId === "phone_number" &&
232
234
  (NOT_PHONE_LAST_WORD.has(splitCamelCaseParts(token).slice(-1)[0] ?? "") ||
233
- (/^[A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*$/.test(token) && splitCamelCaseParts(token).length > 1))) {
235
+ // `[A-Z0-9]*` stops at the first lowercase letter: same matches, linear time.
236
+ (/^[A-Z][A-Z0-9]*[a-z][A-Za-z0-9]*$/.test(token) && splitCamelCaseParts(token).length > 1))) {
234
237
  continue;
235
238
  }
236
239
  // A multi-word name that starts with a flag or action word names a flag or a function