@sgedda/mockifyer-fetch 1.8.104 → 1.8.107

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.
@@ -254,60 +254,6 @@ function collectRequestBodyUtf8(req, onDone, maxBytes = MAX_METRO_POST_BODY_BYTE
254
254
  });
255
255
  req.on("error", (e) => finish(e, ""));
256
256
  }
257
- function getMockFilePathLocal(mockData, dateStr) {
258
- const url = mockData.request.url || "";
259
- const method = (mockData.request.method || "GET").toUpperCase();
260
- let host = "unknown";
261
- let pathSegments = [];
262
- try {
263
- const parsed = new URL(url);
264
- host = parsed.hostname;
265
- pathSegments = parsed.pathname.split("/").filter(Boolean);
266
- }
267
- catch {
268
- return { dir: "unknown", filename: `${method}_${dateStr}.json` };
269
- }
270
- const hostSafe = host.replace(/[^a-zA-Z0-9.-]/g, "_");
271
- const graphqlIdx = pathSegments.lastIndexOf("graphql");
272
- const restIdx = pathSegments.indexOf("rest");
273
- let type;
274
- let remainingSegments;
275
- if (graphqlIdx >= 0) {
276
- type = "graphql";
277
- remainingSegments = pathSegments.slice(graphqlIdx + 1);
278
- }
279
- else if (restIdx >= 0) {
280
- type = "rest";
281
- remainingSegments = pathSegments.slice(restIdx + 1);
282
- }
283
- else {
284
- type = "";
285
- remainingSegments = pathSegments;
286
- }
287
- let identifier = "";
288
- if (mockData.request.data) {
289
- try {
290
- const body = typeof mockData.request.data === "string"
291
- ? JSON.parse(mockData.request.data)
292
- : mockData.request.data;
293
- if (body.operationName)
294
- identifier = body.operationName;
295
- else if (body.path)
296
- identifier = body.path;
297
- else if (body.webAppName)
298
- identifier = body.webAppName;
299
- }
300
- catch {
301
- /* ignore */
302
- }
303
- }
304
- identifier = identifier.replace(/[^a-zA-Z0-9_-]/g, "_").substring(0, 60);
305
- const dir = [hostSafe, type, ...remainingSegments].filter(Boolean).join("/");
306
- const filename = identifier
307
- ? `${method}_${identifier}_${dateStr}.json`
308
- : `${method}_${dateStr}.json`;
309
- return { dir, filename };
310
- }
311
257
  /**
312
258
  * Scenario folder names the dashboard accepts (one path segment).
313
259
  * `pool` is the fixture-pool directory and is not a scenario.
@@ -568,7 +514,7 @@ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig
568
514
  .replace(/T/, "_")
569
515
  .replace(/\..+/, "")
570
516
  .replace(/:/g, "-");
571
- const { dir, filename } = getMockFilePathLocal(mockData, dateStr);
517
+ const { dir, filename } = (0, mockifyer_core_1.getMockFilePath)(mockData, dateStr);
572
518
  const fullDir = path.join(scenarioPath, dir);
573
519
  const filePath = path.join(fullDir, filename);
574
520
  // Check if file already exists - skip saving if it does
@@ -1750,7 +1696,7 @@ function createMockSyncMiddleware(options) {
1750
1696
  }
1751
1697
  const upserts = (0, mockifyer_core_2.parseDomainPathRules)(parsed.upserts ?? parsed.rules ?? {});
1752
1698
  const existing = (0, mockifyer_core_2.readDomainPathRulesFile)(mockDataPath, scenarioName);
1753
- const { rules, changed } = (0, mockifyer_core_2.mergeDomainPathRuleUpserts)(existing, upserts);
1699
+ const { rules, changed } = (0, mockifyer_core_2.mergeDiscoveredDomainPathUpserts)(existing, upserts);
1754
1700
  if (changed) {
1755
1701
  (0, mockifyer_core_2.writeDomainPathRulesFile)(mockDataPath, scenarioName, rules);
1756
1702
  }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Core MockifyerClass - browser and Node compatible via dependency injection.
3
+ * Only imports browser-safe utilities from @sgedda/mockifyer-core.
4
+ */
5
+ import { NodeCapabilities } from './node-capabilities';
6
+ import { MockifyerConfig, HTTPClient } from '@sgedda/mockifyer-core';
7
+ export declare class MockifyerClass {
8
+ private config;
9
+ private httpClient;
10
+ private capabilities;
11
+ private processingRequests;
12
+ private savingResponses;
13
+ private databaseProvider?;
14
+ /** Resolves when async databaseProvider.initialize() completes (expo/hybrid). */
15
+ private databaseProviderInitPromise;
16
+ private currentSessionId;
17
+ private sessionStartTime;
18
+ private readonly SESSION_TIMEOUT_MS;
19
+ private testGenerator?;
20
+ private readonly activationMode;
21
+ /**
22
+ * Promoted pool responses for serve-time `$pool` resolve when Node `fs` is
23
+ * unavailable (React Native / Metro stubs). Seeded via {@link warmPoolResponseCache}.
24
+ */
25
+ private readonly poolResponseCache;
26
+ private readonly domainPathRules;
27
+ /** Runtime toggle: when false, all Mockifyer logic is bypassed (no dashboard, Redis, proxy, or mock lookup). */
28
+ private runtimeEnabled;
29
+ /** Optional storage for persisting enable/disable across restarts. */
30
+ private readonly runtimeEnabledStorage?;
31
+ /**
32
+ * Runtime override for whether local/proxy recordings include response bodies.
33
+ * `undefined` = follow env / defaults ({@link resolveLocalRecordResponses} / {@link resolveRecordResponses}).
34
+ */
35
+ private recordResponsesOverride;
36
+ /** Session id for timeline hops — per-screen id from {@link setFlightRecorderRuntimeContext} when set. */
37
+ private getRuntimeSessionId;
38
+ private unwrapResponseInlineTrace;
39
+ private applyOutboundCorrelation;
40
+ /**
41
+ * Full outbound URL including `params` — hop logs / Atlas curl / include-trace
42
+ * must not drop the query string (fetch splits search into `config.params`).
43
+ */
44
+ private resolveLoggedRequestUrl;
45
+ /** Best-effort dashboard network log. */
46
+ private logNetworkEvent;
47
+ private stashRequestCorrelation;
48
+ private bindStoredHopId;
49
+ private readRequestCorrelation;
50
+ /** Attach dashboard lookup id onto thrown fetch/client errors. */
51
+ private throwWithMockifyerRequestId;
52
+ /**
53
+ * Serve stored mock body with optional `$pool` resolution from the local fixture pool.
54
+ * Always passes `loadPoolResponse` — including React Native where Node `fs`/`path` are
55
+ * missing or Metro-stubbed — so `$pool` refs resolve via disk and/or {@link poolResponseCache}.
56
+ */
57
+ private prepareStoredResponseBody;
58
+ /**
59
+ * Ensure `$pool` fixtures are available in {@link poolResponseCache} when Node fs
60
+ * cannot load them (React Native). Tries database provider, then Metro.
61
+ */
62
+ private warmPoolResponseCache;
63
+ private loadPoolResponseFromProvider;
64
+ private loadPoolResponseFromMetro;
65
+ constructor(config: MockifyerConfig, capabilities?: NodeCapabilities);
66
+ private ensureMockDataDirectory;
67
+ private generateRequestKey;
68
+ /** When set, mock resolution happens on the dashboard `/api/proxy` (Redis/disk), not local `mock-data`. */
69
+ private usesDashboardProxy;
70
+ private findBestMatchingMock;
71
+ private findBestMatchingMockFromProvider;
72
+ private getAllJsonFiles;
73
+ private findBestMatchingMockFromFiles;
74
+ private loadMockData;
75
+ private setupMockResponses;
76
+ private setupResponseInterceptor;
77
+ private maybeMirrorProxyRecordingToClient;
78
+ private tryMirrorProxyRecordingViaMetro;
79
+ private saveResponse;
80
+ private persistMatchedMockAfterLiveCapture;
81
+ /**
82
+ * Generates test file for a mock
83
+ */
84
+ private generateTestForMock;
85
+ private anonymizeHeaders;
86
+ private anonymizeQueryParams;
87
+ /**
88
+ * Updates the logical client lane for subsequent requests (headers, proxy envelope, scenario paths, Redis).
89
+ * Does not re-read native launch arguments or environment variables.
90
+ */
91
+ setClientId(lane: string): void;
92
+ /** Current logical lane id (same value used for isolation). */
93
+ getClientId(): string | undefined;
94
+ /**
95
+ * Turn record mode on/off at runtime (dev menus, tests).
96
+ */
97
+ setRecordMode(enabled: boolean): void;
98
+ /** Whether newly unmatched requests can be recorded (local or proxy record-on-miss). */
99
+ isRecordMode(): boolean;
100
+ /**
101
+ * Whether new recordings store full response bodies (true) or request-only stubs (false, default).
102
+ */
103
+ setRecordResponses(enabled: boolean): void;
104
+ /** True when new recordings include response bodies (not request-only stubs). */
105
+ isRecordResponses(): boolean;
106
+ /**
107
+ * Enable Mockifyer at runtime.
108
+ */
109
+ enableMockifyer(): void;
110
+ /**
111
+ * Disable Mockifyer at runtime.
112
+ */
113
+ disableMockifyer(): void;
114
+ /**
115
+ * Check if Mockifyer is currently enabled at runtime.
116
+ */
117
+ isMockifyerEnabled(): boolean;
118
+ private persistRuntimeEnabledState;
119
+ getHTTPClient(): HTTPClient;
120
+ reloadMockData(syncFromProject?: boolean): Promise<void>;
121
+ clearStaleCacheEntries(): number;
122
+ clearAllMocks(): Promise<void>;
123
+ }