@sgedda/mockifyer-fetch 1.8.46 → 1.8.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/fetch-client.js +2 -0
- package/dist/index.js +132 -40
- package/dist/metro-sync-middleware.d.ts +13 -2
- package/dist/metro-sync-middleware.js +921 -153
- package/dist/utils/fetch-response-body.d.ts +9 -0
- package/dist/utils/fetch-response-body.js +35 -0
- package/package.json +2 -2
- package/src/clients/fetch-client.ts +4 -0
- package/src/index.ts +177 -45
- package/src/metro-sync-middleware.ts +1375 -253
- package/src/utils/fetch-response-body.ts +33 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Metro middleware for mock file synchronization
|
|
3
|
-
*
|
|
3
|
+
*
|
|
4
4
|
* Provides sync mechanisms:
|
|
5
5
|
* 1. POST /mockifyer-save - Direct save endpoint (used by Hybrid Provider for instant sync)
|
|
6
6
|
* 2. GET/POST /mockifyer-domain-path-rules - Load or merge discovered domain-path allowlist keys into scenario file
|
|
@@ -8,18 +8,33 @@
|
|
|
8
8
|
* 4. GET /mockifyer-sync-to-device - Legacy: all files in one response (may fail on large scenarios)
|
|
9
9
|
* 5. GET /mockifyer-pool-response?id= - Load a promoted pool response for RN `$pool` resolve
|
|
10
10
|
* 6. GET /mockifyer-sync - Legacy: iOS simulator mock-data → project folder
|
|
11
|
-
*
|
|
11
|
+
* 7. POST /mockifyer-atlas-html — write crash-scoped trace HTML to mock-data/atlas-html/incidents/
|
|
12
|
+
* 8. GET /atlas-html[/…] (legacy: /mockifyer-atlas-html[/…]) — serve atlas-html static files (index.html, pages, incidents, screenshots)
|
|
13
|
+
* 9. POST /mockifyer-atlas-screenshot — write screen image (png/jpg/webp) under mock-data/atlas-html/screenshots/
|
|
14
|
+
* 10. POST /mockifyer-atlas-render — write full interactive Atlas HTML under mock-data/atlas-html/
|
|
15
|
+
* 11. POST /mockifyer-atlas-body-spill — write full hop body text under mock-data/atlas-html/bodies/
|
|
16
|
+
* 12. POST/GET /mockifyer-network-events — live hop ring buffer for `mockifyer-atlas` CLI
|
|
17
|
+
* 13. GET /mockifyer-network-events/stream — SSE hop stream
|
|
18
|
+
* 14. GET /mockifyer-network-events/analyze — hop summary JSON
|
|
19
|
+
* 15. POST /mockifyer-network-events/snapshot — write hops JSON/NDJSON under atlas-html/
|
|
20
|
+
* 16. POST /mockifyer-network-events/render — render Atlas HTML from buffer hops
|
|
21
|
+
* 17. POST /mockifyer-network-events/clear — clear ring buffer
|
|
22
|
+
*
|
|
12
23
|
* The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
|
|
13
24
|
* Legacy polling-based sync is still available for backward compatibility.
|
|
14
|
-
*
|
|
25
|
+
*
|
|
15
26
|
* Usage: Add to metro.config.js middleware array
|
|
16
27
|
*/
|
|
17
28
|
|
|
18
|
-
import * as fs from
|
|
19
|
-
import * as path from
|
|
20
|
-
import { execSync } from
|
|
21
|
-
import {
|
|
22
|
-
|
|
29
|
+
import * as fs from "fs";
|
|
30
|
+
import * as path from "path";
|
|
31
|
+
import { execSync } from "child_process";
|
|
32
|
+
import {
|
|
33
|
+
MockData,
|
|
34
|
+
TestGenerator,
|
|
35
|
+
TestGenerationOptions,
|
|
36
|
+
} from "@sgedda/mockifyer-core";
|
|
37
|
+
import { logger } from "@sgedda/mockifyer-core";
|
|
23
38
|
import {
|
|
24
39
|
POOL_ID_PATTERN,
|
|
25
40
|
loadPoolResponseItem,
|
|
@@ -30,7 +45,22 @@ import {
|
|
|
30
45
|
writeDomainPathRulesFile,
|
|
31
46
|
type DomainPathRulesMap,
|
|
32
47
|
containsMockifyerSyncEndpointMarker,
|
|
33
|
-
|
|
48
|
+
setAtlasDocScreenshot,
|
|
49
|
+
flushAtlasDocHtmlRewrite,
|
|
50
|
+
setAtlasDocHtmlOutputPath,
|
|
51
|
+
writeAtlasDocHtml,
|
|
52
|
+
writeNetworkBodySpillMap,
|
|
53
|
+
flushNetworkBodySpillsToDir,
|
|
54
|
+
prettyPrintJsonText,
|
|
55
|
+
setAtlasDocMap,
|
|
56
|
+
type AtlasDocMap,
|
|
57
|
+
type NetworkEvent,
|
|
58
|
+
getMetroNetworkEventBuffer,
|
|
59
|
+
resolveNetworkEventBodyRelPaths,
|
|
60
|
+
analyzeMetroNetworkEvents,
|
|
61
|
+
createEmptyAtlasDocMap,
|
|
62
|
+
buildAtlasHarJson,
|
|
63
|
+
} from "@sgedda/mockifyer-core";
|
|
34
64
|
|
|
35
65
|
export interface MetroSyncMiddlewareOptions {
|
|
36
66
|
/** Project root directory (default: process.cwd()) */
|
|
@@ -42,7 +72,7 @@ export interface MetroSyncMiddlewareOptions {
|
|
|
42
72
|
/** Enable automatic test generation when mocks are saved */
|
|
43
73
|
enabled?: boolean;
|
|
44
74
|
/** Test framework to use: 'jest' (default), 'vitest', or 'mocha' */
|
|
45
|
-
framework?:
|
|
75
|
+
framework?: "jest" | "vitest" | "mocha";
|
|
46
76
|
/** Output path for generated tests (default: './tests/generated') */
|
|
47
77
|
outputPath?: string;
|
|
48
78
|
/** Test file naming pattern with placeholders: {endpoint}, {method}, {scenario} (default: '{endpoint}.test.ts') */
|
|
@@ -50,56 +80,111 @@ export interface MetroSyncMiddlewareOptions {
|
|
|
50
80
|
/** Include setup code in generated tests (default: true) */
|
|
51
81
|
includeSetup?: boolean;
|
|
52
82
|
/** Group tests by: 'endpoint', 'scenario', or 'file' (default: 'endpoint') */
|
|
53
|
-
groupBy?:
|
|
83
|
+
groupBy?: "endpoint" | "scenario" | "file";
|
|
54
84
|
/** If true, only generate one test per endpoint (method + pathname), ignoring query parameters (default: false) */
|
|
55
85
|
uniqueTestsPerEndpoint?: boolean;
|
|
56
86
|
};
|
|
57
87
|
}
|
|
58
88
|
|
|
59
|
-
const DEFAULT_SCENARIO =
|
|
89
|
+
const DEFAULT_SCENARIO = "default";
|
|
90
|
+
/** Atlas render POSTs can include many hops + body spills — avoid O(n²) string concat. */
|
|
91
|
+
const MAX_METRO_POST_BODY_BYTES = 64 * 1024 * 1024;
|
|
60
92
|
|
|
61
93
|
let autoSyncInterval: NodeJS.Timeout | null = null;
|
|
62
94
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
95
|
+
/**
|
|
96
|
+
* Buffer an incoming request body with `Buffer.concat` (not `body += chunk`).
|
|
97
|
+
* Large Atlas render payloads hang for minutes with quadratic string concatenation.
|
|
98
|
+
*/
|
|
99
|
+
function collectRequestBodyUtf8(
|
|
100
|
+
req: {
|
|
101
|
+
on: (event: string, cb: (...args: any[]) => void) => void;
|
|
102
|
+
destroy?: () => void;
|
|
103
|
+
},
|
|
104
|
+
onDone: (err: Error | null, body: string) => void,
|
|
105
|
+
maxBytes: number = MAX_METRO_POST_BODY_BYTES,
|
|
106
|
+
): void {
|
|
107
|
+
const chunks: Buffer[] = [];
|
|
108
|
+
let size = 0;
|
|
109
|
+
let settled = false;
|
|
110
|
+
const finish = (err: Error | null, body: string) => {
|
|
111
|
+
if (settled) return;
|
|
112
|
+
settled = true;
|
|
113
|
+
onDone(err, body);
|
|
114
|
+
};
|
|
115
|
+
req.on("data", (chunk: Buffer | string) => {
|
|
116
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
117
|
+
size += buf.length;
|
|
118
|
+
if (size > maxBytes) {
|
|
119
|
+
finish(new Error(`Request body exceeds ${maxBytes} bytes`), "");
|
|
120
|
+
try {
|
|
121
|
+
req.destroy?.();
|
|
122
|
+
} catch {
|
|
123
|
+
// ignore
|
|
124
|
+
}
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
chunks.push(buf);
|
|
128
|
+
});
|
|
129
|
+
req.on("end", () => {
|
|
130
|
+
try {
|
|
131
|
+
finish(null, Buffer.concat(chunks).toString("utf8"));
|
|
132
|
+
} catch (e) {
|
|
133
|
+
finish(e instanceof Error ? e : new Error(String(e)), "");
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
req.on("error", (e: Error) => finish(e, ""));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function getMockFilePathLocal(
|
|
140
|
+
mockData: MockData,
|
|
141
|
+
dateStr: string,
|
|
142
|
+
): { dir: string; filename: string } {
|
|
143
|
+
const url = mockData.request.url || "";
|
|
144
|
+
const method = (mockData.request.method || "GET").toUpperCase();
|
|
145
|
+
let host = "unknown";
|
|
67
146
|
let pathSegments: string[] = [];
|
|
68
147
|
try {
|
|
69
148
|
const parsed = new URL(url);
|
|
70
149
|
host = parsed.hostname;
|
|
71
|
-
pathSegments = parsed.pathname.split(
|
|
150
|
+
pathSegments = parsed.pathname.split("/").filter(Boolean);
|
|
72
151
|
} catch {
|
|
73
|
-
return { dir:
|
|
152
|
+
return { dir: "unknown", filename: `${method}_${dateStr}.json` };
|
|
74
153
|
}
|
|
75
|
-
const hostSafe = host.replace(/[^a-zA-Z0-9.-]/g,
|
|
76
|
-
const graphqlIdx = pathSegments.lastIndexOf(
|
|
77
|
-
const restIdx = pathSegments.indexOf(
|
|
154
|
+
const hostSafe = host.replace(/[^a-zA-Z0-9.-]/g, "_");
|
|
155
|
+
const graphqlIdx = pathSegments.lastIndexOf("graphql");
|
|
156
|
+
const restIdx = pathSegments.indexOf("rest");
|
|
78
157
|
let type: string;
|
|
79
158
|
let remainingSegments: string[];
|
|
80
159
|
if (graphqlIdx >= 0) {
|
|
81
|
-
type =
|
|
160
|
+
type = "graphql";
|
|
82
161
|
remainingSegments = pathSegments.slice(graphqlIdx + 1);
|
|
83
162
|
} else if (restIdx >= 0) {
|
|
84
|
-
type =
|
|
163
|
+
type = "rest";
|
|
85
164
|
remainingSegments = pathSegments.slice(restIdx + 1);
|
|
86
165
|
} else {
|
|
87
|
-
type =
|
|
166
|
+
type = "";
|
|
88
167
|
remainingSegments = pathSegments;
|
|
89
168
|
}
|
|
90
|
-
let identifier =
|
|
169
|
+
let identifier = "";
|
|
91
170
|
if (mockData.request.data) {
|
|
92
171
|
try {
|
|
93
|
-
const body =
|
|
94
|
-
|
|
172
|
+
const body =
|
|
173
|
+
typeof mockData.request.data === "string"
|
|
174
|
+
? JSON.parse(mockData.request.data)
|
|
175
|
+
: mockData.request.data;
|
|
95
176
|
if (body.operationName) identifier = body.operationName;
|
|
96
177
|
else if (body.path) identifier = body.path;
|
|
97
178
|
else if (body.webAppName) identifier = body.webAppName;
|
|
98
|
-
} catch {
|
|
179
|
+
} catch {
|
|
180
|
+
/* ignore */
|
|
181
|
+
}
|
|
99
182
|
}
|
|
100
|
-
identifier = identifier.replace(/[^a-zA-Z0-9_-]/g,
|
|
101
|
-
const dir = [hostSafe, type, ...remainingSegments].filter(Boolean).join(
|
|
102
|
-
const filename = identifier
|
|
183
|
+
identifier = identifier.replace(/[^a-zA-Z0-9_-]/g, "_").substring(0, 60);
|
|
184
|
+
const dir = [hostSafe, type, ...remainingSegments].filter(Boolean).join("/");
|
|
185
|
+
const filename = identifier
|
|
186
|
+
? `${method}_${identifier}_${dateStr}.json`
|
|
187
|
+
: `${method}_${dateStr}.json`;
|
|
103
188
|
return { dir, filename };
|
|
104
189
|
}
|
|
105
190
|
|
|
@@ -114,9 +199,9 @@ function getCurrentScenario(mockDataPath: string): string {
|
|
|
114
199
|
|
|
115
200
|
// Try to load from scenario-config.json
|
|
116
201
|
try {
|
|
117
|
-
const configPath = path.join(mockDataPath,
|
|
202
|
+
const configPath = path.join(mockDataPath, "scenario-config.json");
|
|
118
203
|
if (fs.existsSync(configPath)) {
|
|
119
|
-
const fileContent = fs.readFileSync(configPath,
|
|
204
|
+
const fileContent = fs.readFileSync(configPath, "utf-8");
|
|
120
205
|
const config = JSON.parse(fileContent);
|
|
121
206
|
if (config.currentScenario) {
|
|
122
207
|
return config.currentScenario;
|
|
@@ -137,31 +222,48 @@ function getScenarioPath(scenario: string, mockDataPath: string): string {
|
|
|
137
222
|
return path.join(mockDataPath, scenario);
|
|
138
223
|
}
|
|
139
224
|
|
|
140
|
-
|
|
141
225
|
/**
|
|
142
226
|
* Get test generation config from options or environment variables
|
|
143
227
|
* Options take precedence, then fall back to environment variables (for backward compatibility)
|
|
144
228
|
*/
|
|
145
|
-
function getTestGenerationConfig(
|
|
229
|
+
function getTestGenerationConfig(
|
|
230
|
+
options?: MetroSyncMiddlewareOptions,
|
|
231
|
+
): TestGenerationOptions | null {
|
|
146
232
|
// Check if enabled via options or environment variables
|
|
147
|
-
const enabled =
|
|
233
|
+
const enabled =
|
|
148
234
|
options?.testGeneration?.enabled === true ||
|
|
149
|
-
process.env.MOCKIFYER_GENERATE_TESTS ===
|
|
150
|
-
process.env.MOCKIFYER_GENERATE_TESTS ===
|
|
151
|
-
|
|
235
|
+
process.env.MOCKIFYER_GENERATE_TESTS === "true" ||
|
|
236
|
+
process.env.MOCKIFYER_GENERATE_TESTS === "1";
|
|
237
|
+
|
|
152
238
|
if (!enabled) {
|
|
153
239
|
return null;
|
|
154
240
|
}
|
|
155
241
|
|
|
156
242
|
// Use options if provided, otherwise fall back to environment variables
|
|
157
243
|
return {
|
|
158
|
-
framework:
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
244
|
+
framework:
|
|
245
|
+
options?.testGeneration?.framework ||
|
|
246
|
+
(process.env.MOCKIFYER_TEST_FRAMEWORK as any) ||
|
|
247
|
+
"jest",
|
|
248
|
+
outputPath:
|
|
249
|
+
options?.testGeneration?.outputPath ||
|
|
250
|
+
process.env.MOCKIFYER_TEST_OUTPUT_PATH ||
|
|
251
|
+
"./tests/generated",
|
|
252
|
+
testPattern:
|
|
253
|
+
options?.testGeneration?.testPattern ||
|
|
254
|
+
process.env.MOCKIFYER_TEST_PATTERN ||
|
|
255
|
+
"{endpoint}.test.ts",
|
|
256
|
+
includeSetup:
|
|
257
|
+
options?.testGeneration?.includeSetup !== false &&
|
|
258
|
+
process.env.MOCKIFYER_TEST_INCLUDE_SETUP !== "false",
|
|
259
|
+
groupBy:
|
|
260
|
+
options?.testGeneration?.groupBy ||
|
|
261
|
+
(process.env.MOCKIFYER_TEST_GROUP_BY as any) ||
|
|
262
|
+
"endpoint",
|
|
263
|
+
httpClientType: "fetch",
|
|
264
|
+
uniqueTestsPerEndpoint:
|
|
265
|
+
options?.testGeneration?.uniqueTestsPerEndpoint ||
|
|
266
|
+
process.env.MOCKIFYER_UNIQUE_TESTS_PER_ENDPOINT === "true",
|
|
165
267
|
};
|
|
166
268
|
}
|
|
167
269
|
|
|
@@ -171,7 +273,7 @@ function getTestGenerationConfig(options?: MetroSyncMiddlewareOptions): TestGene
|
|
|
171
273
|
function generateTestForMock(
|
|
172
274
|
mockData: MockData,
|
|
173
275
|
testConfig: TestGenerationOptions,
|
|
174
|
-
projectRoot: string
|
|
276
|
+
projectRoot: string,
|
|
175
277
|
): boolean {
|
|
176
278
|
try {
|
|
177
279
|
// Try to require TestGenerator from mockifyer-core
|
|
@@ -179,21 +281,27 @@ function generateTestForMock(
|
|
|
179
281
|
try {
|
|
180
282
|
let mockifyerCore;
|
|
181
283
|
try {
|
|
182
|
-
mockifyerCore = require(
|
|
284
|
+
mockifyerCore = require("@sgedda/mockifyer-core");
|
|
183
285
|
} catch (e) {
|
|
184
286
|
// Fallback: try relative path (for local file: dependencies)
|
|
185
|
-
const corePath = path.join(
|
|
287
|
+
const corePath = path.join(
|
|
288
|
+
projectRoot,
|
|
289
|
+
"../../packages/mockifyer-core/dist/index.js",
|
|
290
|
+
);
|
|
186
291
|
if (fs.existsSync(corePath)) {
|
|
187
292
|
mockifyerCore = require(corePath);
|
|
188
293
|
} else {
|
|
189
294
|
throw new Error(`Could not find mockifyer-core at ${corePath}`);
|
|
190
295
|
}
|
|
191
296
|
}
|
|
192
|
-
|
|
297
|
+
|
|
193
298
|
TestGeneratorClass = mockifyerCore?.TestGenerator;
|
|
194
|
-
|
|
299
|
+
|
|
195
300
|
if (!TestGeneratorClass) {
|
|
196
|
-
const testGeneratorPath = path.join(
|
|
301
|
+
const testGeneratorPath = path.join(
|
|
302
|
+
projectRoot,
|
|
303
|
+
"../../packages/mockifyer-core/dist/utils/test-generator.js",
|
|
304
|
+
);
|
|
197
305
|
if (fs.existsSync(testGeneratorPath)) {
|
|
198
306
|
const testGeneratorModule = require(testGeneratorPath);
|
|
199
307
|
TestGeneratorClass = testGeneratorModule.TestGenerator;
|
|
@@ -208,7 +316,7 @@ function generateTestForMock(
|
|
|
208
316
|
}
|
|
209
317
|
|
|
210
318
|
const generator = new TestGeneratorClass();
|
|
211
|
-
|
|
319
|
+
|
|
212
320
|
const options: TestGenerationOptions = {
|
|
213
321
|
framework: testConfig.framework,
|
|
214
322
|
outputPath: testConfig.outputPath,
|
|
@@ -219,9 +327,12 @@ function generateTestForMock(
|
|
|
219
327
|
uniqueTestsPerEndpoint: testConfig.uniqueTestsPerEndpoint,
|
|
220
328
|
};
|
|
221
329
|
|
|
222
|
-
const testInfo = generator.analyzeMock(
|
|
330
|
+
const testInfo = generator.analyzeMock(
|
|
331
|
+
mockData,
|
|
332
|
+
options.httpClientType || "fetch",
|
|
333
|
+
);
|
|
223
334
|
const testFilePath = generator.determineTestFilePath(mockData, options);
|
|
224
|
-
|
|
335
|
+
|
|
225
336
|
const absoluteTestPath = path.resolve(projectRoot, testFilePath);
|
|
226
337
|
const testDir = path.dirname(absoluteTestPath);
|
|
227
338
|
|
|
@@ -240,19 +351,24 @@ function generateTestForMock(
|
|
|
240
351
|
// Check if test file already exists
|
|
241
352
|
if (fs.existsSync(absoluteTestPath)) {
|
|
242
353
|
const testName = `${testInfo.method} ${testInfo.endpoint}`;
|
|
243
|
-
|
|
244
|
-
const existingContent = fs.readFileSync(absoluteTestPath,
|
|
245
|
-
if (
|
|
354
|
+
|
|
355
|
+
const existingContent = fs.readFileSync(absoluteTestPath, "utf-8");
|
|
356
|
+
if (
|
|
357
|
+
existingContent.includes(`it('${testName}'`) ||
|
|
358
|
+
existingContent.includes(`it("${testName}"`)
|
|
359
|
+
) {
|
|
246
360
|
return true;
|
|
247
361
|
}
|
|
248
|
-
|
|
362
|
+
|
|
249
363
|
// Append test to existing file
|
|
250
|
-
const testMatch = testCode.match(
|
|
364
|
+
const testMatch = testCode.match(
|
|
365
|
+
/it\('.*?', async \(\) => \{[\s\S]*?\}\);?/,
|
|
366
|
+
);
|
|
251
367
|
if (testMatch) {
|
|
252
368
|
const newTest = testMatch[0];
|
|
253
369
|
const updatedContent = existingContent.replace(
|
|
254
370
|
/(\s+)(\}\);?\s*)$/,
|
|
255
|
-
`$1${newTest}\n$1$2
|
|
371
|
+
`$1${newTest}\n$1$2`,
|
|
256
372
|
);
|
|
257
373
|
fs.writeFileSync(absoluteTestPath, updatedContent);
|
|
258
374
|
return true;
|
|
@@ -277,36 +393,62 @@ function saveMockToProjectFolder(
|
|
|
277
393
|
mockData: MockData,
|
|
278
394
|
projectRoot: string,
|
|
279
395
|
mockDataPath: string,
|
|
280
|
-
testConfig: TestGenerationOptions | null
|
|
281
|
-
): {
|
|
396
|
+
testConfig: TestGenerationOptions | null,
|
|
397
|
+
): {
|
|
398
|
+
success: boolean;
|
|
399
|
+
filename?: string;
|
|
400
|
+
scenario?: string;
|
|
401
|
+
error?: string;
|
|
402
|
+
skipped?: boolean;
|
|
403
|
+
reason?: string;
|
|
404
|
+
} {
|
|
282
405
|
try {
|
|
283
406
|
// CRITICAL: Never save Mockifyer sync endpoint requests to prevent infinite loops
|
|
284
|
-
const url = mockData?.request?.url ||
|
|
407
|
+
const url = mockData?.request?.url || "";
|
|
285
408
|
if (containsMockifyerSyncEndpointMarker(url)) {
|
|
286
|
-
console.warn(
|
|
287
|
-
|
|
409
|
+
console.warn(
|
|
410
|
+
`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`,
|
|
411
|
+
);
|
|
412
|
+
return {
|
|
413
|
+
success: false,
|
|
414
|
+
error: "Cannot save Mockifyer sync endpoint requests",
|
|
415
|
+
};
|
|
288
416
|
}
|
|
289
|
-
|
|
417
|
+
|
|
290
418
|
// Also check if the mockData string contains nested sync requests
|
|
291
419
|
const mockDataStr = JSON.stringify(mockData);
|
|
292
420
|
if (containsMockifyerSyncEndpointMarker(mockDataStr)) {
|
|
293
|
-
logger.warn(
|
|
294
|
-
|
|
421
|
+
logger.warn(
|
|
422
|
+
`[MockSync] ⚠️ Rejecting save - Mock data contains nested Mockifyer sync requests`,
|
|
423
|
+
);
|
|
424
|
+
return {
|
|
425
|
+
success: false,
|
|
426
|
+
error: "Mock data contains nested Mockifyer sync requests",
|
|
427
|
+
};
|
|
295
428
|
}
|
|
296
|
-
|
|
429
|
+
|
|
297
430
|
// Get current scenario and ensure scenario folder exists
|
|
298
431
|
const currentScenario = getCurrentScenario(mockDataPath);
|
|
299
432
|
const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
|
|
300
433
|
fs.mkdirSync(scenarioPath, { recursive: true });
|
|
301
434
|
|
|
302
|
-
const dateStr = new Date()
|
|
435
|
+
const dateStr = new Date()
|
|
436
|
+
.toISOString()
|
|
437
|
+
.replace(/T/, "_")
|
|
438
|
+
.replace(/\..+/, "")
|
|
439
|
+
.replace(/:/g, "-");
|
|
303
440
|
const { dir, filename } = getMockFilePathLocal(mockData, dateStr);
|
|
304
441
|
const fullDir = path.join(scenarioPath, dir);
|
|
305
442
|
const filePath = path.join(fullDir, filename);
|
|
306
443
|
|
|
307
444
|
// Check if file already exists - skip saving if it does
|
|
308
445
|
if (fs.existsSync(filePath)) {
|
|
309
|
-
return {
|
|
446
|
+
return {
|
|
447
|
+
success: true,
|
|
448
|
+
filename: path.join(dir, filename),
|
|
449
|
+
skipped: true,
|
|
450
|
+
reason: "File already exists",
|
|
451
|
+
};
|
|
310
452
|
}
|
|
311
453
|
|
|
312
454
|
fs.mkdirSync(fullDir, { recursive: true });
|
|
@@ -318,7 +460,11 @@ function saveMockToProjectFolder(
|
|
|
318
460
|
generateTestForMock(mockData, testConfig, projectRoot);
|
|
319
461
|
}
|
|
320
462
|
|
|
321
|
-
return {
|
|
463
|
+
return {
|
|
464
|
+
success: true,
|
|
465
|
+
filename: path.join(dir, filename),
|
|
466
|
+
scenario: currentScenario,
|
|
467
|
+
};
|
|
322
468
|
} catch (error) {
|
|
323
469
|
console.error(`[MockSync] ❌ Error saving mock to project folder:`, error);
|
|
324
470
|
return { success: false, error: (error as Error).message };
|
|
@@ -335,25 +481,33 @@ function saveProxyMirrorMockToProject(
|
|
|
335
481
|
mockDataPath: string,
|
|
336
482
|
scenarioName: string,
|
|
337
483
|
relativePath: string,
|
|
338
|
-
testConfig: TestGenerationOptions | null
|
|
484
|
+
testConfig: TestGenerationOptions | null,
|
|
339
485
|
): { success: boolean; filename?: string; scenario?: string; error?: string } {
|
|
340
486
|
try {
|
|
341
|
-
const url = mockData?.request?.url ||
|
|
487
|
+
const url = mockData?.request?.url || "";
|
|
342
488
|
if (containsMockifyerSyncEndpointMarker(url)) {
|
|
343
|
-
console.warn(
|
|
344
|
-
|
|
489
|
+
console.warn(
|
|
490
|
+
`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`,
|
|
491
|
+
);
|
|
492
|
+
return {
|
|
493
|
+
success: false,
|
|
494
|
+
error: "Cannot save Mockifyer sync endpoint requests",
|
|
495
|
+
};
|
|
345
496
|
}
|
|
346
497
|
const mockDataStr = JSON.stringify(mockData);
|
|
347
498
|
if (containsMockifyerSyncEndpointMarker(mockDataStr)) {
|
|
348
|
-
return {
|
|
499
|
+
return {
|
|
500
|
+
success: false,
|
|
501
|
+
error: "Mock data contains nested Mockifyer sync requests",
|
|
502
|
+
};
|
|
349
503
|
}
|
|
350
504
|
const id = scenarioName.trim();
|
|
351
505
|
if (!id) {
|
|
352
|
-
return { success: false, error:
|
|
506
|
+
return { success: false, error: "scenarioName is required" };
|
|
353
507
|
}
|
|
354
|
-
const normalized = relativePath.replace(/\\/g,
|
|
508
|
+
const normalized = relativePath.replace(/\\/g, "/").replace(/^\//, "");
|
|
355
509
|
if (!normalized) {
|
|
356
|
-
return { success: false, error:
|
|
510
|
+
return { success: false, error: "relativePath is required" };
|
|
357
511
|
}
|
|
358
512
|
const scenarioPath = getScenarioPath(id, mockDataPath);
|
|
359
513
|
fs.mkdirSync(scenarioPath, { recursive: true });
|
|
@@ -373,11 +527,15 @@ function saveProxyMirrorMockToProject(
|
|
|
373
527
|
/**
|
|
374
528
|
* Clear all mock files from project folder (current scenario)
|
|
375
529
|
*/
|
|
376
|
-
function clearMockFiles(mockDataPath: string): {
|
|
530
|
+
function clearMockFiles(mockDataPath: string): {
|
|
531
|
+
success: boolean;
|
|
532
|
+
filesDeleted?: number;
|
|
533
|
+
error?: string;
|
|
534
|
+
} {
|
|
377
535
|
try {
|
|
378
536
|
const currentScenario = getCurrentScenario(mockDataPath);
|
|
379
537
|
const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
|
|
380
|
-
|
|
538
|
+
|
|
381
539
|
if (!fs.existsSync(scenarioPath)) {
|
|
382
540
|
return { success: true, filesDeleted: 0 };
|
|
383
541
|
}
|
|
@@ -385,8 +543,8 @@ function clearMockFiles(mockDataPath: string): { success: boolean; filesDeleted?
|
|
|
385
543
|
const files = fs.readdirSync(scenarioPath);
|
|
386
544
|
let deleted = 0;
|
|
387
545
|
|
|
388
|
-
files.forEach(file => {
|
|
389
|
-
if (file.endsWith(
|
|
546
|
+
files.forEach((file) => {
|
|
547
|
+
if (file.endsWith(".json")) {
|
|
390
548
|
const filePath = path.join(scenarioPath, file);
|
|
391
549
|
fs.unlinkSync(filePath);
|
|
392
550
|
deleted++;
|
|
@@ -405,26 +563,31 @@ function clearMockFiles(mockDataPath: string): { success: boolean; filesDeleted?
|
|
|
405
563
|
*/
|
|
406
564
|
function syncFromIOSSimulator(
|
|
407
565
|
projectRoot: string,
|
|
408
|
-
mockDataPath: string
|
|
409
|
-
): {
|
|
566
|
+
mockDataPath: string,
|
|
567
|
+
): {
|
|
568
|
+
success: boolean;
|
|
569
|
+
filesSynced?: number;
|
|
570
|
+
syncedFiles?: string[];
|
|
571
|
+
error?: string;
|
|
572
|
+
} {
|
|
410
573
|
try {
|
|
411
574
|
// Get iOS simulator path
|
|
412
|
-
const homeDir = process.env.HOME || process.env.USERPROFILE ||
|
|
575
|
+
const homeDir = process.env.HOME || process.env.USERPROFILE || "";
|
|
413
576
|
const simulatorPath = path.join(
|
|
414
577
|
homeDir,
|
|
415
|
-
|
|
578
|
+
"Library/Developer/CoreSimulator/Devices",
|
|
416
579
|
);
|
|
417
580
|
|
|
418
581
|
if (!fs.existsSync(simulatorPath)) {
|
|
419
|
-
return { success: false, error:
|
|
582
|
+
return { success: false, error: "iOS Simulator path not found" };
|
|
420
583
|
}
|
|
421
584
|
|
|
422
585
|
// Find the most recent simulator device
|
|
423
586
|
const devices = fs.readdirSync(simulatorPath);
|
|
424
|
-
let latestDevice =
|
|
587
|
+
let latestDevice = "";
|
|
425
588
|
let latestTime = 0;
|
|
426
589
|
|
|
427
|
-
devices.forEach(device => {
|
|
590
|
+
devices.forEach((device) => {
|
|
428
591
|
const devicePath = path.join(simulatorPath, device);
|
|
429
592
|
const stat = fs.statSync(devicePath);
|
|
430
593
|
if (stat.mtimeMs > latestTime) {
|
|
@@ -434,18 +597,18 @@ function syncFromIOSSimulator(
|
|
|
434
597
|
});
|
|
435
598
|
|
|
436
599
|
if (!latestDevice) {
|
|
437
|
-
return { success: false, error:
|
|
600
|
+
return { success: false, error: "No iOS Simulator device found" };
|
|
438
601
|
}
|
|
439
602
|
|
|
440
603
|
// Look for mock-data directory in the simulator
|
|
441
604
|
const appDataPath = path.join(
|
|
442
605
|
simulatorPath,
|
|
443
606
|
latestDevice,
|
|
444
|
-
|
|
607
|
+
"data/Containers/Data/Application",
|
|
445
608
|
);
|
|
446
609
|
|
|
447
610
|
if (!fs.existsSync(appDataPath)) {
|
|
448
|
-
return { success: false, error:
|
|
611
|
+
return { success: false, error: "iOS Simulator app data path not found" };
|
|
449
612
|
}
|
|
450
613
|
|
|
451
614
|
const apps = fs.readdirSync(appDataPath);
|
|
@@ -455,7 +618,7 @@ function syncFromIOSSimulator(
|
|
|
455
618
|
|
|
456
619
|
for (const app of apps) {
|
|
457
620
|
const appPath = path.join(appDataPath, app);
|
|
458
|
-
const mockDataSimPath = path.join(appPath,
|
|
621
|
+
const mockDataSimPath = path.join(appPath, "Documents/mock-data");
|
|
459
622
|
|
|
460
623
|
if (fs.existsSync(mockDataSimPath)) {
|
|
461
624
|
found = true;
|
|
@@ -464,8 +627,8 @@ function syncFromIOSSimulator(
|
|
|
464
627
|
fs.mkdirSync(scenarioPath, { recursive: true });
|
|
465
628
|
|
|
466
629
|
const files = fs.readdirSync(mockDataSimPath);
|
|
467
|
-
files.forEach(file => {
|
|
468
|
-
if (file.endsWith(
|
|
630
|
+
files.forEach((file) => {
|
|
631
|
+
if (file.endsWith(".json")) {
|
|
469
632
|
const sourcePath = path.join(mockDataSimPath, file);
|
|
470
633
|
const destPath = path.join(scenarioPath, file);
|
|
471
634
|
fs.copyFileSync(sourcePath, destPath);
|
|
@@ -479,7 +642,11 @@ function syncFromIOSSimulator(
|
|
|
479
642
|
}
|
|
480
643
|
|
|
481
644
|
if (!found) {
|
|
482
|
-
return {
|
|
645
|
+
return {
|
|
646
|
+
success: false,
|
|
647
|
+
filesSynced: 0,
|
|
648
|
+
error: "mock-data directory not found in simulator",
|
|
649
|
+
};
|
|
483
650
|
}
|
|
484
651
|
|
|
485
652
|
return { success: true, filesSynced, syncedFiles };
|
|
@@ -491,7 +658,9 @@ function syncFromIOSSimulator(
|
|
|
491
658
|
/**
|
|
492
659
|
* Recursive mock JSON files under scenario root (paths relative to scenario, POSIX slashes).
|
|
493
660
|
*/
|
|
494
|
-
function listScenarioMockJsonFiles(
|
|
661
|
+
function listScenarioMockJsonFiles(
|
|
662
|
+
scenarioAbsPath: string,
|
|
663
|
+
): Array<{ relativePath: string; fullPath: string }> {
|
|
495
664
|
const out: Array<{ relativePath: string; fullPath: string }> = [];
|
|
496
665
|
if (!fs.existsSync(scenarioAbsPath)) {
|
|
497
666
|
return out;
|
|
@@ -501,12 +670,12 @@ function listScenarioMockJsonFiles(scenarioAbsPath: string): Array<{ relativePat
|
|
|
501
670
|
const full = path.join(dir, entry.name);
|
|
502
671
|
if (entry.isDirectory()) {
|
|
503
672
|
walk(full);
|
|
504
|
-
} else if (entry.name.endsWith(
|
|
673
|
+
} else if (entry.name.endsWith(".json")) {
|
|
505
674
|
const rel = path.relative(scenarioAbsPath, full);
|
|
506
|
-
const relativePath = rel.split(path.sep).join(
|
|
675
|
+
const relativePath = rel.split(path.sep).join("/");
|
|
507
676
|
if (
|
|
508
|
-
relativePath ===
|
|
509
|
-
relativePath ===
|
|
677
|
+
relativePath === "scenario-config.json" ||
|
|
678
|
+
relativePath === "date-config.json"
|
|
510
679
|
) {
|
|
511
680
|
continue;
|
|
512
681
|
}
|
|
@@ -523,7 +692,7 @@ function listScenarioMockJsonFiles(scenarioAbsPath: string): Array<{ relativePat
|
|
|
523
692
|
*/
|
|
524
693
|
function resolveScenarioRelativeMockPath(
|
|
525
694
|
rawQueryPath: string,
|
|
526
|
-
scenarioAbsPath: string
|
|
695
|
+
scenarioAbsPath: string,
|
|
527
696
|
): { relativePath: string; fullPath: string } | null {
|
|
528
697
|
let decoded: string;
|
|
529
698
|
try {
|
|
@@ -531,17 +700,20 @@ function resolveScenarioRelativeMockPath(
|
|
|
531
700
|
} catch {
|
|
532
701
|
return null;
|
|
533
702
|
}
|
|
534
|
-
const normalized = decoded.replace(/\\/g,
|
|
535
|
-
if (!normalized.endsWith(
|
|
703
|
+
const normalized = decoded.replace(/\\/g, "/").replace(/^\//, "");
|
|
704
|
+
if (!normalized.endsWith(".json") || normalized.includes("..")) {
|
|
536
705
|
return null;
|
|
537
706
|
}
|
|
538
707
|
const fullPath = path.normalize(path.join(scenarioAbsPath, normalized));
|
|
539
708
|
const scenarioResolved = path.resolve(scenarioAbsPath);
|
|
540
709
|
const relativeToScenario = path.relative(scenarioResolved, fullPath);
|
|
541
|
-
if (
|
|
710
|
+
if (
|
|
711
|
+
relativeToScenario.startsWith("..") ||
|
|
712
|
+
path.isAbsolute(relativeToScenario)
|
|
713
|
+
) {
|
|
542
714
|
return null;
|
|
543
715
|
}
|
|
544
|
-
const relativePath = relativeToScenario.split(path.sep).join(
|
|
716
|
+
const relativePath = relativeToScenario.split(path.sep).join("/");
|
|
545
717
|
return { relativePath, fullPath };
|
|
546
718
|
}
|
|
547
719
|
|
|
@@ -564,11 +736,14 @@ function buildSyncToDeviceManifest(mockDataPath: string): {
|
|
|
564
736
|
const stat = fs.statSync(fullPath);
|
|
565
737
|
files.push({ filename: relativePath, modificationTime: stat.mtimeMs });
|
|
566
738
|
} catch (e) {
|
|
567
|
-
logger.warn(
|
|
739
|
+
logger.warn(
|
|
740
|
+
`[MetroSyncMiddleware] Manifest: could not stat ${fullPath}:`,
|
|
741
|
+
e,
|
|
742
|
+
);
|
|
568
743
|
}
|
|
569
744
|
}
|
|
570
745
|
logger.info(
|
|
571
|
-
`[MetroSyncMiddleware] /mockifyer-sync-to-device-manifest: ${files.length} file(s), scenario "${currentScenario}"
|
|
746
|
+
`[MetroSyncMiddleware] /mockifyer-sync-to-device-manifest: ${files.length} file(s), scenario "${currentScenario}"`,
|
|
572
747
|
);
|
|
573
748
|
return { success: true, files, count: files.length };
|
|
574
749
|
} catch (error) {
|
|
@@ -579,7 +754,10 @@ function buildSyncToDeviceManifest(mockDataPath: string): {
|
|
|
579
754
|
/**
|
|
580
755
|
* One mock file for GET /mockifyer-sync-to-device-file?path=
|
|
581
756
|
*/
|
|
582
|
-
function buildSyncToDeviceSingleFilePayload(
|
|
757
|
+
function buildSyncToDeviceSingleFilePayload(
|
|
758
|
+
mockDataPath: string,
|
|
759
|
+
rawPathParam: string,
|
|
760
|
+
): {
|
|
583
761
|
success: boolean;
|
|
584
762
|
filename?: string;
|
|
585
763
|
content?: MockData;
|
|
@@ -589,18 +767,24 @@ function buildSyncToDeviceSingleFilePayload(mockDataPath: string, rawPathParam:
|
|
|
589
767
|
try {
|
|
590
768
|
const currentScenario = getCurrentScenario(mockDataPath);
|
|
591
769
|
const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
|
|
592
|
-
const resolved = resolveScenarioRelativeMockPath(
|
|
770
|
+
const resolved = resolveScenarioRelativeMockPath(
|
|
771
|
+
rawPathParam,
|
|
772
|
+
scenarioPath,
|
|
773
|
+
);
|
|
593
774
|
if (!resolved) {
|
|
594
|
-
return { success: false, error:
|
|
775
|
+
return { success: false, error: "Invalid or unsafe path" };
|
|
595
776
|
}
|
|
596
777
|
const { fullPath, relativePath } = resolved;
|
|
597
778
|
if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {
|
|
598
|
-
return { success: false, error:
|
|
779
|
+
return { success: false, error: "Not found" };
|
|
599
780
|
}
|
|
600
|
-
const raw = fs.readFileSync(fullPath,
|
|
781
|
+
const raw = fs.readFileSync(fullPath, "utf-8");
|
|
601
782
|
const content = JSON.parse(raw) as MockData;
|
|
602
783
|
if (!content?.request || !content?.response) {
|
|
603
|
-
return {
|
|
784
|
+
return {
|
|
785
|
+
success: false,
|
|
786
|
+
error: "Invalid mock JSON (missing request/response)",
|
|
787
|
+
};
|
|
604
788
|
}
|
|
605
789
|
const stat = fs.statSync(fullPath);
|
|
606
790
|
return {
|
|
@@ -619,7 +803,11 @@ function buildSyncToDeviceSingleFilePayload(mockDataPath: string, rawPathParam:
|
|
|
619
803
|
*/
|
|
620
804
|
function buildSyncToDevicePayload(mockDataPath: string): {
|
|
621
805
|
success: boolean;
|
|
622
|
-
files?: Array<{
|
|
806
|
+
files?: Array<{
|
|
807
|
+
filename: string;
|
|
808
|
+
content: MockData;
|
|
809
|
+
modificationTime: number;
|
|
810
|
+
}>;
|
|
623
811
|
count?: number;
|
|
624
812
|
error?: string;
|
|
625
813
|
} {
|
|
@@ -627,14 +815,20 @@ function buildSyncToDevicePayload(mockDataPath: string): {
|
|
|
627
815
|
const currentScenario = getCurrentScenario(mockDataPath);
|
|
628
816
|
const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
|
|
629
817
|
const entries = listScenarioMockJsonFiles(scenarioPath);
|
|
630
|
-
const files: Array<{
|
|
818
|
+
const files: Array<{
|
|
819
|
+
filename: string;
|
|
820
|
+
content: MockData;
|
|
821
|
+
modificationTime: number;
|
|
822
|
+
}> = [];
|
|
631
823
|
|
|
632
824
|
for (const { relativePath, fullPath } of entries) {
|
|
633
825
|
try {
|
|
634
|
-
const raw = fs.readFileSync(fullPath,
|
|
826
|
+
const raw = fs.readFileSync(fullPath, "utf-8");
|
|
635
827
|
const content = JSON.parse(raw) as MockData;
|
|
636
828
|
if (!content?.request || !content?.response) {
|
|
637
|
-
logger.debug(
|
|
829
|
+
logger.debug(
|
|
830
|
+
`[MetroSyncMiddleware] Skipping JSON without request/response: ${relativePath}`,
|
|
831
|
+
);
|
|
638
832
|
continue;
|
|
639
833
|
}
|
|
640
834
|
const stat = fs.statSync(fullPath);
|
|
@@ -649,7 +843,7 @@ function buildSyncToDevicePayload(mockDataPath: string): {
|
|
|
649
843
|
}
|
|
650
844
|
|
|
651
845
|
logger.info(
|
|
652
|
-
`[MetroSyncMiddleware] /mockifyer-sync-to-device: ${files.length} mock file(s) from scenario "${getCurrentScenario(mockDataPath)}"
|
|
846
|
+
`[MetroSyncMiddleware] /mockifyer-sync-to-device: ${files.length} mock file(s) from scenario "${getCurrentScenario(mockDataPath)}"`,
|
|
653
847
|
);
|
|
654
848
|
return { success: true, files, count: files.length };
|
|
655
849
|
} catch (error) {
|
|
@@ -663,11 +857,11 @@ function buildSyncToDevicePayload(mockDataPath: string): {
|
|
|
663
857
|
*/
|
|
664
858
|
function buildPoolResponsePayload(
|
|
665
859
|
mockDataPath: string,
|
|
666
|
-
rawId: string
|
|
860
|
+
rawId: string,
|
|
667
861
|
): { success: boolean; item?: PoolResponseItem; error?: string } {
|
|
668
|
-
const id = String(rawId ||
|
|
862
|
+
const id = String(rawId || "").trim();
|
|
669
863
|
if (!id || !POOL_ID_PATTERN.test(id)) {
|
|
670
|
-
return { success: false, error:
|
|
864
|
+
return { success: false, error: "Invalid pool response id" };
|
|
671
865
|
}
|
|
672
866
|
try {
|
|
673
867
|
const item = loadPoolResponseItem(mockDataPath, id, {
|
|
@@ -675,12 +869,12 @@ function buildPoolResponsePayload(
|
|
|
675
869
|
existsSync: (p) => fs.existsSync(p),
|
|
676
870
|
readFileSync: (p, encoding) => fs.readFileSync(p, encoding),
|
|
677
871
|
writeFileSync: () => {
|
|
678
|
-
throw new Error(
|
|
872
|
+
throw new Error("pool loader is read-only");
|
|
679
873
|
},
|
|
680
874
|
mkdirSync: () => undefined,
|
|
681
875
|
});
|
|
682
876
|
if (!item) {
|
|
683
|
-
return { success: false, error:
|
|
877
|
+
return { success: false, error: "Not found" };
|
|
684
878
|
}
|
|
685
879
|
return { success: true, item };
|
|
686
880
|
} catch (error) {
|
|
@@ -693,62 +887,620 @@ function buildPoolResponsePayload(
|
|
|
693
887
|
* Without this, trailing slashes fall through to Expo Web's SPA and Expo Router treats them as AppDun routes.
|
|
694
888
|
*/
|
|
695
889
|
function normalizeMiddlewarePathname(reqUrl: string): string {
|
|
696
|
-
if (!reqUrl || typeof reqUrl !==
|
|
697
|
-
return
|
|
890
|
+
if (!reqUrl || typeof reqUrl !== "string") {
|
|
891
|
+
return "/";
|
|
698
892
|
}
|
|
699
|
-
let pathname = reqUrl.split(
|
|
700
|
-
if (pathname.length > 1 && pathname.endsWith(
|
|
893
|
+
let pathname = reqUrl.split("?")[0];
|
|
894
|
+
if (pathname.length > 1 && pathname.endsWith("/")) {
|
|
701
895
|
pathname = pathname.slice(0, -1);
|
|
702
896
|
}
|
|
703
897
|
return pathname;
|
|
704
898
|
}
|
|
705
899
|
|
|
900
|
+
function saveAtlasHtmlIncident(
|
|
901
|
+
projectRoot: string,
|
|
902
|
+
mockDataPath: string,
|
|
903
|
+
incidentId: string,
|
|
904
|
+
html: string,
|
|
905
|
+
): {
|
|
906
|
+
success: boolean;
|
|
907
|
+
filePath?: string;
|
|
908
|
+
relativePath?: string;
|
|
909
|
+
error?: string;
|
|
910
|
+
} {
|
|
911
|
+
const id = incidentId.trim();
|
|
912
|
+
if (!id || !html.trim()) {
|
|
913
|
+
return { success: false, error: "incidentId and html are required" };
|
|
914
|
+
}
|
|
915
|
+
if (id.includes("..") || id.includes("/") || id.includes("\\")) {
|
|
916
|
+
return { success: false, error: "Invalid incident id" };
|
|
917
|
+
}
|
|
918
|
+
try {
|
|
919
|
+
const dir = path.join(mockDataPath, "atlas-html", "incidents");
|
|
920
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
921
|
+
const filePath = path.join(dir, `${id}.html`);
|
|
922
|
+
fs.writeFileSync(filePath, html, "utf8");
|
|
923
|
+
const relativeFromRoot = path.relative(projectRoot, filePath);
|
|
924
|
+
return {
|
|
925
|
+
success: true,
|
|
926
|
+
filePath,
|
|
927
|
+
relativePath: relativeFromRoot.split(path.sep).join("/"),
|
|
928
|
+
};
|
|
929
|
+
} catch (error) {
|
|
930
|
+
return { success: false, error: (error as Error).message };
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
function saveAtlasScreenshot(
|
|
935
|
+
projectRoot: string,
|
|
936
|
+
mockDataPath: string,
|
|
937
|
+
relativePath: string,
|
|
938
|
+
base64: string,
|
|
939
|
+
metadata?: {
|
|
940
|
+
sessionId?: string;
|
|
941
|
+
screen?: string;
|
|
942
|
+
scenario?: string;
|
|
943
|
+
pageId?: string;
|
|
944
|
+
capturedAt?: string;
|
|
945
|
+
},
|
|
946
|
+
): {
|
|
947
|
+
success: boolean;
|
|
948
|
+
filePath?: string;
|
|
949
|
+
relativePath?: string;
|
|
950
|
+
error?: string;
|
|
951
|
+
} {
|
|
952
|
+
const rel = relativePath.trim().replace(/^\/+/, "");
|
|
953
|
+
if (!rel || !base64.trim()) {
|
|
954
|
+
return { success: false, error: "relativePath and base64 are required" };
|
|
955
|
+
}
|
|
956
|
+
if (
|
|
957
|
+
rel.includes("..") ||
|
|
958
|
+
!rel.startsWith("screenshots/") ||
|
|
959
|
+
!/\.(png|jpe?g|webp)$/i.test(rel)
|
|
960
|
+
) {
|
|
961
|
+
return {
|
|
962
|
+
success: false,
|
|
963
|
+
error: "relativePath must be screenshots/<name>.(png|jpg|webp)",
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
const fileName = path.basename(rel);
|
|
967
|
+
if (!fileName || fileName === "." || fileName === "..") {
|
|
968
|
+
return { success: false, error: "Invalid screenshot file name" };
|
|
969
|
+
}
|
|
970
|
+
try {
|
|
971
|
+
const dir = path.join(mockDataPath, "atlas-html", "screenshots");
|
|
972
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
973
|
+
const filePath = path.join(dir, fileName);
|
|
974
|
+
fs.writeFileSync(filePath, Buffer.from(base64.trim(), "base64"));
|
|
975
|
+
const relativeFromRoot = path.relative(projectRoot, filePath);
|
|
976
|
+
|
|
977
|
+
// Update Atlas doc map with screenshot metadata (Metro has fs, so HTML will be written)
|
|
978
|
+
if (metadata?.screen && metadata?.sessionId) {
|
|
979
|
+
const htmlPath = path.join(mockDataPath, "atlas-html");
|
|
980
|
+
setAtlasDocHtmlOutputPath(htmlPath);
|
|
981
|
+
setAtlasDocScreenshot({
|
|
982
|
+
scenario: metadata.scenario,
|
|
983
|
+
screen: metadata.screen,
|
|
984
|
+
sessionId: metadata.sessionId,
|
|
985
|
+
screenshotPath: rel,
|
|
986
|
+
capturedAt: metadata.capturedAt ?? new Date().toISOString(),
|
|
987
|
+
pageId: metadata.pageId,
|
|
988
|
+
});
|
|
989
|
+
flushAtlasDocHtmlRewrite();
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
return {
|
|
993
|
+
success: true,
|
|
994
|
+
filePath,
|
|
995
|
+
relativePath: relativeFromRoot.split(path.sep).join("/"),
|
|
996
|
+
};
|
|
997
|
+
} catch (error) {
|
|
998
|
+
return { success: false, error: (error as Error).message };
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
const BODY_SPILL_REL_PATTERN =
|
|
1003
|
+
/^bodies\/[A-Za-z0-9._-]+-(req|res)\.(json|txt)$/;
|
|
1004
|
+
|
|
1005
|
+
/**
|
|
1006
|
+
* Persist a full hop body spill from the device (RN) under atlas-html/bodies/.
|
|
1007
|
+
*/
|
|
1008
|
+
function saveAtlasBodySpill(
|
|
1009
|
+
projectRoot: string,
|
|
1010
|
+
mockDataPath: string,
|
|
1011
|
+
relativePath: string,
|
|
1012
|
+
text: string,
|
|
1013
|
+
): {
|
|
1014
|
+
success: boolean;
|
|
1015
|
+
filePath?: string;
|
|
1016
|
+
relativePath?: string;
|
|
1017
|
+
error?: string;
|
|
1018
|
+
} {
|
|
1019
|
+
const rel = relativePath.trim().replace(/^\/+/, "").replace(/\\/g, "/");
|
|
1020
|
+
if (!rel || typeof text !== "string") {
|
|
1021
|
+
return { success: false, error: "relativePath and text are required" };
|
|
1022
|
+
}
|
|
1023
|
+
if (rel.includes("..") || !BODY_SPILL_REL_PATTERN.test(rel)) {
|
|
1024
|
+
return {
|
|
1025
|
+
success: false,
|
|
1026
|
+
error:
|
|
1027
|
+
"relativePath must be bodies/<id>-req.json or bodies/<id>-res.json",
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
try {
|
|
1031
|
+
const filePath = path.join(mockDataPath, "atlas-html", rel);
|
|
1032
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
1033
|
+
const body = rel.endsWith(".json") ? prettyPrintJsonText(text) : text;
|
|
1034
|
+
fs.writeFileSync(filePath, body, "utf8");
|
|
1035
|
+
const relativeFromRoot = path.relative(projectRoot, filePath);
|
|
1036
|
+
return {
|
|
1037
|
+
success: true,
|
|
1038
|
+
filePath,
|
|
1039
|
+
relativePath: relativeFromRoot.split(path.sep).join("/"),
|
|
1040
|
+
};
|
|
1041
|
+
} catch (error) {
|
|
1042
|
+
return { success: false, error: (error as Error).message };
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
const ATLAS_HTML_CONTENT_TYPES: Record<string, string> = {
|
|
1047
|
+
".html": "text/html; charset=utf-8",
|
|
1048
|
+
".htm": "text/html; charset=utf-8",
|
|
1049
|
+
".png": "image/png",
|
|
1050
|
+
".jpg": "image/jpeg",
|
|
1051
|
+
".jpeg": "image/jpeg",
|
|
1052
|
+
".webp": "image/webp",
|
|
1053
|
+
".gif": "image/gif",
|
|
1054
|
+
".svg": "image/svg+xml",
|
|
1055
|
+
".json": "application/json; charset=utf-8",
|
|
1056
|
+
".md": "text/markdown; charset=utf-8",
|
|
1057
|
+
".txt": "text/plain; charset=utf-8",
|
|
1058
|
+
".css": "text/css; charset=utf-8",
|
|
1059
|
+
".js": "text/javascript; charset=utf-8",
|
|
1060
|
+
};
|
|
1061
|
+
|
|
1062
|
+
/**
|
|
1063
|
+
* Serve any safe file under mock-data/atlas-html/ (index, pages, incidents, screenshots).
|
|
1064
|
+
* Prevents path traversal; directories resolve to index.html.
|
|
1065
|
+
*/
|
|
1066
|
+
function serveAtlasHtmlStatic(
|
|
1067
|
+
mockDataPath: string,
|
|
1068
|
+
relativeUrlPath: string,
|
|
1069
|
+
res: {
|
|
1070
|
+
setHeader: (k: string, v: string) => void;
|
|
1071
|
+
statusCode: number;
|
|
1072
|
+
end: (b?: string | Buffer) => void;
|
|
1073
|
+
},
|
|
1074
|
+
): boolean {
|
|
1075
|
+
let rel = relativeUrlPath.split("?")[0] || "";
|
|
1076
|
+
try {
|
|
1077
|
+
rel = decodeURIComponent(rel);
|
|
1078
|
+
} catch {
|
|
1079
|
+
res.statusCode = 400;
|
|
1080
|
+
res.setHeader("Content-Type", "text/plain");
|
|
1081
|
+
res.end("Invalid path encoding");
|
|
1082
|
+
return true;
|
|
1083
|
+
}
|
|
1084
|
+
rel = rel.replace(/^\/+/, "").replace(/\\/g, "/");
|
|
1085
|
+
if (!rel || rel.endsWith("/")) {
|
|
1086
|
+
rel = `${rel}index.html`.replace(/^\//, "");
|
|
1087
|
+
}
|
|
1088
|
+
if (!rel || rel.includes("..") || path.isAbsolute(rel)) {
|
|
1089
|
+
res.statusCode = 400;
|
|
1090
|
+
res.setHeader("Content-Type", "text/plain");
|
|
1091
|
+
res.end("Invalid atlas-html path");
|
|
1092
|
+
return true;
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
const root = path.resolve(mockDataPath, "atlas-html");
|
|
1096
|
+
const filePath = path.resolve(root, rel);
|
|
1097
|
+
const rootPrefix = root.endsWith(path.sep) ? root : root + path.sep;
|
|
1098
|
+
if (filePath !== root && !filePath.startsWith(rootPrefix)) {
|
|
1099
|
+
res.statusCode = 400;
|
|
1100
|
+
res.setHeader("Content-Type", "text/plain");
|
|
1101
|
+
res.end("Invalid atlas-html path");
|
|
1102
|
+
return true;
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
if (!fs.existsSync(filePath)) {
|
|
1106
|
+
res.statusCode = 404;
|
|
1107
|
+
res.setHeader("Content-Type", "text/plain");
|
|
1108
|
+
res.end(
|
|
1109
|
+
"Atlas HTML file not found — run Dev Menu “Render Atlas docs” first.",
|
|
1110
|
+
);
|
|
1111
|
+
return true;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
const stat = fs.statSync(filePath);
|
|
1115
|
+
if (stat.isDirectory()) {
|
|
1116
|
+
const indexPath = path.join(filePath, "index.html");
|
|
1117
|
+
if (!fs.existsSync(indexPath) || !fs.statSync(indexPath).isFile()) {
|
|
1118
|
+
res.statusCode = 404;
|
|
1119
|
+
res.setHeader("Content-Type", "text/plain");
|
|
1120
|
+
res.end("Atlas HTML index not found in directory.");
|
|
1121
|
+
return true;
|
|
1122
|
+
}
|
|
1123
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
1124
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
1125
|
+
res.end(fs.readFileSync(indexPath, "utf8"));
|
|
1126
|
+
return true;
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
if (!stat.isFile()) {
|
|
1130
|
+
res.statusCode = 404;
|
|
1131
|
+
res.setHeader("Content-Type", "text/plain");
|
|
1132
|
+
res.end("Not a file");
|
|
1133
|
+
return true;
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
1137
|
+
const contentType =
|
|
1138
|
+
ATLAS_HTML_CONTENT_TYPES[ext] || "application/octet-stream";
|
|
1139
|
+
res.setHeader("Content-Type", contentType);
|
|
1140
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
1141
|
+
res.end(fs.readFileSync(filePath));
|
|
1142
|
+
return true;
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
const NETWORK_STREAM_NDJSON_REL = path.join("atlas-html", "atlas.ndjson");
|
|
1146
|
+
|
|
1147
|
+
function appendNetworkEventNdjson(
|
|
1148
|
+
mockDataPath: string,
|
|
1149
|
+
event: NetworkEvent,
|
|
1150
|
+
): void {
|
|
1151
|
+
try {
|
|
1152
|
+
const filePath = path.join(mockDataPath, NETWORK_STREAM_NDJSON_REL);
|
|
1153
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
1154
|
+
fs.appendFileSync(filePath, `${JSON.stringify(event)}\n`, "utf8");
|
|
1155
|
+
} catch {
|
|
1156
|
+
// disk append is best-effort
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
function writeNetworkEventsSnapshot(
|
|
1161
|
+
mockDataPath: string,
|
|
1162
|
+
events: NetworkEvent[],
|
|
1163
|
+
): {
|
|
1164
|
+
dir: string;
|
|
1165
|
+
jsonPath: string;
|
|
1166
|
+
ndjsonPath: string;
|
|
1167
|
+
harPath: string;
|
|
1168
|
+
count: number;
|
|
1169
|
+
} {
|
|
1170
|
+
const dir = path.join(mockDataPath, "atlas-html");
|
|
1171
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1172
|
+
const jsonPath = path.join(dir, "atlas-events.json");
|
|
1173
|
+
const ndjsonPath = path.join(dir, "atlas.ndjson");
|
|
1174
|
+
const harPath = path.join(dir, "atlas.har");
|
|
1175
|
+
fs.writeFileSync(jsonPath, `${JSON.stringify(events, null, 2)}\n`, "utf8");
|
|
1176
|
+
fs.writeFileSync(
|
|
1177
|
+
ndjsonPath,
|
|
1178
|
+
`${events.map((e) => JSON.stringify(e)).join("\n")}${events.length ? "\n" : ""}`,
|
|
1179
|
+
"utf8",
|
|
1180
|
+
);
|
|
1181
|
+
fs.writeFileSync(harPath, buildAtlasHarJson(events), "utf8");
|
|
1182
|
+
return { dir, jsonPath, ndjsonPath, harPath, count: events.length };
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
function renderNetworkEventsAtlasHtml(
|
|
1186
|
+
projectRoot: string,
|
|
1187
|
+
mockDataPath: string,
|
|
1188
|
+
events: NetworkEvent[],
|
|
1189
|
+
scenario?: string,
|
|
1190
|
+
): {
|
|
1191
|
+
success: boolean;
|
|
1192
|
+
written: number;
|
|
1193
|
+
outputDir: string;
|
|
1194
|
+
/** Absolute path to index.html on disk (open with the OS file handler). */
|
|
1195
|
+
indexPath: string;
|
|
1196
|
+
hopCount: number;
|
|
1197
|
+
error?: string;
|
|
1198
|
+
} {
|
|
1199
|
+
const outDir = path.join(mockDataPath, "atlas-html");
|
|
1200
|
+
const doc = createEmptyAtlasDocMap(
|
|
1201
|
+
scenario?.trim() || events[0]?.scenario || "default",
|
|
1202
|
+
);
|
|
1203
|
+
// Flush any buffered large bodies so HTML "Open full …" links resolve on disk.
|
|
1204
|
+
flushNetworkBodySpillsToDir(outDir);
|
|
1205
|
+
const written = writeAtlasDocHtml(outDir, doc, events);
|
|
1206
|
+
writeNetworkEventsSnapshot(mockDataPath, events);
|
|
1207
|
+
const relativeFromRoot = path
|
|
1208
|
+
.relative(projectRoot, outDir)
|
|
1209
|
+
.split(path.sep)
|
|
1210
|
+
.join("/");
|
|
1211
|
+
const indexPath = path.join(outDir, "index.html");
|
|
1212
|
+
return {
|
|
1213
|
+
success: written > 0,
|
|
1214
|
+
written,
|
|
1215
|
+
outputDir: relativeFromRoot,
|
|
1216
|
+
indexPath,
|
|
1217
|
+
hopCount: events.length,
|
|
1218
|
+
error: written > 0 ? undefined : "writeAtlasDocHtml wrote 0 files",
|
|
1219
|
+
};
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
/** GET path under `/atlas-html/` or legacy `/mockifyer-atlas-html/` → file under mock-data/atlas-html/. */
|
|
1223
|
+
function atlasHtmlStaticSuffix(url: string): string | null {
|
|
1224
|
+
const prefixes = ["/atlas-html", "/mockifyer-atlas-html"] as const;
|
|
1225
|
+
for (const prefix of prefixes) {
|
|
1226
|
+
if (url === prefix || url === `${prefix}/`) {
|
|
1227
|
+
return "index.html";
|
|
1228
|
+
}
|
|
1229
|
+
if (url.startsWith(`${prefix}/`)) {
|
|
1230
|
+
return url.slice(prefix.length + 1);
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
return null;
|
|
1234
|
+
}
|
|
1235
|
+
|
|
706
1236
|
/**
|
|
707
1237
|
* Metro middleware function
|
|
708
1238
|
*/
|
|
709
1239
|
export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
710
1240
|
const projectRoot = options?.projectRoot || process.cwd();
|
|
711
|
-
const mockDataPath = path.resolve(
|
|
1241
|
+
const mockDataPath = path.resolve(
|
|
1242
|
+
projectRoot,
|
|
1243
|
+
options?.mockDataPath || "mock-data",
|
|
1244
|
+
);
|
|
712
1245
|
const testConfig = getTestGenerationConfig(options);
|
|
713
|
-
|
|
1246
|
+
|
|
714
1247
|
// Log the resolved paths for debugging
|
|
715
|
-
logger.info(
|
|
1248
|
+
logger.info(
|
|
1249
|
+
`[MetroSyncMiddleware] Initialized with projectRoot: ${projectRoot}, mockDataPath: ${mockDataPath}`,
|
|
1250
|
+
);
|
|
716
1251
|
|
|
717
1252
|
return function mockSyncMiddleware(req: any, res: any, next: any) {
|
|
718
|
-
const url = normalizeMiddlewarePathname(req.url ||
|
|
719
|
-
|
|
1253
|
+
const url = normalizeMiddlewarePathname(req.url || "");
|
|
1254
|
+
|
|
720
1255
|
// Handle POST endpoint for clearing mocks
|
|
721
|
-
if (url ===
|
|
1256
|
+
if (url === "/mockifyer-clear" && req.method === "POST") {
|
|
722
1257
|
const result = clearMockFiles(mockDataPath);
|
|
723
|
-
res.setHeader(
|
|
1258
|
+
res.setHeader("Content-Type", "application/json");
|
|
724
1259
|
res.end(JSON.stringify(result));
|
|
725
1260
|
return;
|
|
726
1261
|
}
|
|
727
|
-
|
|
1262
|
+
|
|
1263
|
+
// Live hop ring buffer for `mockifyer-atlas` interactive CLI
|
|
1264
|
+
if (url === "/mockifyer-network-events" && req.method === "POST") {
|
|
1265
|
+
collectRequestBodyUtf8(req, (err, body) => {
|
|
1266
|
+
if (err) {
|
|
1267
|
+
res.statusCode = 413;
|
|
1268
|
+
res.setHeader("Content-Type", "application/json");
|
|
1269
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
1270
|
+
return;
|
|
1271
|
+
}
|
|
1272
|
+
try {
|
|
1273
|
+
const parsed = JSON.parse(body) as {
|
|
1274
|
+
event?: NetworkEvent;
|
|
1275
|
+
events?: NetworkEvent[];
|
|
1276
|
+
};
|
|
1277
|
+
const incoming: NetworkEvent[] = [];
|
|
1278
|
+
if (parsed.event && typeof parsed.event === "object") {
|
|
1279
|
+
incoming.push(parsed.event);
|
|
1280
|
+
}
|
|
1281
|
+
if (Array.isArray(parsed.events)) {
|
|
1282
|
+
for (const e of parsed.events) {
|
|
1283
|
+
if (e && typeof e === "object") incoming.push(e);
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
if (incoming.length === 0) {
|
|
1287
|
+
res.statusCode = 400;
|
|
1288
|
+
res.setHeader("Content-Type", "application/json");
|
|
1289
|
+
res.end(
|
|
1290
|
+
JSON.stringify({
|
|
1291
|
+
success: false,
|
|
1292
|
+
error: "event or events required",
|
|
1293
|
+
}),
|
|
1294
|
+
);
|
|
1295
|
+
return;
|
|
1296
|
+
}
|
|
1297
|
+
const buffer = getMetroNetworkEventBuffer();
|
|
1298
|
+
const saved = incoming.map((e) => {
|
|
1299
|
+
const stored = buffer.append(e);
|
|
1300
|
+
appendNetworkEventNdjson(mockDataPath, stored);
|
|
1301
|
+
return stored;
|
|
1302
|
+
});
|
|
1303
|
+
res.statusCode = 201;
|
|
1304
|
+
res.setHeader("Content-Type", "application/json");
|
|
1305
|
+
res.end(
|
|
1306
|
+
JSON.stringify({
|
|
1307
|
+
success: true,
|
|
1308
|
+
count: saved.length,
|
|
1309
|
+
size: buffer.size,
|
|
1310
|
+
}),
|
|
1311
|
+
);
|
|
1312
|
+
} catch (error) {
|
|
1313
|
+
res.statusCode = 400;
|
|
1314
|
+
res.setHeader("Content-Type", "application/json");
|
|
1315
|
+
res.end(
|
|
1316
|
+
JSON.stringify({
|
|
1317
|
+
success: false,
|
|
1318
|
+
error: `Invalid JSON: ${(error as Error).message}`,
|
|
1319
|
+
}),
|
|
1320
|
+
);
|
|
1321
|
+
}
|
|
1322
|
+
});
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
if (url === "/mockifyer-network-events" && req.method === "GET") {
|
|
1327
|
+
const fullUrl = req.url || "";
|
|
1328
|
+
const qIndex = fullUrl.indexOf("?");
|
|
1329
|
+
const params = new URLSearchParams(
|
|
1330
|
+
qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "",
|
|
1331
|
+
);
|
|
1332
|
+
const limitRaw = params.get("limit");
|
|
1333
|
+
const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;
|
|
1334
|
+
const buffer = getMetroNetworkEventBuffer();
|
|
1335
|
+
const events = buffer.list(
|
|
1336
|
+
Number.isFinite(limit as number) ? (limit as number) : undefined,
|
|
1337
|
+
);
|
|
1338
|
+
res.setHeader("Content-Type", "application/json");
|
|
1339
|
+
res.end(JSON.stringify({ success: true, size: buffer.size, events }));
|
|
1340
|
+
return;
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
if (url === "/mockifyer-network-events/stream" && req.method === "GET") {
|
|
1344
|
+
const fullUrl = req.url || "";
|
|
1345
|
+
const qIndex = fullUrl.indexOf("?");
|
|
1346
|
+
const params = new URLSearchParams(
|
|
1347
|
+
qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "",
|
|
1348
|
+
);
|
|
1349
|
+
const backlog = params.get("backlog") !== "0";
|
|
1350
|
+
const buffer = getMetroNetworkEventBuffer();
|
|
1351
|
+
res.writeHead(200, {
|
|
1352
|
+
"Content-Type": "text/event-stream",
|
|
1353
|
+
"Cache-Control": "no-cache, no-transform",
|
|
1354
|
+
Connection: "keep-alive",
|
|
1355
|
+
"X-Accel-Buffering": "no",
|
|
1356
|
+
});
|
|
1357
|
+
if (typeof res.flushHeaders === "function") {
|
|
1358
|
+
res.flushHeaders();
|
|
1359
|
+
}
|
|
1360
|
+
res.write(
|
|
1361
|
+
`event: hello\ndata: ${JSON.stringify({ size: buffer.size })}\n\n`,
|
|
1362
|
+
);
|
|
1363
|
+
if (backlog) {
|
|
1364
|
+
const past = [...buffer.list()].reverse();
|
|
1365
|
+
for (const event of past) {
|
|
1366
|
+
res.write(`event: hop\ndata: ${JSON.stringify(event)}\n\n`);
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
const unsubscribe = buffer.subscribe((event) => {
|
|
1370
|
+
try {
|
|
1371
|
+
res.write(`event: hop\ndata: ${JSON.stringify(event)}\n\n`);
|
|
1372
|
+
} catch {
|
|
1373
|
+
unsubscribe();
|
|
1374
|
+
}
|
|
1375
|
+
});
|
|
1376
|
+
const keepAlive = setInterval(() => {
|
|
1377
|
+
try {
|
|
1378
|
+
res.write(": ping\n\n");
|
|
1379
|
+
} catch {
|
|
1380
|
+
clearInterval(keepAlive);
|
|
1381
|
+
unsubscribe();
|
|
1382
|
+
}
|
|
1383
|
+
}, 15_000);
|
|
1384
|
+
const onClose = () => {
|
|
1385
|
+
clearInterval(keepAlive);
|
|
1386
|
+
unsubscribe();
|
|
1387
|
+
};
|
|
1388
|
+
req.on("close", onClose);
|
|
1389
|
+
req.on("aborted", onClose);
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
if (url === "/mockifyer-network-events/analyze" && req.method === "GET") {
|
|
1394
|
+
const fullUrl = req.url || "";
|
|
1395
|
+
const qIndex = fullUrl.indexOf("?");
|
|
1396
|
+
const params = new URLSearchParams(
|
|
1397
|
+
qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "",
|
|
1398
|
+
);
|
|
1399
|
+
const slowRaw = params.get("slowMs");
|
|
1400
|
+
const slowMs = slowRaw ? Number.parseInt(slowRaw, 10) : undefined;
|
|
1401
|
+
const buffer = getMetroNetworkEventBuffer();
|
|
1402
|
+
const analysis = analyzeMetroNetworkEvents(buffer.list(), {
|
|
1403
|
+
slowMs: Number.isFinite(slowMs as number)
|
|
1404
|
+
? (slowMs as number)
|
|
1405
|
+
: undefined,
|
|
1406
|
+
});
|
|
1407
|
+
res.setHeader("Content-Type", "application/json");
|
|
1408
|
+
res.end(JSON.stringify({ success: true, analysis }));
|
|
1409
|
+
return;
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
if (url === "/mockifyer-network-events/snapshot" && req.method === "POST") {
|
|
1413
|
+
const buffer = getMetroNetworkEventBuffer();
|
|
1414
|
+
const events = [...buffer.list()].reverse();
|
|
1415
|
+
const result = writeNetworkEventsSnapshot(mockDataPath, events);
|
|
1416
|
+
res.statusCode = 201;
|
|
1417
|
+
res.setHeader("Content-Type", "application/json");
|
|
1418
|
+
res.end(
|
|
1419
|
+
JSON.stringify({
|
|
1420
|
+
success: true,
|
|
1421
|
+
count: result.count,
|
|
1422
|
+
dir: path.relative(projectRoot, result.dir).split(path.sep).join("/"),
|
|
1423
|
+
jsonPath: path
|
|
1424
|
+
.relative(projectRoot, result.jsonPath)
|
|
1425
|
+
.split(path.sep)
|
|
1426
|
+
.join("/"),
|
|
1427
|
+
ndjsonPath: path
|
|
1428
|
+
.relative(projectRoot, result.ndjsonPath)
|
|
1429
|
+
.split(path.sep)
|
|
1430
|
+
.join("/"),
|
|
1431
|
+
harPath: path
|
|
1432
|
+
.relative(projectRoot, result.harPath)
|
|
1433
|
+
.split(path.sep)
|
|
1434
|
+
.join("/"),
|
|
1435
|
+
}),
|
|
1436
|
+
);
|
|
1437
|
+
return;
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
if (url === "/mockifyer-network-events/render" && req.method === "POST") {
|
|
1441
|
+
collectRequestBodyUtf8(req, (err, body) => {
|
|
1442
|
+
if (err) {
|
|
1443
|
+
res.statusCode = 413;
|
|
1444
|
+
res.setHeader("Content-Type", "application/json");
|
|
1445
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
1446
|
+
return;
|
|
1447
|
+
}
|
|
1448
|
+
let scenario: string | undefined;
|
|
1449
|
+
if (body.trim()) {
|
|
1450
|
+
try {
|
|
1451
|
+
const parsed = JSON.parse(body) as { scenario?: string };
|
|
1452
|
+
if (typeof parsed.scenario === "string") scenario = parsed.scenario;
|
|
1453
|
+
} catch {
|
|
1454
|
+
// empty / ignore
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
const buffer = getMetroNetworkEventBuffer();
|
|
1458
|
+
const events = [...buffer.list()].reverse();
|
|
1459
|
+
const result = renderNetworkEventsAtlasHtml(
|
|
1460
|
+
projectRoot,
|
|
1461
|
+
mockDataPath,
|
|
1462
|
+
events,
|
|
1463
|
+
scenario,
|
|
1464
|
+
);
|
|
1465
|
+
res.statusCode = result.success ? 201 : 500;
|
|
1466
|
+
res.setHeader("Content-Type", "application/json");
|
|
1467
|
+
res.end(JSON.stringify(result));
|
|
1468
|
+
});
|
|
1469
|
+
return;
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
if (url === "/mockifyer-network-events/clear" && req.method === "POST") {
|
|
1473
|
+
const buffer = getMetroNetworkEventBuffer();
|
|
1474
|
+
buffer.clear();
|
|
1475
|
+
res.setHeader("Content-Type", "application/json");
|
|
1476
|
+
res.end(JSON.stringify({ success: true, size: 0 }));
|
|
1477
|
+
return;
|
|
1478
|
+
}
|
|
1479
|
+
|
|
728
1480
|
// Handle GET endpoint for domain-path rules (RN Hybrid hydrate at startup)
|
|
729
|
-
if (url ===
|
|
730
|
-
const fullUrl = req.url ||
|
|
731
|
-
const qIndex = fullUrl.indexOf(
|
|
732
|
-
const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) :
|
|
1481
|
+
if (url === "/mockifyer-domain-path-rules" && req.method === "GET") {
|
|
1482
|
+
const fullUrl = req.url || "";
|
|
1483
|
+
const qIndex = fullUrl.indexOf("?");
|
|
1484
|
+
const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "";
|
|
733
1485
|
const params = new URLSearchParams(query);
|
|
734
|
-
const scenarioParam = params.get(
|
|
1486
|
+
const scenarioParam = params.get("scenario");
|
|
735
1487
|
const scenarioName =
|
|
736
|
-
scenarioParam && scenarioParam.trim() !==
|
|
1488
|
+
scenarioParam && scenarioParam.trim() !== ""
|
|
737
1489
|
? scenarioParam.trim()
|
|
738
1490
|
: getCurrentScenario(mockDataPath);
|
|
739
1491
|
const rules = readDomainPathRulesFile(mockDataPath, scenarioName);
|
|
740
|
-
res.setHeader(
|
|
1492
|
+
res.setHeader("Content-Type", "application/json");
|
|
741
1493
|
res.end(JSON.stringify({ success: true, scenario: scenarioName, rules }));
|
|
742
1494
|
return;
|
|
743
1495
|
}
|
|
744
1496
|
|
|
745
1497
|
// Handle POST endpoint for domain-path rules discovery merge (Hybrid / RN)
|
|
746
|
-
if (url ===
|
|
747
|
-
let body =
|
|
748
|
-
req.on(
|
|
1498
|
+
if (url === "/mockifyer-domain-path-rules" && req.method === "POST") {
|
|
1499
|
+
let body = "";
|
|
1500
|
+
req.on("data", (chunk: Buffer) => {
|
|
749
1501
|
body += chunk.toString();
|
|
750
1502
|
});
|
|
751
|
-
req.on(
|
|
1503
|
+
req.on("end", () => {
|
|
752
1504
|
try {
|
|
753
1505
|
const parsed = JSON.parse(body) as {
|
|
754
1506
|
scenario?: string;
|
|
@@ -756,25 +1508,350 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
756
1508
|
rules?: DomainPathRulesMap;
|
|
757
1509
|
};
|
|
758
1510
|
const scenarioName =
|
|
759
|
-
typeof parsed.scenario ===
|
|
1511
|
+
typeof parsed.scenario === "string" && parsed.scenario.trim() !== ""
|
|
760
1512
|
? parsed.scenario.trim()
|
|
761
1513
|
: getCurrentScenario(mockDataPath);
|
|
762
|
-
const upserts = parseDomainPathRules(
|
|
1514
|
+
const upserts = parseDomainPathRules(
|
|
1515
|
+
parsed.upserts ?? parsed.rules ?? {},
|
|
1516
|
+
);
|
|
763
1517
|
const existing = readDomainPathRulesFile(mockDataPath, scenarioName);
|
|
764
|
-
const { rules, changed } = mergeDomainPathRuleUpserts(
|
|
1518
|
+
const { rules, changed } = mergeDomainPathRuleUpserts(
|
|
1519
|
+
existing,
|
|
1520
|
+
upserts,
|
|
1521
|
+
);
|
|
765
1522
|
if (changed) {
|
|
766
1523
|
writeDomainPathRulesFile(mockDataPath, scenarioName, rules);
|
|
767
1524
|
}
|
|
768
|
-
res.setHeader(
|
|
769
|
-
res.end(
|
|
1525
|
+
res.setHeader("Content-Type", "application/json");
|
|
1526
|
+
res.end(
|
|
1527
|
+
JSON.stringify({
|
|
1528
|
+
success: true,
|
|
1529
|
+
changed,
|
|
1530
|
+
scenario: scenarioName,
|
|
1531
|
+
rules,
|
|
1532
|
+
}),
|
|
1533
|
+
);
|
|
770
1534
|
} catch (error) {
|
|
771
1535
|
res.statusCode = 400;
|
|
772
|
-
res.setHeader(
|
|
1536
|
+
res.setHeader("Content-Type", "application/json");
|
|
773
1537
|
res.end(
|
|
774
1538
|
JSON.stringify({
|
|
775
1539
|
success: false,
|
|
776
1540
|
error: `Invalid JSON: ${(error as Error).message}`,
|
|
777
|
-
})
|
|
1541
|
+
}),
|
|
1542
|
+
);
|
|
1543
|
+
}
|
|
1544
|
+
});
|
|
1545
|
+
return;
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
// Generate-on-click for terminal OSC-8 links (terminals cannot hijack OSC-8).
|
|
1549
|
+
// GET /mockifyer-atlas-open?id=<hopId>&side=req|res|html
|
|
1550
|
+
if (
|
|
1551
|
+
req.method === "GET" &&
|
|
1552
|
+
(url === "/mockifyer-atlas-open" || url.startsWith("/mockifyer-atlas-open?"))
|
|
1553
|
+
) {
|
|
1554
|
+
const fullUrl = String(req.url || "");
|
|
1555
|
+
const q = fullUrl.includes("?") ? fullUrl.slice(fullUrl.indexOf("?") + 1) : "";
|
|
1556
|
+
const params = new URLSearchParams(q);
|
|
1557
|
+
const hopId = (params.get("id") || "").trim();
|
|
1558
|
+
const sideParam = (params.get("side") || "html").trim().toLowerCase();
|
|
1559
|
+
const side =
|
|
1560
|
+
sideParam === "req" || sideParam === "res" ? sideParam : "html";
|
|
1561
|
+
|
|
1562
|
+
const buffer = getMetroNetworkEventBuffer();
|
|
1563
|
+
// Buffer is newest-first; render expects chronological / display order.
|
|
1564
|
+
const events = [...buffer.list()].reverse();
|
|
1565
|
+
const rendered = renderNetworkEventsAtlasHtml(projectRoot, mockDataPath, events);
|
|
1566
|
+
if (!rendered.success) {
|
|
1567
|
+
res.statusCode = 500;
|
|
1568
|
+
res.setHeader("Content-Type", "application/json");
|
|
1569
|
+
res.end(
|
|
1570
|
+
JSON.stringify({
|
|
1571
|
+
success: false,
|
|
1572
|
+
error: rendered.error || "atlas render failed",
|
|
1573
|
+
}),
|
|
1574
|
+
);
|
|
1575
|
+
return;
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
if (side === "html") {
|
|
1579
|
+
res.statusCode = 302;
|
|
1580
|
+
res.setHeader("Location", "/atlas-html/index.html");
|
|
1581
|
+
res.end();
|
|
1582
|
+
return;
|
|
1583
|
+
}
|
|
1584
|
+
|
|
1585
|
+
const event =
|
|
1586
|
+
(hopId
|
|
1587
|
+
? events.find((e) => e && (e.id === hopId || e.requestId === hopId))
|
|
1588
|
+
: undefined) || events[0];
|
|
1589
|
+
if (!event) {
|
|
1590
|
+
res.statusCode = 404;
|
|
1591
|
+
res.setHeader("Content-Type", "application/json");
|
|
1592
|
+
res.end(JSON.stringify({ success: false, error: "hop not found" }));
|
|
1593
|
+
return;
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
const rels = resolveNetworkEventBodyRelPaths(event);
|
|
1597
|
+
const rel = side === "req" ? rels.req : rels.res;
|
|
1598
|
+
const abs = path.join(mockDataPath, "atlas-html", rel);
|
|
1599
|
+
if (!fs.existsSync(abs)) {
|
|
1600
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
1601
|
+
const preview =
|
|
1602
|
+
side === "req" ? event.requestBodyPreview : event.responseBodyPreview;
|
|
1603
|
+
const text =
|
|
1604
|
+
preview != null && String(preview).trim() !== ""
|
|
1605
|
+
? String(preview)
|
|
1606
|
+
: JSON.stringify(
|
|
1607
|
+
{
|
|
1608
|
+
note: "No body captured for this hop yet",
|
|
1609
|
+
id: event.id,
|
|
1610
|
+
side,
|
|
1611
|
+
},
|
|
1612
|
+
null,
|
|
1613
|
+
2,
|
|
1614
|
+
);
|
|
1615
|
+
fs.writeFileSync(
|
|
1616
|
+
abs,
|
|
1617
|
+
text.endsWith("\n") ? text : `${text}\n`,
|
|
1618
|
+
"utf8",
|
|
1619
|
+
);
|
|
1620
|
+
}
|
|
1621
|
+
res.statusCode = 302;
|
|
1622
|
+
res.setHeader(
|
|
1623
|
+
"Location",
|
|
1624
|
+
`/atlas-html/${rel.split(path.sep).join("/")}`,
|
|
1625
|
+
);
|
|
1626
|
+
res.end();
|
|
1627
|
+
return;
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
// Atlas HTML static files (index, pages, incidents, screenshots) — must not fall through to Expo web shell.
|
|
1631
|
+
// Prefer /atlas-html/; keep /mockifyer-atlas-html/ as a legacy alias.
|
|
1632
|
+
if (req.method === "GET") {
|
|
1633
|
+
const atlasSuffix = atlasHtmlStaticSuffix(url);
|
|
1634
|
+
if (atlasSuffix != null && serveAtlasHtmlStatic(mockDataPath, atlasSuffix, res)) {
|
|
1635
|
+
return;
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
if (url === "/mockifyer-atlas-html" && req.method === "POST") {
|
|
1640
|
+
let body = "";
|
|
1641
|
+
req.on("data", (chunk: Buffer) => {
|
|
1642
|
+
body += chunk.toString();
|
|
1643
|
+
});
|
|
1644
|
+
req.on("end", () => {
|
|
1645
|
+
try {
|
|
1646
|
+
const parsed = JSON.parse(body) as {
|
|
1647
|
+
incidentId?: string;
|
|
1648
|
+
html?: string;
|
|
1649
|
+
};
|
|
1650
|
+
const incidentId =
|
|
1651
|
+
typeof parsed.incidentId === "string" ? parsed.incidentId : "";
|
|
1652
|
+
const html = typeof parsed.html === "string" ? parsed.html : "";
|
|
1653
|
+
const result = saveAtlasHtmlIncident(
|
|
1654
|
+
projectRoot,
|
|
1655
|
+
mockDataPath,
|
|
1656
|
+
incidentId,
|
|
1657
|
+
html,
|
|
1658
|
+
);
|
|
1659
|
+
res.setHeader("Content-Type", "application/json");
|
|
1660
|
+
res.statusCode = result.success ? 201 : 400;
|
|
1661
|
+
res.end(JSON.stringify(result));
|
|
1662
|
+
} catch (error) {
|
|
1663
|
+
res.statusCode = 400;
|
|
1664
|
+
res.setHeader("Content-Type", "application/json");
|
|
1665
|
+
res.end(
|
|
1666
|
+
JSON.stringify({
|
|
1667
|
+
success: false,
|
|
1668
|
+
error: `Invalid JSON: ${(error as Error).message}`,
|
|
1669
|
+
}),
|
|
1670
|
+
);
|
|
1671
|
+
}
|
|
1672
|
+
});
|
|
1673
|
+
return;
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
// Atlas screen screenshot (device → project mock-data/atlas-html/screenshots/)
|
|
1677
|
+
if (url === "/mockifyer-atlas-screenshot" && req.method === "POST") {
|
|
1678
|
+
collectRequestBodyUtf8(req, (err, body) => {
|
|
1679
|
+
if (err) {
|
|
1680
|
+
res.statusCode = 413;
|
|
1681
|
+
res.setHeader("Content-Type", "application/json");
|
|
1682
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
try {
|
|
1686
|
+
const parsed = JSON.parse(body) as {
|
|
1687
|
+
relativePath?: string;
|
|
1688
|
+
base64?: string;
|
|
1689
|
+
sessionId?: string;
|
|
1690
|
+
screen?: string;
|
|
1691
|
+
scenario?: string;
|
|
1692
|
+
pageId?: string;
|
|
1693
|
+
capturedAt?: string;
|
|
1694
|
+
};
|
|
1695
|
+
const relativePath =
|
|
1696
|
+
typeof parsed.relativePath === "string" ? parsed.relativePath : "";
|
|
1697
|
+
const base64 = typeof parsed.base64 === "string" ? parsed.base64 : "";
|
|
1698
|
+
const metadata = {
|
|
1699
|
+
sessionId:
|
|
1700
|
+
typeof parsed.sessionId === "string"
|
|
1701
|
+
? parsed.sessionId
|
|
1702
|
+
: undefined,
|
|
1703
|
+
screen:
|
|
1704
|
+
typeof parsed.screen === "string" ? parsed.screen : undefined,
|
|
1705
|
+
scenario:
|
|
1706
|
+
typeof parsed.scenario === "string" ? parsed.scenario : undefined,
|
|
1707
|
+
pageId:
|
|
1708
|
+
typeof parsed.pageId === "string" ? parsed.pageId : undefined,
|
|
1709
|
+
capturedAt:
|
|
1710
|
+
typeof parsed.capturedAt === "string"
|
|
1711
|
+
? parsed.capturedAt
|
|
1712
|
+
: undefined,
|
|
1713
|
+
};
|
|
1714
|
+
const result = saveAtlasScreenshot(
|
|
1715
|
+
projectRoot,
|
|
1716
|
+
mockDataPath,
|
|
1717
|
+
relativePath,
|
|
1718
|
+
base64,
|
|
1719
|
+
metadata,
|
|
1720
|
+
);
|
|
1721
|
+
res.setHeader("Content-Type", "application/json");
|
|
1722
|
+
res.statusCode = result.success ? 201 : 400;
|
|
1723
|
+
res.end(JSON.stringify(result));
|
|
1724
|
+
} catch (error) {
|
|
1725
|
+
res.statusCode = 400;
|
|
1726
|
+
res.setHeader("Content-Type", "application/json");
|
|
1727
|
+
res.end(
|
|
1728
|
+
JSON.stringify({
|
|
1729
|
+
success: false,
|
|
1730
|
+
error: `Invalid JSON: ${(error as Error).message}`,
|
|
1731
|
+
}),
|
|
1732
|
+
);
|
|
1733
|
+
}
|
|
1734
|
+
});
|
|
1735
|
+
return;
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
// Full hop body spill (device → project mock-data/atlas-html/bodies/)
|
|
1739
|
+
if (url === "/mockifyer-atlas-body-spill" && req.method === "POST") {
|
|
1740
|
+
collectRequestBodyUtf8(req, (err, body) => {
|
|
1741
|
+
if (err) {
|
|
1742
|
+
res.statusCode = 413;
|
|
1743
|
+
res.setHeader("Content-Type", "application/json");
|
|
1744
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
1745
|
+
return;
|
|
1746
|
+
}
|
|
1747
|
+
try {
|
|
1748
|
+
const parsed = JSON.parse(body) as {
|
|
1749
|
+
relativePath?: string;
|
|
1750
|
+
text?: string;
|
|
1751
|
+
};
|
|
1752
|
+
const relativePath =
|
|
1753
|
+
typeof parsed.relativePath === "string" ? parsed.relativePath : "";
|
|
1754
|
+
const text = typeof parsed.text === "string" ? parsed.text : "";
|
|
1755
|
+
const result = saveAtlasBodySpill(
|
|
1756
|
+
projectRoot,
|
|
1757
|
+
mockDataPath,
|
|
1758
|
+
relativePath,
|
|
1759
|
+
text,
|
|
1760
|
+
);
|
|
1761
|
+
res.setHeader("Content-Type", "application/json");
|
|
1762
|
+
res.statusCode = result.success ? 201 : 400;
|
|
1763
|
+
res.end(JSON.stringify(result));
|
|
1764
|
+
} catch (error) {
|
|
1765
|
+
res.statusCode = 400;
|
|
1766
|
+
res.setHeader("Content-Type", "application/json");
|
|
1767
|
+
res.end(
|
|
1768
|
+
JSON.stringify({
|
|
1769
|
+
success: false,
|
|
1770
|
+
error: `Invalid JSON: ${(error as Error).message}`,
|
|
1771
|
+
}),
|
|
1772
|
+
);
|
|
1773
|
+
}
|
|
1774
|
+
});
|
|
1775
|
+
return;
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
// Full Atlas interactive HTML (Dev Menu → requestAtlasDocsRender)
|
|
1779
|
+
if (url === "/mockifyer-atlas-render" && req.method === "POST") {
|
|
1780
|
+
collectRequestBodyUtf8(req, (err, body) => {
|
|
1781
|
+
if (err) {
|
|
1782
|
+
res.statusCode = 413;
|
|
1783
|
+
res.setHeader("Content-Type", "application/json");
|
|
1784
|
+
res.end(JSON.stringify({ success: false, error: err.message }));
|
|
1785
|
+
return;
|
|
1786
|
+
}
|
|
1787
|
+
try {
|
|
1788
|
+
const parsed = JSON.parse(body) as {
|
|
1789
|
+
outputRelativeDir?: string;
|
|
1790
|
+
doc?: AtlasDocMap;
|
|
1791
|
+
events?: NetworkEvent[];
|
|
1792
|
+
bodySpills?: Record<string, string>;
|
|
1793
|
+
};
|
|
1794
|
+
const rel =
|
|
1795
|
+
typeof parsed.outputRelativeDir === "string" &&
|
|
1796
|
+
parsed.outputRelativeDir.trim()
|
|
1797
|
+
? parsed.outputRelativeDir.trim().replace(/^[/\\]+/, "")
|
|
1798
|
+
: "atlas-html";
|
|
1799
|
+
if (rel.includes("..")) {
|
|
1800
|
+
res.statusCode = 400;
|
|
1801
|
+
res.setHeader("Content-Type", "application/json");
|
|
1802
|
+
res.end(
|
|
1803
|
+
JSON.stringify({
|
|
1804
|
+
success: false,
|
|
1805
|
+
error: "Invalid outputRelativeDir",
|
|
1806
|
+
}),
|
|
1807
|
+
);
|
|
1808
|
+
return;
|
|
1809
|
+
}
|
|
1810
|
+
const outDir = path.join(mockDataPath, rel);
|
|
1811
|
+
const doc = parsed.doc;
|
|
1812
|
+
if (!doc || typeof doc !== "object") {
|
|
1813
|
+
res.statusCode = 400;
|
|
1814
|
+
res.setHeader("Content-Type", "application/json");
|
|
1815
|
+
res.end(
|
|
1816
|
+
JSON.stringify({ success: false, error: "doc is required" }),
|
|
1817
|
+
);
|
|
1818
|
+
return;
|
|
1819
|
+
}
|
|
1820
|
+
setAtlasDocMap(doc);
|
|
1821
|
+
setAtlasDocHtmlOutputPath(outDir);
|
|
1822
|
+
const spillWritten = writeNetworkBodySpillMap(
|
|
1823
|
+
outDir,
|
|
1824
|
+
parsed.bodySpills,
|
|
1825
|
+
);
|
|
1826
|
+
const events = Array.isArray(parsed.events) ? parsed.events : [];
|
|
1827
|
+
const written = writeAtlasDocHtml(outDir, doc, events);
|
|
1828
|
+
const relativeFromRoot = path
|
|
1829
|
+
.relative(projectRoot, outDir)
|
|
1830
|
+
.split(path.sep)
|
|
1831
|
+
.join("/");
|
|
1832
|
+
res.setHeader("Content-Type", "application/json");
|
|
1833
|
+
res.statusCode = written > 0 ? 201 : 500;
|
|
1834
|
+
res.end(
|
|
1835
|
+
JSON.stringify({
|
|
1836
|
+
success: written > 0,
|
|
1837
|
+
written,
|
|
1838
|
+
bodySpillsWritten: spillWritten,
|
|
1839
|
+
dir: outDir,
|
|
1840
|
+
outputDir: relativeFromRoot,
|
|
1841
|
+
indexPath: path.join(outDir, "index.html"),
|
|
1842
|
+
hopCount: events.length,
|
|
1843
|
+
error:
|
|
1844
|
+
written > 0 ? undefined : "writeAtlasDocHtml wrote 0 files",
|
|
1845
|
+
}),
|
|
1846
|
+
);
|
|
1847
|
+
} catch (error) {
|
|
1848
|
+
res.statusCode = 400;
|
|
1849
|
+
res.setHeader("Content-Type", "application/json");
|
|
1850
|
+
res.end(
|
|
1851
|
+
JSON.stringify({
|
|
1852
|
+
success: false,
|
|
1853
|
+
error: `Invalid JSON: ${(error as Error).message}`,
|
|
1854
|
+
}),
|
|
778
1855
|
);
|
|
779
1856
|
}
|
|
780
1857
|
});
|
|
@@ -782,74 +1859,87 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
782
1859
|
}
|
|
783
1860
|
|
|
784
1861
|
// Handle POST endpoint for direct save (HybridProvider)
|
|
785
|
-
if (url ===
|
|
786
|
-
let body =
|
|
787
|
-
|
|
788
|
-
req.on(
|
|
1862
|
+
if (url === "/mockifyer-save" && req.method === "POST") {
|
|
1863
|
+
let body = "";
|
|
1864
|
+
|
|
1865
|
+
req.on("data", (chunk: Buffer) => {
|
|
789
1866
|
body += chunk.toString();
|
|
790
1867
|
});
|
|
791
|
-
|
|
792
|
-
req.on(
|
|
1868
|
+
|
|
1869
|
+
req.on("end", () => {
|
|
793
1870
|
try {
|
|
794
1871
|
const parsed = JSON.parse(body);
|
|
795
1872
|
if (
|
|
796
1873
|
parsed &&
|
|
797
|
-
typeof parsed ===
|
|
1874
|
+
typeof parsed === "object" &&
|
|
798
1875
|
parsed.__mockifyerProxyMirror === true &&
|
|
799
1876
|
parsed.mockData
|
|
800
1877
|
) {
|
|
801
|
-
const scenarioName =
|
|
802
|
-
|
|
1878
|
+
const scenarioName =
|
|
1879
|
+
typeof parsed.scenarioName === "string"
|
|
1880
|
+
? parsed.scenarioName
|
|
1881
|
+
: "";
|
|
1882
|
+
const relativePath =
|
|
1883
|
+
typeof parsed.relativePath === "string"
|
|
1884
|
+
? parsed.relativePath
|
|
1885
|
+
: "";
|
|
803
1886
|
const result = saveProxyMirrorMockToProject(
|
|
804
1887
|
parsed.mockData,
|
|
805
1888
|
projectRoot,
|
|
806
1889
|
mockDataPath,
|
|
807
1890
|
scenarioName,
|
|
808
1891
|
relativePath,
|
|
809
|
-
testConfig
|
|
1892
|
+
testConfig,
|
|
810
1893
|
);
|
|
811
|
-
res.setHeader(
|
|
1894
|
+
res.setHeader("Content-Type", "application/json");
|
|
812
1895
|
res.end(JSON.stringify(result));
|
|
813
1896
|
return;
|
|
814
1897
|
}
|
|
815
1898
|
const mockData = parsed;
|
|
816
|
-
const result = saveMockToProjectFolder(
|
|
817
|
-
|
|
818
|
-
|
|
1899
|
+
const result = saveMockToProjectFolder(
|
|
1900
|
+
mockData,
|
|
1901
|
+
projectRoot,
|
|
1902
|
+
mockDataPath,
|
|
1903
|
+
testConfig,
|
|
1904
|
+
);
|
|
1905
|
+
|
|
1906
|
+
res.setHeader("Content-Type", "application/json");
|
|
819
1907
|
res.end(JSON.stringify(result));
|
|
820
1908
|
} catch (error) {
|
|
821
1909
|
res.statusCode = 400;
|
|
822
|
-
res.setHeader(
|
|
823
|
-
res.end(
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
1910
|
+
res.setHeader("Content-Type", "application/json");
|
|
1911
|
+
res.end(
|
|
1912
|
+
JSON.stringify({
|
|
1913
|
+
success: false,
|
|
1914
|
+
error: `Invalid JSON: ${(error as Error).message}`,
|
|
1915
|
+
}),
|
|
1916
|
+
);
|
|
827
1917
|
}
|
|
828
1918
|
});
|
|
829
1919
|
return;
|
|
830
1920
|
}
|
|
831
1921
|
|
|
832
1922
|
// Project folder → device/simulator: manifest (small JSON)
|
|
833
|
-
if (url ===
|
|
1923
|
+
if (url === "/mockifyer-sync-to-device-manifest" && req.method === "GET") {
|
|
834
1924
|
const payload = buildSyncToDeviceManifest(mockDataPath);
|
|
835
|
-
res.setHeader(
|
|
1925
|
+
res.setHeader("Content-Type", "application/json");
|
|
836
1926
|
res.statusCode = payload.success ? 200 : 500;
|
|
837
1927
|
res.end(JSON.stringify(payload));
|
|
838
1928
|
return;
|
|
839
1929
|
}
|
|
840
1930
|
|
|
841
1931
|
// Promoted pool response for RN `$pool` serve-time resolve
|
|
842
|
-
if (url ===
|
|
843
|
-
const fullUrl = req.url ||
|
|
844
|
-
const qIndex = fullUrl.indexOf(
|
|
845
|
-
const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) :
|
|
1932
|
+
if (url === "/mockifyer-pool-response" && req.method === "GET") {
|
|
1933
|
+
const fullUrl = req.url || "";
|
|
1934
|
+
const qIndex = fullUrl.indexOf("?");
|
|
1935
|
+
const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "";
|
|
846
1936
|
const params = new URLSearchParams(query);
|
|
847
|
-
const idParam = params.get(
|
|
1937
|
+
const idParam = params.get("id") || "";
|
|
848
1938
|
const payload = buildPoolResponsePayload(mockDataPath, idParam);
|
|
849
|
-
res.setHeader(
|
|
1939
|
+
res.setHeader("Content-Type", "application/json");
|
|
850
1940
|
if (payload.success) {
|
|
851
1941
|
res.statusCode = 200;
|
|
852
|
-
} else if (payload.error ===
|
|
1942
|
+
} else if (payload.error === "Not found") {
|
|
853
1943
|
res.statusCode = 404;
|
|
854
1944
|
} else {
|
|
855
1945
|
res.statusCode = 400;
|
|
@@ -859,17 +1949,20 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
859
1949
|
}
|
|
860
1950
|
|
|
861
1951
|
// Single file for HybridProvider (avoids multi‑MB single response)
|
|
862
|
-
if (url ===
|
|
863
|
-
const fullUrl = req.url ||
|
|
864
|
-
const qIndex = fullUrl.indexOf(
|
|
865
|
-
const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) :
|
|
1952
|
+
if (url === "/mockifyer-sync-to-device-file" && req.method === "GET") {
|
|
1953
|
+
const fullUrl = req.url || "";
|
|
1954
|
+
const qIndex = fullUrl.indexOf("?");
|
|
1955
|
+
const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : "";
|
|
866
1956
|
const params = new URLSearchParams(query);
|
|
867
|
-
const pathParam = params.get(
|
|
868
|
-
const payload = buildSyncToDeviceSingleFilePayload(
|
|
869
|
-
|
|
1957
|
+
const pathParam = params.get("path") || "";
|
|
1958
|
+
const payload = buildSyncToDeviceSingleFilePayload(
|
|
1959
|
+
mockDataPath,
|
|
1960
|
+
pathParam,
|
|
1961
|
+
);
|
|
1962
|
+
res.setHeader("Content-Type", "application/json");
|
|
870
1963
|
if (payload.success) {
|
|
871
1964
|
res.statusCode = 200;
|
|
872
|
-
} else if (payload.error ===
|
|
1965
|
+
} else if (payload.error === "Not found") {
|
|
873
1966
|
res.statusCode = 404;
|
|
874
1967
|
} else {
|
|
875
1968
|
res.statusCode = 400;
|
|
@@ -879,111 +1972,138 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
879
1972
|
}
|
|
880
1973
|
|
|
881
1974
|
// Legacy: all files in one response (may OOM / timeout on large scenarios)
|
|
882
|
-
if (url ===
|
|
1975
|
+
if (url === "/mockifyer-sync-to-device" && req.method === "GET") {
|
|
883
1976
|
const payload = buildSyncToDevicePayload(mockDataPath);
|
|
884
|
-
res.setHeader(
|
|
1977
|
+
res.setHeader("Content-Type", "application/json");
|
|
885
1978
|
res.statusCode = payload.success ? 200 : 500;
|
|
886
1979
|
res.end(JSON.stringify(payload));
|
|
887
1980
|
return;
|
|
888
1981
|
}
|
|
889
|
-
|
|
1982
|
+
|
|
890
1983
|
// Handle GET endpoint for sync status
|
|
891
|
-
if (url ===
|
|
1984
|
+
if (url === "/mockifyer-sync/status" && req.method === "GET") {
|
|
892
1985
|
const currentScenario = getCurrentScenario(mockDataPath);
|
|
893
1986
|
const scenarioPath = getScenarioPath(currentScenario, mockDataPath);
|
|
894
|
-
const files = fs.existsSync(scenarioPath)
|
|
895
|
-
? fs
|
|
1987
|
+
const files = fs.existsSync(scenarioPath)
|
|
1988
|
+
? fs
|
|
1989
|
+
.readdirSync(scenarioPath)
|
|
1990
|
+
.filter((f: string) => f.endsWith(".json"))
|
|
896
1991
|
: [];
|
|
897
|
-
|
|
898
|
-
res.setHeader(
|
|
899
|
-
res.end(
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
1992
|
+
|
|
1993
|
+
res.setHeader("Content-Type", "application/json");
|
|
1994
|
+
res.end(
|
|
1995
|
+
JSON.stringify({
|
|
1996
|
+
success: true,
|
|
1997
|
+
scenario: currentScenario,
|
|
1998
|
+
fileCount: files.length,
|
|
1999
|
+
files: files.slice(0, 10), // Return first 10 files
|
|
2000
|
+
}),
|
|
2001
|
+
);
|
|
905
2002
|
return;
|
|
906
2003
|
}
|
|
907
|
-
|
|
2004
|
+
|
|
908
2005
|
// Handle GET endpoint for sync (legacy polling-based sync)
|
|
909
|
-
if (url ===
|
|
2006
|
+
if (url === "/mockifyer-sync" && req.method === "GET") {
|
|
910
2007
|
const result = syncFromIOSSimulator(projectRoot, mockDataPath);
|
|
911
|
-
res.setHeader(
|
|
2008
|
+
res.setHeader("Content-Type", "application/json");
|
|
912
2009
|
res.end(JSON.stringify(result));
|
|
913
2010
|
return;
|
|
914
2011
|
}
|
|
915
|
-
|
|
2012
|
+
|
|
916
2013
|
// Handle GET endpoint for scenario config
|
|
917
|
-
if (url ===
|
|
2014
|
+
if (url === "/mockifyer-scenario-config" && req.method === "GET") {
|
|
918
2015
|
try {
|
|
919
2016
|
// Check environment variable first (highest priority)
|
|
920
2017
|
if (process.env.MOCKIFYER_SCENARIO) {
|
|
921
|
-
logger.info(
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
2018
|
+
logger.info(
|
|
2019
|
+
`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${process.env.MOCKIFYER_SCENARIO}`,
|
|
2020
|
+
);
|
|
2021
|
+
res.setHeader("Content-Type", "application/json");
|
|
2022
|
+
res.end(
|
|
2023
|
+
JSON.stringify({
|
|
2024
|
+
success: true,
|
|
2025
|
+
currentScenario: process.env.MOCKIFYER_SCENARIO,
|
|
2026
|
+
}),
|
|
2027
|
+
);
|
|
927
2028
|
return;
|
|
928
2029
|
}
|
|
929
|
-
|
|
930
|
-
const configPath = path.join(mockDataPath,
|
|
2030
|
+
|
|
2031
|
+
const configPath = path.join(mockDataPath, "scenario-config.json");
|
|
931
2032
|
const resolvedPath = path.resolve(configPath);
|
|
932
|
-
logger.info(
|
|
933
|
-
|
|
934
|
-
|
|
2033
|
+
logger.info(
|
|
2034
|
+
`[MetroSyncMiddleware] Reading scenario config from: ${resolvedPath}`,
|
|
2035
|
+
);
|
|
2036
|
+
logger.info(
|
|
2037
|
+
`[MetroSyncMiddleware] mockDataPath: ${mockDataPath}, projectRoot: ${projectRoot}`,
|
|
2038
|
+
);
|
|
2039
|
+
|
|
935
2040
|
if (fs.existsSync(configPath)) {
|
|
936
|
-
const fileContent = fs.readFileSync(configPath,
|
|
2041
|
+
const fileContent = fs.readFileSync(configPath, "utf-8");
|
|
937
2042
|
logger.info(`[MetroSyncMiddleware] File content: ${fileContent}`);
|
|
938
2043
|
const config = JSON.parse(fileContent);
|
|
939
2044
|
const scenario = config.currentScenario || DEFAULT_SCENARIO;
|
|
940
|
-
logger.info(
|
|
941
|
-
|
|
942
|
-
|
|
2045
|
+
logger.info(
|
|
2046
|
+
`[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`,
|
|
2047
|
+
);
|
|
2048
|
+
|
|
2049
|
+
res.setHeader("Content-Type", "application/json");
|
|
943
2050
|
// Return format expected by ExpoFileSystemProvider: { success: true, currentScenario: ... }
|
|
944
|
-
res.end(
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
2051
|
+
res.end(
|
|
2052
|
+
JSON.stringify({
|
|
2053
|
+
success: true,
|
|
2054
|
+
currentScenario: scenario,
|
|
2055
|
+
}),
|
|
2056
|
+
);
|
|
948
2057
|
} else {
|
|
949
|
-
logger.info(
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
2058
|
+
logger.info(
|
|
2059
|
+
`[MetroSyncMiddleware] Config file not found at ${resolvedPath}, returning default scenario`,
|
|
2060
|
+
);
|
|
2061
|
+
res.setHeader("Content-Type", "application/json");
|
|
2062
|
+
res.end(
|
|
2063
|
+
JSON.stringify({
|
|
2064
|
+
success: true,
|
|
2065
|
+
currentScenario: DEFAULT_SCENARIO,
|
|
2066
|
+
}),
|
|
2067
|
+
);
|
|
955
2068
|
}
|
|
956
2069
|
} catch (error) {
|
|
957
|
-
logger.error(
|
|
2070
|
+
logger.error(
|
|
2071
|
+
`[MetroSyncMiddleware] Error reading scenario config:`,
|
|
2072
|
+
error,
|
|
2073
|
+
);
|
|
958
2074
|
res.statusCode = 500;
|
|
959
|
-
res.setHeader(
|
|
960
|
-
res.end(
|
|
2075
|
+
res.setHeader("Content-Type", "application/json");
|
|
2076
|
+
res.end(
|
|
2077
|
+
JSON.stringify({ success: false, error: (error as Error).message }),
|
|
2078
|
+
);
|
|
961
2079
|
}
|
|
962
2080
|
return;
|
|
963
2081
|
}
|
|
964
|
-
|
|
2082
|
+
|
|
965
2083
|
// Handle POST endpoint for scenario config sync
|
|
966
|
-
if (url ===
|
|
967
|
-
let body =
|
|
968
|
-
req.on(
|
|
2084
|
+
if (url === "/mockifyer-scenario-config" && req.method === "POST") {
|
|
2085
|
+
let body = "";
|
|
2086
|
+
req.on("data", (chunk: Buffer) => {
|
|
969
2087
|
body += chunk.toString();
|
|
970
2088
|
});
|
|
971
|
-
req.on(
|
|
2089
|
+
req.on("end", () => {
|
|
972
2090
|
try {
|
|
973
2091
|
const config = JSON.parse(body);
|
|
974
|
-
const configPath = path.join(mockDataPath,
|
|
2092
|
+
const configPath = path.join(mockDataPath, "scenario-config.json");
|
|
975
2093
|
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
|
|
976
|
-
res.setHeader(
|
|
2094
|
+
res.setHeader("Content-Type", "application/json");
|
|
977
2095
|
res.end(JSON.stringify({ success: true }));
|
|
978
2096
|
} catch (error) {
|
|
979
2097
|
res.statusCode = 400;
|
|
980
|
-
res.setHeader(
|
|
981
|
-
res.end(
|
|
2098
|
+
res.setHeader("Content-Type", "application/json");
|
|
2099
|
+
res.end(
|
|
2100
|
+
JSON.stringify({ success: false, error: (error as Error).message }),
|
|
2101
|
+
);
|
|
982
2102
|
}
|
|
983
2103
|
});
|
|
984
2104
|
return;
|
|
985
2105
|
}
|
|
986
|
-
|
|
2106
|
+
|
|
987
2107
|
// Continue to next middleware if not handled
|
|
988
2108
|
next();
|
|
989
2109
|
};
|
|
@@ -994,14 +2114,17 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
994
2114
|
*/
|
|
995
2115
|
export function startAutoSync(
|
|
996
2116
|
intervalMs: number = 5000,
|
|
997
|
-
options?: MetroSyncMiddlewareOptions
|
|
2117
|
+
options?: MetroSyncMiddlewareOptions,
|
|
998
2118
|
): void {
|
|
999
2119
|
if (autoSyncInterval) {
|
|
1000
2120
|
return;
|
|
1001
2121
|
}
|
|
1002
2122
|
|
|
1003
2123
|
const projectRoot = options?.projectRoot || process.cwd();
|
|
1004
|
-
const mockDataPath = path.resolve(
|
|
2124
|
+
const mockDataPath = path.resolve(
|
|
2125
|
+
projectRoot,
|
|
2126
|
+
options?.mockDataPath || "mock-data",
|
|
2127
|
+
);
|
|
1005
2128
|
|
|
1006
2129
|
logger.info(`[MockSync] Starting auto-sync every ${intervalMs}ms`);
|
|
1007
2130
|
autoSyncInterval = setInterval(() => {
|
|
@@ -1021,4 +2144,3 @@ export function stopAutoSync(): void {
|
|
|
1021
2144
|
|
|
1022
2145
|
// Export sync function for manual use
|
|
1023
2146
|
export { syncFromIOSSimulator };
|
|
1024
|
-
|