@sgedda/mockifyer-fetch 1.8.71 → 1.8.85

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/index.d.ts CHANGED
@@ -6,6 +6,9 @@ export interface MockifyerInstance extends HTTPClient {
6
6
  clearAllMocks: () => Promise<void>;
7
7
  setClientId: (lane: string) => void;
8
8
  getClientId: () => string | undefined;
9
+ enableMockifyer: () => void;
10
+ disableMockifyer: () => void;
11
+ isMockifyerEnabled: () => boolean;
9
12
  }
10
13
  export declare function setupMockifyer(config: MockifyerConfig): MockifyerInstance;
11
14
  export type { InitMockifyerForDashboardProxyOptions, InitMockifyerForLocalFilesystemOptions };
package/dist/index.js CHANGED
@@ -52,6 +52,27 @@ class MockifyerClass {
52
52
  return this.currentSessionId;
53
53
  });
54
54
  }
55
+ unwrapResponseInlineTrace(response) {
56
+ const correlation = this.readRequestCorrelation(response.config);
57
+ const parentRequestId = correlation?.requestId?.trim();
58
+ if (!parentRequestId) {
59
+ response.data = (0, mockifyer_core_1.unwrapAndMergeInlineTraceEnvelope)(response.data);
60
+ return;
61
+ }
62
+ const scenario = this.config.proxy?.scenario?.trim() ||
63
+ (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath);
64
+ response.data = (0, mockifyer_core_1.unwrapInlineTraceEnvelopeEmittingNetworkEvents)(response.data, {
65
+ parentRequestId,
66
+ config: this.config,
67
+ scenario,
68
+ clientId: this.config.clientId,
69
+ sessionId: this.getRuntimeSessionId(),
70
+ transport: this.usesDashboardProxy() ? 'proxy' : 'fetch',
71
+ });
72
+ }
73
+ applyOutboundCorrelation(config) {
74
+ return (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config, (0, mockifyer_core_1.resolveNetworkLogIncludeTraceOptions)(this.config));
75
+ }
55
76
  /** Best-effort dashboard network log. */
56
77
  logNetworkEvent(partial, correlation) {
57
78
  const scenario = this.config.proxy?.scenario?.trim() ||
@@ -86,10 +107,8 @@ class MockifyerClass {
86
107
  transport: eventPartial.transport ?? 'fetch',
87
108
  requestId: correlation?.requestId ?? eventPartial.requestId,
88
109
  parentRequestId: correlation?.parentRequestId ?? eventPartial.parentRequestId,
89
- requestBodyPreview: eventPartial.requestBodyPreview ??
90
- (requestBody !== undefined ? (0, mockifyer_core_1.toNetworkLogBodyPreview)(requestBody) : undefined),
91
- responseBodyPreview: eventPartial.responseBodyPreview ??
92
- (responseBody !== undefined ? (0, mockifyer_core_1.toNetworkLogBodyPreview)(businessResponseBody) : undefined),
110
+ requestBodyPreview: eventPartial.requestBodyPreview,
111
+ responseBodyPreview: eventPartial.responseBodyPreview,
93
112
  },
94
113
  });
95
114
  }
@@ -281,6 +300,31 @@ class MockifyerClass {
281
300
  }
282
301
  this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
283
302
  this.domainPathRules = new mockifyer_core_1.DomainPathRulesSession({ config: this.config });
303
+ this.runtimeEnabledStorage = (0, mockifyer_core_1.resolveRuntimeEnabledStorage)(config.persistRuntimeEnabled);
304
+ if (config.persistRuntimeEnabled === true && !this.runtimeEnabledStorage) {
305
+ mockifyer_core_2.logger.warn('[Mockifyer-Fetch] persistRuntimeEnabled: true but no storage found. ' +
306
+ 'Install @react-native-async-storage/async-storage (RN) or use a custom { getItem, setItem }.');
307
+ }
308
+ this.runtimeEnabled = (0, mockifyer_core_1.resolveInitialRuntimeEnabled)({
309
+ initialRuntimeEnabled: config.initialRuntimeEnabled,
310
+ startDisabled: config.startDisabled,
311
+ runtimeMode: config.runtimeMode,
312
+ launchScenarioPresent: (0, mockifyer_core_1.isScenarioLaunchFromNativeArguments)(),
313
+ });
314
+ if (!this.runtimeEnabled) {
315
+ const reason = typeof config.initialRuntimeEnabled === 'boolean'
316
+ ? 'persisted / initialRuntimeEnabled: false'
317
+ : config.runtimeMode === 'manual'
318
+ ? 'runtimeMode: "manual"'
319
+ : 'startDisabled: true';
320
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Starting with Mockifyer DISABLED (${reason}). Call enableMockifyer() to activate.`);
321
+ }
322
+ else if ((0, mockifyer_core_1.isScenarioLaunchFromNativeArguments)()) {
323
+ mockifyer_core_2.logger.info('[Mockifyer-Fetch] Starting with Mockifyer ENABLED (native launch scenario argument).');
324
+ }
325
+ else if (typeof config.initialRuntimeEnabled === 'boolean' && config.initialRuntimeEnabled) {
326
+ mockifyer_core_2.logger.info('[Mockifyer-Fetch] Starting with Mockifyer ENABLED (restored from persisted preference).');
327
+ }
284
328
  (0, mockifyer_core_1.configureFlightRecorder)((0, mockifyer_core_1.resolveFlightRecorderConfig)(this.config));
285
329
  (0, mockifyer_core_1.configureAtlas)(this.config, {
286
330
  scenario: (0, mockifyer_core_1.getCurrentScenario)(this.config.mockDataPath, this.config.clientId),
@@ -554,6 +598,11 @@ class MockifyerClass {
554
598
  }
555
599
  setupMockResponses() {
556
600
  this.httpClient.interceptors.request.use(async (config) => {
601
+ // CRITICAL: Runtime toggle — if disabled, bypass all Mockifyer logic
602
+ if (!this.runtimeEnabled) {
603
+ config.__mockifyer_bypass = true;
604
+ return config;
605
+ }
557
606
  // CRITICAL: Completely bypass Mockifyer interception for sync endpoints
558
607
  // This prevents any Mockifyer processing (mocking, saving, etc.) for these endpoints
559
608
  const url = config.url || '';
@@ -570,7 +619,7 @@ class MockifyerClass {
570
619
  if (!(0, mockifyer_core_1.shouldApplyMockifyer)(this.activationMode, config.headers, {
571
620
  useProxyLane: { proxyBaseUrl: this.config.proxy?.baseUrl, resolvedClientId: this.config.clientId },
572
621
  })) {
573
- (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config);
622
+ this.applyOutboundCorrelation(config);
574
623
  config.__mockifyer_bypass = true;
575
624
  return config;
576
625
  }
@@ -579,7 +628,7 @@ class MockifyerClass {
579
628
  config.__mockifyer_bypass = true;
580
629
  return config;
581
630
  }
582
- let correlation = (0, mockifyer_core_1.applyOutboundRequestCorrelation)(config);
631
+ let correlation = this.applyOutboundCorrelation(config);
583
632
  this.stashRequestCorrelation(config, correlation);
584
633
  // Normalize empty params: treat {} the same as undefined for consistent matching
585
634
  const rawParams = config.params || {};
@@ -816,7 +865,7 @@ class MockifyerClass {
816
865
  requestBody: response.config?.data,
817
866
  responseBody: response.data,
818
867
  }, this.readRequestCorrelation(response.config));
819
- response.data = (0, mockifyer_core_1.unwrapAndMergeInlineTraceEnvelope)(response.data);
868
+ this.unwrapResponseInlineTrace(response);
820
869
  const capturedResponse = {
821
870
  status: response.status,
822
871
  data: (0, mockifyer_core_1.stripMockifyerTraceFromBody)(response.data),
@@ -850,7 +899,7 @@ class MockifyerClass {
850
899
  requestBody: response.config?.data,
851
900
  responseBody: response.data,
852
901
  }, this.readRequestCorrelation(response.config));
853
- response.data = (0, mockifyer_core_1.unwrapAndMergeInlineTraceEnvelope)(response.data);
902
+ this.unwrapResponseInlineTrace(response);
854
903
  // Only save locally if recordMode is enabled AND we're not proxying upstream calls.
855
904
  // When proxy is configured, recording should happen on the proxy (e.g. dashboard → Redis).
856
905
  if (this.config.recordMode && !this.config.proxy?.baseUrl) {
@@ -1313,6 +1362,38 @@ class MockifyerClass {
1313
1362
  getClientId() {
1314
1363
  return this.config.clientId;
1315
1364
  }
1365
+ /**
1366
+ * Enable Mockifyer at runtime. All subsequent requests will go through Mockifyer
1367
+ * (mock lookup, recording, dashboard/Redis proxy, etc.).
1368
+ * When `persistRuntimeEnabled` is set, the preference is saved for the next app launch.
1369
+ */
1370
+ enableMockifyer() {
1371
+ this.runtimeEnabled = true;
1372
+ mockifyer_core_2.logger.info('[Mockifyer-Fetch] Mockifyer enabled at runtime');
1373
+ void this.persistRuntimeEnabledState(true);
1374
+ }
1375
+ /**
1376
+ * Disable Mockifyer at runtime. All subsequent requests will bypass Mockifyer completely
1377
+ * (no dashboard, Redis, proxy, mock lookup, or recording).
1378
+ * When `persistRuntimeEnabled` is set, the preference is saved for the next app launch.
1379
+ */
1380
+ disableMockifyer() {
1381
+ this.runtimeEnabled = false;
1382
+ mockifyer_core_2.logger.info('[Mockifyer-Fetch] Mockifyer disabled at runtime - all requests will bypass');
1383
+ void this.persistRuntimeEnabledState(false);
1384
+ }
1385
+ /**
1386
+ * Check if Mockifyer is currently enabled at runtime.
1387
+ */
1388
+ isMockifyerEnabled() {
1389
+ return this.runtimeEnabled;
1390
+ }
1391
+ async persistRuntimeEnabledState(enabled) {
1392
+ if (!this.runtimeEnabledStorage) {
1393
+ return;
1394
+ }
1395
+ await (0, mockifyer_core_1.savePersistedRuntimeEnabled)(this.runtimeEnabledStorage, enabled);
1396
+ }
1316
1397
  getHTTPClient() {
1317
1398
  return this.httpClient;
1318
1399
  }
@@ -1386,6 +1467,7 @@ function setupMockifyer(config) {
1386
1467
  }
1387
1468
  (0, mockifyer_core_1.initializeDateManipulation)(resolvedConfig);
1388
1469
  (0, mockifyer_core_1.initializeScenario)(resolvedConfig);
1470
+ (0, mockifyer_core_1.scheduleRuntimeDateSyncFromConfig)(resolvedConfig);
1389
1471
  const mockifyer = new MockifyerClass(resolvedConfig);
1390
1472
  const httpClient = mockifyer.getHTTPClient();
1391
1473
  // Always store original fetch (even if not patching global)
@@ -1503,6 +1585,9 @@ function setupMockifyer(config) {
1503
1585
  extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
1504
1586
  extendedClient.setClientId = (lane) => mockifyer.setClientId(lane);
1505
1587
  extendedClient.getClientId = () => mockifyer.getClientId();
1588
+ extendedClient.enableMockifyer = () => mockifyer.enableMockifyer();
1589
+ extendedClient.disableMockifyer = () => mockifyer.disableMockifyer();
1590
+ extendedClient.isMockifyerEnabled = () => mockifyer.isMockifyerEnabled();
1506
1591
  (0, mockifyer_core_1.registerMockifyerInstance)(extendedClient);
1507
1592
  return extendedClient;
1508
1593
  }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Metro terminal keys for Mockifyer:
3
+ * - `a` (default): start/stop Atlas capture (stop generates HTML)
4
+ * - `m` (default): open the Mockifyer dashboard in the browser
5
+ *
6
+ * Opening `mockifyer-atlas` (SSE `/mockifyer-network-events/stream`) auto-starts
7
+ * capture when idle — then press `a` once to stop & generate.
8
+ *
9
+ * Disable Atlas with `atlasKey: false`, dashboard with `dashboardKey: false`.
10
+ */
11
+ import * as readline from "readline";
12
+ export declare const DEFAULT_METRO_ATLAS_KEY = "a";
13
+ export declare const DEFAULT_METRO_DASHBOARD_KEY = "m";
14
+ export declare const DEFAULT_METRO_DASHBOARD_URL = "http://localhost:3002";
15
+ export type AtlasKeyOption = string | false;
16
+ export type MetroAtlasSessionPhase = "idle" | "capturing" | "rendering";
17
+ export type MetroAtlasSessionStartReason = "key" | "stream";
18
+ export interface AttachMetroAtlasKeyHandlerOptions {
19
+ /**
20
+ * Key that toggles Atlas capture (default `"a"`).
21
+ * Pass `false` to disable.
22
+ */
23
+ atlasKey?: AtlasKeyOption;
24
+ /**
25
+ * Key that opens the dashboard in the browser (default `"m"`).
26
+ * Pass `false` to disable.
27
+ */
28
+ dashboardKey?: AtlasKeyOption;
29
+ /**
30
+ * Dashboard origin (default: `MOCKIFYER_DASHBOARD_URL` or `http://localhost:3002`).
31
+ * Mount prefix from `MOCKIFYER_DASHBOARD_BASE` is appended when set.
32
+ */
33
+ dashboardUrl?: string;
34
+ /** Called on session start (clear hop buffer, etc.). Required when Atlas key is enabled. */
35
+ onSessionStart?: () => void;
36
+ /** Called on session stop — generate Atlas HTML. Required when Atlas key is enabled. */
37
+ onSessionStop?: () => void | Promise<void>;
38
+ /** Override stdin (tests). */
39
+ stdin?: NodeJS.ReadStream;
40
+ /** Override defer delay in ms (tests). */
41
+ deferMs?: number;
42
+ /** Override URL opener (tests). */
43
+ openUrl?: (url: string) => void;
44
+ }
45
+ export interface AttachedMetroAtlasKeyHandler {
46
+ /** Resolved Atlas key (lowercase), or null if disabled. */
47
+ key: string | null;
48
+ /** Resolved dashboard key (lowercase), or null if disabled. */
49
+ dashboardKey: string | null;
50
+ /** Resolved dashboard browse URL. */
51
+ dashboardUrl: string | null;
52
+ /** Detach listener and clear module attach flag. */
53
+ detach: () => void;
54
+ }
55
+ /**
56
+ * Normalize a single-char key option: default when undefined, `false` → disabled.
57
+ */
58
+ export declare function resolveKeyOption(value: AtlasKeyOption | undefined, defaultKey: string): string | null;
59
+ /**
60
+ * Normalize `atlasKey` option: default `"a"`, `false` → disabled, else single char.
61
+ */
62
+ export declare function resolveAtlasKeyOption(atlasKey?: AtlasKeyOption): string | null;
63
+ /**
64
+ * Normalize `dashboardKey` option: default `"m"`, `false` → disabled.
65
+ */
66
+ export declare function resolveDashboardKeyOption(dashboardKey?: AtlasKeyOption): string | null;
67
+ /**
68
+ * Resolve dashboard browse URL for Metro `m`.
69
+ * Precedence: explicit → `MOCKIFYER_DASHBOARD_URL` → `http://localhost:3002`,
70
+ * then append `MOCKIFYER_DASHBOARD_BASE` when set.
71
+ */
72
+ export declare function resolveMetroDashboardUrl(explicit?: string): string;
73
+ /**
74
+ * Open a URL with the OS default handler (browser / file).
75
+ */
76
+ export declare function openMetroBrowseUrl(target: string): void;
77
+ /**
78
+ * Whether a keypress matches a bound key (no ctrl/meta).
79
+ */
80
+ export declare function matchesAtlasKey(str: string | undefined, key: readline.Key | undefined, atlasKey: string): boolean;
81
+ /** Current session phase (idle / capturing / rendering). Exported for tests. */
82
+ export declare function getMetroAtlasSessionPhase(): MetroAtlasSessionPhase;
83
+ /** Active SSE stream subscriber count (tests / diagnostics). */
84
+ export declare function getMetroAtlasStreamSubscriberCount(): number;
85
+ /**
86
+ * Start capture when idle. No-op if already capturing/rendering or Atlas key off.
87
+ * @returns true if a new session was started
88
+ */
89
+ export declare function startMetroAtlasSession(reason?: MetroAtlasSessionStartReason): boolean;
90
+ /**
91
+ * Stop capture and generate Atlas HTML when capturing.
92
+ * @returns true if stop/render was kicked off
93
+ */
94
+ export declare function stopMetroAtlasSession(): boolean;
95
+ /** Open the dashboard URL when the dashboard key is enabled. */
96
+ export declare function openMetroDashboard(): boolean;
97
+ /**
98
+ * First SSE client for `/mockifyer-network-events/stream` auto-starts capture.
99
+ */
100
+ export declare function notifyMetroAtlasStreamClientConnected(): void;
101
+ /**
102
+ * SSE client disconnected — capture stays open until Metro `a` (or explicit stop).
103
+ */
104
+ export declare function notifyMetroAtlasStreamClientDisconnected(): void;
105
+ /**
106
+ * Detach a previously attached handler (idempotent). Exported for tests.
107
+ */
108
+ export declare function detachMetroAtlasKeyHandler(): void;
109
+ /**
110
+ * Listen for Metro terminal keys (Atlas capture + open dashboard).
111
+ * Safe to call once per process; subsequent calls are no-ops until detach.
112
+ */
113
+ export declare function attachMetroAtlasKeyHandler(options: AttachMetroAtlasKeyHandlerOptions): AttachedMetroAtlasKeyHandler;