@curl-runner/cli 1.13.0 → 1.15.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.
@@ -0,0 +1,181 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import type { ExecutionResult } from '../types/config';
3
+ import { BaselineManager } from './baseline-manager';
4
+
5
+ describe('BaselineManager', () => {
6
+ describe('getBaselinePath', () => {
7
+ test('should generate correct baseline path', () => {
8
+ const manager = new BaselineManager({});
9
+ expect(manager.getBaselinePath('tests/api.yaml', 'staging')).toBe(
10
+ 'tests/__baselines__/api.staging.baseline.json',
11
+ );
12
+ });
13
+
14
+ test('should use custom directory', () => {
15
+ const manager = new BaselineManager({ dir: '.baselines' });
16
+ expect(manager.getBaselinePath('api.yaml', 'prod')).toBe('.baselines/api.prod.baseline.json');
17
+ });
18
+
19
+ test('should handle nested paths', () => {
20
+ const manager = new BaselineManager({});
21
+ expect(manager.getBaselinePath('tests/integration/users.yaml', 'staging')).toBe(
22
+ 'tests/integration/__baselines__/users.staging.baseline.json',
23
+ );
24
+ });
25
+
26
+ test('should handle labels with special characters', () => {
27
+ const manager = new BaselineManager({});
28
+ expect(manager.getBaselinePath('api.yaml', 'v1.0.0')).toBe(
29
+ '__baselines__/api.v1.0.0.baseline.json',
30
+ );
31
+ });
32
+ });
33
+
34
+ describe('getBaselineDir', () => {
35
+ test('should return correct directory', () => {
36
+ const manager = new BaselineManager({});
37
+ expect(manager.getBaselineDir('tests/api.yaml')).toBe('tests/__baselines__');
38
+ });
39
+
40
+ test('should use custom directory', () => {
41
+ const manager = new BaselineManager({ dir: 'snapshots' });
42
+ expect(manager.getBaselineDir('api.yaml')).toBe('snapshots');
43
+ });
44
+ });
45
+
46
+ describe('createBaseline', () => {
47
+ const mockResult: ExecutionResult = {
48
+ request: { url: 'https://api.example.com', name: 'Get Users' },
49
+ success: true,
50
+ status: 200,
51
+ headers: {
52
+ 'Content-Type': 'application/json',
53
+ 'X-Request-Id': 'abc123',
54
+ },
55
+ body: {
56
+ id: 1,
57
+ name: 'Test',
58
+ timestamp: '2024-01-01',
59
+ },
60
+ metrics: {
61
+ duration: 150,
62
+ },
63
+ };
64
+
65
+ test('should create baseline with all fields', () => {
66
+ const manager = new BaselineManager({});
67
+ const baseline = manager.createBaseline(mockResult, {});
68
+
69
+ expect(baseline.status).toBe(200);
70
+ expect(baseline.body).toEqual(mockResult.body);
71
+ expect(baseline.headers).toBeDefined();
72
+ expect(baseline.hash).toBeDefined();
73
+ expect(baseline.capturedAt).toBeDefined();
74
+ expect(baseline.timing).toBeUndefined();
75
+ });
76
+
77
+ test('should include timing when configured', () => {
78
+ const manager = new BaselineManager({});
79
+ const baseline = manager.createBaseline(mockResult, { includeTimings: true });
80
+
81
+ expect(baseline.timing).toBe(150);
82
+ });
83
+
84
+ test('should normalize headers (lowercase, sorted)', () => {
85
+ const manager = new BaselineManager({});
86
+ const baseline = manager.createBaseline(mockResult, {});
87
+
88
+ expect(baseline.headers).toEqual({
89
+ 'content-type': 'application/json',
90
+ 'x-request-id': 'abc123',
91
+ });
92
+ });
93
+ });
94
+
95
+ describe('hash', () => {
96
+ test('should generate consistent hashes', () => {
97
+ const manager = new BaselineManager({});
98
+ const content = { id: 1, name: 'test' };
99
+
100
+ const hash1 = manager.hash(content);
101
+ const hash2 = manager.hash(content);
102
+
103
+ expect(hash1).toBe(hash2);
104
+ });
105
+
106
+ test('should generate different hashes for different content', () => {
107
+ const manager = new BaselineManager({});
108
+
109
+ const hash1 = manager.hash({ id: 1 });
110
+ const hash2 = manager.hash({ id: 2 });
111
+
112
+ expect(hash1).not.toBe(hash2);
113
+ });
114
+
115
+ test('should produce 8 character hash', () => {
116
+ const manager = new BaselineManager({});
117
+ const hash = manager.hash({ data: 'test' });
118
+
119
+ expect(hash).toHaveLength(8);
120
+ });
121
+ });
122
+
123
+ describe('mergeConfig', () => {
124
+ test('should return null if not enabled', () => {
125
+ const config = BaselineManager.mergeConfig({}, undefined);
126
+ expect(config).toBeNull();
127
+ });
128
+
129
+ test('should return null if explicitly disabled', () => {
130
+ const config = BaselineManager.mergeConfig({}, { enabled: false });
131
+ expect(config).toBeNull();
132
+ });
133
+
134
+ test('should handle boolean true', () => {
135
+ const config = BaselineManager.mergeConfig({}, true);
136
+ expect(config).toEqual({
137
+ enabled: true,
138
+ exclude: [],
139
+ match: {},
140
+ includeTimings: false,
141
+ });
142
+ });
143
+
144
+ test('should merge global and request excludes', () => {
145
+ const config = BaselineManager.mergeConfig(
146
+ { exclude: ['*.timestamp'] },
147
+ { enabled: true, exclude: ['body.id'] },
148
+ );
149
+ expect(config?.exclude).toEqual(['*.timestamp', 'body.id']);
150
+ });
151
+
152
+ test('should merge match rules', () => {
153
+ const config = BaselineManager.mergeConfig(
154
+ { match: { 'body.id': '*' } },
155
+ { enabled: true, match: { 'body.token': 'regex:^[a-z]+$' } },
156
+ );
157
+ expect(config?.match).toEqual({
158
+ 'body.id': '*',
159
+ 'body.token': 'regex:^[a-z]+$',
160
+ });
161
+ });
162
+
163
+ test('should use global enabled', () => {
164
+ const config = BaselineManager.mergeConfig({ enabled: true }, undefined);
165
+ expect(config?.enabled).toBe(true);
166
+ });
167
+
168
+ test('should inherit includeTimings from global', () => {
169
+ const config = BaselineManager.mergeConfig({ enabled: true, includeTimings: true }, true);
170
+ expect(config?.includeTimings).toBe(true);
171
+ });
172
+
173
+ test('should allow request to override includeTimings', () => {
174
+ const config = BaselineManager.mergeConfig(
175
+ { enabled: true, includeTimings: false },
176
+ { enabled: true, includeTimings: true },
177
+ );
178
+ expect(config?.includeTimings).toBe(true);
179
+ });
180
+ });
181
+ });
@@ -0,0 +1,266 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import type {
4
+ Baseline,
5
+ BaselineFile,
6
+ DiffConfig,
7
+ ExecutionResult,
8
+ GlobalDiffConfig,
9
+ } from '../types/config';
10
+
11
+ const BASELINE_VERSION = 1;
12
+ const DEFAULT_BASELINE_DIR = '__baselines__';
13
+
14
+ /**
15
+ * Manages baseline files: reading, writing, and listing.
16
+ */
17
+ export class BaselineManager {
18
+ private baselineDir: string;
19
+ private writeLocks: Map<string, Promise<void>> = new Map();
20
+
21
+ constructor(globalConfig: GlobalDiffConfig = {}) {
22
+ this.baselineDir = globalConfig.dir || DEFAULT_BASELINE_DIR;
23
+ }
24
+
25
+ /**
26
+ * Gets the baseline file path for a label.
27
+ */
28
+ getBaselinePath(yamlPath: string, label: string): string {
29
+ const dir = path.dirname(yamlPath);
30
+ const basename = path.basename(yamlPath, path.extname(yamlPath));
31
+ return path.join(dir, this.baselineDir, `${basename}.${label}.baseline.json`);
32
+ }
33
+
34
+ /**
35
+ * Gets the baseline directory for a YAML file.
36
+ */
37
+ getBaselineDir(yamlPath: string): string {
38
+ return path.join(path.dirname(yamlPath), this.baselineDir);
39
+ }
40
+
41
+ /**
42
+ * Loads baseline file for a specific label.
43
+ */
44
+ async load(yamlPath: string, label: string): Promise<BaselineFile | null> {
45
+ const baselinePath = this.getBaselinePath(yamlPath, label);
46
+ try {
47
+ const file = Bun.file(baselinePath);
48
+ if (!(await file.exists())) {
49
+ return null;
50
+ }
51
+ const content = await file.text();
52
+ return JSON.parse(content) as BaselineFile;
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Saves baseline file with write queue for parallel safety.
60
+ */
61
+ async save(yamlPath: string, label: string, data: BaselineFile): Promise<void> {
62
+ const baselinePath = this.getBaselinePath(yamlPath, label);
63
+
64
+ const existingLock = this.writeLocks.get(baselinePath);
65
+ const writePromise = (async () => {
66
+ if (existingLock) {
67
+ await existingLock;
68
+ }
69
+
70
+ const dir = path.dirname(baselinePath);
71
+ await fs.mkdir(dir, { recursive: true });
72
+
73
+ const content = JSON.stringify(data, null, 2);
74
+ await Bun.write(baselinePath, content);
75
+ })();
76
+
77
+ this.writeLocks.set(baselinePath, writePromise);
78
+ await writePromise;
79
+ this.writeLocks.delete(baselinePath);
80
+ }
81
+
82
+ /**
83
+ * Gets a single baseline by request name.
84
+ */
85
+ async get(yamlPath: string, label: string, requestName: string): Promise<Baseline | null> {
86
+ const file = await this.load(yamlPath, label);
87
+ return file?.baselines[requestName] || null;
88
+ }
89
+
90
+ /**
91
+ * Lists all available baseline labels for a YAML file.
92
+ */
93
+ async listLabels(yamlPath: string): Promise<string[]> {
94
+ const dir = this.getBaselineDir(yamlPath);
95
+ const basename = path.basename(yamlPath, path.extname(yamlPath));
96
+
97
+ try {
98
+ const files = await fs.readdir(dir);
99
+ const labels: string[] = [];
100
+
101
+ for (const file of files) {
102
+ const match = file.match(new RegExp(`^${basename}\\.(.+)\\.baseline\\.json$`));
103
+ if (match) {
104
+ labels.push(match[1]);
105
+ }
106
+ }
107
+
108
+ return labels.sort();
109
+ } catch {
110
+ return [];
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Creates a baseline from execution result.
116
+ */
117
+ createBaseline(result: ExecutionResult, config: DiffConfig): Baseline {
118
+ const baseline: Baseline = {
119
+ hash: '',
120
+ capturedAt: new Date().toISOString(),
121
+ };
122
+
123
+ if (result.status !== undefined) {
124
+ baseline.status = result.status;
125
+ }
126
+
127
+ if (result.headers) {
128
+ baseline.headers = this.normalizeHeaders(result.headers);
129
+ }
130
+
131
+ if (result.body !== undefined) {
132
+ baseline.body = result.body;
133
+ }
134
+
135
+ if (config.includeTimings && result.metrics?.duration !== undefined) {
136
+ baseline.timing = result.metrics.duration;
137
+ }
138
+
139
+ baseline.hash = this.hash(baseline);
140
+
141
+ return baseline;
142
+ }
143
+
144
+ /**
145
+ * Normalizes headers for consistent comparison.
146
+ */
147
+ private normalizeHeaders(headers: Record<string, string>): Record<string, string> {
148
+ const normalized: Record<string, string> = {};
149
+ const sortedKeys = Object.keys(headers).sort();
150
+ for (const key of sortedKeys) {
151
+ normalized[key.toLowerCase()] = headers[key];
152
+ }
153
+ return normalized;
154
+ }
155
+
156
+ /**
157
+ * Generates a hash for baseline content.
158
+ */
159
+ hash(content: unknown): string {
160
+ const str = JSON.stringify(content);
161
+ const hasher = new Bun.CryptoHasher('md5');
162
+ hasher.update(str);
163
+ return hasher.digest('hex').slice(0, 8);
164
+ }
165
+
166
+ /**
167
+ * Saves execution results as a baseline.
168
+ */
169
+ async saveBaseline(
170
+ yamlPath: string,
171
+ label: string,
172
+ results: ExecutionResult[],
173
+ config: DiffConfig,
174
+ ): Promise<void> {
175
+ const baselines: Record<string, Baseline> = {};
176
+
177
+ for (const result of results) {
178
+ if (result.skipped || !result.success) {
179
+ continue;
180
+ }
181
+ const name = result.request.name || result.request.url;
182
+ baselines[name] = this.createBaseline(result, config);
183
+ }
184
+
185
+ const file: BaselineFile = {
186
+ version: BASELINE_VERSION,
187
+ label,
188
+ capturedAt: new Date().toISOString(),
189
+ baselines,
190
+ };
191
+
192
+ await this.save(yamlPath, label, file);
193
+ }
194
+
195
+ /**
196
+ * Deletes baselines older than specified days.
197
+ */
198
+ async cleanOldBaselines(yamlPath: string, olderThanDays: number): Promise<number> {
199
+ const dir = this.getBaselineDir(yamlPath);
200
+ const cutoff = Date.now() - olderThanDays * 24 * 60 * 60 * 1000;
201
+ let deleted = 0;
202
+
203
+ try {
204
+ const files = await fs.readdir(dir);
205
+
206
+ for (const file of files) {
207
+ if (!file.endsWith('.baseline.json')) {
208
+ continue;
209
+ }
210
+
211
+ const filePath = path.join(dir, file);
212
+ const stat = await fs.stat(filePath);
213
+
214
+ if (stat.mtimeMs < cutoff) {
215
+ await fs.unlink(filePath);
216
+ deleted++;
217
+ }
218
+ }
219
+ } catch {
220
+ // Directory doesn't exist or other error
221
+ }
222
+
223
+ return deleted;
224
+ }
225
+
226
+ /**
227
+ * Merges request-level config with global config.
228
+ */
229
+ static mergeConfig(
230
+ globalConfig: GlobalDiffConfig | undefined,
231
+ requestConfig: DiffConfig | boolean | undefined,
232
+ ): DiffConfig | null {
233
+ if (!requestConfig && !globalConfig?.enabled) {
234
+ return null;
235
+ }
236
+
237
+ if (requestConfig === true) {
238
+ return {
239
+ enabled: true,
240
+ exclude: globalConfig?.exclude || [],
241
+ match: globalConfig?.match || {},
242
+ includeTimings: globalConfig?.includeTimings || false,
243
+ };
244
+ }
245
+
246
+ if (typeof requestConfig === 'object' && requestConfig.enabled !== false) {
247
+ return {
248
+ enabled: true,
249
+ exclude: [...(globalConfig?.exclude || []), ...(requestConfig.exclude || [])],
250
+ match: { ...(globalConfig?.match || {}), ...(requestConfig.match || {}) },
251
+ includeTimings: requestConfig.includeTimings ?? globalConfig?.includeTimings ?? false,
252
+ };
253
+ }
254
+
255
+ if (globalConfig?.enabled && requestConfig === undefined) {
256
+ return {
257
+ enabled: true,
258
+ exclude: globalConfig.exclude || [],
259
+ match: globalConfig.match || {},
260
+ includeTimings: globalConfig.includeTimings || false,
261
+ };
262
+ }
263
+
264
+ return null;
265
+ }
266
+ }