nucleus-core-ts 0.10.237 → 0.10.239

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.
Files changed (108) hide show
  1. package/dist/.build-ok +1 -1
  2. package/dist/fe/components/Replay/_components/ReplayCaption/index.d.ts +3 -0
  3. package/dist/fe/components/Replay/_components/ReplayCaption/index.js +53 -0
  4. package/dist/fe/components/Replay/_components/ReplayCaption/types.d.ts +12 -0
  5. package/dist/fe/components/Replay/_components/ReplayCaption/types.js +1 -0
  6. package/dist/fe/components/Replay/_components/ReplayChapters/index.d.ts +3 -0
  7. package/dist/fe/components/Replay/_components/ReplayChapters/index.js +56 -0
  8. package/dist/fe/components/Replay/_components/ReplayChapters/types.d.ts +8 -0
  9. package/dist/fe/components/Replay/_components/ReplayChapters/types.js +1 -0
  10. package/dist/fe/components/Replay/_components/ReplayControls/index.d.ts +3 -0
  11. package/dist/fe/components/Replay/_components/ReplayControls/index.js +88 -0
  12. package/dist/fe/components/Replay/_components/ReplayControls/types.d.ts +15 -0
  13. package/dist/fe/components/Replay/_components/ReplayControls/types.js +1 -0
  14. package/dist/fe/components/Replay/_components/ReplayCursor/index.d.ts +6 -0
  15. package/dist/fe/components/Replay/_components/ReplayCursor/index.js +91 -0
  16. package/dist/fe/components/Replay/_components/ReplayCursor/types.d.ts +11 -0
  17. package/dist/fe/components/Replay/_components/ReplayCursor/types.js +1 -0
  18. package/dist/fe/components/Replay/_components/ReplayEnded/index.d.ts +9 -0
  19. package/dist/fe/components/Replay/_components/ReplayEnded/index.js +36 -0
  20. package/dist/fe/components/Replay/_components/ReplayFailure/index.d.ts +3 -0
  21. package/dist/fe/components/Replay/_components/ReplayFailure/index.js +32 -0
  22. package/dist/fe/components/Replay/_components/ReplayFailure/types.d.ts +6 -0
  23. package/dist/fe/components/Replay/_components/ReplayFailure/types.js +1 -0
  24. package/dist/fe/components/Replay/_components/ReplayPlayer/ReplayView.d.ts +10 -0
  25. package/dist/fe/components/Replay/_components/ReplayPlayer/ReplayView.js +100 -0
  26. package/dist/fe/components/Replay/_components/ReplayPlayer/index.d.ts +6 -0
  27. package/dist/fe/components/Replay/_components/ReplayPlayer/index.js +28 -0
  28. package/dist/fe/components/Replay/_components/ReplayPlayer/types.d.ts +9 -0
  29. package/dist/fe/components/Replay/_components/ReplayPlayer/types.js +1 -0
  30. package/dist/fe/components/Replay/_components/ReplaySkeleton/index.d.ts +4 -0
  31. package/dist/fe/components/Replay/_components/ReplaySkeleton/index.js +148 -0
  32. package/dist/fe/components/Replay/_components/ReplayStage/ReplayVeil.d.ts +2 -0
  33. package/dist/fe/components/Replay/_components/ReplayStage/ReplayVeil.js +34 -0
  34. package/dist/fe/components/Replay/_components/ReplayStage/index.d.ts +6 -0
  35. package/dist/fe/components/Replay/_components/ReplayStage/index.js +76 -0
  36. package/dist/fe/components/Replay/_components/ReplayStage/types.d.ts +18 -0
  37. package/dist/fe/components/Replay/_components/ReplayStage/types.js +1 -0
  38. package/dist/fe/components/Replay/_components/index.d.ts +11 -0
  39. package/dist/fe/components/Replay/_components/index.js +10 -0
  40. package/dist/fe/components/Replay/_hooks/index.d.ts +3 -0
  41. package/dist/fe/components/Replay/_hooks/index.js +3 -0
  42. package/dist/fe/components/Replay/_hooks/useReplayPlayer.d.ts +6 -0
  43. package/dist/fe/components/Replay/_hooks/useReplayPlayer.js +63 -0
  44. package/dist/fe/components/Replay/_hooks/useShimmer.d.ts +3 -0
  45. package/dist/fe/components/Replay/_hooks/useShimmer.js +31 -0
  46. package/dist/fe/components/Replay/_hooks/useStageScale.d.ts +5 -0
  47. package/dist/fe/components/Replay/_hooks/useStageScale.js +24 -0
  48. package/dist/fe/components/Replay/_store/index.d.ts +1 -0
  49. package/dist/fe/components/Replay/_store/index.js +1 -0
  50. package/dist/fe/components/Replay/_store/replayStore.d.ts +13 -0
  51. package/dist/fe/components/Replay/_store/replayStore.js +74 -0
  52. package/dist/fe/components/Replay/_types/index.d.ts +1 -0
  53. package/dist/fe/components/Replay/_types/index.js +1 -0
  54. package/dist/fe/components/Replay/_types/player.d.ts +105 -0
  55. package/dist/fe/components/Replay/_types/player.js +1 -0
  56. package/dist/fe/components/Replay/_utils/controller.d.ts +10 -0
  57. package/dist/fe/components/Replay/_utils/controller.js +208 -0
  58. package/dist/fe/components/Replay/_utils/controllerReports.d.ts +18 -0
  59. package/dist/fe/components/Replay/_utils/controllerReports.js +70 -0
  60. package/dist/fe/components/Replay/_utils/copy.d.ts +29 -0
  61. package/dist/fe/components/Replay/_utils/copy.js +75 -0
  62. package/dist/fe/components/Replay/_utils/cursorMotion.d.ts +38 -0
  63. package/dist/fe/components/Replay/_utils/cursorMotion.js +98 -0
  64. package/dist/fe/components/Replay/_utils/frameBridge.d.ts +40 -0
  65. package/dist/fe/components/Replay/_utils/frameBridge.js +167 -0
  66. package/dist/fe/components/Replay/_utils/framePoints.d.ts +17 -0
  67. package/dist/fe/components/Replay/_utils/framePoints.js +24 -0
  68. package/dist/fe/components/Replay/_utils/frameUrl.d.ts +21 -0
  69. package/dist/fe/components/Replay/_utils/frameUrl.js +23 -0
  70. package/dist/fe/components/Replay/_utils/index.d.ts +7 -0
  71. package/dist/fe/components/Replay/_utils/index.js +7 -0
  72. package/dist/fe/components/Replay/_utils/replayCss.d.ts +2 -0
  73. package/dist/fe/components/Replay/_utils/replayCss.js +4 -0
  74. package/dist/fe/components/Replay/_utils/replayLayout.d.ts +2 -0
  75. package/dist/fe/components/Replay/_utils/replayLayout.js +20 -0
  76. package/dist/fe/components/Replay/_utils/replayPalette.d.ts +1 -0
  77. package/dist/fe/components/Replay/_utils/replayPalette.js +8 -0
  78. package/dist/fe/components/Replay/_utils/replayParts.d.ts +1 -0
  79. package/dist/fe/components/Replay/_utils/replayParts.js +56 -0
  80. package/dist/fe/components/Replay/_utils/replayProgress.d.ts +14 -0
  81. package/dist/fe/components/Replay/_utils/replayProgress.js +39 -0
  82. package/dist/fe/components/Replay/index.d.ts +5 -0
  83. package/dist/fe/components/Replay/index.js +5 -0
  84. package/dist/src/Client/Replay/index.d.ts +1 -0
  85. package/dist/src/Client/Replay/index.js +1 -0
  86. package/dist/src/Client/Replay/recorder/anchors.d.ts +18 -0
  87. package/dist/src/Client/Replay/recorder/anchors.js +39 -0
  88. package/dist/src/Client/Replay/recorder/bundle.d.ts +60 -0
  89. package/dist/src/Client/Replay/recorder/bundle.js +103 -0
  90. package/dist/src/Client/Replay/recorder/clock.d.ts +13 -0
  91. package/dist/src/Client/Replay/recorder/clock.js +9 -0
  92. package/dist/src/Client/Replay/recorder/factoryTap.d.ts +22 -0
  93. package/dist/src/Client/Replay/recorder/factoryTap.js +24 -0
  94. package/dist/src/Client/Replay/recorder/fetchTee.d.ts +37 -0
  95. package/dist/src/Client/Replay/recorder/fetchTee.js +121 -0
  96. package/dist/src/Client/Replay/recorder/index.d.ts +9 -0
  97. package/dist/src/Client/Replay/recorder/index.js +9 -0
  98. package/dist/src/Client/Replay/recorder/privacy.d.ts +27 -0
  99. package/dist/src/Client/Replay/recorder/privacy.js +115 -0
  100. package/dist/src/Client/Replay/recorder/redact.d.ts +8 -0
  101. package/dist/src/Client/Replay/recorder/redact.js +100 -0
  102. package/dist/src/Client/Replay/recorder/socketTap.d.ts +21 -0
  103. package/dist/src/Client/Replay/recorder/socketTap.js +43 -0
  104. package/dist/src/Client/Replay/recorder/sse.d.ts +15 -0
  105. package/dist/src/Client/Replay/recorder/sse.js +56 -0
  106. package/dist/src/Client/Replay/recorder/steps.d.ts +27 -0
  107. package/dist/src/Client/Replay/recorder/steps.js +152 -0
  108. package/package.json +5 -1
@@ -0,0 +1,103 @@
1
+ import { parseChapterChunk, parseManifest } from '../contract/parse';
2
+ import { createFindings, RULES } from './privacy';
3
+ import { scrubAnswer, scrubSocket, scrubStep, scrubStream } from './redact';
4
+ const chunkName = (index)=>`chapter-${String(index + 1).padStart(2, '0')}.json`;
5
+ /** The chapter an offset falls in: the last one starting at or before it, the first for earlier offsets. */ function chapterIndex(chapters, at) {
6
+ let found = 0;
7
+ chapters.forEach((chapter, i)=>{
8
+ if (chapter.from <= at) found = i;
9
+ });
10
+ return found;
11
+ }
12
+ /** Captions are authored after recording, so an empty one is checked with a stand-in and reported in `uncaptioned` instead. */ function contractProblems(manifest, chunks) {
13
+ const filled = {
14
+ ...manifest,
15
+ steps: manifest.steps.map((step)=>step.caption.en === '' ? {
16
+ ...step,
17
+ caption: {
18
+ ...step.caption,
19
+ en: '-'
20
+ }
21
+ } : step)
22
+ };
23
+ const parsed = parseManifest(JSON.stringify(filled));
24
+ const out = parsed.ok ? [] : parsed.errors.map((error)=>`manifest ${error}`);
25
+ for (const [path, chunk] of Object.entries(chunks)){
26
+ const result = parseChapterChunk(JSON.stringify(chunk));
27
+ if (!result.ok) out.push(...result.errors.map((error)=>`${path} ${error}`));
28
+ }
29
+ return out;
30
+ }
31
+ /**
32
+ * Turns what the taps and the step capture recorded into a contract v2 recording: a manifest and one chunk per
33
+ * chapter. Every string is scanned first (see `PrivacyOptions`); nothing is invented, and what a rule finds is
34
+ * removed or mapped and counted in `manifest.redactions`.
35
+ */ export function buildRecording(input) {
36
+ const { meta } = input;
37
+ const options = meta.privacy ?? {};
38
+ const findings = createFindings();
39
+ const specs = input.chapters ?? [
40
+ {
41
+ id: 'main',
42
+ title: meta.title,
43
+ from: 0,
44
+ to: meta.clock.durationMs
45
+ }
46
+ ];
47
+ const chapters = specs.map((spec, i)=>({
48
+ id: spec.id,
49
+ title: spec.title,
50
+ from: spec.from,
51
+ to: spec.to,
52
+ rate: spec.rate ?? 1,
53
+ chunk: chunkName(i)
54
+ }));
55
+ const chunks = Object.fromEntries(chapters.map((chapter)=>[
56
+ chapter.chunk,
57
+ {
58
+ answers: [],
59
+ streams: [],
60
+ sockets: []
61
+ }
62
+ ]));
63
+ const place = (at)=>chunks[chapters[chapterIndex(chapters, at ?? 0)]?.chunk ?? ''];
64
+ input.answers.forEach((answer, i)=>place(answer.at)?.answers.push(scrubAnswer(answer, `answers[${i}]`, options, findings)));
65
+ input.streams.forEach((stream, i)=>place(stream.openAt)?.streams.push(scrubStream(stream, `streams[${i}]`, options, findings)));
66
+ input.sockets.forEach((socket, i)=>place(socket.openAt)?.sockets.push(scrubSocket(socket, `sockets[${i}]`, options, findings)));
67
+ const steps = input.steps.map((step, i)=>scrubStep(input.chapters ? step : {
68
+ ...step,
69
+ chapter: 'main'
70
+ }, `steps[${i}]`, options, findings));
71
+ const boot = (meta.boot ?? []).map((answer, i)=>scrubAnswer(answer, `boot[${i}]`, options, findings));
72
+ const rules = [
73
+ 'identity',
74
+ ...RULES
75
+ ];
76
+ const manifest = {
77
+ schemaVersion: 2,
78
+ id: meta.id,
79
+ title: meta.title,
80
+ startPath: meta.startPath,
81
+ viewport: meta.viewport,
82
+ targetAttribute: meta.targetAttribute ?? 'data-tour',
83
+ clock: meta.clock,
84
+ chapters,
85
+ steps,
86
+ boot,
87
+ assets: meta.assets ?? {},
88
+ source: meta.source,
89
+ redactions: rules.flatMap((rule)=>findings.counts.has(rule) ? [
90
+ {
91
+ rule,
92
+ count: findings.counts.get(rule) ?? 0
93
+ }
94
+ ] : [])
95
+ };
96
+ return {
97
+ manifest,
98
+ chunks,
99
+ unresolved: findings.unresolved,
100
+ uncaptioned: steps.filter((s)=>s.caption.en === '').map((s)=>s.id),
101
+ problems: contractProblems(manifest, chunks)
102
+ };
103
+ }
@@ -0,0 +1,13 @@
1
+ import type { Ms } from '../contract/types';
2
+ /** The one clock every tap and the step capture read: offsets from 0, plus the wall clock at 0. */
3
+ export interface RecorderClock {
4
+ /** `Date.now()` at offset 0; becomes `manifest.clock.epochMs`. */
5
+ readonly epochMs: number;
6
+ /** Milliseconds since the recording started (`performance.now` based, so it never jumps backwards). */
7
+ at: () => Ms;
8
+ }
9
+ export interface RecorderClockSources {
10
+ now?: () => number;
11
+ wall?: () => number;
12
+ }
13
+ export declare function createRecorderClock(sources?: RecorderClockSources): RecorderClock;
@@ -0,0 +1,9 @@
1
+ export function createRecorderClock(sources = {}) {
2
+ const now = sources.now ?? (()=>performance.now());
3
+ const wall = sources.wall ?? (()=>Date.now());
4
+ const origin = now();
5
+ return {
6
+ epochMs: wall(),
7
+ at: ()=>Math.max(0, Math.round(now() - origin))
8
+ };
9
+ }
@@ -0,0 +1,22 @@
1
+ import type { JsonValue, RecordedAnswer } from '../contract/types';
2
+ import type { RecorderClock } from './clock';
3
+ /** Anything JSON.stringify can take; what a typed API factory carries in `data`, `errors` and payloads. */
4
+ export type JsonLike = object | string | number | boolean | null | undefined;
5
+ /** The structural part of nucleus `ApiResponse` the tap reads. */
6
+ export interface TappableResult {
7
+ isSuccess: boolean;
8
+ code?: number | null;
9
+ data?: JsonLike;
10
+ errors?: JsonLike;
11
+ }
12
+ /** JSON round trip: a private, plain copy typed as JSON. Values JSON cannot carry (functions, undefined) vanish. */
13
+ export declare function toJson(value: JsonLike): JsonValue;
14
+ export interface FactoryTapOptions {
15
+ clock: RecorderClock;
16
+ onAnswer: (answer: RecordedAnswer) => void;
17
+ }
18
+ /**
19
+ * Wraps a typed API factory `(key, payload) => Promise<ApiResponse>` without changing its result: the response is
20
+ * returned untouched and each finished call is reported as a `RecordedAnswer`. `at` is when the answer arrived.
21
+ */
22
+ export declare function tapFactory<K extends string, P, R extends TappableResult>(factory: (key: K, payload: P) => Promise<R>, options: FactoryTapOptions): (key: K, payload: P) => Promise<R>;
@@ -0,0 +1,24 @@
1
+ /** JSON round trip: a private, plain copy typed as JSON. Values JSON cannot carry (functions, undefined) vanish. */ export function toJson(value) {
2
+ const text = JSON.stringify(value);
3
+ return text === undefined ? null : JSON.parse(text);
4
+ }
5
+ /**
6
+ * Wraps a typed API factory `(key, payload) => Promise<ApiResponse>` without changing its result: the response is
7
+ * returned untouched and each finished call is reported as a `RecordedAnswer`. `at` is when the answer arrived.
8
+ */ export function tapFactory(factory, options) {
9
+ return async (key, payload)=>{
10
+ const response = await factory(key, payload);
11
+ const answer = {
12
+ key,
13
+ status: response.code ?? 503,
14
+ body: toJson(response.isSuccess ? response.data : response.errors),
15
+ at: options.clock.at()
16
+ };
17
+ const sent = payload === undefined ? null : toJson(payload);
18
+ options.onAnswer(sent === null ? answer : {
19
+ ...answer,
20
+ payload: sent
21
+ });
22
+ return response;
23
+ };
24
+ }
@@ -0,0 +1,37 @@
1
+ import type { RecordedStream } from '../contract/types';
2
+ import type { RecorderClock } from './clock';
3
+ export type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
4
+ /** A request path the app declares as a server-sent stream. */
5
+ export interface StreamDeclaration {
6
+ /** Becomes the stream id (`name`, then `name-2`, ...). */
7
+ name: string;
8
+ /** Path pattern as in `matchPath`: literal segments, `*`, trailing `**`. */
9
+ path: string;
10
+ method?: 'GET' | 'POST';
11
+ /** Replayed in real time, never recorded. Defaults to a comment line every 15 s. */
12
+ heartbeat?: RecordedStream['heartbeat'];
13
+ }
14
+ /** A response the app declares as an asset: only its url, type and size are kept, never the body. */
15
+ export interface AssetCandidate {
16
+ /** Path without the query (queries carry tokens). */
17
+ url: string;
18
+ type: string;
19
+ bytes: number;
20
+ }
21
+ export interface FetchTeeOptions {
22
+ clock: RecorderClock;
23
+ streams: StreamDeclaration[];
24
+ /** Path patterns of assets. */
25
+ assets?: string[];
26
+ }
27
+ export interface FetchTee {
28
+ fetch: FetchLike;
29
+ /** Live objects: a stream that is still open has `closeAt: null`. */
30
+ streams: () => RecordedStream[];
31
+ assets: () => AssetCandidate[];
32
+ }
33
+ /**
34
+ * Wraps `fetch`: responses to declared stream paths are teed and parsed as SSE into `RecordedStream`s; responses
35
+ * to declared asset paths become `AssetCandidate`s; everything else passes through untouched.
36
+ */
37
+ export declare function teeFetch(real: FetchLike, options: FetchTeeOptions): FetchTee;
@@ -0,0 +1,121 @@
1
+ import { matchPath, parseRequestUrl } from '../streams/path';
2
+ import { createSseParser } from './sse';
3
+ const DEFAULT_HEARTBEAT = {
4
+ everyMs: 15000,
5
+ line: ': hb\n\n'
6
+ };
7
+ function methodOf(input, init) {
8
+ return (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();
9
+ }
10
+ function urlOf(input) {
11
+ return input instanceof Request ? input.url : input;
12
+ }
13
+ /** Reads a tee branch to its end (or error, or abort), handing each chunk over; never throws. */ async function drain(body, signal, chunk) {
14
+ const reader = body.getReader();
15
+ const stop = ()=>{
16
+ void reader.cancel().catch(()=>{});
17
+ };
18
+ signal?.addEventListener('abort', stop, {
19
+ once: true
20
+ });
21
+ try {
22
+ for(;;){
23
+ const { done, value } = await reader.read();
24
+ if (done) return;
25
+ chunk(value);
26
+ }
27
+ } catch {
28
+ // an aborted or broken stream ends the recording of it; the frames so far stay
29
+ } finally{
30
+ signal?.removeEventListener('abort', stop);
31
+ }
32
+ }
33
+ /** Splits a response in two: the app gets one branch untouched, the recorder reads the other. */ function split(response) {
34
+ if (response.body === null) return null;
35
+ const [a, b] = response.body.tee();
36
+ return {
37
+ forApp: new Response(a, {
38
+ status: response.status,
39
+ statusText: response.statusText,
40
+ headers: response.headers
41
+ }),
42
+ observed: b
43
+ };
44
+ }
45
+ /**
46
+ * Wraps `fetch`: responses to declared stream paths are teed and parsed as SSE into `RecordedStream`s; responses
47
+ * to declared asset paths become `AssetCandidate`s; everything else passes through untouched.
48
+ */ export function teeFetch(real, options) {
49
+ const { clock } = options;
50
+ const streams = [];
51
+ const assets = [];
52
+ const used = new Map();
53
+ const record = (declared, method, path, response, signal)=>{
54
+ const tee = split(response);
55
+ if (tee === null) return response;
56
+ const n = (used.get(declared.name) ?? 0) + 1;
57
+ used.set(declared.name, n);
58
+ const stream = {
59
+ id: n === 1 ? declared.name : `${declared.name}-${n}`,
60
+ transport: 'sse',
61
+ match: {
62
+ method: method === 'POST' ? 'POST' : 'GET',
63
+ path
64
+ },
65
+ openAt: clock.at(),
66
+ closeAt: null,
67
+ heartbeat: declared.heartbeat ?? DEFAULT_HEARTBEAT,
68
+ frames: []
69
+ };
70
+ streams.push(stream);
71
+ const parser = createSseParser();
72
+ const decoder = new TextDecoder();
73
+ void drain(tee.observed, signal, (bytes)=>{
74
+ for (const parsed of parser.push(decoder.decode(bytes, {
75
+ stream: true
76
+ }))){
77
+ const frame = {
78
+ seq: stream.frames.length,
79
+ at: clock.at(),
80
+ data: parsed.data
81
+ };
82
+ stream.frames.push(parsed.event === undefined ? frame : {
83
+ ...frame,
84
+ event: parsed.event
85
+ });
86
+ }
87
+ }).then(()=>{
88
+ stream.closeAt = clock.at();
89
+ });
90
+ return tee.forApp;
91
+ };
92
+ const recordAsset = (path, response, signal)=>{
93
+ const tee = split(response);
94
+ const candidate = {
95
+ url: path,
96
+ type: response.headers.get('content-type') ?? '',
97
+ bytes: 0
98
+ };
99
+ assets.push(candidate);
100
+ if (tee === null) return response;
101
+ void drain(tee.observed, signal, (bytes)=>{
102
+ candidate.bytes += bytes.byteLength;
103
+ });
104
+ return tee.forApp;
105
+ };
106
+ const wrapped = async (input, init)=>{
107
+ const response = await real(input, init);
108
+ const method = methodOf(input, init);
109
+ const { path } = parseRequestUrl(urlOf(input));
110
+ const signal = init?.signal ?? (input instanceof Request ? input.signal : null);
111
+ const declared = options.streams.find((s)=>(s.method ?? 'GET') === method && matchPath(s.path, path));
112
+ if (declared && response.ok) return record(declared, method, path, response, signal);
113
+ if (method === 'GET' && response.ok && options.assets?.some((pattern)=>matchPath(pattern, path))) return recordAsset(path, response, signal);
114
+ return response;
115
+ };
116
+ return {
117
+ fetch: wrapped,
118
+ streams: ()=>streams,
119
+ assets: ()=>assets
120
+ };
121
+ }
@@ -0,0 +1,9 @@
1
+ export * from './anchors';
2
+ export * from './bundle';
3
+ export * from './clock';
4
+ export * from './factoryTap';
5
+ export * from './fetchTee';
6
+ export * from './privacy';
7
+ export * from './socketTap';
8
+ export * from './sse';
9
+ export * from './steps';
@@ -0,0 +1,9 @@
1
+ export * from './anchors';
2
+ export * from './bundle';
3
+ export * from './clock';
4
+ export * from './factoryTap';
5
+ export * from './fetchTee';
6
+ export * from './privacy';
7
+ export * from './socketTap';
8
+ export * from './sse';
9
+ export * from './steps';
@@ -0,0 +1,27 @@
1
+ /** What the sanitizer looks for. Every hit is mapped by the identity table or removed, never kept. */
2
+ export interface PrivacyOptions {
3
+ /** Exact text to replace by another: user id, name, email, tenant, repository. Longest key wins. Replacements must not hold quotes or backslashes. */
4
+ identity?: Record<string, string>;
5
+ /** Emails that stay: exact addresses, or `@domain` for a whole domain. */
6
+ allowEmails?: string[];
7
+ /** IPv4 addresses that stay. */
8
+ allowIps?: string[];
9
+ /** Host names that are internal to the company; every match is removed. */
10
+ internalHosts?: RegExp;
11
+ }
12
+ export interface PrivacyHit {
13
+ rule: string;
14
+ /** Where it was found: `answers[3].body.items[0].email`. */
15
+ where: string;
16
+ /** The first characters only; a hit is a secret, so it is never printed whole. */
17
+ sample: string;
18
+ }
19
+ export declare const RULES: readonly string[];
20
+ /** Collects what a pass removed or mapped. */
21
+ export interface Findings {
22
+ counts: Map<string, number>;
23
+ unresolved: PrivacyHit[];
24
+ }
25
+ export declare function createFindings(): Findings;
26
+ /** Maps identity entries, then removes every rule hit from one string; unmapped hits are reported. `name` is the key the string sits under. */
27
+ export declare function scrubText(text: string, where: string, name: string, options: PrivacyOptions, findings: Findings): string;
@@ -0,0 +1,115 @@
1
+ /** What the sanitizer looks for. Every hit is mapped by the identity table or removed, never kept. */ export const RULES = [
2
+ 'bearer',
3
+ 'jwt',
4
+ 'key',
5
+ 'email',
6
+ 'ipv4',
7
+ 'host'
8
+ ];
9
+ const SECRET_NAME = /key|secret|token|password|passwd|credential|authorization/i;
10
+ const SECRET_VALUE = /^[A-Za-z0-9+/_=.-]{20,}$/;
11
+ const TEXT_RULES = [
12
+ [
13
+ 'bearer',
14
+ /Bearer\s+[A-Za-z0-9._~+/=-]{8,}/gi
15
+ ],
16
+ [
17
+ 'jwt',
18
+ /eyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*/g
19
+ ],
20
+ [
21
+ 'key',
22
+ /\bsk-[A-Za-z0-9_-]{16,}/g
23
+ ],
24
+ [
25
+ 'key',
26
+ /(?<=(?:key|secret|token|password)["'\\]*\s*[:=]\s*["'\\]*)[A-Za-z0-9+/_=-]{20,}/gi
27
+ ],
28
+ [
29
+ 'email',
30
+ /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/g
31
+ ],
32
+ [
33
+ 'ipv4',
34
+ /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g
35
+ ]
36
+ ];
37
+ function emailAllowed(email, allow) {
38
+ const lower = email.toLowerCase();
39
+ return allow.some((entry)=>entry.startsWith('@') ? lower.endsWith(entry.toLowerCase()) : lower === entry.toLowerCase());
40
+ }
41
+ function escapeJson(value) {
42
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
43
+ }
44
+ function isJsonText(text) {
45
+ return text.startsWith('{') || text.startsWith('[');
46
+ }
47
+ export function createFindings() {
48
+ return {
49
+ counts: new Map(),
50
+ unresolved: []
51
+ };
52
+ }
53
+ function count(findings, rule, by = 1) {
54
+ findings.counts.set(rule, (findings.counts.get(rule) ?? 0) + by);
55
+ }
56
+ function mapIdentity(text, identity, findings) {
57
+ const json = isJsonText(text);
58
+ let segments = [
59
+ {
60
+ text,
61
+ mapped: false
62
+ }
63
+ ];
64
+ for (const key of Object.keys(identity).sort((a, b)=>b.length - a.length)){
65
+ if (key === '') continue;
66
+ const to = json ? escapeJson(identity[key] ?? '') : identity[key] ?? '';
67
+ segments = segments.flatMap((segment)=>{
68
+ if (segment.mapped || !segment.text.includes(key)) return [
69
+ segment
70
+ ];
71
+ const parts = segment.text.split(key);
72
+ count(findings, 'identity', parts.length - 1);
73
+ return parts.flatMap((part, i)=>(i === 0 ? [] : [
74
+ {
75
+ text: to,
76
+ mapped: true
77
+ }
78
+ ]).concat([
79
+ {
80
+ text: part,
81
+ mapped: false
82
+ }
83
+ ]));
84
+ });
85
+ }
86
+ return segments;
87
+ }
88
+ function sampleOf(text) {
89
+ return `${text.slice(0, 4)}...`;
90
+ }
91
+ function removeHits(text, where, name, options, findings) {
92
+ const hit = (rule, found)=>{
93
+ count(findings, rule);
94
+ findings.unresolved.push({
95
+ rule,
96
+ where,
97
+ sample: sampleOf(found)
98
+ });
99
+ return '';
100
+ };
101
+ let out = text;
102
+ for (const [rule, pattern] of TEXT_RULES){
103
+ out = out.replace(pattern, (found)=>{
104
+ if (rule === 'email' && emailAllowed(found, options.allowEmails ?? [])) return found;
105
+ if (rule === 'ipv4' && (options.allowIps ?? []).includes(found)) return found;
106
+ return hit(rule, found);
107
+ });
108
+ }
109
+ const hosts = options.internalHosts;
110
+ if (hosts) out = out.replace(new RegExp(hosts.source, hosts.flags.includes('g') ? hosts.flags : `${hosts.flags}g`), (found)=>hit('host', found));
111
+ return SECRET_NAME.test(name) && SECRET_VALUE.test(out) ? hit('key', out) : out;
112
+ }
113
+ /** Maps identity entries, then removes every rule hit from one string; unmapped hits are reported. `name` is the key the string sits under. */ export function scrubText(text, where, name, options, findings) {
114
+ return mapIdentity(text, options.identity ?? {}, findings).map((segment)=>segment.mapped ? segment.text : removeHits(segment.text, where, name, options, findings)).join('');
115
+ }
@@ -0,0 +1,8 @@
1
+ import type { JsonValue, RecordedAnswer, RecordedSocket, RecordedStream, ReplayStep } from '../contract/types';
2
+ import { type Findings, type PrivacyOptions } from './privacy';
3
+ /** Walks a JSON value and scrubs every string in it; keys are kept (they are the product's own field names). */
4
+ export declare function scrubJson(value: JsonValue, where: string, name: string, options: PrivacyOptions, findings: Findings): JsonValue;
5
+ export declare function scrubAnswer(answer: RecordedAnswer, where: string, options: PrivacyOptions, findings: Findings): RecordedAnswer;
6
+ export declare function scrubStream(stream: RecordedStream, where: string, options: PrivacyOptions, findings: Findings): RecordedStream;
7
+ export declare function scrubSocket(socket: RecordedSocket, where: string, options: PrivacyOptions, findings: Findings): RecordedSocket;
8
+ export declare function scrubStep(step: ReplayStep, where: string, options: PrivacyOptions, findings: Findings): ReplayStep;
@@ -0,0 +1,100 @@
1
+ import { scrubText } from './privacy';
2
+ /** Walks a JSON value and scrubs every string in it; keys are kept (they are the product's own field names). */ export function scrubJson(value, where, name, options, findings) {
3
+ if (typeof value === 'string') return scrubText(value, where, name, options, findings);
4
+ if (Array.isArray(value)) return value.map((item, i)=>scrubJson(item, `${where}[${i}]`, name, options, findings));
5
+ if (value !== null && typeof value === 'object') {
6
+ return Object.fromEntries(Object.entries(value).map(([key, item])=>[
7
+ key,
8
+ scrubJson(item, `${where}.${key}`, key, options, findings)
9
+ ]));
10
+ }
11
+ return value;
12
+ }
13
+ export function scrubAnswer(answer, where, options, findings) {
14
+ const out = {
15
+ ...answer,
16
+ body: scrubJson(answer.body, `${where}.body`, 'body', options, findings)
17
+ };
18
+ if (answer.payload !== undefined) out.payload = scrubJson(answer.payload, `${where}.payload`, 'payload', options, findings);
19
+ return out;
20
+ }
21
+ export function scrubStream(stream, where, options, findings) {
22
+ const text = (value, at, name)=>scrubText(value, `${where}.${at}`, name, options, findings);
23
+ const { query } = stream.match;
24
+ return {
25
+ ...stream,
26
+ match: {
27
+ ...stream.match,
28
+ path: text(stream.match.path, 'match.path', 'path'),
29
+ ...query ? {
30
+ query: Object.fromEntries(Object.entries(query).map(([key, value])=>[
31
+ key,
32
+ text(value, `match.query.${key}`, key)
33
+ ]))
34
+ } : {}
35
+ },
36
+ frames: stream.frames.map((frame, i)=>({
37
+ ...frame,
38
+ data: text(frame.data, `frames[${i}].data`, 'data')
39
+ }))
40
+ };
41
+ }
42
+ export function scrubSocket(socket, where, options, findings) {
43
+ return {
44
+ ...socket,
45
+ match: {
46
+ path: scrubText(socket.match.path, `${where}.match.path`, 'path', options, findings)
47
+ },
48
+ messages: socket.messages.map((message, i)=>({
49
+ ...message,
50
+ data: scrubText(message.data, `${where}.messages[${i}].data`, 'data', options, findings)
51
+ }))
52
+ };
53
+ }
54
+ function scrubAction(action, where, options, findings) {
55
+ const text = (value, name)=>scrubText(value, where, name, options, findings);
56
+ switch(action.kind){
57
+ case 'navigate':
58
+ return {
59
+ ...action,
60
+ path: text(action.path, 'path')
61
+ };
62
+ case 'type':
63
+ return {
64
+ ...action,
65
+ value: text(action.value, action.target)
66
+ };
67
+ case 'select':
68
+ return {
69
+ ...action,
70
+ value: text(action.value, 'value'),
71
+ ...action.optionValue === undefined ? {} : {
72
+ optionValue: text(action.optionValue, 'optionValue')
73
+ }
74
+ };
75
+ case 'file':
76
+ return {
77
+ ...action,
78
+ files: action.files.map((file)=>({
79
+ ...file,
80
+ name: text(file.name, 'file')
81
+ }))
82
+ };
83
+ default:
84
+ return action;
85
+ }
86
+ }
87
+ function scrubCaption(caption, where, options, findings) {
88
+ const out = {
89
+ en: ''
90
+ };
91
+ for (const [lang, text] of Object.entries(caption))out[lang] = scrubText(text, `${where}.${lang}`, 'caption', options, findings);
92
+ return out;
93
+ }
94
+ export function scrubStep(step, where, options, findings) {
95
+ return {
96
+ ...step,
97
+ caption: scrubCaption(step.caption, `${where}.caption`, options, findings),
98
+ actions: step.actions.map((action, i)=>scrubAction(action, `${where}.actions[${i}]`, options, findings))
99
+ };
100
+ }
@@ -0,0 +1,21 @@
1
+ import type { RecordedSocket } from '../contract/types';
2
+ import type { RecorderClock } from './clock';
3
+ /** What a WebSocket constructor builds, as far as the tap needs. */
4
+ export type TappableSocketConstructor = new (url: string | URL, protocols?: string | string[]) => EventTarget;
5
+ /** A socket path the app declares; frames from the server are recorded, the query string never is. */
6
+ export interface SocketDeclaration {
7
+ /** Becomes the socket id (`name`, then `name-2`, ...). */
8
+ name: string;
9
+ path: string;
10
+ }
11
+ export interface SocketTapOptions {
12
+ clock: RecorderClock;
13
+ sockets: SocketDeclaration[];
14
+ }
15
+ export interface SocketTap {
16
+ /** Install in place of `WebSocket`: `Object.assign(globalThis, { WebSocket: tap.Socket })`. */
17
+ Socket: TappableSocketConstructor;
18
+ sockets: () => RecordedSocket[];
19
+ }
20
+ /** Wraps a WebSocket constructor: sockets to declared paths record their server-to-client text messages. */
21
+ export declare function tapWebSocket(Native: TappableSocketConstructor, options: SocketTapOptions): SocketTap;
@@ -0,0 +1,43 @@
1
+ import { matchPath, parseRequestUrl } from '../streams/path';
2
+ /** Wraps a WebSocket constructor: sockets to declared paths record their server-to-client text messages. */ export function tapWebSocket(Native, options) {
3
+ const { clock } = options;
4
+ const recorded = [];
5
+ const used = new Map();
6
+ class TappedSocket extends Native {
7
+ constructor(url, protocols){
8
+ super(url, protocols);
9
+ const { path } = parseRequestUrl(url);
10
+ const declared = options.sockets.find((s)=>matchPath(s.path, path));
11
+ if (!declared) return;
12
+ const n = (used.get(declared.name) ?? 0) + 1;
13
+ used.set(declared.name, n);
14
+ const socket = {
15
+ id: n === 1 ? declared.name : `${declared.name}-${n}`,
16
+ match: {
17
+ path
18
+ },
19
+ openAt: clock.at(),
20
+ closeAt: null,
21
+ messages: []
22
+ };
23
+ recorded.push(socket);
24
+ this.addEventListener('open', ()=>{
25
+ socket.openAt = clock.at();
26
+ });
27
+ this.addEventListener('message', (event)=>{
28
+ if ('data' in event && typeof event.data === 'string') socket.messages.push({
29
+ at: clock.at(),
30
+ data: event.data
31
+ });
32
+ });
33
+ this.addEventListener('close', (event)=>{
34
+ socket.closeAt = clock.at();
35
+ if ('code' in event && typeof event.code === 'number') socket.closeCode = event.code;
36
+ });
37
+ }
38
+ }
39
+ return {
40
+ Socket: TappedSocket,
41
+ sockets: ()=>recorded
42
+ };
43
+ }