@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.
@@ -0,0 +1,503 @@
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
+ import { spawn } from "child_process";
13
+ import { logger } from "@sgedda/mockifyer-core";
14
+
15
+ /** Keys already used by @react-native/community-cli-plugin (avoid stealing). */
16
+ const RESERVED_METRO_KEYS = new Set(["r", "d", "j", "i"]);
17
+
18
+ export const DEFAULT_METRO_ATLAS_KEY = "a";
19
+ export const DEFAULT_METRO_DASHBOARD_KEY = "m";
20
+ export const DEFAULT_METRO_DASHBOARD_URL = "http://localhost:3002";
21
+
22
+ /** Delay so RN/Expo CLI can own raw-mode stdin first. */
23
+ const ATTACH_DEFER_MS = 1000;
24
+
25
+ export type AtlasKeyOption = string | false;
26
+
27
+ export type MetroAtlasSessionPhase = "idle" | "capturing" | "rendering";
28
+
29
+ export type MetroAtlasSessionStartReason = "key" | "stream";
30
+
31
+ export interface AttachMetroAtlasKeyHandlerOptions {
32
+ /**
33
+ * Key that toggles Atlas capture (default `"a"`).
34
+ * Pass `false` to disable.
35
+ */
36
+ atlasKey?: AtlasKeyOption;
37
+ /**
38
+ * Key that opens the dashboard in the browser (default `"m"`).
39
+ * Pass `false` to disable.
40
+ */
41
+ dashboardKey?: AtlasKeyOption;
42
+ /**
43
+ * Dashboard origin (default: `MOCKIFYER_DASHBOARD_URL` or `http://localhost:3002`).
44
+ * Mount prefix from `MOCKIFYER_DASHBOARD_BASE` is appended when set.
45
+ */
46
+ dashboardUrl?: string;
47
+ /** Called on session start (clear hop buffer, etc.). Required when Atlas key is enabled. */
48
+ onSessionStart?: () => void;
49
+ /** Called on session stop — generate Atlas HTML. Required when Atlas key is enabled. */
50
+ onSessionStop?: () => void | Promise<void>;
51
+ /** Override stdin (tests). */
52
+ stdin?: NodeJS.ReadStream;
53
+ /** Override defer delay in ms (tests). */
54
+ deferMs?: number;
55
+ /** Override URL opener (tests). */
56
+ openUrl?: (url: string) => void;
57
+ }
58
+
59
+ export interface AttachedMetroAtlasKeyHandler {
60
+ /** Resolved Atlas key (lowercase), or null if disabled. */
61
+ key: string | null;
62
+ /** Resolved dashboard key (lowercase), or null if disabled. */
63
+ dashboardKey: string | null;
64
+ /** Resolved dashboard browse URL. */
65
+ dashboardUrl: string | null;
66
+ /** Detach listener and clear module attach flag. */
67
+ detach: () => void;
68
+ }
69
+
70
+ interface SessionCallbacks {
71
+ key: string | null;
72
+ dashboardKey: string | null;
73
+ dashboardUrl: string | null;
74
+ onSessionStart?: () => void;
75
+ onSessionStop?: () => void | Promise<void>;
76
+ openUrl: (url: string) => void;
77
+ }
78
+
79
+ let attached = false;
80
+ let weSetRawMode = false;
81
+ let activeHandler: ((str: string, key: readline.Key) => void) | null = null;
82
+ let activeStdin: NodeJS.ReadStream | null = null;
83
+ let pendingTimer: ReturnType<typeof setTimeout> | null = null;
84
+ let sessionPhase: MetroAtlasSessionPhase = "idle";
85
+ let sessionStartedAt: number | null = null;
86
+ let sessionCallbacks: SessionCallbacks | null = null;
87
+ let streamSubscriberCount = 0;
88
+
89
+ /**
90
+ * Normalize a single-char key option: default when undefined, `false` → disabled.
91
+ */
92
+ export function resolveKeyOption(
93
+ value: AtlasKeyOption | undefined,
94
+ defaultKey: string,
95
+ ): string | null {
96
+ if (value === false) return null;
97
+ const raw =
98
+ value === undefined || value === null ? defaultKey : String(value).trim();
99
+ if (!raw) return null;
100
+ const key = raw.length === 1 ? raw.toLowerCase() : raw.toLowerCase().charAt(0);
101
+ return key || null;
102
+ }
103
+
104
+ /**
105
+ * Normalize `atlasKey` option: default `"a"`, `false` → disabled, else single char.
106
+ */
107
+ export function resolveAtlasKeyOption(
108
+ atlasKey?: AtlasKeyOption,
109
+ ): string | null {
110
+ return resolveKeyOption(atlasKey, DEFAULT_METRO_ATLAS_KEY);
111
+ }
112
+
113
+ /**
114
+ * Normalize `dashboardKey` option: default `"m"`, `false` → disabled.
115
+ */
116
+ export function resolveDashboardKeyOption(
117
+ dashboardKey?: AtlasKeyOption,
118
+ ): string | null {
119
+ return resolveKeyOption(dashboardKey, DEFAULT_METRO_DASHBOARD_KEY);
120
+ }
121
+
122
+ /**
123
+ * Resolve dashboard browse URL for Metro `m`.
124
+ * Precedence: explicit → `MOCKIFYER_DASHBOARD_URL` → `http://localhost:3002`,
125
+ * then append `MOCKIFYER_DASHBOARD_BASE` when set.
126
+ */
127
+ export function resolveMetroDashboardUrl(explicit?: string): string {
128
+ const fromExplicit = explicit?.trim();
129
+ const fromEnv =
130
+ typeof process !== "undefined"
131
+ ? process.env.MOCKIFYER_DASHBOARD_URL?.trim()
132
+ : undefined;
133
+ const base = (fromExplicit || fromEnv || DEFAULT_METRO_DASHBOARD_URL).replace(
134
+ /\/+$/,
135
+ "",
136
+ );
137
+ const mountRaw =
138
+ typeof process !== "undefined"
139
+ ? process.env.MOCKIFYER_DASHBOARD_BASE?.trim()
140
+ : undefined;
141
+ if (!mountRaw) return base;
142
+ const mount = mountRaw.replace(/\/+$/, "");
143
+ if (!mount || mount === "/") return base;
144
+ return `${base}${mount.startsWith("/") ? mount : `/${mount}`}`;
145
+ }
146
+
147
+ /**
148
+ * Open a URL with the OS default handler (browser / file).
149
+ */
150
+ export function openMetroBrowseUrl(target: string): void {
151
+ const platform = process.platform;
152
+ const child =
153
+ platform === "darwin"
154
+ ? spawn("open", [target], { detached: true, stdio: "ignore" })
155
+ : platform === "win32"
156
+ ? spawn("cmd", ["/c", "start", "", target], {
157
+ detached: true,
158
+ stdio: "ignore",
159
+ windowsVerbatimArguments: true,
160
+ })
161
+ : spawn("xdg-open", [target], { detached: true, stdio: "ignore" });
162
+ child.once("error", (err) => {
163
+ console.error(`[Mockifyer] could not open: ${err.message}`);
164
+ console.log(`[Mockifyer] open manually: ${target}`);
165
+ });
166
+ child.unref();
167
+ }
168
+
169
+ /**
170
+ * Whether a keypress matches a bound key (no ctrl/meta).
171
+ */
172
+ export function matchesAtlasKey(
173
+ str: string | undefined,
174
+ key: readline.Key | undefined,
175
+ atlasKey: string,
176
+ ): boolean {
177
+ if (!atlasKey) return false;
178
+ if (key?.ctrl || key?.meta) return false;
179
+ if (key?.name === atlasKey) return true;
180
+ if (typeof str === "string" && str.toLowerCase() === atlasKey) return true;
181
+ return false;
182
+ }
183
+
184
+ /** Current session phase (idle / capturing / rendering). Exported for tests. */
185
+ export function getMetroAtlasSessionPhase(): MetroAtlasSessionPhase {
186
+ return sessionPhase;
187
+ }
188
+
189
+ /** Active SSE stream subscriber count (tests / diagnostics). */
190
+ export function getMetroAtlasStreamSubscriberCount(): number {
191
+ return streamSubscriberCount;
192
+ }
193
+
194
+ function formatSessionDuration(startedAt: number): string {
195
+ const ms = Date.now() - startedAt;
196
+ if (ms < 1000) return `${ms}ms`;
197
+ const sec = Math.round(ms / 1000);
198
+ if (sec < 60) return `${sec}s`;
199
+ const min = Math.floor(sec / 60);
200
+ const rem = sec % 60;
201
+ return `${min}m ${rem}s`;
202
+ }
203
+
204
+ /**
205
+ * Start capture when idle. No-op if already capturing/rendering or Atlas key off.
206
+ * @returns true if a new session was started
207
+ */
208
+ export function startMetroAtlasSession(
209
+ reason: MetroAtlasSessionStartReason = "key",
210
+ ): boolean {
211
+ if (!sessionCallbacks?.key || !sessionCallbacks.onSessionStart) return false;
212
+ if (sessionPhase !== "idle") return false;
213
+
214
+ const { key, onSessionStart } = sessionCallbacks;
215
+ sessionPhase = "capturing";
216
+ sessionStartedAt = Date.now();
217
+ try {
218
+ onSessionStart();
219
+ } catch (err) {
220
+ sessionPhase = "idle";
221
+ sessionStartedAt = null;
222
+ const message = err instanceof Error ? err.message : String(err);
223
+ console.error(`[Mockifyer] Atlas session start failed: ${message}`);
224
+ return false;
225
+ }
226
+
227
+ if (reason === "stream") {
228
+ console.log(
229
+ `[Mockifyer] Atlas capture started (stream connected) — press ${key} to stop & generate HTML.`,
230
+ );
231
+ } else {
232
+ console.log(
233
+ `[Mockifyer] Atlas capture started — press ${key} again to stop & generate HTML.`,
234
+ );
235
+ }
236
+ return true;
237
+ }
238
+
239
+ /**
240
+ * Stop capture and generate Atlas HTML when capturing.
241
+ * @returns true if stop/render was kicked off
242
+ */
243
+ export function stopMetroAtlasSession(): boolean {
244
+ if (!sessionCallbacks?.onSessionStop) return false;
245
+ if (sessionPhase !== "capturing") return false;
246
+
247
+ const { onSessionStop } = sessionCallbacks;
248
+ const startedAt = sessionStartedAt ?? Date.now();
249
+ const duration = formatSessionDuration(startedAt);
250
+ sessionPhase = "rendering";
251
+ console.log(
252
+ `[Mockifyer] Atlas capture stopped (${duration}) — generating HTML…`,
253
+ );
254
+ Promise.resolve()
255
+ .then(() => onSessionStop())
256
+ .catch((err: unknown) => {
257
+ const message = err instanceof Error ? err.message : String(err);
258
+ console.error(`[Mockifyer] Atlas render failed: ${message}`);
259
+ })
260
+ .finally(() => {
261
+ sessionPhase = "idle";
262
+ sessionStartedAt = null;
263
+ });
264
+ return true;
265
+ }
266
+
267
+ /** Open the dashboard URL when the dashboard key is enabled. */
268
+ export function openMetroDashboard(): boolean {
269
+ if (!sessionCallbacks?.dashboardKey || !sessionCallbacks.dashboardUrl) {
270
+ return false;
271
+ }
272
+ const url = sessionCallbacks.dashboardUrl;
273
+ console.log(`[Mockifyer] Opening dashboard → ${url}`);
274
+ try {
275
+ sessionCallbacks.openUrl(url);
276
+ } catch (err) {
277
+ const message = err instanceof Error ? err.message : String(err);
278
+ console.error(`[Mockifyer] Could not open dashboard: ${message}`);
279
+ return false;
280
+ }
281
+ return true;
282
+ }
283
+
284
+ /**
285
+ * First SSE client for `/mockifyer-network-events/stream` auto-starts capture.
286
+ */
287
+ export function notifyMetroAtlasStreamClientConnected(): void {
288
+ streamSubscriberCount += 1;
289
+ if (streamSubscriberCount === 1) {
290
+ startMetroAtlasSession("stream");
291
+ }
292
+ }
293
+
294
+ /**
295
+ * SSE client disconnected — capture stays open until Metro `a` (or explicit stop).
296
+ */
297
+ export function notifyMetroAtlasStreamClientDisconnected(): void {
298
+ streamSubscriberCount = Math.max(0, streamSubscriberCount - 1);
299
+ }
300
+
301
+ function clearPendingTimer(): void {
302
+ if (pendingTimer != null) {
303
+ clearTimeout(pendingTimer);
304
+ pendingTimer = null;
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Detach a previously attached handler (idempotent). Exported for tests.
310
+ */
311
+ export function detachMetroAtlasKeyHandler(): void {
312
+ clearPendingTimer();
313
+ if (activeHandler && activeStdin) {
314
+ activeStdin.removeListener("keypress", activeHandler);
315
+ }
316
+ if (weSetRawMode && activeStdin?.isTTY && typeof activeStdin.setRawMode === "function") {
317
+ try {
318
+ activeStdin.setRawMode(false);
319
+ } catch {
320
+ // ignore
321
+ }
322
+ }
323
+ activeHandler = null;
324
+ activeStdin = null;
325
+ weSetRawMode = false;
326
+ attached = false;
327
+ sessionPhase = "idle";
328
+ sessionStartedAt = null;
329
+ sessionCallbacks = null;
330
+ streamSubscriberCount = 0;
331
+ }
332
+
333
+ function warnIfReserved(key: string, label: string): void {
334
+ if (RESERVED_METRO_KEYS.has(key)) {
335
+ logger.warn(
336
+ `[Mockifyer] ${label} "${key}" conflicts with Metro/RN CLI — pick another letter`,
337
+ );
338
+ }
339
+ }
340
+
341
+ /**
342
+ * Listen for Metro terminal keys (Atlas capture + open dashboard).
343
+ * Safe to call once per process; subsequent calls are no-ops until detach.
344
+ */
345
+ export function attachMetroAtlasKeyHandler(
346
+ options: AttachMetroAtlasKeyHandlerOptions,
347
+ ): AttachedMetroAtlasKeyHandler {
348
+ const atlasKey = resolveAtlasKeyOption(options.atlasKey);
349
+ const dashboardKey = resolveDashboardKeyOption(options.dashboardKey);
350
+ const dashboardUrl =
351
+ dashboardKey != null
352
+ ? resolveMetroDashboardUrl(options.dashboardUrl)
353
+ : null;
354
+
355
+ if (atlasKey == null && dashboardKey == null) {
356
+ return {
357
+ key: null,
358
+ dashboardKey: null,
359
+ dashboardUrl: null,
360
+ detach: () => undefined,
361
+ };
362
+ }
363
+
364
+ if (atlasKey != null) warnIfReserved(atlasKey, "atlasKey");
365
+ if (dashboardKey != null) warnIfReserved(dashboardKey, "dashboardKey");
366
+
367
+ if (
368
+ atlasKey != null &&
369
+ dashboardKey != null &&
370
+ atlasKey === dashboardKey
371
+ ) {
372
+ logger.warn(
373
+ `[Mockifyer] atlasKey and dashboardKey are both "${atlasKey}" — dashboard key ignored`,
374
+ );
375
+ }
376
+
377
+ const effectiveDashboardKey =
378
+ atlasKey != null && dashboardKey === atlasKey ? null : dashboardKey;
379
+
380
+ sessionCallbacks = {
381
+ key: atlasKey,
382
+ dashboardKey: effectiveDashboardKey,
383
+ dashboardUrl: effectiveDashboardKey != null ? dashboardUrl : null,
384
+ onSessionStart: options.onSessionStart,
385
+ onSessionStop: options.onSessionStop,
386
+ openUrl: options.openUrl ?? openMetroBrowseUrl,
387
+ };
388
+
389
+ if (attached) {
390
+ return {
391
+ key: atlasKey,
392
+ dashboardKey: effectiveDashboardKey,
393
+ dashboardUrl: sessionCallbacks.dashboardUrl,
394
+ detach: detachMetroAtlasKeyHandler,
395
+ };
396
+ }
397
+
398
+ const stdin = options.stdin ?? process.stdin;
399
+ const deferMs = options.deferMs ?? ATTACH_DEFER_MS;
400
+
401
+ const onKeypress = (str: string, keyObj: readline.Key): void => {
402
+ if (keyObj?.ctrl && keyObj.name === "c") {
403
+ if (weSetRawMode) {
404
+ try {
405
+ if (typeof stdin.setRawMode === "function") stdin.setRawMode(false);
406
+ } catch {
407
+ // ignore
408
+ }
409
+ process.exit(0);
410
+ }
411
+ return;
412
+ }
413
+
414
+ if (
415
+ effectiveDashboardKey &&
416
+ matchesAtlasKey(str, keyObj, effectiveDashboardKey)
417
+ ) {
418
+ openMetroDashboard();
419
+ return;
420
+ }
421
+
422
+ if (!atlasKey || !matchesAtlasKey(str, keyObj, atlasKey)) return;
423
+
424
+ if (sessionPhase === "rendering") {
425
+ console.log("[Mockifyer] Atlas render already in progress…");
426
+ return;
427
+ }
428
+
429
+ if (sessionPhase === "idle") {
430
+ startMetroAtlasSession("key");
431
+ return;
432
+ }
433
+
434
+ stopMetroAtlasSession();
435
+ };
436
+
437
+ const doAttach = (): void => {
438
+ if (attached) return;
439
+ if (!stdin.isTTY) {
440
+ logger.info(
441
+ "[Mockifyer] Metro keys skipped (stdin is not a TTY — use mockifyer-atlas or Dev Menu)",
442
+ );
443
+ return;
444
+ }
445
+
446
+ readline.emitKeypressEvents(stdin);
447
+ if (typeof stdin.setRawMode === "function" && stdin.isRaw !== true) {
448
+ try {
449
+ stdin.setRawMode(true);
450
+ weSetRawMode = true;
451
+ } catch (err) {
452
+ logger.warn(
453
+ "[Mockifyer] Could not enable raw stdin for Metro keys:",
454
+ err,
455
+ );
456
+ return;
457
+ }
458
+ }
459
+
460
+ if (typeof stdin.resume === "function") {
461
+ stdin.resume();
462
+ }
463
+
464
+ activeHandler = onKeypress;
465
+ activeStdin = stdin;
466
+ stdin.on("keypress", onKeypress);
467
+ attached = true;
468
+
469
+ const parts: string[] = [];
470
+ if (atlasKey) {
471
+ parts.push(
472
+ `Press ${atlasKey} to start/stop Atlas capture (stop generates HTML; stream auto-starts)`,
473
+ );
474
+ }
475
+ if (effectiveDashboardKey && dashboardUrl) {
476
+ parts.push(`Press ${effectiveDashboardKey} to open dashboard (${dashboardUrl})`);
477
+ }
478
+ if (parts.length > 0) {
479
+ console.log(`[Mockifyer] info ${parts.join(". ")}.`);
480
+ }
481
+ };
482
+
483
+ clearPendingTimer();
484
+ if (deferMs <= 0) {
485
+ doAttach();
486
+ } else {
487
+ pendingTimer = setTimeout(() => {
488
+ pendingTimer = null;
489
+ doAttach();
490
+ }, deferMs);
491
+ // Don't keep the process alive solely for the defer timer.
492
+ if (typeof pendingTimer === "object" && pendingTimer && "unref" in pendingTimer) {
493
+ (pendingTimer as NodeJS.Timeout).unref();
494
+ }
495
+ }
496
+
497
+ return {
498
+ key: atlasKey,
499
+ dashboardKey: effectiveDashboardKey,
500
+ dashboardUrl: sessionCallbacks.dashboardUrl,
501
+ detach: detachMetroAtlasKeyHandler,
502
+ };
503
+ }
@@ -88,7 +88,12 @@ const NODE_BUILTINS = [
88
88
  * Optional React Native peer dependencies — stubbed when not installed so
89
89
  * `tryGetClientIdFromLaunchArguments` and similar helpers no-op instead of crashing Metro.
90
90
  */
91
- const OPTIONAL_RN_PEER_MODULES = ['react-native-launch-arguments'] as const;
91
+ const OPTIONAL_RN_PEER_MODULES = [
92
+ 'react-native-launch-arguments',
93
+ '@react-native-async-storage/async-storage',
94
+ '@sgedda/mockifyer-axios',
95
+ '@sgedda/mockifyer-fetch',
96
+ ] as const;
92
97
 
93
98
  function isMockifyerStubbedModule(moduleName: string): boolean {
94
99
  return (
@@ -166,6 +171,9 @@ export interface ConfigureMetroOptions {
166
171
  * syncMiddleware: {
167
172
  * projectRoot: __dirname,
168
173
  * mockDataPath: './mock-data',
174
+ * // atlasKey: 'a' (default) — Metro terminal: start/stop Atlas capture (stop → HTML)
175
+ * // dashboardKey: 'm' (default) — open dashboard in browser
176
+ * // dashboardUrl: 'http://localhost:3002' — or MOCKIFYER_DASHBOARD_URL
169
177
  * },
170
178
  * });
171
179
  * ```
@@ -212,14 +220,31 @@ export function configureMetroForMockifyer(
212
220
  moduleName: string,
213
221
  platform: string | null
214
222
  ): { filePath: string; type: string } | null | undefined => {
215
- // Handle Node built-ins and optional RN peers - return empty module stub
216
- if (isMockifyerStubbedModule(moduleName)) {
223
+ // Always stub Node built-ins
224
+ if ((NODE_BUILTINS as readonly string[]).includes(moduleName)) {
217
225
  return {
218
226
  filePath: emptyModulePath,
219
227
  type: 'sourceFile',
220
228
  };
221
229
  }
222
230
 
231
+ // Stub optional RN peers only when not installed
232
+ if ((OPTIONAL_RN_PEER_MODULES as readonly string[]).includes(moduleName)) {
233
+ // Try to resolve the module - if it exists, let Metro handle it normally
234
+ try {
235
+ const resolved = context.resolveRequest(context, moduleName, platform);
236
+ if (resolved) {
237
+ return resolved;
238
+ }
239
+ } catch {
240
+ // Module not installed - stub it
241
+ return {
242
+ filePath: emptyModulePath,
243
+ type: 'sourceFile',
244
+ };
245
+ }
246
+ }
247
+
223
248
  const mockifyerCoreRn = resolveMockifyerCoreReactNativeEntry(moduleName, platform);
224
249
  if (mockifyerCoreRn) {
225
250
  return mockifyerCoreRn;
@@ -245,6 +270,9 @@ export function configureMetroForMockifyer(
245
270
  projectRoot: options.syncMiddleware.projectRoot || process.cwd(),
246
271
  mockDataPath: options.syncMiddleware.mockDataPath || 'mock-data',
247
272
  testGeneration: options.syncMiddleware.testGeneration,
273
+ atlasKey: options.syncMiddleware.atlasKey,
274
+ dashboardKey: options.syncMiddleware.dashboardKey,
275
+ dashboardUrl: options.syncMiddleware.dashboardUrl,
248
276
  });
249
277
 
250
278
  // Add middleware to server config