@sgedda/mockifyer-fetch 1.8.100 → 1.8.104

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.
@@ -34,6 +34,10 @@ export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<an
34
34
  });
35
35
  private resolvedClientLane;
36
36
  protected performRequest<D = any>(config: HTTPRequestConfig<D>): Promise<HTTPResponse<any>>;
37
+ /** Update whether `/api/proxy` sends `record` (record-on-miss). */
38
+ setProxyRecordOnMiss(recordOnMiss: boolean | undefined): void;
39
+ /** Update whether `/api/proxy` asks the dashboard to store response bodies. */
40
+ setProxyRecordResponses(recordResponses: boolean): void;
37
41
  protected getDefaultHeaders(): Record<string, string>;
38
42
  protected getDefaultConfig(): Record<string, any>;
39
43
  }
@@ -3,6 +3,47 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FetchHTTPClient = void 0;
4
4
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
5
5
  const core_proxy_1 = require("../core-proxy");
6
+ function headerContentType(headers) {
7
+ const contentType = headers.get('content-type');
8
+ return contentType ? contentType.toLowerCase() : undefined;
9
+ }
10
+ /** Native Fetch body types that must not be JSON.stringified (bypass / direct upstream). */
11
+ function isNativeFetchBody(value) {
12
+ return (typeof value === 'string' ||
13
+ (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) ||
14
+ (typeof FormData !== 'undefined' && value instanceof FormData) ||
15
+ (typeof Blob !== 'undefined' && value instanceof Blob) ||
16
+ (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) ||
17
+ (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(value)));
18
+ }
19
+ function plainObjectToUrlEncoded(body) {
20
+ const params = new URLSearchParams();
21
+ for (const [key, value] of Object.entries(body)) {
22
+ if (value === undefined || value === null)
23
+ continue;
24
+ params.append(key, String(value));
25
+ }
26
+ return params;
27
+ }
28
+ /**
29
+ * Build a RequestInit body for direct (non-proxy) fetch.
30
+ * JSON.stringify on URLSearchParams/FormData yields "{}" and corrupts OAuth/uploads on bypass paths.
31
+ */
32
+ function buildDirectFetchBody(data, method, headers) {
33
+ const upperMethod = method.toUpperCase();
34
+ if (upperMethod === 'GET' || upperMethod === 'HEAD' || data === undefined || data === null) {
35
+ return undefined;
36
+ }
37
+ if (isNativeFetchBody(data)) {
38
+ return data;
39
+ }
40
+ if (typeof data === 'object' &&
41
+ !Array.isArray(data) &&
42
+ headerContentType(headers)?.includes('application/x-www-form-urlencoded')) {
43
+ return plainObjectToUrlEncoded(data);
44
+ }
45
+ return JSON.stringify(data);
46
+ }
6
47
  class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
7
48
  constructor(config) {
8
49
  super();
@@ -71,7 +112,7 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
71
112
  const requestConfig = {
72
113
  method: config.method || 'GET',
73
114
  headers,
74
- body: config.data ? JSON.stringify(config.data) : undefined
115
+ body: buildDirectFetchBody(config.data, config.method || 'GET', headers),
75
116
  };
76
117
  // Use original fetch if available (when global fetch is patched), otherwise use global fetch
77
118
  const fetchFn = this._originalFetch || fetch;
@@ -143,6 +184,14 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
143
184
  ...(mockifyerTrace ? { mockifyerTrace } : {}),
144
185
  };
145
186
  }
187
+ /** Update whether `/api/proxy` sends `record` (record-on-miss). */
188
+ setProxyRecordOnMiss(recordOnMiss) {
189
+ this.proxyRecordOnMiss = recordOnMiss;
190
+ }
191
+ /** Update whether `/api/proxy` asks the dashboard to store response bodies. */
192
+ setProxyRecordResponses(recordResponses) {
193
+ this.proxyRecordResponses = recordResponses;
194
+ }
146
195
  getDefaultHeaders() {
147
196
  return this.defaultHeaders;
148
197
  }
package/dist/index.d.ts CHANGED
@@ -6,6 +6,10 @@ export interface MockifyerInstance extends HTTPClient {
6
6
  clearAllMocks: () => Promise<void>;
7
7
  setClientId: (lane: string) => void;
8
8
  getClientId: () => string | undefined;
9
+ setRecordMode: (enabled: boolean) => void;
10
+ isRecordMode: () => boolean;
11
+ setRecordResponses: (enabled: boolean) => void;
12
+ isRecordResponses: () => boolean;
9
13
  enableMockifyer: () => void;
10
14
  disableMockifyer: () => void;
11
15
  isMockifyerEnabled: () => boolean;
package/dist/index.js CHANGED
@@ -39,6 +39,7 @@ const core_proxy_1 = require("./core-proxy");
39
39
  const proxy_upstream_tls_insecure_1 = require("@sgedda/mockifyer-core/utils/proxy-upstream-tls-insecure");
40
40
  const fetch_client_1 = require("./clients/fetch-client");
41
41
  const fetch_response_body_1 = require("./utils/fetch-response-body");
42
+ const resolve_patched_fetch_request_1 = require("./utils/resolve-patched-fetch-request");
42
43
  class MockifyerClass {
43
44
  /** Session id for timeline hops — per-screen id from {@link setFlightRecorderRuntimeContext} when set. */
44
45
  getRuntimeSessionId() {
@@ -253,6 +254,11 @@ class MockifyerClass {
253
254
  * unavailable (React Native / Metro stubs). Seeded via {@link warmPoolResponseCache}.
254
255
  */
255
256
  this.poolResponseCache = new Map();
257
+ /**
258
+ * Runtime override for whether local/proxy recordings include response bodies.
259
+ * `undefined` = follow env / defaults ({@link resolveLocalRecordResponses} / {@link resolveRecordResponses}).
260
+ */
261
+ this.recordResponsesOverride = undefined;
256
262
  // Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
257
263
  if (config.databaseProvider && config.databaseProvider.type) {
258
264
  const supportedTypes = ['filesystem', 'expo-filesystem', 'hybrid', 'memory', 'redis', 'sqlite'];
@@ -314,7 +320,10 @@ class MockifyerClass {
314
320
  this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
315
321
  }
316
322
  this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
317
- this.domainPathRules = new mockifyer_core_1.DomainPathRulesSession({ config: this.config });
323
+ this.domainPathRules = new mockifyer_core_1.DomainPathRulesSession({
324
+ config: this.config,
325
+ getRecordMode: () => this.config.recordMode === true,
326
+ });
318
327
  this.runtimeEnabledStorage = (0, mockifyer_core_1.resolveRuntimeEnabledStorage)(config.persistRuntimeEnabled);
319
328
  if (config.persistRuntimeEnabled === true && !this.runtimeEnabledStorage) {
320
329
  mockifyer_core_2.logger.warn('[Mockifyer-Fetch] persistRuntimeEnabled: true but no storage found. ' +
@@ -1111,29 +1120,39 @@ class MockifyerClass {
1111
1120
  const duration = startTime ? Date.now() - startTime : undefined;
1112
1121
  const correlation = this.readRequestCorrelation(response.config);
1113
1122
  const hopIds = (0, mockifyer_core_1.resolvePersistedHopIds)(saveDecision.action === 'overwrite' ? existingMock?.mockData : undefined, correlation);
1114
- const mockData = {
1115
- request: {
1116
- method: response.config?.method?.toUpperCase() || 'GET',
1117
- url: response.config?.url || '',
1118
- headers: this.anonymizeHeaders(response.config?.headers || {}),
1119
- data: response.config?.data,
1120
- queryParams: normalizedParamsForSave,
1121
- },
1123
+ const storedRequest = {
1124
+ method: response.config?.method?.toUpperCase() || 'GET',
1125
+ url: response.config?.url || '',
1126
+ headers: this.anonymizeHeaders(response.config?.headers || {}),
1127
+ data: response.config?.data,
1128
+ queryParams: normalizedParamsForSave,
1129
+ };
1130
+ // Prefer explicit override / config; else request-only default (same as proxy).
1131
+ const recordBodies = (0, mockifyer_core_1.resolveLocalRecordResponses)(this.recordResponsesOverride ??
1132
+ this.config.proxy?.recordResponses ??
1133
+ this.config.recordResponses);
1134
+ const mockData = (0, mockifyer_core_1.buildLocalRecordingMockData)({
1135
+ request: storedRequest,
1122
1136
  response: {
1123
1137
  status: response.status,
1124
1138
  data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
1125
1139
  headers: response.headers || {},
1126
1140
  },
1127
- timestamp: new Date().toISOString(),
1128
- duration,
1129
- sessionId: saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
1130
- ? existingMock.mockData.sessionId
1131
- : this.currentSessionId,
1132
- requestId: hopIds.requestId,
1133
- parentRequestId: hopIds.parentRequestId,
1134
- parentRequestIds: hopIds.parentRequestIds,
1135
- ...((0, mockifyer_core_1.newRecordingUsesAlwaysUseRealApi)() ? { alwaysUseRealApi: true } : {}),
1136
- };
1141
+ recordResponses: recordBodies,
1142
+ meta: {
1143
+ timestamp: new Date().toISOString(),
1144
+ duration,
1145
+ sessionId: saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
1146
+ ? existingMock.mockData.sessionId
1147
+ : this.currentSessionId,
1148
+ requestId: hopIds.requestId,
1149
+ parentRequestId: hopIds.parentRequestId,
1150
+ parentRequestIds: hopIds.parentRequestIds,
1151
+ ...((0, mockifyer_core_1.newRecordingUsesAlwaysUseRealApi)() || !recordBodies
1152
+ ? { alwaysUseRealApi: true }
1153
+ : {}),
1154
+ },
1155
+ });
1137
1156
  (0, mockifyer_core_1.applyRecordingPassthroughFlag)(mockData, saveDecision.alwaysUseRealApi);
1138
1157
  if (this.databaseProvider) {
1139
1158
  try {
@@ -1177,11 +1196,57 @@ class MockifyerClass {
1177
1196
  else {
1178
1197
  console.warn('[Mockifyer] Cannot save mock: no database provider and fs/path not available');
1179
1198
  }
1199
+ await this.ensureInboundParentStubForChild(hopIds.parentRequestId, response.config);
1180
1200
  }
1181
1201
  finally {
1182
1202
  this.savingResponses.delete(requestKey);
1183
1203
  }
1184
1204
  }
1205
+ /**
1206
+ * When a child hop is recorded locally, persist a synthetic inbound-parent stub so
1207
+ * Hops does not show "Missing entry hop" for the ALS gateway id.
1208
+ */
1209
+ async ensureInboundParentStubForChild(parentRequestId, config) {
1210
+ const activeInbound = (0, mockifyer_core_1.getActiveInboundRequest)();
1211
+ const hop = (0, mockifyer_core_1.readOutboundParentHopFromConfig)(config) ??
1212
+ (activeInbound ? { method: activeInbound.method, url: activeInbound.url } : undefined);
1213
+ try {
1214
+ await (0, mockifyer_core_1.ensureLocalInboundParentStubSaved)({
1215
+ parentRequestId,
1216
+ hop,
1217
+ parentExists: (id) => {
1218
+ if (!fs || !path || this.databaseProvider) {
1219
+ return false;
1220
+ }
1221
+ const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId);
1222
+ const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
1223
+ return fs.existsSync(path.join(scenarioPath, (0, mockifyer_core_1.inboundParentStubFilename)(id)));
1224
+ },
1225
+ save: async (row) => {
1226
+ if (this.databaseProvider) {
1227
+ await this.databaseProvider.save(row.mock);
1228
+ return;
1229
+ }
1230
+ if (!fs || !path) {
1231
+ return;
1232
+ }
1233
+ const currentScenario = (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId);
1234
+ const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, currentScenario);
1235
+ (0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, currentScenario);
1236
+ const filePath = path.join(scenarioPath, row.filename);
1237
+ if (fs.existsSync(filePath)) {
1238
+ return;
1239
+ }
1240
+ fs.writeFileSync(filePath, JSON.stringify(row.mock, null, 2));
1241
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Saved inbound parent stub: ${currentScenario}/${row.filename}`);
1242
+ },
1243
+ });
1244
+ }
1245
+ catch (error) {
1246
+ const message = error instanceof Error ? error.message : String(error);
1247
+ mockifyer_core_2.logger.warn(`[Mockifyer-Fetch] Failed to save inbound parent stub: ${message}`);
1248
+ }
1249
+ }
1185
1250
  async persistMatchedMockAfterLiveCapture(cachedMock, capturedResponse, durationMs, liveCorrelation) {
1186
1251
  const updated = (0, mockifyer_core_1.buildMockDataAfterLiveCapture)(cachedMock.mockData, capturedResponse, durationMs);
1187
1252
  (0, mockifyer_core_1.applyPersistedHopIds)(updated, (0, mockifyer_core_1.resolvePersistedHopIds)(cachedMock.mockData, liveCorrelation));
@@ -1369,6 +1434,62 @@ class MockifyerClass {
1369
1434
  getClientId() {
1370
1435
  return this.config.clientId;
1371
1436
  }
1437
+ /**
1438
+ * Turn record mode on/off at runtime (dev menus, tests).
1439
+ * Also updates `proxy.recordOnMiss` when a dashboard proxy is configured so
1440
+ * Redis/proxy recording follows the same switch as local hybrid saves.
1441
+ *
1442
+ * When enabling: flips existing allowlist `recordResponses` to true and new
1443
+ * discoveries enable recording. When disabled, allowlist discovery stops
1444
+ * persisting new keys (so browsing does not poison the rules file).
1445
+ */
1446
+ setRecordMode(enabled) {
1447
+ const next = Boolean(enabled);
1448
+ this.config.recordMode = next;
1449
+ if (next) {
1450
+ // Recording needs live upstream calls; fail-on-miss conflicts with that.
1451
+ this.config.failOnMissingMock = false;
1452
+ this.domainPathRules.enableRecordResponsesForAllRules();
1453
+ }
1454
+ if (this.config.proxy?.baseUrl) {
1455
+ this.config.proxy = {
1456
+ ...this.config.proxy,
1457
+ recordOnMiss: next,
1458
+ };
1459
+ const client = this.httpClient;
1460
+ client.setProxyRecordOnMiss?.(next);
1461
+ }
1462
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] recordMode set to: ${next}`);
1463
+ }
1464
+ /** Whether newly unmatched requests can be recorded (local or proxy record-on-miss). */
1465
+ isRecordMode() {
1466
+ return this.config.recordMode === true;
1467
+ }
1468
+ /**
1469
+ * Whether new recordings store full response bodies (true) or request-only stubs (false, default).
1470
+ * Matches dashboard proxy `recordResponses` / env `MOCKIFYER_RECORD_RESPONSES`.
1471
+ */
1472
+ setRecordResponses(enabled) {
1473
+ const next = Boolean(enabled);
1474
+ this.recordResponsesOverride = next;
1475
+ this.config.recordResponses = next;
1476
+ if (this.config.proxy) {
1477
+ this.config.proxy = {
1478
+ ...this.config.proxy,
1479
+ recordResponses: next,
1480
+ };
1481
+ }
1482
+ const client = this.httpClient;
1483
+ client.setProxyRecordResponses?.(next);
1484
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] recordResponses (store bodies) set to: ${next}`);
1485
+ }
1486
+ /** True when new recordings include response bodies (not request-only stubs). */
1487
+ isRecordResponses() {
1488
+ if (this.config.proxy?.baseUrl) {
1489
+ return (0, mockifyer_core_1.resolveRecordResponses)(this.recordResponsesOverride ?? this.config.proxy.recordResponses);
1490
+ }
1491
+ return (0, mockifyer_core_1.resolveLocalRecordResponses)(this.recordResponsesOverride ?? this.config.recordResponses);
1492
+ }
1372
1493
  /**
1373
1494
  * Enable Mockifyer at runtime. All subsequent requests will go through Mockifyer
1374
1495
  * (mock lookup, recording, dashboard/Redis proxy, etc.).
@@ -1406,6 +1527,9 @@ class MockifyerClass {
1406
1527
  }
1407
1528
  async reloadMockData(syncFromProject = true) {
1408
1529
  await this.databaseProviderInitPromise;
1530
+ // `$pool` fixtures are cached write-once for RN (no Node fs). Clear so a reload
1531
+ // picks up updated pool response bodies from the provider / Metro sync.
1532
+ this.poolResponseCache.clear();
1409
1533
  // If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
1410
1534
  // For HybridProvider, this will also sync files from project folder to device
1411
1535
  if (this.databaseProvider && typeof this.databaseProvider.reload === 'function') {
@@ -1495,25 +1619,31 @@ function setupMockifyer(config) {
1495
1619
  const mockifyerInstance = mockifyer;
1496
1620
  const originalFetchForPatched = global.__mockifyer_original_fetch || originalFetch;
1497
1621
  global.fetch = async function (input, init) {
1622
+ // Disabled means the real network: do not rebuild the call. The interceptor
1623
+ // bypass flag still runs FetchHTTPClient, which JSON.parses `{`/`[` bodies
1624
+ // (throwing on invalid JSON), JSON.stringifies FormData/Blob/URLSearchParams,
1625
+ // and drops credentials, abort signals, and Request-only method/headers/body.
1626
+ if (!mockifyerInstance.isMockifyerEnabled()) {
1627
+ return await originalFetchForPatched(input, init);
1628
+ }
1498
1629
  const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
1499
- const method = init?.method || 'GET';
1500
- const headers = init?.headers || {};
1501
- const body = init?.body;
1502
1630
  // Skip Mockifyer sync endpoints, dashboard plumbing, and Resend API
1503
1631
  if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url) ||
1504
1632
  url.includes('api.resend.com') ||
1505
1633
  (0, mockifyer_core_1.isMockifyerDashboardPlumbingApiUrl)(url)) {
1506
1634
  return await originalFetchForPatched(input, init);
1507
1635
  }
1508
- const simpleRequestKey = `${method}:${url}`;
1636
+ const resolved = await (0, resolve_patched_fetch_request_1.resolvePatchedFetchRequest)(input, init);
1637
+ const method = resolved.method;
1638
+ const simpleRequestKey = `${method}:${resolved.url}`;
1509
1639
  const isProcessing = mockifyerInstance.processingRequests?.has(simpleRequestKey);
1510
1640
  if (isProcessing) {
1511
1641
  return await originalFetchForPatched(input, init);
1512
1642
  }
1513
1643
  let params = undefined;
1514
- let baseUrl = url;
1644
+ let baseUrl = resolved.url;
1515
1645
  try {
1516
- const urlObj = new URL(url);
1646
+ const urlObj = new URL(resolved.url);
1517
1647
  if (urlObj.search) {
1518
1648
  params = {};
1519
1649
  urlObj.searchParams.forEach((value, key) => {
@@ -1526,27 +1656,13 @@ function setupMockifyer(config) {
1526
1656
  catch (error) {
1527
1657
  // URL parsing failed, use URL as-is
1528
1658
  }
1529
- let headersObj = {};
1530
- if (headers instanceof Headers) {
1531
- headers.forEach((value, key) => {
1532
- headersObj[key] = value;
1533
- });
1534
- }
1535
- else if (Array.isArray(headers)) {
1536
- headers.forEach(([key, value]) => {
1537
- headersObj[key] = value;
1538
- });
1539
- }
1540
- else {
1541
- headersObj = { ...headers };
1542
- }
1543
1659
  try {
1544
1660
  const requestConfig = {
1545
1661
  url: baseUrl,
1546
1662
  method: method,
1547
- headers: headersObj,
1663
+ headers: resolved.headers,
1548
1664
  params: params,
1549
- data: body ? (typeof body === 'string' ? (body.startsWith('{') || body.startsWith('[') ? JSON.parse(body) : body) : body) : undefined
1665
+ data: resolved.body
1550
1666
  };
1551
1667
  const response = await httpClient.request(requestConfig);
1552
1668
  const responseHeaders = new Headers();
@@ -1592,6 +1708,10 @@ function setupMockifyer(config) {
1592
1708
  extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
1593
1709
  extendedClient.setClientId = (lane) => mockifyer.setClientId(lane);
1594
1710
  extendedClient.getClientId = () => mockifyer.getClientId();
1711
+ extendedClient.setRecordMode = (enabled) => mockifyer.setRecordMode(enabled);
1712
+ extendedClient.isRecordMode = () => mockifyer.isRecordMode();
1713
+ extendedClient.setRecordResponses = (enabled) => mockifyer.setRecordResponses(enabled);
1714
+ extendedClient.isRecordResponses = () => mockifyer.isRecordResponses();
1595
1715
  extendedClient.enableMockifyer = () => mockifyer.enableMockifyer();
1596
1716
  extendedClient.disableMockifyer = () => mockifyer.disableMockifyer();
1597
1717
  extendedClient.isMockifyerEnabled = () => mockifyer.isMockifyerEnabled();
@@ -91,6 +91,16 @@ export declare function bufferAtlasBodySpill(relativePath: string, text: string)
91
91
  relativePath?: string;
92
92
  error?: string;
93
93
  };
94
+ /**
95
+ * Write hop bodies for an Atlas HTML render.
96
+ *
97
+ * Device uploads sit in the Metro spill buffer and are often omitted from the
98
+ * render POST (`bodySpills` is capped at 2MB, so a max-size body never fits).
99
+ * Flush that buffer before writing the payload. Buffering the payload first
100
+ * evicts older spills once the in-memory cap is hit, and those files are then
101
+ * missing from disk.
102
+ */
103
+ export declare function persistAtlasRenderBodySpills(outDir: string, bodySpills: Record<string, string> | undefined): number;
94
104
  /**
95
105
  * Metro middleware function
96
106
  */