@sgedda/mockifyer-fetch 1.8.47 → 1.8.72

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.
@@ -9,6 +9,17 @@
9
9
  * 4. GET /mockifyer-sync-to-device - Legacy: all files in one response (may fail on large scenarios)
10
10
  * 5. GET /mockifyer-pool-response?id= - Load a promoted pool response for RN `$pool` resolve
11
11
  * 6. GET /mockifyer-sync - Legacy: iOS simulator mock-data → project folder
12
+ * 7. POST /mockifyer-atlas-html — write crash-scoped trace HTML to mock-data/atlas-html/incidents/
13
+ * 8. GET /atlas-html[/…] (legacy: /mockifyer-atlas-html[/…]) — serve atlas-html static files (index.html, pages, incidents, screenshots)
14
+ * 9. POST /mockifyer-atlas-screenshot — write screen image (png/jpg/webp) under mock-data/atlas-html/screenshots/
15
+ * 10. POST /mockifyer-atlas-render — write full interactive Atlas HTML under mock-data/atlas-html/
16
+ * 11. POST /mockifyer-atlas-body-spill — write full hop body text under mock-data/atlas-html/bodies/
17
+ * 12. POST/GET /mockifyer-network-events — live hop ring buffer for `mockifyer-atlas` CLI
18
+ * 13. GET /mockifyer-network-events/stream — SSE hop stream
19
+ * 14. GET /mockifyer-network-events/analyze — hop summary JSON
20
+ * 15. POST /mockifyer-network-events/snapshot — write hops JSON/NDJSON under atlas-html/
21
+ * 16. POST /mockifyer-network-events/render — render Atlas HTML from buffer hops
22
+ * 17. POST /mockifyer-network-events/clear — clear ring buffer
12
23
  *
13
24
  * The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
14
25
  * Legacy polling-based sync is still available for backward compatibility.
@@ -57,43 +68,85 @@ const fs = __importStar(require("fs"));
57
68
  const path = __importStar(require("path"));
58
69
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
59
70
  const mockifyer_core_2 = require("@sgedda/mockifyer-core");
60
- const DEFAULT_SCENARIO = 'default';
71
+ const DEFAULT_SCENARIO = "default";
72
+ /** Atlas render POSTs can include many hops + body spills — avoid O(n²) string concat. */
73
+ const MAX_METRO_POST_BODY_BYTES = 64 * 1024 * 1024;
61
74
  let autoSyncInterval = null;
75
+ /**
76
+ * Buffer an incoming request body with `Buffer.concat` (not `body += chunk`).
77
+ * Large Atlas render payloads hang for minutes with quadratic string concatenation.
78
+ */
79
+ function collectRequestBodyUtf8(req, onDone, maxBytes = MAX_METRO_POST_BODY_BYTES) {
80
+ const chunks = [];
81
+ let size = 0;
82
+ let settled = false;
83
+ const finish = (err, body) => {
84
+ if (settled)
85
+ return;
86
+ settled = true;
87
+ onDone(err, body);
88
+ };
89
+ req.on("data", (chunk) => {
90
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
91
+ size += buf.length;
92
+ if (size > maxBytes) {
93
+ finish(new Error(`Request body exceeds ${maxBytes} bytes`), "");
94
+ try {
95
+ req.destroy?.();
96
+ }
97
+ catch {
98
+ // ignore
99
+ }
100
+ return;
101
+ }
102
+ chunks.push(buf);
103
+ });
104
+ req.on("end", () => {
105
+ try {
106
+ finish(null, Buffer.concat(chunks).toString("utf8"));
107
+ }
108
+ catch (e) {
109
+ finish(e instanceof Error ? e : new Error(String(e)), "");
110
+ }
111
+ });
112
+ req.on("error", (e) => finish(e, ""));
113
+ }
62
114
  function getMockFilePathLocal(mockData, dateStr) {
63
- const url = mockData.request.url || '';
64
- const method = (mockData.request.method || 'GET').toUpperCase();
65
- let host = 'unknown';
115
+ const url = mockData.request.url || "";
116
+ const method = (mockData.request.method || "GET").toUpperCase();
117
+ let host = "unknown";
66
118
  let pathSegments = [];
67
119
  try {
68
120
  const parsed = new URL(url);
69
121
  host = parsed.hostname;
70
- pathSegments = parsed.pathname.split('/').filter(Boolean);
122
+ pathSegments = parsed.pathname.split("/").filter(Boolean);
71
123
  }
72
124
  catch {
73
- return { dir: 'unknown', filename: `${method}_${dateStr}.json` };
125
+ return { dir: "unknown", filename: `${method}_${dateStr}.json` };
74
126
  }
75
- const hostSafe = host.replace(/[^a-zA-Z0-9.-]/g, '_');
76
- const graphqlIdx = pathSegments.lastIndexOf('graphql');
77
- const restIdx = pathSegments.indexOf('rest');
127
+ const hostSafe = host.replace(/[^a-zA-Z0-9.-]/g, "_");
128
+ const graphqlIdx = pathSegments.lastIndexOf("graphql");
129
+ const restIdx = pathSegments.indexOf("rest");
78
130
  let type;
79
131
  let remainingSegments;
80
132
  if (graphqlIdx >= 0) {
81
- type = 'graphql';
133
+ type = "graphql";
82
134
  remainingSegments = pathSegments.slice(graphqlIdx + 1);
83
135
  }
84
136
  else if (restIdx >= 0) {
85
- type = 'rest';
137
+ type = "rest";
86
138
  remainingSegments = pathSegments.slice(restIdx + 1);
87
139
  }
88
140
  else {
89
- type = '';
141
+ type = "";
90
142
  remainingSegments = pathSegments;
91
143
  }
92
- let identifier = '';
144
+ let identifier = "";
93
145
  if (mockData.request.data) {
94
146
  try {
95
- const body = typeof mockData.request.data === 'string'
96
- ? JSON.parse(mockData.request.data) : mockData.request.data;
147
+ const body = typeof mockData.request.data === "string"
148
+ ? JSON.parse(mockData.request.data)
149
+ : mockData.request.data;
97
150
  if (body.operationName)
98
151
  identifier = body.operationName;
99
152
  else if (body.path)
@@ -101,11 +154,15 @@ function getMockFilePathLocal(mockData, dateStr) {
101
154
  else if (body.webAppName)
102
155
  identifier = body.webAppName;
103
156
  }
104
- catch { /* ignore */ }
157
+ catch {
158
+ /* ignore */
159
+ }
105
160
  }
106
- identifier = identifier.replace(/[^a-zA-Z0-9_-]/g, '_').substring(0, 60);
107
- const dir = [hostSafe, type, ...remainingSegments].filter(Boolean).join('/');
108
- const filename = identifier ? `${method}_${identifier}_${dateStr}.json` : `${method}_${dateStr}.json`;
161
+ identifier = identifier.replace(/[^a-zA-Z0-9_-]/g, "_").substring(0, 60);
162
+ const dir = [hostSafe, type, ...remainingSegments].filter(Boolean).join("/");
163
+ const filename = identifier
164
+ ? `${method}_${identifier}_${dateStr}.json`
165
+ : `${method}_${dateStr}.json`;
109
166
  return { dir, filename };
110
167
  }
111
168
  /**
@@ -118,9 +175,9 @@ function getCurrentScenario(mockDataPath) {
118
175
  }
119
176
  // Try to load from scenario-config.json
120
177
  try {
121
- const configPath = path.join(mockDataPath, 'scenario-config.json');
178
+ const configPath = path.join(mockDataPath, "scenario-config.json");
122
179
  if (fs.existsSync(configPath)) {
123
- const fileContent = fs.readFileSync(configPath, 'utf-8');
180
+ const fileContent = fs.readFileSync(configPath, "utf-8");
124
181
  const config = JSON.parse(fileContent);
125
182
  if (config.currentScenario) {
126
183
  return config.currentScenario;
@@ -146,20 +203,30 @@ function getScenarioPath(scenario, mockDataPath) {
146
203
  function getTestGenerationConfig(options) {
147
204
  // Check if enabled via options or environment variables
148
205
  const enabled = options?.testGeneration?.enabled === true ||
149
- process.env.MOCKIFYER_GENERATE_TESTS === 'true' ||
150
- process.env.MOCKIFYER_GENERATE_TESTS === '1';
206
+ process.env.MOCKIFYER_GENERATE_TESTS === "true" ||
207
+ process.env.MOCKIFYER_GENERATE_TESTS === "1";
151
208
  if (!enabled) {
152
209
  return null;
153
210
  }
154
211
  // Use options if provided, otherwise fall back to environment variables
155
212
  return {
156
- framework: options?.testGeneration?.framework || process.env.MOCKIFYER_TEST_FRAMEWORK || 'jest',
157
- outputPath: options?.testGeneration?.outputPath || process.env.MOCKIFYER_TEST_OUTPUT_PATH || './tests/generated',
158
- testPattern: options?.testGeneration?.testPattern || process.env.MOCKIFYER_TEST_PATTERN || '{endpoint}.test.ts',
159
- includeSetup: options?.testGeneration?.includeSetup !== false && process.env.MOCKIFYER_TEST_INCLUDE_SETUP !== 'false',
160
- groupBy: options?.testGeneration?.groupBy || process.env.MOCKIFYER_TEST_GROUP_BY || 'endpoint',
161
- httpClientType: 'fetch',
162
- uniqueTestsPerEndpoint: options?.testGeneration?.uniqueTestsPerEndpoint || process.env.MOCKIFYER_UNIQUE_TESTS_PER_ENDPOINT === 'true',
213
+ framework: options?.testGeneration?.framework ||
214
+ process.env.MOCKIFYER_TEST_FRAMEWORK ||
215
+ "jest",
216
+ outputPath: options?.testGeneration?.outputPath ||
217
+ process.env.MOCKIFYER_TEST_OUTPUT_PATH ||
218
+ "./tests/generated",
219
+ testPattern: options?.testGeneration?.testPattern ||
220
+ process.env.MOCKIFYER_TEST_PATTERN ||
221
+ "{endpoint}.test.ts",
222
+ includeSetup: options?.testGeneration?.includeSetup !== false &&
223
+ process.env.MOCKIFYER_TEST_INCLUDE_SETUP !== "false",
224
+ groupBy: options?.testGeneration?.groupBy ||
225
+ process.env.MOCKIFYER_TEST_GROUP_BY ||
226
+ "endpoint",
227
+ httpClientType: "fetch",
228
+ uniqueTestsPerEndpoint: options?.testGeneration?.uniqueTestsPerEndpoint ||
229
+ process.env.MOCKIFYER_UNIQUE_TESTS_PER_ENDPOINT === "true",
163
230
  };
164
231
  }
165
232
  /**
@@ -172,11 +239,11 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
172
239
  try {
173
240
  let mockifyerCore;
174
241
  try {
175
- mockifyerCore = require('@sgedda/mockifyer-core');
242
+ mockifyerCore = require("@sgedda/mockifyer-core");
176
243
  }
177
244
  catch (e) {
178
245
  // Fallback: try relative path (for local file: dependencies)
179
- const corePath = path.join(projectRoot, '../../packages/mockifyer-core/dist/index.js');
246
+ const corePath = path.join(projectRoot, "../../packages/mockifyer-core/dist/index.js");
180
247
  if (fs.existsSync(corePath)) {
181
248
  mockifyerCore = require(corePath);
182
249
  }
@@ -186,7 +253,7 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
186
253
  }
187
254
  TestGeneratorClass = mockifyerCore?.TestGenerator;
188
255
  if (!TestGeneratorClass) {
189
- const testGeneratorPath = path.join(projectRoot, '../../packages/mockifyer-core/dist/utils/test-generator.js');
256
+ const testGeneratorPath = path.join(projectRoot, "../../packages/mockifyer-core/dist/utils/test-generator.js");
190
257
  if (fs.existsSync(testGeneratorPath)) {
191
258
  const testGeneratorModule = require(testGeneratorPath);
192
259
  TestGeneratorClass = testGeneratorModule.TestGenerator;
@@ -209,7 +276,7 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
209
276
  httpClientType: testConfig.httpClientType,
210
277
  uniqueTestsPerEndpoint: testConfig.uniqueTestsPerEndpoint,
211
278
  };
212
- const testInfo = generator.analyzeMock(mockData, options.httpClientType || 'fetch');
279
+ const testInfo = generator.analyzeMock(mockData, options.httpClientType || "fetch");
213
280
  const testFilePath = generator.determineTestFilePath(mockData, options);
214
281
  const absoluteTestPath = path.resolve(projectRoot, testFilePath);
215
282
  const testDir = path.dirname(absoluteTestPath);
@@ -225,8 +292,9 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
225
292
  // Check if test file already exists
226
293
  if (fs.existsSync(absoluteTestPath)) {
227
294
  const testName = `${testInfo.method} ${testInfo.endpoint}`;
228
- const existingContent = fs.readFileSync(absoluteTestPath, 'utf-8');
229
- if (existingContent.includes(`it('${testName}'`) || existingContent.includes(`it("${testName}"`)) {
295
+ const existingContent = fs.readFileSync(absoluteTestPath, "utf-8");
296
+ if (existingContent.includes(`it('${testName}'`) ||
297
+ existingContent.includes(`it("${testName}"`)) {
230
298
  return true;
231
299
  }
232
300
  // Append test to existing file
@@ -256,28 +324,43 @@ function generateTestForMock(mockData, testConfig, projectRoot) {
256
324
  function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig) {
257
325
  try {
258
326
  // CRITICAL: Never save Mockifyer sync endpoint requests to prevent infinite loops
259
- const url = mockData?.request?.url || '';
327
+ const url = mockData?.request?.url || "";
260
328
  if ((0, mockifyer_core_2.containsMockifyerSyncEndpointMarker)(url)) {
261
329
  console.warn(`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`);
262
- return { success: false, error: 'Cannot save Mockifyer sync endpoint requests' };
330
+ return {
331
+ success: false,
332
+ error: "Cannot save Mockifyer sync endpoint requests",
333
+ };
263
334
  }
264
335
  // Also check if the mockData string contains nested sync requests
265
336
  const mockDataStr = JSON.stringify(mockData);
266
337
  if ((0, mockifyer_core_2.containsMockifyerSyncEndpointMarker)(mockDataStr)) {
267
338
  mockifyer_core_1.logger.warn(`[MockSync] ⚠️ Rejecting save - Mock data contains nested Mockifyer sync requests`);
268
- return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
339
+ return {
340
+ success: false,
341
+ error: "Mock data contains nested Mockifyer sync requests",
342
+ };
269
343
  }
270
344
  // Get current scenario and ensure scenario folder exists
271
345
  const currentScenario = getCurrentScenario(mockDataPath);
272
346
  const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
273
347
  fs.mkdirSync(scenarioPath, { recursive: true });
274
- const dateStr = new Date().toISOString().replace(/T/, '_').replace(/\..+/, '').replace(/:/g, '-');
348
+ const dateStr = new Date()
349
+ .toISOString()
350
+ .replace(/T/, "_")
351
+ .replace(/\..+/, "")
352
+ .replace(/:/g, "-");
275
353
  const { dir, filename } = getMockFilePathLocal(mockData, dateStr);
276
354
  const fullDir = path.join(scenarioPath, dir);
277
355
  const filePath = path.join(fullDir, filename);
278
356
  // Check if file already exists - skip saving if it does
279
357
  if (fs.existsSync(filePath)) {
280
- return { success: true, filename: path.join(dir, filename), skipped: true, reason: 'File already exists' };
358
+ return {
359
+ success: true,
360
+ filename: path.join(dir, filename),
361
+ skipped: true,
362
+ reason: "File already exists",
363
+ };
281
364
  }
282
365
  fs.mkdirSync(fullDir, { recursive: true });
283
366
  // Write to file
@@ -286,7 +369,11 @@ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig
286
369
  if (testConfig) {
287
370
  generateTestForMock(mockData, testConfig, projectRoot);
288
371
  }
289
- return { success: true, filename: path.join(dir, filename), scenario: currentScenario };
372
+ return {
373
+ success: true,
374
+ filename: path.join(dir, filename),
375
+ scenario: currentScenario,
376
+ };
290
377
  }
291
378
  catch (error) {
292
379
  console.error(`[MockSync] ❌ Error saving mock to project folder:`, error);
@@ -299,22 +386,28 @@ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig
299
386
  */
300
387
  function saveProxyMirrorMockToProject(mockData, projectRoot, mockDataPath, scenarioName, relativePath, testConfig) {
301
388
  try {
302
- const url = mockData?.request?.url || '';
389
+ const url = mockData?.request?.url || "";
303
390
  if ((0, mockifyer_core_2.containsMockifyerSyncEndpointMarker)(url)) {
304
391
  console.warn(`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`);
305
- return { success: false, error: 'Cannot save Mockifyer sync endpoint requests' };
392
+ return {
393
+ success: false,
394
+ error: "Cannot save Mockifyer sync endpoint requests",
395
+ };
306
396
  }
307
397
  const mockDataStr = JSON.stringify(mockData);
308
398
  if ((0, mockifyer_core_2.containsMockifyerSyncEndpointMarker)(mockDataStr)) {
309
- return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
399
+ return {
400
+ success: false,
401
+ error: "Mock data contains nested Mockifyer sync requests",
402
+ };
310
403
  }
311
404
  const id = scenarioName.trim();
312
405
  if (!id) {
313
- return { success: false, error: 'scenarioName is required' };
406
+ return { success: false, error: "scenarioName is required" };
314
407
  }
315
- const normalized = relativePath.replace(/\\/g, '/').replace(/^\//, '');
408
+ const normalized = relativePath.replace(/\\/g, "/").replace(/^\//, "");
316
409
  if (!normalized) {
317
- return { success: false, error: 'relativePath is required' };
410
+ return { success: false, error: "relativePath is required" };
318
411
  }
319
412
  const scenarioPath = getScenarioPath(id, mockDataPath);
320
413
  fs.mkdirSync(scenarioPath, { recursive: true });
@@ -343,8 +436,8 @@ function clearMockFiles(mockDataPath) {
343
436
  }
344
437
  const files = fs.readdirSync(scenarioPath);
345
438
  let deleted = 0;
346
- files.forEach(file => {
347
- if (file.endsWith('.json')) {
439
+ files.forEach((file) => {
440
+ if (file.endsWith(".json")) {
348
441
  const filePath = path.join(scenarioPath, file);
349
442
  fs.unlinkSync(filePath);
350
443
  deleted++;
@@ -363,16 +456,16 @@ function clearMockFiles(mockDataPath) {
363
456
  function syncFromIOSSimulator(projectRoot, mockDataPath) {
364
457
  try {
365
458
  // Get iOS simulator path
366
- const homeDir = process.env.HOME || process.env.USERPROFILE || '';
367
- const simulatorPath = path.join(homeDir, 'Library/Developer/CoreSimulator/Devices');
459
+ const homeDir = process.env.HOME || process.env.USERPROFILE || "";
460
+ const simulatorPath = path.join(homeDir, "Library/Developer/CoreSimulator/Devices");
368
461
  if (!fs.existsSync(simulatorPath)) {
369
- return { success: false, error: 'iOS Simulator path not found' };
462
+ return { success: false, error: "iOS Simulator path not found" };
370
463
  }
371
464
  // Find the most recent simulator device
372
465
  const devices = fs.readdirSync(simulatorPath);
373
- let latestDevice = '';
466
+ let latestDevice = "";
374
467
  let latestTime = 0;
375
- devices.forEach(device => {
468
+ devices.forEach((device) => {
376
469
  const devicePath = path.join(simulatorPath, device);
377
470
  const stat = fs.statSync(devicePath);
378
471
  if (stat.mtimeMs > latestTime) {
@@ -381,12 +474,12 @@ function syncFromIOSSimulator(projectRoot, mockDataPath) {
381
474
  }
382
475
  });
383
476
  if (!latestDevice) {
384
- return { success: false, error: 'No iOS Simulator device found' };
477
+ return { success: false, error: "No iOS Simulator device found" };
385
478
  }
386
479
  // Look for mock-data directory in the simulator
387
- const appDataPath = path.join(simulatorPath, latestDevice, 'data/Containers/Data/Application');
480
+ const appDataPath = path.join(simulatorPath, latestDevice, "data/Containers/Data/Application");
388
481
  if (!fs.existsSync(appDataPath)) {
389
- return { success: false, error: 'iOS Simulator app data path not found' };
482
+ return { success: false, error: "iOS Simulator app data path not found" };
390
483
  }
391
484
  const apps = fs.readdirSync(appDataPath);
392
485
  let found = false;
@@ -394,15 +487,15 @@ function syncFromIOSSimulator(projectRoot, mockDataPath) {
394
487
  const syncedFiles = [];
395
488
  for (const app of apps) {
396
489
  const appPath = path.join(appDataPath, app);
397
- const mockDataSimPath = path.join(appPath, 'Documents/mock-data');
490
+ const mockDataSimPath = path.join(appPath, "Documents/mock-data");
398
491
  if (fs.existsSync(mockDataSimPath)) {
399
492
  found = true;
400
493
  const currentScenario = getCurrentScenario(mockDataPath);
401
494
  const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
402
495
  fs.mkdirSync(scenarioPath, { recursive: true });
403
496
  const files = fs.readdirSync(mockDataSimPath);
404
- files.forEach(file => {
405
- if (file.endsWith('.json')) {
497
+ files.forEach((file) => {
498
+ if (file.endsWith(".json")) {
406
499
  const sourcePath = path.join(mockDataSimPath, file);
407
500
  const destPath = path.join(scenarioPath, file);
408
501
  fs.copyFileSync(sourcePath, destPath);
@@ -414,7 +507,11 @@ function syncFromIOSSimulator(projectRoot, mockDataPath) {
414
507
  }
415
508
  }
416
509
  if (!found) {
417
- return { success: false, filesSynced: 0, error: 'mock-data directory not found in simulator' };
510
+ return {
511
+ success: false,
512
+ filesSynced: 0,
513
+ error: "mock-data directory not found in simulator",
514
+ };
418
515
  }
419
516
  return { success: true, filesSynced, syncedFiles };
420
517
  }
@@ -436,11 +533,11 @@ function listScenarioMockJsonFiles(scenarioAbsPath) {
436
533
  if (entry.isDirectory()) {
437
534
  walk(full);
438
535
  }
439
- else if (entry.name.endsWith('.json')) {
536
+ else if (entry.name.endsWith(".json")) {
440
537
  const rel = path.relative(scenarioAbsPath, full);
441
- const relativePath = rel.split(path.sep).join('/');
442
- if (relativePath === 'scenario-config.json' ||
443
- relativePath === 'date-config.json') {
538
+ const relativePath = rel.split(path.sep).join("/");
539
+ if (relativePath === "scenario-config.json" ||
540
+ relativePath === "date-config.json") {
444
541
  continue;
445
542
  }
446
543
  out.push({ relativePath, fullPath: full });
@@ -461,17 +558,18 @@ function resolveScenarioRelativeMockPath(rawQueryPath, scenarioAbsPath) {
461
558
  catch {
462
559
  return null;
463
560
  }
464
- const normalized = decoded.replace(/\\/g, '/').replace(/^\//, '');
465
- if (!normalized.endsWith('.json') || normalized.includes('..')) {
561
+ const normalized = decoded.replace(/\\/g, "/").replace(/^\//, "");
562
+ if (!normalized.endsWith(".json") || normalized.includes("..")) {
466
563
  return null;
467
564
  }
468
565
  const fullPath = path.normalize(path.join(scenarioAbsPath, normalized));
469
566
  const scenarioResolved = path.resolve(scenarioAbsPath);
470
567
  const relativeToScenario = path.relative(scenarioResolved, fullPath);
471
- if (relativeToScenario.startsWith('..') || path.isAbsolute(relativeToScenario)) {
568
+ if (relativeToScenario.startsWith("..") ||
569
+ path.isAbsolute(relativeToScenario)) {
472
570
  return null;
473
571
  }
474
- const relativePath = relativeToScenario.split(path.sep).join('/');
572
+ const relativePath = relativeToScenario.split(path.sep).join("/");
475
573
  return { relativePath, fullPath };
476
574
  }
477
575
  /**
@@ -508,16 +606,19 @@ function buildSyncToDeviceSingleFilePayload(mockDataPath, rawPathParam) {
508
606
  const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
509
607
  const resolved = resolveScenarioRelativeMockPath(rawPathParam, scenarioPath);
510
608
  if (!resolved) {
511
- return { success: false, error: 'Invalid or unsafe path' };
609
+ return { success: false, error: "Invalid or unsafe path" };
512
610
  }
513
611
  const { fullPath, relativePath } = resolved;
514
612
  if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {
515
- return { success: false, error: 'Not found' };
613
+ return { success: false, error: "Not found" };
516
614
  }
517
- const raw = fs.readFileSync(fullPath, 'utf-8');
615
+ const raw = fs.readFileSync(fullPath, "utf-8");
518
616
  const content = JSON.parse(raw);
519
617
  if (!content?.request || !content?.response) {
520
- return { success: false, error: 'Invalid mock JSON (missing request/response)' };
618
+ return {
619
+ success: false,
620
+ error: "Invalid mock JSON (missing request/response)",
621
+ };
521
622
  }
522
623
  const stat = fs.statSync(fullPath);
523
624
  return {
@@ -542,7 +643,7 @@ function buildSyncToDevicePayload(mockDataPath) {
542
643
  const files = [];
543
644
  for (const { relativePath, fullPath } of entries) {
544
645
  try {
545
- const raw = fs.readFileSync(fullPath, 'utf-8');
646
+ const raw = fs.readFileSync(fullPath, "utf-8");
546
647
  const content = JSON.parse(raw);
547
648
  if (!content?.request || !content?.response) {
548
649
  mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] Skipping JSON without request/response: ${relativePath}`);
@@ -571,9 +672,9 @@ function buildSyncToDevicePayload(mockDataPath) {
571
672
  * Used by React Native serve-time `$pool` resolution when Node fs is unavailable.
572
673
  */
573
674
  function buildPoolResponsePayload(mockDataPath, rawId) {
574
- const id = String(rawId || '').trim();
675
+ const id = String(rawId || "").trim();
575
676
  if (!id || !mockifyer_core_2.POOL_ID_PATTERN.test(id)) {
576
- return { success: false, error: 'Invalid pool response id' };
677
+ return { success: false, error: "Invalid pool response id" };
577
678
  }
578
679
  try {
579
680
  const item = (0, mockifyer_core_2.loadPoolResponseItem)(mockDataPath, id, {
@@ -581,12 +682,12 @@ function buildPoolResponsePayload(mockDataPath, rawId) {
581
682
  existsSync: (p) => fs.existsSync(p),
582
683
  readFileSync: (p, encoding) => fs.readFileSync(p, encoding),
583
684
  writeFileSync: () => {
584
- throw new Error('pool loader is read-only');
685
+ throw new Error("pool loader is read-only");
585
686
  },
586
687
  mkdirSync: () => undefined,
587
688
  });
588
689
  if (!item) {
589
- return { success: false, error: 'Not found' };
690
+ return { success: false, error: "Not found" };
590
691
  }
591
692
  return { success: true, item };
592
693
  }
@@ -599,58 +700,488 @@ function buildPoolResponsePayload(mockDataPath, rawId) {
599
700
  * Without this, trailing slashes fall through to Expo Web's SPA and Expo Router treats them as AppDun routes.
600
701
  */
601
702
  function normalizeMiddlewarePathname(reqUrl) {
602
- if (!reqUrl || typeof reqUrl !== 'string') {
603
- return '/';
703
+ if (!reqUrl || typeof reqUrl !== "string") {
704
+ return "/";
604
705
  }
605
- let pathname = reqUrl.split('?')[0];
606
- if (pathname.length > 1 && pathname.endsWith('/')) {
706
+ let pathname = reqUrl.split("?")[0];
707
+ if (pathname.length > 1 && pathname.endsWith("/")) {
607
708
  pathname = pathname.slice(0, -1);
608
709
  }
609
710
  return pathname;
610
711
  }
712
+ function saveAtlasHtmlIncident(projectRoot, mockDataPath, incidentId, html) {
713
+ const id = incidentId.trim();
714
+ if (!id || !html.trim()) {
715
+ return { success: false, error: "incidentId and html are required" };
716
+ }
717
+ if (id.includes("..") || id.includes("/") || id.includes("\\")) {
718
+ return { success: false, error: "Invalid incident id" };
719
+ }
720
+ try {
721
+ const dir = path.join(mockDataPath, "atlas-html", "incidents");
722
+ fs.mkdirSync(dir, { recursive: true });
723
+ const filePath = path.join(dir, `${id}.html`);
724
+ fs.writeFileSync(filePath, html, "utf8");
725
+ const relativeFromRoot = path.relative(projectRoot, filePath);
726
+ return {
727
+ success: true,
728
+ filePath,
729
+ relativePath: relativeFromRoot.split(path.sep).join("/"),
730
+ };
731
+ }
732
+ catch (error) {
733
+ return { success: false, error: error.message };
734
+ }
735
+ }
736
+ function saveAtlasScreenshot(projectRoot, mockDataPath, relativePath, base64, metadata) {
737
+ const rel = relativePath.trim().replace(/^\/+/, "");
738
+ if (!rel || !base64.trim()) {
739
+ return { success: false, error: "relativePath and base64 are required" };
740
+ }
741
+ if (rel.includes("..") ||
742
+ !rel.startsWith("screenshots/") ||
743
+ !/\.(png|jpe?g|webp)$/i.test(rel)) {
744
+ return {
745
+ success: false,
746
+ error: "relativePath must be screenshots/<name>.(png|jpg|webp)",
747
+ };
748
+ }
749
+ const fileName = path.basename(rel);
750
+ if (!fileName || fileName === "." || fileName === "..") {
751
+ return { success: false, error: "Invalid screenshot file name" };
752
+ }
753
+ try {
754
+ const dir = path.join(mockDataPath, "atlas-html", "screenshots");
755
+ fs.mkdirSync(dir, { recursive: true });
756
+ const filePath = path.join(dir, fileName);
757
+ fs.writeFileSync(filePath, Buffer.from(base64.trim(), "base64"));
758
+ const relativeFromRoot = path.relative(projectRoot, filePath);
759
+ // Update Atlas doc map with screenshot metadata (Metro has fs, so HTML will be written)
760
+ if (metadata?.screen && metadata?.sessionId) {
761
+ const htmlPath = path.join(mockDataPath, "atlas-html");
762
+ (0, mockifyer_core_2.setAtlasDocHtmlOutputPath)(htmlPath);
763
+ (0, mockifyer_core_2.setAtlasDocScreenshot)({
764
+ scenario: metadata.scenario,
765
+ screen: metadata.screen,
766
+ sessionId: metadata.sessionId,
767
+ screenshotPath: rel,
768
+ capturedAt: metadata.capturedAt ?? new Date().toISOString(),
769
+ pageId: metadata.pageId,
770
+ });
771
+ (0, mockifyer_core_2.flushAtlasDocHtmlRewrite)();
772
+ }
773
+ return {
774
+ success: true,
775
+ filePath,
776
+ relativePath: relativeFromRoot.split(path.sep).join("/"),
777
+ };
778
+ }
779
+ catch (error) {
780
+ return { success: false, error: error.message };
781
+ }
782
+ }
783
+ const BODY_SPILL_REL_PATTERN = /^bodies\/[A-Za-z0-9._-]+-(req|res)\.(json|txt)$/;
784
+ /**
785
+ * Persist a full hop body spill from the device (RN) under atlas-html/bodies/.
786
+ */
787
+ function saveAtlasBodySpill(projectRoot, mockDataPath, relativePath, text) {
788
+ const rel = relativePath.trim().replace(/^\/+/, "").replace(/\\/g, "/");
789
+ if (!rel || typeof text !== "string") {
790
+ return { success: false, error: "relativePath and text are required" };
791
+ }
792
+ if (rel.includes("..") || !BODY_SPILL_REL_PATTERN.test(rel)) {
793
+ return {
794
+ success: false,
795
+ error: "relativePath must be bodies/<id>-req.json or bodies/<id>-res.json",
796
+ };
797
+ }
798
+ try {
799
+ const filePath = path.join(mockDataPath, "atlas-html", rel);
800
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
801
+ const body = rel.endsWith(".json") ? (0, mockifyer_core_2.prettyPrintJsonText)(text) : text;
802
+ fs.writeFileSync(filePath, body, "utf8");
803
+ const relativeFromRoot = path.relative(projectRoot, filePath);
804
+ return {
805
+ success: true,
806
+ filePath,
807
+ relativePath: relativeFromRoot.split(path.sep).join("/"),
808
+ };
809
+ }
810
+ catch (error) {
811
+ return { success: false, error: error.message };
812
+ }
813
+ }
814
+ const ATLAS_HTML_CONTENT_TYPES = {
815
+ ".html": "text/html; charset=utf-8",
816
+ ".htm": "text/html; charset=utf-8",
817
+ ".png": "image/png",
818
+ ".jpg": "image/jpeg",
819
+ ".jpeg": "image/jpeg",
820
+ ".webp": "image/webp",
821
+ ".gif": "image/gif",
822
+ ".svg": "image/svg+xml",
823
+ ".json": "application/json; charset=utf-8",
824
+ ".md": "text/markdown; charset=utf-8",
825
+ ".txt": "text/plain; charset=utf-8",
826
+ ".css": "text/css; charset=utf-8",
827
+ ".js": "text/javascript; charset=utf-8",
828
+ };
829
+ /**
830
+ * Serve any safe file under mock-data/atlas-html/ (index, pages, incidents, screenshots).
831
+ * Prevents path traversal; directories resolve to index.html.
832
+ */
833
+ function serveAtlasHtmlStatic(mockDataPath, relativeUrlPath, res) {
834
+ let rel = relativeUrlPath.split("?")[0] || "";
835
+ try {
836
+ rel = decodeURIComponent(rel);
837
+ }
838
+ catch {
839
+ res.statusCode = 400;
840
+ res.setHeader("Content-Type", "text/plain");
841
+ res.end("Invalid path encoding");
842
+ return true;
843
+ }
844
+ rel = rel.replace(/^\/+/, "").replace(/\\/g, "/");
845
+ if (!rel || rel.endsWith("/")) {
846
+ rel = `${rel}index.html`.replace(/^\//, "");
847
+ }
848
+ if (!rel || rel.includes("..") || path.isAbsolute(rel)) {
849
+ res.statusCode = 400;
850
+ res.setHeader("Content-Type", "text/plain");
851
+ res.end("Invalid atlas-html path");
852
+ return true;
853
+ }
854
+ const root = path.resolve(mockDataPath, "atlas-html");
855
+ const filePath = path.resolve(root, rel);
856
+ const rootPrefix = root.endsWith(path.sep) ? root : root + path.sep;
857
+ if (filePath !== root && !filePath.startsWith(rootPrefix)) {
858
+ res.statusCode = 400;
859
+ res.setHeader("Content-Type", "text/plain");
860
+ res.end("Invalid atlas-html path");
861
+ return true;
862
+ }
863
+ if (!fs.existsSync(filePath)) {
864
+ res.statusCode = 404;
865
+ res.setHeader("Content-Type", "text/plain");
866
+ res.end("Atlas HTML file not found — run Dev Menu “Render Atlas docs” first.");
867
+ return true;
868
+ }
869
+ const stat = fs.statSync(filePath);
870
+ if (stat.isDirectory()) {
871
+ const indexPath = path.join(filePath, "index.html");
872
+ if (!fs.existsSync(indexPath) || !fs.statSync(indexPath).isFile()) {
873
+ res.statusCode = 404;
874
+ res.setHeader("Content-Type", "text/plain");
875
+ res.end("Atlas HTML index not found in directory.");
876
+ return true;
877
+ }
878
+ res.setHeader("Content-Type", "text/html; charset=utf-8");
879
+ res.setHeader("Cache-Control", "no-cache");
880
+ res.end(fs.readFileSync(indexPath, "utf8"));
881
+ return true;
882
+ }
883
+ if (!stat.isFile()) {
884
+ res.statusCode = 404;
885
+ res.setHeader("Content-Type", "text/plain");
886
+ res.end("Not a file");
887
+ return true;
888
+ }
889
+ const ext = path.extname(filePath).toLowerCase();
890
+ const contentType = ATLAS_HTML_CONTENT_TYPES[ext] || "application/octet-stream";
891
+ res.setHeader("Content-Type", contentType);
892
+ res.setHeader("Cache-Control", "no-cache");
893
+ res.end(fs.readFileSync(filePath));
894
+ return true;
895
+ }
896
+ const NETWORK_STREAM_NDJSON_REL = path.join("atlas-html", "atlas.ndjson");
897
+ function appendNetworkEventNdjson(mockDataPath, event) {
898
+ try {
899
+ const filePath = path.join(mockDataPath, NETWORK_STREAM_NDJSON_REL);
900
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
901
+ fs.appendFileSync(filePath, `${JSON.stringify(event)}\n`, "utf8");
902
+ }
903
+ catch {
904
+ // disk append is best-effort
905
+ }
906
+ }
907
+ function writeNetworkEventsSnapshot(mockDataPath, events) {
908
+ const dir = path.join(mockDataPath, "atlas-html");
909
+ fs.mkdirSync(dir, { recursive: true });
910
+ const jsonPath = path.join(dir, "atlas-events.json");
911
+ const ndjsonPath = path.join(dir, "atlas.ndjson");
912
+ const harPath = path.join(dir, "atlas.har");
913
+ fs.writeFileSync(jsonPath, `${JSON.stringify(events, null, 2)}\n`, "utf8");
914
+ fs.writeFileSync(ndjsonPath, `${events.map((e) => JSON.stringify(e)).join("\n")}${events.length ? "\n" : ""}`, "utf8");
915
+ fs.writeFileSync(harPath, (0, mockifyer_core_2.buildAtlasHarJson)(events), "utf8");
916
+ return { dir, jsonPath, ndjsonPath, harPath, count: events.length };
917
+ }
918
+ function renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events, scenario) {
919
+ const outDir = path.join(mockDataPath, "atlas-html");
920
+ const doc = (0, mockifyer_core_2.createEmptyAtlasDocMap)(scenario?.trim() || events[0]?.scenario || "default");
921
+ // Flush any buffered large bodies so HTML "Open full …" links resolve on disk.
922
+ (0, mockifyer_core_2.flushNetworkBodySpillsToDir)(outDir);
923
+ const written = (0, mockifyer_core_2.writeAtlasDocHtml)(outDir, doc, events);
924
+ writeNetworkEventsSnapshot(mockDataPath, events);
925
+ const relativeFromRoot = path
926
+ .relative(projectRoot, outDir)
927
+ .split(path.sep)
928
+ .join("/");
929
+ const indexPath = path.join(outDir, "index.html");
930
+ return {
931
+ success: written > 0,
932
+ written,
933
+ outputDir: relativeFromRoot,
934
+ indexPath,
935
+ hopCount: events.length,
936
+ error: written > 0 ? undefined : "writeAtlasDocHtml wrote 0 files",
937
+ };
938
+ }
939
+ /** GET path under `/atlas-html/` or legacy `/mockifyer-atlas-html/` → file under mock-data/atlas-html/. */
940
+ function atlasHtmlStaticSuffix(url) {
941
+ const prefixes = ["/atlas-html", "/mockifyer-atlas-html"];
942
+ for (const prefix of prefixes) {
943
+ if (url === prefix || url === `${prefix}/`) {
944
+ return "index.html";
945
+ }
946
+ if (url.startsWith(`${prefix}/`)) {
947
+ return url.slice(prefix.length + 1);
948
+ }
949
+ }
950
+ return null;
951
+ }
611
952
  /**
612
953
  * Metro middleware function
613
954
  */
614
955
  function createMockSyncMiddleware(options) {
615
956
  const projectRoot = options?.projectRoot || process.cwd();
616
- const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
957
+ const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || "mock-data");
617
958
  const testConfig = getTestGenerationConfig(options);
618
959
  // Log the resolved paths for debugging
619
960
  mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Initialized with projectRoot: ${projectRoot}, mockDataPath: ${mockDataPath}`);
620
961
  return function mockSyncMiddleware(req, res, next) {
621
- const url = normalizeMiddlewarePathname(req.url || '');
962
+ const url = normalizeMiddlewarePathname(req.url || "");
622
963
  // Handle POST endpoint for clearing mocks
623
- if (url === '/mockifyer-clear' && req.method === 'POST') {
964
+ if (url === "/mockifyer-clear" && req.method === "POST") {
624
965
  const result = clearMockFiles(mockDataPath);
625
- res.setHeader('Content-Type', 'application/json');
966
+ res.setHeader("Content-Type", "application/json");
626
967
  res.end(JSON.stringify(result));
627
968
  return;
628
969
  }
970
+ // Live hop ring buffer for `mockifyer-atlas` interactive CLI
971
+ if (url === "/mockifyer-network-events" && req.method === "POST") {
972
+ collectRequestBodyUtf8(req, (err, body) => {
973
+ if (err) {
974
+ res.statusCode = 413;
975
+ res.setHeader("Content-Type", "application/json");
976
+ res.end(JSON.stringify({ success: false, error: err.message }));
977
+ return;
978
+ }
979
+ try {
980
+ const parsed = JSON.parse(body);
981
+ const incoming = [];
982
+ if (parsed.event && typeof parsed.event === "object") {
983
+ incoming.push(parsed.event);
984
+ }
985
+ if (Array.isArray(parsed.events)) {
986
+ for (const e of parsed.events) {
987
+ if (e && typeof e === "object")
988
+ incoming.push(e);
989
+ }
990
+ }
991
+ if (incoming.length === 0) {
992
+ res.statusCode = 400;
993
+ res.setHeader("Content-Type", "application/json");
994
+ res.end(JSON.stringify({
995
+ success: false,
996
+ error: "event or events required",
997
+ }));
998
+ return;
999
+ }
1000
+ const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1001
+ const saved = incoming.map((e) => {
1002
+ const stored = buffer.append(e);
1003
+ appendNetworkEventNdjson(mockDataPath, stored);
1004
+ return stored;
1005
+ });
1006
+ res.statusCode = 201;
1007
+ res.setHeader("Content-Type", "application/json");
1008
+ res.end(JSON.stringify({
1009
+ success: true,
1010
+ count: saved.length,
1011
+ size: buffer.size,
1012
+ }));
1013
+ }
1014
+ catch (error) {
1015
+ res.statusCode = 400;
1016
+ res.setHeader("Content-Type", "application/json");
1017
+ res.end(JSON.stringify({
1018
+ success: false,
1019
+ error: `Invalid JSON: ${error.message}`,
1020
+ }));
1021
+ }
1022
+ });
1023
+ return;
1024
+ }
1025
+ if (url === "/mockifyer-network-events" && req.method === "GET") {
1026
+ const fullUrl = req.url || "";
1027
+ const qIndex = fullUrl.indexOf("?");
1028
+ const params = new URLSearchParams(qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "");
1029
+ const limitRaw = params.get("limit");
1030
+ const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;
1031
+ const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1032
+ const events = buffer.list(Number.isFinite(limit) ? limit : undefined);
1033
+ res.setHeader("Content-Type", "application/json");
1034
+ res.end(JSON.stringify({ success: true, size: buffer.size, events }));
1035
+ return;
1036
+ }
1037
+ if (url === "/mockifyer-network-events/stream" && req.method === "GET") {
1038
+ const fullUrl = req.url || "";
1039
+ const qIndex = fullUrl.indexOf("?");
1040
+ const params = new URLSearchParams(qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "");
1041
+ const backlog = params.get("backlog") !== "0";
1042
+ const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1043
+ res.writeHead(200, {
1044
+ "Content-Type": "text/event-stream",
1045
+ "Cache-Control": "no-cache, no-transform",
1046
+ Connection: "keep-alive",
1047
+ "X-Accel-Buffering": "no",
1048
+ });
1049
+ if (typeof res.flushHeaders === "function") {
1050
+ res.flushHeaders();
1051
+ }
1052
+ res.write(`event: hello\ndata: ${JSON.stringify({ size: buffer.size })}\n\n`);
1053
+ if (backlog) {
1054
+ const past = [...buffer.list()].reverse();
1055
+ for (const event of past) {
1056
+ res.write(`event: hop\ndata: ${JSON.stringify(event)}\n\n`);
1057
+ }
1058
+ }
1059
+ const unsubscribe = buffer.subscribe((event) => {
1060
+ try {
1061
+ res.write(`event: hop\ndata: ${JSON.stringify(event)}\n\n`);
1062
+ }
1063
+ catch {
1064
+ unsubscribe();
1065
+ }
1066
+ });
1067
+ const keepAlive = setInterval(() => {
1068
+ try {
1069
+ res.write(": ping\n\n");
1070
+ }
1071
+ catch {
1072
+ clearInterval(keepAlive);
1073
+ unsubscribe();
1074
+ }
1075
+ }, 15000);
1076
+ const onClose = () => {
1077
+ clearInterval(keepAlive);
1078
+ unsubscribe();
1079
+ };
1080
+ req.on("close", onClose);
1081
+ req.on("aborted", onClose);
1082
+ return;
1083
+ }
1084
+ if (url === "/mockifyer-network-events/analyze" && req.method === "GET") {
1085
+ const fullUrl = req.url || "";
1086
+ const qIndex = fullUrl.indexOf("?");
1087
+ const params = new URLSearchParams(qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "");
1088
+ const slowRaw = params.get("slowMs");
1089
+ const slowMs = slowRaw ? Number.parseInt(slowRaw, 10) : undefined;
1090
+ const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1091
+ const analysis = (0, mockifyer_core_2.analyzeMetroNetworkEvents)(buffer.list(), {
1092
+ slowMs: Number.isFinite(slowMs)
1093
+ ? slowMs
1094
+ : undefined,
1095
+ });
1096
+ res.setHeader("Content-Type", "application/json");
1097
+ res.end(JSON.stringify({ success: true, analysis }));
1098
+ return;
1099
+ }
1100
+ if (url === "/mockifyer-network-events/snapshot" && req.method === "POST") {
1101
+ const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1102
+ const events = [...buffer.list()].reverse();
1103
+ const result = writeNetworkEventsSnapshot(mockDataPath, events);
1104
+ res.statusCode = 201;
1105
+ res.setHeader("Content-Type", "application/json");
1106
+ res.end(JSON.stringify({
1107
+ success: true,
1108
+ count: result.count,
1109
+ dir: path.relative(projectRoot, result.dir).split(path.sep).join("/"),
1110
+ jsonPath: path
1111
+ .relative(projectRoot, result.jsonPath)
1112
+ .split(path.sep)
1113
+ .join("/"),
1114
+ ndjsonPath: path
1115
+ .relative(projectRoot, result.ndjsonPath)
1116
+ .split(path.sep)
1117
+ .join("/"),
1118
+ harPath: path
1119
+ .relative(projectRoot, result.harPath)
1120
+ .split(path.sep)
1121
+ .join("/"),
1122
+ }));
1123
+ return;
1124
+ }
1125
+ if (url === "/mockifyer-network-events/render" && req.method === "POST") {
1126
+ collectRequestBodyUtf8(req, (err, body) => {
1127
+ if (err) {
1128
+ res.statusCode = 413;
1129
+ res.setHeader("Content-Type", "application/json");
1130
+ res.end(JSON.stringify({ success: false, error: err.message }));
1131
+ return;
1132
+ }
1133
+ let scenario;
1134
+ if (body.trim()) {
1135
+ try {
1136
+ const parsed = JSON.parse(body);
1137
+ if (typeof parsed.scenario === "string")
1138
+ scenario = parsed.scenario;
1139
+ }
1140
+ catch {
1141
+ // empty / ignore
1142
+ }
1143
+ }
1144
+ const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1145
+ const events = [...buffer.list()].reverse();
1146
+ const result = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events, scenario);
1147
+ res.statusCode = result.success ? 201 : 500;
1148
+ res.setHeader("Content-Type", "application/json");
1149
+ res.end(JSON.stringify(result));
1150
+ });
1151
+ return;
1152
+ }
1153
+ if (url === "/mockifyer-network-events/clear" && req.method === "POST") {
1154
+ const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1155
+ buffer.clear();
1156
+ res.setHeader("Content-Type", "application/json");
1157
+ res.end(JSON.stringify({ success: true, size: 0 }));
1158
+ return;
1159
+ }
629
1160
  // Handle GET endpoint for domain-path rules (RN Hybrid hydrate at startup)
630
- if (url === '/mockifyer-domain-path-rules' && req.method === 'GET') {
631
- const fullUrl = req.url || '';
632
- const qIndex = fullUrl.indexOf('?');
633
- const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : '';
1161
+ if (url === "/mockifyer-domain-path-rules" && req.method === "GET") {
1162
+ const fullUrl = req.url || "";
1163
+ const qIndex = fullUrl.indexOf("?");
1164
+ const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "";
634
1165
  const params = new URLSearchParams(query);
635
- const scenarioParam = params.get('scenario');
636
- const scenarioName = scenarioParam && scenarioParam.trim() !== ''
1166
+ const scenarioParam = params.get("scenario");
1167
+ const scenarioName = scenarioParam && scenarioParam.trim() !== ""
637
1168
  ? scenarioParam.trim()
638
1169
  : getCurrentScenario(mockDataPath);
639
1170
  const rules = (0, mockifyer_core_2.readDomainPathRulesFile)(mockDataPath, scenarioName);
640
- res.setHeader('Content-Type', 'application/json');
1171
+ res.setHeader("Content-Type", "application/json");
641
1172
  res.end(JSON.stringify({ success: true, scenario: scenarioName, rules }));
642
1173
  return;
643
1174
  }
644
1175
  // Handle POST endpoint for domain-path rules discovery merge (Hybrid / RN)
645
- if (url === '/mockifyer-domain-path-rules' && req.method === 'POST') {
646
- let body = '';
647
- req.on('data', (chunk) => {
1176
+ if (url === "/mockifyer-domain-path-rules" && req.method === "POST") {
1177
+ let body = "";
1178
+ req.on("data", (chunk) => {
648
1179
  body += chunk.toString();
649
1180
  });
650
- req.on('end', () => {
1181
+ req.on("end", () => {
651
1182
  try {
652
1183
  const parsed = JSON.parse(body);
653
- const scenarioName = typeof parsed.scenario === 'string' && parsed.scenario.trim() !== ''
1184
+ const scenarioName = typeof parsed.scenario === "string" && parsed.scenario.trim() !== ""
654
1185
  ? parsed.scenario.trim()
655
1186
  : getCurrentScenario(mockDataPath);
656
1187
  const upserts = (0, mockifyer_core_2.parseDomainPathRules)(parsed.upserts ?? parsed.rules ?? {});
@@ -659,12 +1190,243 @@ function createMockSyncMiddleware(options) {
659
1190
  if (changed) {
660
1191
  (0, mockifyer_core_2.writeDomainPathRulesFile)(mockDataPath, scenarioName, rules);
661
1192
  }
662
- res.setHeader('Content-Type', 'application/json');
663
- res.end(JSON.stringify({ success: true, changed, scenario: scenarioName, rules }));
1193
+ res.setHeader("Content-Type", "application/json");
1194
+ res.end(JSON.stringify({
1195
+ success: true,
1196
+ changed,
1197
+ scenario: scenarioName,
1198
+ rules,
1199
+ }));
1200
+ }
1201
+ catch (error) {
1202
+ res.statusCode = 400;
1203
+ res.setHeader("Content-Type", "application/json");
1204
+ res.end(JSON.stringify({
1205
+ success: false,
1206
+ error: `Invalid JSON: ${error.message}`,
1207
+ }));
1208
+ }
1209
+ });
1210
+ return;
1211
+ }
1212
+ // Generate-on-click for terminal OSC-8 links (terminals cannot hijack OSC-8).
1213
+ // GET /mockifyer-atlas-open?id=<hopId>&side=req|res|html
1214
+ if (req.method === "GET" &&
1215
+ (url === "/mockifyer-atlas-open" || url.startsWith("/mockifyer-atlas-open?"))) {
1216
+ const fullUrl = String(req.url || "");
1217
+ const q = fullUrl.includes("?") ? fullUrl.slice(fullUrl.indexOf("?") + 1) : "";
1218
+ const params = new URLSearchParams(q);
1219
+ const hopId = (params.get("id") || "").trim();
1220
+ const sideParam = (params.get("side") || "html").trim().toLowerCase();
1221
+ const side = sideParam === "req" || sideParam === "res" ? sideParam : "html";
1222
+ const buffer = (0, mockifyer_core_2.getMetroNetworkEventBuffer)();
1223
+ // Buffer is newest-first; render expects chronological / display order.
1224
+ const events = [...buffer.list()].reverse();
1225
+ const rendered = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events);
1226
+ if (!rendered.success) {
1227
+ res.statusCode = 500;
1228
+ res.setHeader("Content-Type", "application/json");
1229
+ res.end(JSON.stringify({
1230
+ success: false,
1231
+ error: rendered.error || "atlas render failed",
1232
+ }));
1233
+ return;
1234
+ }
1235
+ if (side === "html") {
1236
+ res.statusCode = 302;
1237
+ res.setHeader("Location", "/atlas-html/index.html");
1238
+ res.end();
1239
+ return;
1240
+ }
1241
+ const event = (hopId
1242
+ ? events.find((e) => e && (e.id === hopId || e.requestId === hopId))
1243
+ : undefined) || events[0];
1244
+ if (!event) {
1245
+ res.statusCode = 404;
1246
+ res.setHeader("Content-Type", "application/json");
1247
+ res.end(JSON.stringify({ success: false, error: "hop not found" }));
1248
+ return;
1249
+ }
1250
+ const rels = (0, mockifyer_core_2.resolveNetworkEventBodyRelPaths)(event);
1251
+ const rel = side === "req" ? rels.req : rels.res;
1252
+ const abs = path.join(mockDataPath, "atlas-html", rel);
1253
+ if (!fs.existsSync(abs)) {
1254
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
1255
+ const preview = side === "req" ? event.requestBodyPreview : event.responseBodyPreview;
1256
+ const text = preview != null && String(preview).trim() !== ""
1257
+ ? String(preview)
1258
+ : JSON.stringify({
1259
+ note: "No body captured for this hop yet",
1260
+ id: event.id,
1261
+ side,
1262
+ }, null, 2);
1263
+ fs.writeFileSync(abs, text.endsWith("\n") ? text : `${text}\n`, "utf8");
1264
+ }
1265
+ res.statusCode = 302;
1266
+ res.setHeader("Location", `/atlas-html/${rel.split(path.sep).join("/")}`);
1267
+ res.end();
1268
+ return;
1269
+ }
1270
+ // Atlas HTML static files (index, pages, incidents, screenshots) — must not fall through to Expo web shell.
1271
+ // Prefer /atlas-html/; keep /mockifyer-atlas-html/ as a legacy alias.
1272
+ if (req.method === "GET") {
1273
+ const atlasSuffix = atlasHtmlStaticSuffix(url);
1274
+ if (atlasSuffix != null && serveAtlasHtmlStatic(mockDataPath, atlasSuffix, res)) {
1275
+ return;
1276
+ }
1277
+ }
1278
+ if (url === "/mockifyer-atlas-html" && req.method === "POST") {
1279
+ let body = "";
1280
+ req.on("data", (chunk) => {
1281
+ body += chunk.toString();
1282
+ });
1283
+ req.on("end", () => {
1284
+ try {
1285
+ const parsed = JSON.parse(body);
1286
+ const incidentId = typeof parsed.incidentId === "string" ? parsed.incidentId : "";
1287
+ const html = typeof parsed.html === "string" ? parsed.html : "";
1288
+ const result = saveAtlasHtmlIncident(projectRoot, mockDataPath, incidentId, html);
1289
+ res.setHeader("Content-Type", "application/json");
1290
+ res.statusCode = result.success ? 201 : 400;
1291
+ res.end(JSON.stringify(result));
1292
+ }
1293
+ catch (error) {
1294
+ res.statusCode = 400;
1295
+ res.setHeader("Content-Type", "application/json");
1296
+ res.end(JSON.stringify({
1297
+ success: false,
1298
+ error: `Invalid JSON: ${error.message}`,
1299
+ }));
1300
+ }
1301
+ });
1302
+ return;
1303
+ }
1304
+ // Atlas screen screenshot (device → project mock-data/atlas-html/screenshots/)
1305
+ if (url === "/mockifyer-atlas-screenshot" && req.method === "POST") {
1306
+ collectRequestBodyUtf8(req, (err, body) => {
1307
+ if (err) {
1308
+ res.statusCode = 413;
1309
+ res.setHeader("Content-Type", "application/json");
1310
+ res.end(JSON.stringify({ success: false, error: err.message }));
1311
+ return;
1312
+ }
1313
+ try {
1314
+ const parsed = JSON.parse(body);
1315
+ const relativePath = typeof parsed.relativePath === "string" ? parsed.relativePath : "";
1316
+ const base64 = typeof parsed.base64 === "string" ? parsed.base64 : "";
1317
+ const metadata = {
1318
+ sessionId: typeof parsed.sessionId === "string"
1319
+ ? parsed.sessionId
1320
+ : undefined,
1321
+ screen: typeof parsed.screen === "string" ? parsed.screen : undefined,
1322
+ scenario: typeof parsed.scenario === "string" ? parsed.scenario : undefined,
1323
+ pageId: typeof parsed.pageId === "string" ? parsed.pageId : undefined,
1324
+ capturedAt: typeof parsed.capturedAt === "string"
1325
+ ? parsed.capturedAt
1326
+ : undefined,
1327
+ };
1328
+ const result = saveAtlasScreenshot(projectRoot, mockDataPath, relativePath, base64, metadata);
1329
+ res.setHeader("Content-Type", "application/json");
1330
+ res.statusCode = result.success ? 201 : 400;
1331
+ res.end(JSON.stringify(result));
1332
+ }
1333
+ catch (error) {
1334
+ res.statusCode = 400;
1335
+ res.setHeader("Content-Type", "application/json");
1336
+ res.end(JSON.stringify({
1337
+ success: false,
1338
+ error: `Invalid JSON: ${error.message}`,
1339
+ }));
1340
+ }
1341
+ });
1342
+ return;
1343
+ }
1344
+ // Full hop body spill (device → project mock-data/atlas-html/bodies/)
1345
+ if (url === "/mockifyer-atlas-body-spill" && req.method === "POST") {
1346
+ collectRequestBodyUtf8(req, (err, body) => {
1347
+ if (err) {
1348
+ res.statusCode = 413;
1349
+ res.setHeader("Content-Type", "application/json");
1350
+ res.end(JSON.stringify({ success: false, error: err.message }));
1351
+ return;
1352
+ }
1353
+ try {
1354
+ const parsed = JSON.parse(body);
1355
+ const relativePath = typeof parsed.relativePath === "string" ? parsed.relativePath : "";
1356
+ const text = typeof parsed.text === "string" ? parsed.text : "";
1357
+ const result = saveAtlasBodySpill(projectRoot, mockDataPath, relativePath, text);
1358
+ res.setHeader("Content-Type", "application/json");
1359
+ res.statusCode = result.success ? 201 : 400;
1360
+ res.end(JSON.stringify(result));
1361
+ }
1362
+ catch (error) {
1363
+ res.statusCode = 400;
1364
+ res.setHeader("Content-Type", "application/json");
1365
+ res.end(JSON.stringify({
1366
+ success: false,
1367
+ error: `Invalid JSON: ${error.message}`,
1368
+ }));
1369
+ }
1370
+ });
1371
+ return;
1372
+ }
1373
+ // Full Atlas interactive HTML (Dev Menu → requestAtlasDocsRender)
1374
+ if (url === "/mockifyer-atlas-render" && req.method === "POST") {
1375
+ collectRequestBodyUtf8(req, (err, body) => {
1376
+ if (err) {
1377
+ res.statusCode = 413;
1378
+ res.setHeader("Content-Type", "application/json");
1379
+ res.end(JSON.stringify({ success: false, error: err.message }));
1380
+ return;
1381
+ }
1382
+ try {
1383
+ const parsed = JSON.parse(body);
1384
+ const rel = typeof parsed.outputRelativeDir === "string" &&
1385
+ parsed.outputRelativeDir.trim()
1386
+ ? parsed.outputRelativeDir.trim().replace(/^[/\\]+/, "")
1387
+ : "atlas-html";
1388
+ if (rel.includes("..")) {
1389
+ res.statusCode = 400;
1390
+ res.setHeader("Content-Type", "application/json");
1391
+ res.end(JSON.stringify({
1392
+ success: false,
1393
+ error: "Invalid outputRelativeDir",
1394
+ }));
1395
+ return;
1396
+ }
1397
+ const outDir = path.join(mockDataPath, rel);
1398
+ const doc = parsed.doc;
1399
+ if (!doc || typeof doc !== "object") {
1400
+ res.statusCode = 400;
1401
+ res.setHeader("Content-Type", "application/json");
1402
+ res.end(JSON.stringify({ success: false, error: "doc is required" }));
1403
+ return;
1404
+ }
1405
+ (0, mockifyer_core_2.setAtlasDocMap)(doc);
1406
+ (0, mockifyer_core_2.setAtlasDocHtmlOutputPath)(outDir);
1407
+ const spillWritten = (0, mockifyer_core_2.writeNetworkBodySpillMap)(outDir, parsed.bodySpills);
1408
+ const events = Array.isArray(parsed.events) ? parsed.events : [];
1409
+ const written = (0, mockifyer_core_2.writeAtlasDocHtml)(outDir, doc, events);
1410
+ const relativeFromRoot = path
1411
+ .relative(projectRoot, outDir)
1412
+ .split(path.sep)
1413
+ .join("/");
1414
+ res.setHeader("Content-Type", "application/json");
1415
+ res.statusCode = written > 0 ? 201 : 500;
1416
+ res.end(JSON.stringify({
1417
+ success: written > 0,
1418
+ written,
1419
+ bodySpillsWritten: spillWritten,
1420
+ dir: outDir,
1421
+ outputDir: relativeFromRoot,
1422
+ indexPath: path.join(outDir, "index.html"),
1423
+ hopCount: events.length,
1424
+ error: written > 0 ? undefined : "writeAtlasDocHtml wrote 0 files",
1425
+ }));
664
1426
  }
665
1427
  catch (error) {
666
1428
  res.statusCode = 400;
667
- res.setHeader('Content-Type', 'application/json');
1429
+ res.setHeader("Content-Type", "application/json");
668
1430
  res.end(JSON.stringify({
669
1431
  success: false,
670
1432
  error: `Invalid JSON: ${error.message}`,
@@ -674,33 +1436,37 @@ function createMockSyncMiddleware(options) {
674
1436
  return;
675
1437
  }
676
1438
  // Handle POST endpoint for direct save (HybridProvider)
677
- if (url === '/mockifyer-save' && req.method === 'POST') {
678
- let body = '';
679
- req.on('data', (chunk) => {
1439
+ if (url === "/mockifyer-save" && req.method === "POST") {
1440
+ let body = "";
1441
+ req.on("data", (chunk) => {
680
1442
  body += chunk.toString();
681
1443
  });
682
- req.on('end', () => {
1444
+ req.on("end", () => {
683
1445
  try {
684
1446
  const parsed = JSON.parse(body);
685
1447
  if (parsed &&
686
- typeof parsed === 'object' &&
1448
+ typeof parsed === "object" &&
687
1449
  parsed.__mockifyerProxyMirror === true &&
688
1450
  parsed.mockData) {
689
- const scenarioName = typeof parsed.scenarioName === 'string' ? parsed.scenarioName : '';
690
- const relativePath = typeof parsed.relativePath === 'string' ? parsed.relativePath : '';
1451
+ const scenarioName = typeof parsed.scenarioName === "string"
1452
+ ? parsed.scenarioName
1453
+ : "";
1454
+ const relativePath = typeof parsed.relativePath === "string"
1455
+ ? parsed.relativePath
1456
+ : "";
691
1457
  const result = saveProxyMirrorMockToProject(parsed.mockData, projectRoot, mockDataPath, scenarioName, relativePath, testConfig);
692
- res.setHeader('Content-Type', 'application/json');
1458
+ res.setHeader("Content-Type", "application/json");
693
1459
  res.end(JSON.stringify(result));
694
1460
  return;
695
1461
  }
696
1462
  const mockData = parsed;
697
1463
  const result = saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig);
698
- res.setHeader('Content-Type', 'application/json');
1464
+ res.setHeader("Content-Type", "application/json");
699
1465
  res.end(JSON.stringify(result));
700
1466
  }
701
1467
  catch (error) {
702
1468
  res.statusCode = 400;
703
- res.setHeader('Content-Type', 'application/json');
1469
+ res.setHeader("Content-Type", "application/json");
704
1470
  res.end(JSON.stringify({
705
1471
  success: false,
706
1472
  error: `Invalid JSON: ${error.message}`,
@@ -710,26 +1476,26 @@ function createMockSyncMiddleware(options) {
710
1476
  return;
711
1477
  }
712
1478
  // Project folder → device/simulator: manifest (small JSON)
713
- if (url === '/mockifyer-sync-to-device-manifest' && req.method === 'GET') {
1479
+ if (url === "/mockifyer-sync-to-device-manifest" && req.method === "GET") {
714
1480
  const payload = buildSyncToDeviceManifest(mockDataPath);
715
- res.setHeader('Content-Type', 'application/json');
1481
+ res.setHeader("Content-Type", "application/json");
716
1482
  res.statusCode = payload.success ? 200 : 500;
717
1483
  res.end(JSON.stringify(payload));
718
1484
  return;
719
1485
  }
720
1486
  // Promoted pool response for RN `$pool` serve-time resolve
721
- if (url === '/mockifyer-pool-response' && req.method === 'GET') {
722
- const fullUrl = req.url || '';
723
- const qIndex = fullUrl.indexOf('?');
724
- const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : '';
1487
+ if (url === "/mockifyer-pool-response" && req.method === "GET") {
1488
+ const fullUrl = req.url || "";
1489
+ const qIndex = fullUrl.indexOf("?");
1490
+ const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "";
725
1491
  const params = new URLSearchParams(query);
726
- const idParam = params.get('id') || '';
1492
+ const idParam = params.get("id") || "";
727
1493
  const payload = buildPoolResponsePayload(mockDataPath, idParam);
728
- res.setHeader('Content-Type', 'application/json');
1494
+ res.setHeader("Content-Type", "application/json");
729
1495
  if (payload.success) {
730
1496
  res.statusCode = 200;
731
1497
  }
732
- else if (payload.error === 'Not found') {
1498
+ else if (payload.error === "Not found") {
733
1499
  res.statusCode = 404;
734
1500
  }
735
1501
  else {
@@ -739,18 +1505,18 @@ function createMockSyncMiddleware(options) {
739
1505
  return;
740
1506
  }
741
1507
  // Single file for HybridProvider (avoids multi‑MB single response)
742
- if (url === '/mockifyer-sync-to-device-file' && req.method === 'GET') {
743
- const fullUrl = req.url || '';
744
- const qIndex = fullUrl.indexOf('?');
745
- const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : '';
1508
+ if (url === "/mockifyer-sync-to-device-file" && req.method === "GET") {
1509
+ const fullUrl = req.url || "";
1510
+ const qIndex = fullUrl.indexOf("?");
1511
+ const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "";
746
1512
  const params = new URLSearchParams(query);
747
- const pathParam = params.get('path') || '';
1513
+ const pathParam = params.get("path") || "";
748
1514
  const payload = buildSyncToDeviceSingleFilePayload(mockDataPath, pathParam);
749
- res.setHeader('Content-Type', 'application/json');
1515
+ res.setHeader("Content-Type", "application/json");
750
1516
  if (payload.success) {
751
1517
  res.statusCode = 200;
752
1518
  }
753
- else if (payload.error === 'Not found') {
1519
+ else if (payload.error === "Not found") {
754
1520
  res.statusCode = 404;
755
1521
  }
756
1522
  else {
@@ -760,21 +1526,23 @@ function createMockSyncMiddleware(options) {
760
1526
  return;
761
1527
  }
762
1528
  // Legacy: all files in one response (may OOM / timeout on large scenarios)
763
- if (url === '/mockifyer-sync-to-device' && req.method === 'GET') {
1529
+ if (url === "/mockifyer-sync-to-device" && req.method === "GET") {
764
1530
  const payload = buildSyncToDevicePayload(mockDataPath);
765
- res.setHeader('Content-Type', 'application/json');
1531
+ res.setHeader("Content-Type", "application/json");
766
1532
  res.statusCode = payload.success ? 200 : 500;
767
1533
  res.end(JSON.stringify(payload));
768
1534
  return;
769
1535
  }
770
1536
  // Handle GET endpoint for sync status
771
- if (url === '/mockifyer-sync/status' && req.method === 'GET') {
1537
+ if (url === "/mockifyer-sync/status" && req.method === "GET") {
772
1538
  const currentScenario = getCurrentScenario(mockDataPath);
773
1539
  const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
774
1540
  const files = fs.existsSync(scenarioPath)
775
- ? fs.readdirSync(scenarioPath).filter((f) => f.endsWith('.json'))
1541
+ ? fs
1542
+ .readdirSync(scenarioPath)
1543
+ .filter((f) => f.endsWith(".json"))
776
1544
  : [];
777
- res.setHeader('Content-Type', 'application/json');
1545
+ res.setHeader("Content-Type", "application/json");
778
1546
  res.end(JSON.stringify({
779
1547
  success: true,
780
1548
  scenario: currentScenario,
@@ -784,76 +1552,76 @@ function createMockSyncMiddleware(options) {
784
1552
  return;
785
1553
  }
786
1554
  // Handle GET endpoint for sync (legacy polling-based sync)
787
- if (url === '/mockifyer-sync' && req.method === 'GET') {
1555
+ if (url === "/mockifyer-sync" && req.method === "GET") {
788
1556
  const result = syncFromIOSSimulator(projectRoot, mockDataPath);
789
- res.setHeader('Content-Type', 'application/json');
1557
+ res.setHeader("Content-Type", "application/json");
790
1558
  res.end(JSON.stringify(result));
791
1559
  return;
792
1560
  }
793
1561
  // Handle GET endpoint for scenario config
794
- if (url === '/mockifyer-scenario-config' && req.method === 'GET') {
1562
+ if (url === "/mockifyer-scenario-config" && req.method === "GET") {
795
1563
  try {
796
1564
  // Check environment variable first (highest priority)
797
1565
  if (process.env.MOCKIFYER_SCENARIO) {
798
1566
  mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${process.env.MOCKIFYER_SCENARIO}`);
799
- res.setHeader('Content-Type', 'application/json');
1567
+ res.setHeader("Content-Type", "application/json");
800
1568
  res.end(JSON.stringify({
801
1569
  success: true,
802
- currentScenario: process.env.MOCKIFYER_SCENARIO
1570
+ currentScenario: process.env.MOCKIFYER_SCENARIO,
803
1571
  }));
804
1572
  return;
805
1573
  }
806
- const configPath = path.join(mockDataPath, 'scenario-config.json');
1574
+ const configPath = path.join(mockDataPath, "scenario-config.json");
807
1575
  const resolvedPath = path.resolve(configPath);
808
1576
  mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Reading scenario config from: ${resolvedPath}`);
809
1577
  mockifyer_core_1.logger.info(`[MetroSyncMiddleware] mockDataPath: ${mockDataPath}, projectRoot: ${projectRoot}`);
810
1578
  if (fs.existsSync(configPath)) {
811
- const fileContent = fs.readFileSync(configPath, 'utf-8');
1579
+ const fileContent = fs.readFileSync(configPath, "utf-8");
812
1580
  mockifyer_core_1.logger.info(`[MetroSyncMiddleware] File content: ${fileContent}`);
813
1581
  const config = JSON.parse(fileContent);
814
1582
  const scenario = config.currentScenario || DEFAULT_SCENARIO;
815
1583
  mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`);
816
- res.setHeader('Content-Type', 'application/json');
1584
+ res.setHeader("Content-Type", "application/json");
817
1585
  // Return format expected by ExpoFileSystemProvider: { success: true, currentScenario: ... }
818
1586
  res.end(JSON.stringify({
819
1587
  success: true,
820
- currentScenario: scenario
1588
+ currentScenario: scenario,
821
1589
  }));
822
1590
  }
823
1591
  else {
824
1592
  mockifyer_core_1.logger.info(`[MetroSyncMiddleware] Config file not found at ${resolvedPath}, returning default scenario`);
825
- res.setHeader('Content-Type', 'application/json');
1593
+ res.setHeader("Content-Type", "application/json");
826
1594
  res.end(JSON.stringify({
827
1595
  success: true,
828
- currentScenario: DEFAULT_SCENARIO
1596
+ currentScenario: DEFAULT_SCENARIO,
829
1597
  }));
830
1598
  }
831
1599
  }
832
1600
  catch (error) {
833
1601
  mockifyer_core_1.logger.error(`[MetroSyncMiddleware] Error reading scenario config:`, error);
834
1602
  res.statusCode = 500;
835
- res.setHeader('Content-Type', 'application/json');
1603
+ res.setHeader("Content-Type", "application/json");
836
1604
  res.end(JSON.stringify({ success: false, error: error.message }));
837
1605
  }
838
1606
  return;
839
1607
  }
840
1608
  // Handle POST endpoint for scenario config sync
841
- if (url === '/mockifyer-scenario-config' && req.method === 'POST') {
842
- let body = '';
843
- req.on('data', (chunk) => {
1609
+ if (url === "/mockifyer-scenario-config" && req.method === "POST") {
1610
+ let body = "";
1611
+ req.on("data", (chunk) => {
844
1612
  body += chunk.toString();
845
1613
  });
846
- req.on('end', () => {
1614
+ req.on("end", () => {
847
1615
  try {
848
1616
  const config = JSON.parse(body);
849
- const configPath = path.join(mockDataPath, 'scenario-config.json');
1617
+ const configPath = path.join(mockDataPath, "scenario-config.json");
850
1618
  fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
851
- res.setHeader('Content-Type', 'application/json');
1619
+ res.setHeader("Content-Type", "application/json");
852
1620
  res.end(JSON.stringify({ success: true }));
853
1621
  }
854
1622
  catch (error) {
855
1623
  res.statusCode = 400;
856
- res.setHeader('Content-Type', 'application/json');
1624
+ res.setHeader("Content-Type", "application/json");
857
1625
  res.end(JSON.stringify({ success: false, error: error.message }));
858
1626
  }
859
1627
  });
@@ -871,7 +1639,7 @@ function startAutoSync(intervalMs = 5000, options) {
871
1639
  return;
872
1640
  }
873
1641
  const projectRoot = options?.projectRoot || process.cwd();
874
- const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || 'mock-data');
1642
+ const mockDataPath = path.resolve(projectRoot, options?.mockDataPath || "mock-data");
875
1643
  mockifyer_core_1.logger.info(`[MockSync] Starting auto-sync every ${intervalMs}ms`);
876
1644
  autoSyncInterval = setInterval(() => {
877
1645
  syncFromIOSSimulator(projectRoot, mockDataPath);