@keploy/capture-sdk 3.1.0-rc.1 → 3.1.0-rc.2
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/README.md +398 -58
- package/body-redact/package.json +6 -0
- package/body-worker-start/package.json +6 -0
- package/dist/body-jobs.d.ts +134 -0
- package/dist/body-redact.d.ts +23 -0
- package/dist/body-redact.js +1 -0
- package/dist/body-redact.js.map +1 -0
- package/dist/body-redact.mjs +1 -0
- package/dist/body-redact.mjs.map +1 -0
- package/dist/body-worker-none.d.ts +3 -0
- package/dist/body-worker-none.js +1 -0
- package/dist/body-worker-none.js.map +1 -0
- package/dist/body-worker-none.mjs +1 -0
- package/dist/body-worker-none.mjs.map +1 -0
- package/dist/body-worker-start.d.ts +3 -0
- package/dist/body-worker-start.js +1 -0
- package/dist/body-worker-start.js.map +1 -0
- package/dist/body-worker-start.mjs +1 -0
- package/dist/body-worker-start.mjs.map +1 -0
- package/dist/body-worker-unbundled.d.ts +1 -0
- package/dist/body-worker-unbundled.mjs +1 -0
- package/dist/body-worker-unbundled.mjs.map +1 -0
- package/dist/body-worker.d.ts +1 -0
- package/dist/body-worker.js +1 -0
- package/dist/body-worker.js.map +1 -0
- package/dist/errors.d.ts +38 -6
- package/dist/index.bundler.mjs +1 -0
- package/dist/index.bundler.mjs.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -11
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -11
- package/dist/index.mjs.map +1 -1
- package/dist/leave.d.ts +67 -0
- package/dist/module-of.d.ts +45 -0
- package/dist/network.d.ts +52 -37
- package/dist/privacy.d.ts +23 -2
- package/dist/recorder.d.ts +30 -6
- package/dist/request-term.d.ts +2 -0
- package/dist/request-term.js +1 -2
- package/dist/request-term.js.map +1 -1
- package/dist/request-term.mjs +1 -2
- package/dist/request-term.mjs.map +1 -1
- package/dist/strict-attributes.d.ts +9 -0
- package/dist/strict-attributes.js +1 -0
- package/dist/strict-attributes.js.map +1 -0
- package/dist/strict-attributes.mjs +1 -0
- package/dist/strict-attributes.mjs.map +1 -0
- package/dist/transport.d.ts +35 -3
- package/dist/types.d.ts +21 -5
- package/package.json +31 -4
- package/strict-attributes/package.json +6 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../contract/src/privacy.ts","../src/redact.ts","../src/privacy.ts","../src/session-id.ts","../src/errors.ts","../src/leave.ts","../package.json","../src/module-of.ts","../src/body-jobs.ts","../src/term-candidate.ts","../src/network.ts","../src/transport.ts","../src/recorder.ts","../src/identity.ts","../src/index.ts"],"names":["ESCAPED","decoded","v","includes","replace","e","decodeURIComponent","CREDENTIAL_NAMES","Set","CREDENTIAL_CODE_NAMES","CARD_EXPIRY_NAMES","CREDENTIAL_SUFFIX","PAGING_CURSORS","PAGE_OWN_NAMES","nameParts","raw","kind","split","map","n","toLowerCase","filter","isCredentialPart","part","has","test","isCredentialName","isCredentialParts","parts","some","length","join","PAIR_SEPARATOR","decodePart","plus","NESTED_QUERY","NESTED_PAIRS","scrubRelative","value","rules","depth","hashAt","indexOf","beforeHash","slice","q","path","query","fragment","out","scrubPath","scrubPairs","scrubFragment","ownValueEnd","form","at","search","parens","squares","braces","i","c","holdsCredentialName","text","k","next","m","matchAll","whole","pairs","_","ctx","pair","eq","bare","name","gone","before","strict","names","pieces","push","pairNames","spaced","own","rest","tail","inner","scrubAbsolute","startsWith","scrubNestedUrl","encodeURIComponent","segments","bases","seg","segment","semi","base","head","route","exec","AUTHORITY","spliceAbsolute","url","URL","hash","pathname","username","password","protocol","host","scheme","slashes","authority","lastIndexOf","scrubUrl","lead","trimStart","trail","trimEnd","URL_START","URL_END","NEXT_URL","scanEnd","start","brackets","list","end","lastIndex","urlEnd","CSS_URL_OPEN","keyRules","NOT_CAPTURED_WHY","left","REDACTED","PLAIN_WORDS","CAMEL_WORDS","EXCHANGE_CODES","isSensitiveKey","key","EMAIL_DOMAIN","isEmailLocalChar","code","KNOWN_TOKEN_RE","SSN_RE","PHONE_RE","JWT_RE","IPV4_RE","isLikelyCardNumber","digits","isVisa","isMastercard","isAmex","isDiscover","isJcbDiners","sum","double","d","charCodeAt","passesLuhn","patternRanges","re","into","index","applyRanges","ranges","sort","a","b","pos","with_","redactStringValue","extra","kept","floor","Math","max","domain","emailRanges","s","cardRanges","detectorRanges","redactTokens","tokenRanges","MAYBE_TOKEN","JSON","stringify","BODY_URL_RULES","TEXT_URL_RULES","scrubTextUrls","TAIL_URL_RULES","WHOLE_URL","URL_START_WORD","URL_LINE","line","edits","spans","groups","attr","inCssUrl","urlSpans","urlEdits","scrubEscapedUrls","ESCAPED_URL","span","plain","escape","ESCAPED_SLASH_AT","slash","scrubHeaderUrls","body","mode","EMBEDDED_NAME_IN_CODE","EMBEDDED_NAME_IN_STRING","EMBEDDED_NAME_IN_HEADER","EMBEDDED_NAME","scripts","open","close","gt","to","scriptRanges","r","valueStart","EMBEDDED_VALUE","EMBEDDED_VALUE_IN_STRING","valueEnd","embeddedPairRanges","TRUNCATED_SUFFIX","KEY_RULES","STRICT_KEY_RULES","urlWork","scanned","startsPair","unit","eachPair","visit","j","from","inQuery","stop","pagePairs","equals","maskPairs","linkPage","linkPageValue","maskPageUrl","ROUTE_FRAGMENT","looksRandom","Number","isUrlLike","paths","segmentWords","w","STRONG_WORDS","STRONG_COMPOUNDS","CREDENTIAL_WORDS","STEP_WORDS","WEAK_WORDS","CONFIRMED_THINGS","LINK_AUX","confirms","words","linkKind","previous","joined","isId","isUid","atob","mayPrecedeToken","linkStep","every","afterCredentialWord","CALLBACK_WORDS","inviteLink","isLinkPage","action","pairValue","find","actsOn","ROUTE_RULE","parseRoute","keep","declared","secret","declaredKeys","generation","matches","named","found","keptAt","declaredOf","values","add","credentialText","MAX_DECODINGS","pathParts","declare","sure","befores","get","set","asciiLower","beforeOf","collectSecrets","owned","invite","handed","token","id","stronger","held","auth0","state","callback","oauth","originOf","href","origin","pageSecrets","scan","Map","main","tooLong","p","crafted","forms","secrets","room","keys","shared","SHARE_ENCODINGS","toString","padStart","outside","random","secretPattern","scrubWork","lowered","units","Uint16Array","min","LOWER_CHUNK","String","fromCharCode","subarray","indicesOf","fail","Int32Array","scrubCap","scrubBase","unbudgeted","scrub","cap","overBudget","ScrubOverCap","mayReplace","f","marker","first","last","endsWith","REDACTED_UNITS","crossesMarkers","matcher","long","lower","bounded","replaceWhere","budgeted","grows","spliced","prev","ALNUM","ESCAPE_BEFORE","boundedAt","SEPARATORS","level","SEGMENT_STOP","SEGMENT_SOFT_STOP","MAX_BEFORE","separatorEndingAt","sep","l","matrixAt","repeat","strings","wordAt","word","more","runStartOf","authorityAt","longest","pieceEnd","spent","piece","lengths","segmentBefore","scrubText","mayHold","json","scrubJson","scrubPlain","heldIn","jsonUnescaped","hex","parseInt","JSON_TOKEN","NAME_ENDS","parse","jsonSpelling","narrowed","pop","opened","written","scrubbed","unescapedMap","escapes","spelledAt","lo","hi","mid","secretRanges","all","lists","runStart","runEnd","slack","unionSlack","order","Array","x","y","capped","budget","startOf","heap","swap","t","down","marked","scrubAtOnce","ok","longestFirst","size","jsonLower","flatMap","HTML_VOCABULARY","StyleTexts","constructor","page","this","styles","texts","present","members","addText","style","dropText","note","delete","forget","drop","observe","event","isPlainRecord","data","type","clear","walk","node","source","removes","isArray","adds","parentId","prune","root","inStyle","pending","seen","styled","tagName","childNodes","child","recordsIn","Error","atLeast","super","countOf","startsOver","how","meeting","onlyGrows","least","escaped","readings","reading","writesAtLeast","scrubSecrets","shape","plainLower","mayHoldJson","copy","styleText","declaration","scrubOf","record","css","attributes","memo","splitsAtHash","counted","h","imul","memoKey","bucket","hit","ends","bodyEnd","quote","fill","nextStop","pastSpace","cssData","closed","scrubCssComment","scrubCss","scrubBody","Object","elements","renamed","prototype","hasOwnProperty","call","findContentType","headers","entries","BUILTIN_PII_PATTERNS","pattern","DEFAULT_SENSITIVE_HEADERS","normalizeName","UUID","JWT","SLUG","isTokenShaped","MAYBE_PII","isCallbackPath","OAUTH_NAMES","oauthPairs","codes","states","isPlainState","known","inDom","navigating","scrubUrlAs","navigation","outer","scrubUrlValue","strictKept","LINK_WORD","URL_ATTRIBUTES","TEXT_ATTRIBUTES","FIELD_TAGS","OWN_RULE","URLISH","blanked","tag","svg","REFRESH","MAYBE_SCRUBBED","maybeScrubbed","queryReads","WeakMap","pageBefore","read","readOf","linkPairs","cut","charAt","knownPrefix","pageRules","headBases","headTokens","idParts","tokenRuns","holdsToken","tokens","linkPathTokens","isLinkToken","PAGE_RULES","STRICT_PAGE_RULES","IDENT","identEnd","cssUnescape","_m","char","fromCodePoint","scrubCssUrls","len","space","take","quoted","cssEscape","HTML_NAMED","Tab","NewLine","excl","quot","QUOT","num","dollar","percnt","amp","AMP","apos","lpar","rpar","ast","midast","comma","period","sol","colon","lt","LT","GT","quest","commat","lsqb","lbrack","bsol","rsqb","rbrack","Hat","lowbar","UnderBar","grave","DiacriticalGrave","lcub","lbrace","verbar","vert","VerticalLine","rcub","rbrace","nbsp","NonBreakingSpace","encodeHtml","RAW_TEXT","HTML_URL_ATTRIBUTE","scrubDomAttributes","scrubAttributes","scrubStyleObject","scrubAttributeText","scrubAttributeValue","property","isTextAttribute","scrubDomText","candidate","scrubSrcset","html","dec","legacy","decodeHtml","nameAt","mask","tagged","RegExp","firstEdits","after","scrubHtml","refresh","scrubContent","isNavigation","WHOLLY_URL","scrubDomCss","scrubTextRun","run","textContent","isTextNode","scrubTextRuns","children","scrubDomTree","stack","isStyle","isSVG","scrubTree","maskHeaderUrls","maskUrl","STRICT_HEADERS","isCredentialHeader","defaultPrivacyConfig","maskSelectors","unmaskSelectors","blockSelectors","maskNetworkBodies","sensitiveHeaders","piiPatterns","secretRoutes","keepRoutes","mergePrivacyConfig","partial","defined","fromEntries","merged","compileGlobal","patterns","flags","bodyCode","MASKED","PrivacyEngine","config","builtinPatterns","userPatterns","privacyMode","settle","maskText","result","rawUrl","maskQueryValues","maskNetworkData","bodies","masked","requestHeaders","maskHeaders","responseHeaders","job","bodyJob","redact","requestBody","responseBody","requestType","responseType","getConfig","updateConfig","sensitiveSet","SESSION_ID_MAX_LENGTH","SESSION_ID_PATTERN","SESSION_ID_RULE","isValidSessionId","SERVER_EVIDENCE","SERVER_OPTIONAL_EVIDENCE","withDocs","briefs","table","docs","summary","remedy","command","manual","evidence","optionalEvidence","SDK_ERRORS","KUI_E_INGEST_KEY_REJECTED","KUI_E_INGEST_ENDPOINT_NOT_FOUND","KUI_E_SESSION_CONFLICT","KUI_E_INGEST_REJECTED","KUI_E_SESSION_ID_INVALID","KUI_E_DOM_RECORDER_UNAVAILABLE","KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE","KUI_E_PRIVACY_ROUTE_INVALID","KUI_E_CAPTURE_DECLINED","KUI_E_PRIVACY_CONFLICT","SDK_WARNINGS","KUI_E_EVENT_UNSERIALISABLE","KUI_E_EVENT_OVERSIZED","KUI_E_EVENT_OVERSIZED_SCRUBBING","KUI_E_NAVIGATION_UNWRAPPED","KUI_E_REQUEST_TERM_FAILED","KUI_E_BODY_WORKER_UNAVAILABLE","oneLine","trim","warningLine","prose","fields","evidenceJson","noticeLine","rendered","describeValue","codeForStatus","status","NO_SERVER_ERROR","message","issues","SERVER_TEXT_LIMIT","parseServerError","parsed","shaped","error","sentence","issuesOf","ISSUES_LIMIT","item","ctor","CaptureError","serverMessage","server","IngestRejection","init","endpoint","sessionId","SessionIdRefusal","received","rule","StrictAttributesRefusal","reason","DomRecorderRefusal","PrivacyRouteRefusal","option","CaptureDeclined","signal","PrivacyConflict","describeReceived","outcome","threw","returned","then","leftBy","going","leaving","stands","judging","leaves","leaveMark","landed","WeakSet","went","watched","stays","stayed","cancelled","stay","due","judge","setTimeout","whenStayed","waiting","unlessHeld","load","answered","Promise","wait","done","err","whenJudged","tell","told","stand","staying","resolve","reject","go","started","nav","globalThis","undo","by","yes","leave","defaultPrevented","onLeave","currentEntry","navigationType","isTrusted","persisted","was","destination","sameDocument","downloadRequest","transition","addEventListener","LEAVE","watchLeave","on","proof","options","capture","passive","listen","target","types","removeEventListener","version","moduleOf","namespace","default","ownChunk","beside","built","catch","near","cause","codeLoad","worker","running","codeOffline","codeFailed","workerStarting","starting","posted","ids","sinceTheLeave","mark","later","fn","requestIdleCallback","timeout","valueOf","online","unwait","warned","warn","why","console","bodyWorkerWarningLine","Event","whenOnline","navigator","onLine","serviceWorker","controller","controlled","back","poll","setInterval","clearInterval","loadCode","loaded","redactBodies","TypeError","startWorker","startBodyWorker","onmessage","owner","onerror","post","prepare","soonIdle","soonTask","prepareSoon","idle","ready","ofTheLeave","noted","postMessage","alone","failed","terminate","orphans","again","letGo","hidden","releaseWorker","wanted","total","cutBodyNote","notCapturedBodyNote","mainThread","limit","responseLimit","BodyJobs","sent","answer","holds","now","final","pass","request","OBJECT_START","NOT_SPACE","termCode","termLoaded","absolute","document","baseURI","headersToRecord","Headers","forEach","assign","truncate","maxSize","formDataText","enc","binaryBody","bytes","ArrayBuffer","Uint8Array","buffer","byteOffset","byteLength","TextDecoder","fatal","decode","maskedSent","xhr","URLSearchParams","FormData","Blob","isView","Document","hasChildNodes","isRequest","Symbol","toStringTag","MULTIPART_TYPE","utf8","ignoreBOM","stops","async","blob","arrayBuffer","cutText","typedArrayTag","Reflect","getOwnPropertyDescriptor","getPrototypeOf","NETWORK_MEMBERS","dress","network","defineProperty","configurable","clone","writable","relayResponse","report","finished","pageStream","Stream","PageResponse","decoder","over","ended","stopped","reported","queue","pageText","once","hand","shift","enqueue","chunk","textEnd","byobRequest","respond","pump","reader","apply","typedArrayName","bytesOf","stream","cancel","pull","highWaterMark","statusText","getReader","recordedUrl","location","NetworkInterceptor","privacyEngine","maxBodySize","ignored","active","inflight","unloadCuts","place","admit","originalFetch","originalXhrOpen","originalXhrSend","originalXhrSetHeader","privacyConfig","ignoreUrls","ignores","termWarned","patchFetch","patchXHR","askForCode","restoreFetch","restoreXHR","timeoutMs","timer","allSettled","bound","race","clearTimeout","cutInflight","cutBodies","reportDue","hasInflight","admits","admitted","emitFor","emit","track","recording","finally","recordResponse","response","contentLength","relayed","fetch","input","inspected","Request","startTime","performance","method","requestText","formData","readRequestCopy","readRequestBody","serializeBody","term","termFor","empty","reportWhenKnown","Date","statusCode","duration","locked","XMLHttpRequest","originalOpen","originalSend","send","currentRun","u","masks","meta","origSetHeader","setRequestHeader","forwardOpen","readyState","rawHeaders","getAllResponseHeaders","idx","responseText","maskedXhrResponse","XMLSerializer","serializeToString","serializeXhrBody","relay","bodyNow","termNow","responseNow","recorded","requestTerm","couldBeGraphql","subtle","crypto","recordTermFor","termFailed","termWarningLine","placed","SDK_VERSION","KEEPALIVE_QUOTA_BYTES","say","utf8Length","TextEncoder","encode","MAX_BATCH_BYTES","MAX_QUEUE_BYTES","Transport","retryQueue","batchCounter","flushTimer","current","metadata","captureIdentity","nextSeq","drainPending","holding","asked","rushDeferred","wakeSender","inflightKeepaliveBytes","envelopeBytes","reportedUnserialisable","reportedOversized","reportedScrubOversized","reportedNavigationUnwrapped","jsonOf","inFlight","queued","failures","notBefore","batchSize","detail","discard","endsSessionOnly","serverReason","onSessionEnd","onCaptureEnd","onError","payload","mintBatchId","paced","flush","batchInterval","window","handleOnline","handleUnload","handleVisibility","hold","release","drained","disarmWhenDrained","pendingCount","seq","reportUnserialisable","dropped","reportOversized","eventBytes","evicted","maxQueueSize","fit","pastShare","events","onFailing","baseline","rrwebType","onDropped","eventId","eventType","warnOversized","reportScrubOversized","reportNavigationUnwrapped","batchId","sdk","drain","full","flight","reviveNext","formFlight","sendWithRetry","unshift","trimToCapacity","backoff","ms","wire","CompressionStream","Response","compressed","pipeThrough","buf","encoding","compressPayload","attempt","abandoned","apiKey","keepalive","early","onWire","dispatched","onDelivered","MAX_RETRY_ATTEMPTS","delay","pow","reclaimInFlight","uncount","biggest","count","most","cost","batch","splice","randomUUID","rand","sign","retry","trimmed","reverse","flushOnUnload","beforeUnload","postKeepalive","beforeOnlineFlush","beforeUnloadFlush","visibilityState","beforeHiddenFlush","queueSize","uuid","rrwebImport","rrwebLoaded","loadRRWeb","rrweb","strictImport","strictLoaded","loadRecorder","keepStrict","landers","reactions","refusal","viewport","el","documentElement","width","innerWidth","clientWidth","height","innerHeight","clientHeight","withoutQuery","documentSecrets","secretsFor","secretsGeneration","secretsMatch","secretKey","remember","changed","chars","oldest","visitedUrls","secretsOf","getEntriesByType","visited","navigationListeners","historyWrap","historyCall","announced","aims","lastAim","credited","inCall","onNavigate","userInitiated","api","currentTarget","entryKeyAt","delta","steps","findIndex","traversing","original","aim","args","onEntryChange","initiated","said","userInitiatedHere","initiator","initiatorHere","notifyNavigation","fragmentOnly","earlierMove","listener","untouched","put","restore","had","deleteProperty","onNavigation","history","pushState","replaceState","traversals","refused","isExtensible","replaceable","methods","enumerable","install","wrapHistory","traverse","unwrapHistory","KeployCaptureRecorder","_KeployCaptureRecorder","phase","userPaused","droppedWhileShut","baselineLost","retakeTimer","retakeAtOnce","retakeDelay","outage","failing","rebaseline","lost","rebaselined","snapshotDropped","getState","takeFullSnapshot","rrwebRecord","delivered","mirror","getNode","styleNodes","inPage","onEvent","onScrubOversized","onRRWeb","landing","onlineRetry","onlinePoll","rrwebStopFn","rrwebRequested","sessionTimer","visibilityHandler","stopNavigation","lastHref","seenHref","startPaused","onNavigationUnwrapped","routes","privacy","declareRoutes","produced","sampleRate","sessionIdGenerator","userAgent","referrer","language","devicePixelRatio","timestamp","gatherMetadata","openDomGate","navigated","unavailable","startRRWeb","maxDuration","maxSessionDuration","stopDom","stopOnlinePoll","emitEvent","recordedRRWebEvent","isUserPaused","pause","resume","refuseLate","landedBeforeTheRetry","getSessionId","sessionOpen","getMetadata","workerInControl","retryWhenOnline","land","loading","whenLanded","rrwebOptions","loadedLate","late","failure","awaitingRRWeb","typed","maskInputOptions","color","date","email","file","month","number","range","tel","time","week","textarea","select","editable","textMask","unmask","maskTextFn","element","closest","maskTextSelector","blockSelector","userTriggeredOnInput","isConnected","doc","ownerDocument","frame","defaultView","frameElement","noticeUnheardMove","scrubPageUrl","recordedPageUrl","scrubDomUrls","ev","byId","followers","nextId","scrubAddedTextRuns","change","attrs","localName","namespaceURI","styleTexts","sheet","replaceSync","fontSource","acceptsNetwork","prepared","mintSessionNonce","getRandomValues","currentOrigin","CaptureIdentityBuilder","captureId","nonce","t0WallMs","origins","build","identity","sessionNonce","appOrigins","declineLogged","KeployCapture","_KeployCapture","static","recorder","transport","transportConfig","endCapture","continuous","endSession","instance","paused","nextSessionPaused","cancelNextSession","begin","byInput","ending","restartPending","getInstance","getCaptureIdentity","builder","refuse","honorPrivacySignals","globalPrivacyControl","doNotTrack","msDoNotTrack","privacySignal","decline","handleEvent","opening","networkCapture","netEvent","declined","info","live","stopCollecting","Ke","H","it","fe","He","$i","st","et","Fe","Me","te","St","fl","ul","Os","bt","ee","de","tt","Rn","Bi","Ds","O","Sn","Ui","An"],"mappings":"AAwCA,IAAMA,EACJ,4PASK,SAASC,EAAQC,GACtB,OAAOA,EAAEC,SAAS,KAAOD,EAAEE,QAAQJ,EAAUK,GAAMC,mBAAmBD,IAAMH,CAC9E,CAOA,IAAMK,EAAwC,IAAIC,IAAI,CACpD,WACA,SACA,MACA,SACA,QACA,cACA,eACA,UACA,gBACA,OACA,SACA,eACA,aACA,UACA,YACA,SACA,MACA,uBACA,aACA,aACA,MACA,MACA,MACA,aAIA,QACA,QACA,cACA,QACA,eAOA,SACA,aAEA,YACA,qBAIA,eACA,aACA,YACA,cAIA,QACA,OACA,YACA,YACA,YACA,gBAEA,MAOA,MACA,SACA,OACA,OACA,SACA,iBACA,cACA,OACA,UACA,UACA,YACA,YACA,YACA,aACA,aACA,kBACA,eACA,aACA,eACA,gBACA,kBAGA,kBACA,oBAYWC,EAA6C,IAAID,IAAI,CAChE,aACA,iBACA,WACA,oBACA,mBACA,aACA,mBACA,cACA,YACA,UACA,UACA,UACA,WACA,gBACA,UACA,YACA,WACA,UACA,aAIIE,EAAyC,IAAIF,IAAI,CACrD,aACA,iBACA,iBACA,qBACA,UACA,cACA,eACA,cAC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,IAAM6vC,EAAcwG,EAAcU,kBAClCV,EAAcW,oBACdX,EAAcU,mBAAoB,EACH,OAA3BV,EAAcQ,UAClBR,EAAcY,MAAM56C,EAAMwzC,GAAa,GAAM9f,MAAO9C,IAGlDsE,QAAQF,KACN,uDACApE,MAIAgC,EAAU,CAAEC,SAAS,EAAMC,SAAS,GAC1CgG,SAASvG,iBAAiB,cAAe5uB,EAAOivB,GAChDkG,SAASvG,iBAAiB,UAAW5uB,EAAOivB,GAG5C,IAAMqpB,EFySD3L,GAAa,QExSlB0J,EAAce,gBAAiB,EAC/Bf,EAAcW,kBAAoB,KAChCsB,IACAnjB,SAAS5F,oBAAoB,cAAevvB,EAAOivB,GACnDkG,SAAS5F,oBAAoB,UAAWvvB,EAAOivB,GAC/ConB,EAAce,gBAAiB,EAC/Bf,EAAcW,kBAAoB,OAEtC,CAaQ,KAAA1F,GACN/8B,KAAKgiC,SAASjF,QACd/8B,KAAKyjB,QAAQoE,WACf,CAEQ,MAAAmV,GACNh9B,KAAKgiC,SAAShF,QAChB,UACFgH,sBAAAC,mBAAAC,6BAAAC,yBAAAC,sBAAAC,oBAAAC,4BAAAC,yBAAAC,sBAAAC,oBAAAC,0BAAAC,iBAAAC,mBAAAC,4BAAAC,yBAAAC,sBAAAC,uBAAAC,8BAAAC,gBAAAC,oBAAAC,oBAAAC,2BAAAC,oBAAAC,uBAAAC,uBAAAC","sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n//\n// This file alone of @keploy/contract is Apache-2.0, not the package's\n// distribution licence: @keploy/capture-sdk (Apache-2.0) inlines it into\n// its bundle, which runs in every customer's browser. packages/contract/\n// README.md carries the same carve-out, and tools/check-release-ready.mjs\n// refuses an SDK bundle that inlines a source not under a permissive\n// licence (tools/release-sources.mjs).\n\n/**\n * ONE RULE FOR A CREDENTIAL'S NAME, for every place a name is read: a\n * JSON body's key, a form's and a multipart body's field, a `name=value`\n * pair in an HTML, XML, RSC or text body, a query parameter of a request's\n * URL, of a link held in a body, of the page's own URL and of every URL\n * the DOM holds, and of a URL the replay runtime's mock-contract report\n * prints into a CI log.\n *\n * It was six rules in two packages: the SDK's body-key rule, its form\n * rule, its URL rule and its page rule, and the runtime's report list,\n * each with names the others lacked. `?jwt=` was scrubbed from a page's\n * URL and kept in a request's; `{\"email_otp\":\"482913\"}` was kept in a body\n * whose URL scrubbed `?sms_otp=`; a paging cursor was kept in a URL and\n * redacted in the response that handed it out, so a replayed page asked\n * for `?pageToken=%5BREDACTED%5D` and matched nothing; a request a replay\n * missed was printed into the customer's CI log with an `auth_token` in\n * clear (found in review). privacy-names.test.ts holds this rule's table;\n * each consumer's own test holds what it records to it.\n *\n * NO IMPORTS. @keploy/capture-sdk, whose only runtime dependency is\n * rrweb, and @keploy/replay-runtime, whose dist/test.mjs may import only\n * Node builtins, both bundle this module inline; it must pull in nothing.\n */\n\n/**\n * One code point percent-encoded as UTF-8, overlong forms and surrogates\n * excluded: exactly the escape sequences decodeURIComponent decodes, so\n * only those are handed to it and a crafted name costs no exceptions --\n * 15,000 names of `%` threw on every one, 2 s a URL once the parameters\n * were no longer capped (MEASURED).\n */\nconst ESCAPED =\n /%[0-7][\\da-f]|%(?:c[2-9a-f]|d[\\da-f])%[89ab][\\da-f]|%e0%[ab][\\da-f]%[89ab][\\da-f]|%e[1-9a-ce-f](?:%[89ab][\\da-f]){2}|%ed%[89][\\da-f]%[89ab][\\da-f]|%f0%[9ab][\\da-f](?:%[89ab][\\da-f]){2}|%f[1-3](?:%[89ab][\\da-f]){3}|%f4%8[\\da-f](?:%[89ab][\\da-f]){2}/gi;\n\n/**\n * `v` with every escape sequence that spells one code point decoded, as\n * decodeURIComponent decodes it, and every other byte as written: escape\n * by escape, not all or nothing. All or nothing, a string with one\n * malformed escape decoded none, so a text could not be decoded piece by\n * piece (found in review).\n */\nexport function decoded(v: string): string {\n return v.includes(\"%\") ? v.replace(ESCAPED, (e) => decodeURIComponent(e)) : v;\n}\n\n/**\n * The names a credential, a secret or a card's data goes by, read whole\n * (nameParts): what a JSON key, a form field and a query parameter are\n * all redacted under.\n */\nconst CREDENTIAL_NAMES: ReadonlySet<string> = new Set([\n \"password\",\n \"passwd\",\n \"pwd\",\n \"secret\",\n \"token\",\n \"accesstoken\",\n \"refreshtoken\",\n \"idtoken\",\n \"authorization\",\n \"auth\",\n \"apikey\",\n \"clientsecret\",\n \"privatekey\",\n \"session\",\n \"sessionid\",\n \"cookie\",\n \"ssn\",\n \"socialsecuritynumber\",\n \"creditcard\",\n \"cardnumber\",\n \"cvv\",\n \"cvc\",\n \"pin\",\n \"passphrase\",\n // WordPress's new-password pair, Drupal's current-password field,\n // WordPress's reset key, and the PKCE secret an OAuth\n // authorization-code exchange carries.\n \"pass1\",\n \"pass2\",\n \"currentpass\",\n \"rpkey\",\n \"codeverifier\",\n // A freshly minted secret as Keploy's api-server returns it: the\n // createUIIngestKey / createServiceAccountKey / createPersonalAccessToken\n // / createAppCIToken results carry the raw key as `rawKey` (beside a\n // `token` that is only its metadata), and a saved test-run credential\n // is an `APIKeyAuth {Key, Value}`, whose secret is the generic `Value`.\n // The SDK's dashboard-shapes.test.ts holds api-server's schema to this.\n \"rawkey\",\n \"apikeyauth\",\n // Header names a pair can carry.\n \"setcookie\",\n \"proxyauthorization\",\n // SAML's response, WordPress's confirmation key, Supabase's token hash\n // and Clerk's ticket: named here rather than by a `hash` or `ticket`\n // suffix, which would take an app's own `commitHash` or `supportTicket`.\n \"samlresponse\",\n \"confirmkey\",\n \"tokenhash\",\n \"clerkticket\",\n // The names a verification, reset or sign-in link carries its secret\n // under: a nonce, an HMAC, a login hash, a magic link, PHP's session\n // cookie and OAuth 1.0a's verifier.\n \"nonce\",\n \"hmac\",\n \"loginhash\",\n \"magiclink\",\n \"phpsessid\",\n \"oauthverifier\",\n // Azure's SAS signature.\n \"sig\",\n // The names a header carries a credential under, read here too since a\n // request's URL, a form and a body carry them as often: a session id\n // (`sid`, PHP's `sessid`), an anti-forgery token, a bearer, an\n // assertion an OAuth client or a SAML response signs, and the keys and\n // codes a vendor names by their kind (Azure's `subscription-key` is\n // accepted in a query string).\n \"sid\",\n \"sessid\",\n \"csrf\",\n \"xsrf\",\n \"bearer\",\n \"authentication\",\n \"credentials\",\n \"pass\",\n \"tokenid\",\n \"authkey\",\n \"secretkey\",\n \"accesskey\",\n \"clientkey\",\n \"signingkey\",\n \"sessionkey\",\n \"subscriptionkey\",\n \"functionskey\",\n \"factorcode\",\n \"jwtassertion\",\n \"samlassertion\",\n \"clientassertion\",\n // A cloud's temporary credentials as its SDK returns them: AWS STS's\n // `SecretAccessKey` and Alibaba Cloud's `AccessKeySecret`.\n \"secretaccesskey\",\n \"accesskeysecret\",\n]);\n\n/**\n * The names a one-time code goes by: a credential under these names and no\n * other. A bare `code` is not one (`?code=US`, a promo code), and neither\n * is a `zip_code`, a `country_code` or an `error_code`. `oobcode` is\n * Firebase's email-action link code; `linkcode` is SuperTokens' magic link\n * code, read from the page's fragment and posted as `linkCode`. `otp` and\n * `totp` end in `otp`, and CREDENTIAL_SUFFIX reads them with every other\n * name that does (`email_otp`, `sms_otp`).\n */\nexport const CREDENTIAL_CODE_NAMES: ReadonlySet<string> = new Set([\n \"invitecode\",\n \"invitationcode\",\n \"authcode\",\n \"authorizationcode\",\n \"verificationcode\",\n \"verifycode\",\n \"confirmationcode\",\n \"confirmcode\",\n \"resetcode\",\n \"mfacode\",\n \"smscode\",\n \"otpcode\",\n \"totpcode\",\n \"twofactorcode\",\n \"2facode\",\n \"logincode\",\n \"passcode\",\n \"oobcode\",\n \"linkcode\",\n]);\n\n/** A card's expiry by a name that can only be a card's (Stripe's exp_month, ...): cardholder data to PCI. */\nconst CARD_EXPIRY_NAMES: ReadonlySet<string> = new Set([\n \"cardexpiry\",\n \"cardexpiration\",\n \"cardexpirydate\",\n \"cardexpirationdate\",\n \"cardexp\",\n \"cardexpdate\",\n \"cardexpmonth\",\n \"cardexpyear\",\n \"ccexp\",\n \"ccexpiry\",\n \"ccexpiration\",\n \"ccexpdate\",\n \"ccexpmonth\",\n \"ccexpyear\",\n \"creditcardexpiry\",\n \"creditcardexpiration\",\n \"expmonth\",\n \"expyear\",\n \"expirymonth\",\n \"expiryyear\",\n \"expirationmonth\",\n \"expirationyear\",\n]);\n\n/**\n * A name that ends in a credential word: `userPassword`, `x-api-key`,\n * `authToken`, Magic's `magic_credential`, an `x_signature` (S3's\n * `X-Amz-Signature`), an `id_jwt`, an `email_otp`, a `JSESSIONID`. The\n * confirmation fields every sign-up form carries (Rails/Laravel\n * `password_confirmation`, Django `password1`/`password2`) end in a word\n * after `password`; a boolean such as `passwordlessEnabled` does not, and\n * keeps its value. A recorded curl command (api-server's LoginCurl.Curl)\n * carries its Authorization header and its form body: redacted whole.\n */\nconst CREDENTIAL_SUFFIX =\n /(?:password(?:\\d|confirm|confirmation|new|old|repeat|again|verify|retype)?|passwd|secret|token|apikey|privatekey|passphrase|signature|sessionid|jwt|otp|credential|curl)$/;\n\n/**\n * A paging cursor: a name ending in `token` that is no credential but the\n * page of results a request asks for -- a page's to request again, and\n * part of what the request is. A response's `nextPageToken` redacted made\n * a replayed page ask for `?pageToken=%5BREDACTED%5D`, which nothing\n * recorded answers (found in review). Kept under every kind of name.\n */\nexport const PAGING_CURSORS: ReadonlySet<string> = new Set([\n \"pagetoken\",\n \"nextpagetoken\",\n \"prevpagetoken\",\n \"previouspagetoken\",\n \"pagingtoken\",\n \"paginationtoken\",\n \"nexttoken\",\n \"prevtoken\",\n \"previoustoken\",\n \"continuationtoken\",\n \"nextcontinuationtoken\",\n \"cursortoken\",\n \"synctoken\",\n \"nextsynctoken\",\n \"startingtoken\",\n \"starttoken\",\n \"skiptoken\",\n \"deltatoken\",\n \"resumptiontoken\",\n \"scrolltoken\",\n \"aftertoken\",\n \"beforetoken\",\n]);\n\n/**\n * Credential names a page's own URL, and every URL its DOM holds, use as\n * an app's parameter as often -- `?auth=1`, a talk's `?session=`, a map's\n * `?pin=`, a `?sig=` -- and keep by name there, as #36's tests require:\n * the recorded page must be the page visited, and those URLs scrub a\n * value of theirs that looks generated by its shape. Every other place a\n * name is read takes them for the credentials they are.\n */\nexport const PAGE_OWN_NAMES: ReadonlySet<string> = new Set([\n \"auth\",\n \"session\",\n \"cookie\",\n \"pin\",\n \"sig\",\n]);\n\n/**\n * Where a name is read, which decides two things and nothing else:\n * - `key`: a JSON body's key, a HAR-style pair's name, a header's name.\n * Read without splitting at `.`: a dotted JSON key is a flat key\n * (`\"auth.login.title\"` in a translation bundle, `\"token.ttl\"` in a\n * config), and a credential key redacts its whole value, a flag\n * included -- `{\"auth.enabled\":true}` would become a string.\n * - `param`: a form's or a multipart body's field, a text body's\n * `name=value` pair, a query parameter of a request's URL, of a link\n * held in a body or of a URL the runtime's report prints. Read at\n * each `.` part too, as Spring's binder and `qs` with `allowDots`\n * read `user.password`.\n * - `page`: a query parameter of the page's own URL or of a URL the DOM\n * holds, read as `param` is, less PAGE_OWN_NAMES.\n */\nexport type NameKind = \"key\" | \"param\" | \"page\";\n\n/**\n * Every part a name is read under: percent-decoded escape by escape, each\n * `[...]` part (`user[password]`) and, but for a `key`, each `.` part, and\n * each part lower-cased without `-`, `_`, `$` (OData's `$skiptoken`), `+`\n * (a space in a query or a form: `api+key`) and whitespace.\n */\nexport function nameParts(raw: string, kind: NameKind): string[] {\n return decoded(raw)\n .split(kind === \"key\" ? /[[\\]]+/ : /[[\\].]+/)\n .map((n) => n.toLowerCase().replace(/[-_$+\\s]/g, \"\"))\n .filter((n) => n !== \"\");\n}\n\n/** Whether one part of a name, as nameParts reads it, is a credential's. */\nexport function isCredentialPart(part: string, kind: NameKind): boolean {\n if (PAGING_CURSORS.has(part)) return false;\n if (kind === \"page\" && PAGE_OWN_NAMES.has(part)) return false;\n return (\n CREDENTIAL_NAMES.has(part) ||\n CREDENTIAL_CODE_NAMES.has(part) ||\n CARD_EXPIRY_NAMES.has(part) ||\n CREDENTIAL_SUFFIX.test(part)\n );\n}\n\n/**\n * THE RULE: whether a name, as written, is a credential's -- any of its\n * parts (nameParts) is one (isCredentialPart), or, for a name of more\n * than one part, the parts read as one word: `session[id]` is a\n * `sessionid` and `api[key]` an `apikey`, though neither part is a\n * credential's alone (found in review: a token under `?session[id]=` was\n * recorded once brackets were read as parts).\n */\nexport function isCredentialName(raw: string, kind: NameKind): boolean {\n return isCredentialParts(nameParts(raw, kind), kind);\n}\n\n/**\n * THE RULE over a name already split (nameParts): any part is a\n * credential's, or the parts read as one word. What a reader that holds a\n * name's parts asks -- the page's own pair read and its secret collection\n * read a name per part, and `?api[key]=` taught the page-wide scrub no\n * value (found in review).\n */\nexport function isCredentialParts(\n parts: readonly string[],\n kind: NameKind,\n): boolean {\n return (\n parts.some((part) => isCredentialPart(part, kind)) ||\n (parts.length > 1 && isCredentialPart(parts.join(\"\"), kind))\n );\n}\n\n/* ------------------------------------------------------------------ */\n/* ONE URL SCRUBBER */\n/* ------------------------------------------------------------------ */\n/*\n * Every URL the SDK records, and every URL and key the replay runtime\n * prints into a CI log or attaches as evidence, is scrubbed by this\n * walker: a request's URL and every URL its request and response headers\n * carry (Location, Content-Location, Link and Refresh as a request's URL\n * is, any other by a credential's name), a URL anywhere in a request's or a\n * response's body (a JSON string that is one or holds one, an HTML, XML,\n * RSC or text body, a form's or a multipart part's value), the page's own\n * URL and every URL the DOM holds. It was five scrubbers, and only the\n * DOM's read a URL whole: a body's read a query after `?` and never a\n * fragment, a `wss:` or a custom scheme, a request's never a URL nested or\n * encoded in a value nor a path's `;jsessionid=`, and the report never a\n * fragment (found in review). What a URL is made of is read here the same\n * for every URL; what differs is passed in (UrlRules):\n *\n * - `kind`: how a name is read (isCredentialName): `param`, or `page` for\n * the page's own URL and the DOM's, which keep PAGE_OWN_NAMES.\n * - `strict`: every query and fragment-pair value replaced.\n * - `whole`: a URL the replay key reads -- a request's, and one the\n * mock-contract report prints. A pair runs from `&` to `&`, as the key\n * reads one, and a credential anywhere in it -- under a `;name=` inside\n * it, in a URL nested or encoded in its value -- replaces its whole\n * value, so the key holds `[REDACTED]`, which canonical-key.v2 matches\n * any live value against. Otherwise a `;` that a `name=` follows\n * separates pairs too, and only the credential's own value goes, a\n * nested URL scrubbed and written back encoded.\n * - `raw`: a URL a body holds, every byte the scrub does not replace\n * kept (a nested URL written back as it came).\n * - the SDK's value rules for the page's URL and the DOM's, which no\n * other URL takes: a value by its shape or a PII pattern, an OAuth\n * response's code and state, a link page's key, a page credential's\n * cut, a path's JWT or link token. A request's URL is its identity at\n * replay, and a name is what says one of its values is secret.\n */\n\n/** What a value rule is told about the pair it judges. */\nexport interface PairContext {\n /** The path the pair's query or fragment belongs to, a hash route's appended. */\n readonly path: string;\n /** Every pair of that query or fragment, as written. */\n readonly pairs: readonly string[];\n /** How many URLs the pair is nested in. */\n readonly depth: number;\n}\n\n/** How a URL is scrubbed: see the block above. */\nexport interface UrlRules {\n readonly kind: \"param\" | \"page\";\n readonly strict: boolean;\n readonly whole: boolean;\n /**\n * A nested URL written back as it came: raw when it came raw, encoded\n * when it came encoded -- a body's text, where every byte the scrub does\n * not replace is kept. Otherwise (the page's URL, the DOM's) it is\n * written back encoded.\n */\n readonly raw?: boolean;\n /**\n * A credential's own value ends at the first character ownValueEnd\n * stops at (whitespace, `,`, `;`, a quote, a `)` it does not open ...),\n * the text after it kept: a text body's line (`/api/x?token=... 200\n * OK`), a CSV row, a header's list. Otherwise -- a JSON string, a form's\n * value, every URL the page or a request holds -- it runs to the next\n * pair, a space in it the credential's own (`?password=correct horse`),\n * and fails closed (found in review). What follows it in the pair is\n * read by `tail`.\n */\n readonly spaced?: boolean;\n /**\n * In a `spaced` read, a credential's own value ends at its first\n * whitespace alone, and a pair's is replaced even when empty (a path\n * parameter's empty value is kept, as always): a form body's URLs,\n * whose values the form read then takes to the next `&`. Cut at a\n * `,`, a form value's URL was left with a tail that read took for the\n * credential's, and the whole value went (found in review).\n */\n readonly form?: boolean;\n /** The text a credential's own value leaves after it in a pair (`spaced`), read: it can hold a list's next URL. */\n readonly tail?: (text: string) => string;\n /** In a text, a `,` before a URL with a scheme and an authority ends the URL before it (NEXT_URL). */\n readonly list?: boolean;\n /** A pair's replacement value, decided before its name is read, or null. */\n readonly before?: (\n name: string,\n raw: string,\n ctx: PairContext,\n ) => string | null;\n /** Whether a pair's value goes by what it is (its shape, a PII pattern), its name aside. */\n readonly value?: (name: string, raw: string, decoded: string) => boolean;\n /** Whether a bare name (`?<token>`, no `=`) goes, by its shape. */\n readonly bare?: (raw: string) => boolean;\n /** Whether a path segment goes whole, its `;` parameters with it (a JWT). */\n readonly segment?: (segment: string) => boolean;\n /** Whether a path segment's head, its `;` parameters aside, goes (a link's token). */\n readonly head?: (\n path: string,\n base: string,\n index: number,\n bases: readonly string[],\n ) => boolean;\n}\n\n/**\n * Where a query's pair ends and the next starts, outside `whole`: at a\n * `&`, and at a `;` that a `name=` follows -- many servers read\n * `?a=1;token=...` as two pairs. A `;` inside a value (`?q=ada;lovelace`,\n * `?ids=1;2;3`) is the value's: split at every `;`, strict recorded\n * `q=[REDACTED];lovelace`, the rest of what was typed, as a bare name\n * (found in review). Split by it, a query holds its separators at odd\n * indexes. An Android intent's closing `;end` is no value's either:\n * `#Intent;S.token=...;end` lost it with the credential, and the intent\n * no longer parsed (found in review).\n */\nexport const PAIR_SEPARATOR = /(&|;(?=[^;&=#]+=|end$))/;\n\n/**\n * The names one `&` pair carries, as written: its own and each a `;`\n * inside it starts (PAIR_SEPARATOR) -- what `whole` reads a pair by.\n */\nexport function pairNames(pair: string): string[] {\n const names: string[] = [];\n const pieces = pair.split(PAIR_SEPARATOR);\n for (let i = 0; i < pieces.length; i += 2) {\n const eq = pieces[i]!.indexOf(\"=\");\n if (eq > 0) names.push(pieces[i]!.slice(0, eq));\n }\n return names;\n}\n\n/**\n * A query part decoded as a form decodes it, or as it came when an escape\n * is malformed: checked first, because a thrown URIError per pair cost a\n * 256 KB URL of `a=%&` pairs 267 ms on every full snapshot.\n */\nexport function decodePart(raw: string): string {\n const plus = raw.replace(/\\+/g, \" \");\n if (!/%/.test(plus)) return plus;\n if (/%(?![0-9A-Fa-f]{2})/.test(plus)) return raw;\n try {\n return decodeURIComponent(plus);\n } catch {\n return raw;\n }\n}\n\n/**\n * One level of nesting: a URL inside a URL is scrubbed; a URL inside that\n * which carries a query or a fragment of its own (NESTED_QUERY), or pairs\n * of its own (NESTED_PAIRS), is replaced whole, unread -- fail-closed,\n * and a crafted link cannot nest without end.\n */\nexport const MAX_NESTING = 1;\n\n/** A URL value with a query or a fragment after its path. */\nconst NESTED_QUERY = /^(?:[a-z][a-z0-9+.-]*:\\/\\/|\\/)[^?#]*[?#]./i;\n\n/**\n * A value that is no URL but holds a URL's pairs: a query after a second\n * `?` (`?a=1?token=...`), or pairs a `&` or `;` separated before they\n * were encoded (`?a=1%26token%3D...`).\n */\nconst NESTED_PAIRS = /[&;?#][^&;=?#]+=/;\n\n/**\n * A value that is itself a URL -- `?next=https://...`, `?redirect=/welcome?token=...`\n * -- or holds a URL's pairs, scrubbed one level down; null when it is\n * neither.\n */\nfunction scrubNestedUrl(\n value: string,\n rules: UrlRules,\n depth: number,\n): string | null {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value))\n return scrubAbsolute(value, rules, depth + 1);\n if (value.startsWith(\"/\")) return scrubRelative(value, rules, depth + 1);\n if (NESTED_PAIRS.test(value))\n return /[?#]/.test(value)\n ? scrubRelative(value, rules, depth + 1)\n : scrubPairs(value, rules, depth + 1);\n return null;\n}\n\n/**\n * A relative URL -- a path, `?query`, `#fragment`, or `//host/...` --\n * scrubbed as an absolute one is, without a base to parse it against:\n * its path, query and fragment found by their delimiters. Returned as it\n * came when nothing in it is scrubbed.\n */\nfunction scrubRelative(value: string, rules: UrlRules, depth: number): string {\n const hashAt = value.indexOf(\"#\");\n const beforeHash = hashAt === -1 ? value : value.slice(0, hashAt);\n const q = beforeHash.indexOf(\"?\");\n const path = q === -1 ? beforeHash : beforeHash.slice(0, q);\n const query = q === -1 ? null : beforeHash.slice(q + 1);\n const fragment = hashAt === -1 ? null : value.slice(hashAt + 1);\n const out =\n scrubPath(path, rules) +\n (query === null ? \"\" : `?${scrubPairs(query, rules, depth, path)}`) +\n (fragment === null\n ? \"\"\n : `#${scrubFragment(fragment, rules, depth, path)}`);\n return out === value ? value : out;\n}\n\n/**\n * Where a credential's own value in a text ends: at whitespace, `,`, `;`,\n * a quote, `<`, `>`, a backslash, a backtick, or a `)`, `]` or `}` it\n * does not open -- `?sig=(abc)` is one value. Ended at whitespace alone, a\n * CSV row's later columns, a `;rest` and CSS's `);color:red}` went with\n * the credential (found in review). In a form (`form`), at whitespace\n * alone.\n */\nfunction ownValueEnd(raw: string, form = false): number {\n if (form) {\n const at = raw.search(/\\s/);\n return at === -1 ? raw.length : at;\n }\n let parens = 0;\n let squares = 0;\n let braces = 0;\n for (let i = 0; i < raw.length; i++) {\n const c = raw[i]!;\n if (/[\\s,;\"'<>\\\\`]/.test(c)) return i;\n if (c === \"(\") parens++;\n else if (c === \"[\") squares++;\n else if (c === \"{\") braces++;\n else if (c === \")\" && parens-- === 0) return i;\n else if (c === \"]\" && squares-- === 0) return i;\n else if (c === \"}\" && braces-- === 0) return i;\n }\n return raw.length;\n}\n\n/** Whether a value, decoded as often as it was encoded (up to four times), names a credential under any of its pairs. */\nexport function holdsCredentialName(value: string, kind: NameKind): boolean {\n // Escape by escape (decoded): all or nothing, one malformed escape\n // (`%25zz`, a lone `%E0`) left every other escape unread and the\n // credential's name with it (found in review).\n let text = value;\n for (let k = 0; k < 4; k++) {\n const next = decoded(text);\n if (next === text) break;\n text = next;\n }\n // A pair's lead, never a path's `/`: a `/name=` segment is a path's\n // (`/dl/api_key=foo bar.txt`), which no read judges (found in review: a\n // file's name went whole).\n for (const m of text.matchAll(/(?:^|[?&;#])([^?&;#=/\\s]+)=/g))\n if (isCredentialName(m[1]!, kind)) return true;\n return false;\n}\n\n/** A query's (or a fragment's) pairs, each scrubbed; its separators kept as they came. */\nfunction scrubPairs(\n query: string,\n rules: UrlRules,\n depth = 0,\n path = \"\",\n): string {\n // Outside `whole`, a `;` separates pairs too, as many servers read one\n // (`?a=1;token=...`), where a `name=` follows it; inside a value\n // (`?q=ada;lovelace`) it is the value's (PAIR_SEPARATOR). The separators\n // are kept as they came.\n const parts = query.split(rules.whole ? /(&)/ : PAIR_SEPARATOR);\n const pairs = parts.filter((_, i) => i % 2 === 0);\n const ctx: PairContext = { path, pairs, depth };\n return pairs\n .map((pair) => {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) {\n return rules.bare?.(pair) === true ? \"[REDACTED]\" : pair;\n }\n const name = pair.slice(0, eq);\n const raw = pair.slice(eq + 1);\n if (raw === \"\") return pair;\n const value = decodePart(raw);\n // Replaced whole: a value that holds a credential somewhere in it\n // (a deep URL, one encoded twice or in part) can hold it after a\n // space as well as before (found in review: it was kept in clear).\n const gone = (): string => `${name}=[REDACTED]`;\n const before = rules.before?.(name, raw, ctx) ?? null;\n if (before !== null) return `${name}=${before}`;\n if (\n rules.strict ||\n (rules.whole ? pairNames(pair) : [name]).some((n) =>\n isCredentialName(n, rules.kind),\n ) ||\n rules.value?.(name, raw, value) === true\n ) {\n if (rules.spaced !== true) return gone();\n // In a text an own value that is empty is an empty value, kept, as\n // a path parameter's is (`?sig=,1`), and what follows it is read\n // all the same (`?token=,https://b/...`, found in review); a\n // form's is replaced, as it always was.\n const own = ownValueEnd(raw, rules.form);\n const rest = raw.slice(own);\n return `${name}=${own === 0 && !rules.form ? \"\" : \"[REDACTED]\"}${rules.tail?.(rest) ?? rest}`;\n }\n if (\n depth >= MAX_NESTING &&\n (NESTED_QUERY.test(value) || NESTED_PAIRS.test(value))\n )\n // Past one level the page's URL and the DOM's replace such a value\n // unread: no key is computed from them. A request's URL, the\n // report's and a body's -- a link the page requests next -- lose\n // it only for a credential's name in it, at any depth: replaced\n // unread, a value with none changed the request's key, or the\n // link's, which then no recorded request matched (found in review).\n return rules.kind === \"page\" || holdsCredentialName(value, rules.kind)\n ? gone()\n : pair;\n const inner = scrubNestedUrl(value, rules, depth);\n if (inner !== null && inner !== value) {\n // A request's key reads the pair whole: a value redacted in part\n // is one no key matches a live one against.\n if (rules.whole) return gone();\n if (rules.raw !== true) return `${name}=${encodeURIComponent(inner)}`;\n // A body's bytes are the server's: a nested URL is written back as\n // it came -- raw, or encoded as encodeURIComponent encodes it --\n // and one encoded any other way (`/reset%3Ftoken=...`) cannot be,\n // so its value goes whole (found in review: it was re-encoded).\n if (raw === value) return `${name}=${inner}`;\n return encodeURIComponent(value) === raw\n ? `${name}=${encodeURIComponent(inner)}`\n : gone();\n }\n // A value encoded more than once -- a redirect chain's hop,\n // `?redirect=https%253A%252F%252F...%253Fjwt%253D...`, or a path whose\n // `?` is still encoded once decoded, `?next=%2Freset%253Ftoken%253D...`\n // -- holds a URL no read above sees, though the nested read found a\n // URL in it: its whole value goes when a credential's name is in it,\n // decoded as often as it was encoded (found in review: one the nested\n // read returned unchanged was kept).\n if (decoded(value) !== value && holdsCredentialName(value, rules.kind))\n return gone();\n return pair;\n })\n .map((pair, i) => (i === 0 ? \"\" : parts[2 * i - 1]) + pair)\n .join(\"\");\n}\n\n/**\n * A path: a segment the rules take whole (a JWT) is replaced, a `;name=`\n * path parameter (Java's `;jsessionid=`) has a credential's value\n * replaced, and a segment's head the rules name (a link's token) is\n * replaced. Nothing else in a\n * path is judged: slugs, digests and file names are where a flow's pages\n * come from.\n */\nfunction scrubPath(path: string, rules: UrlRules): string {\n const segments = path.split(\"/\");\n const bases = segments.map((seg) => seg.split(\";\")[0]!);\n return segments\n .map((seg, i) => {\n if (rules.segment?.(seg) === true) return \"[REDACTED]\";\n const semi = seg.indexOf(\";\");\n const base = bases[i]!;\n const head =\n rules.head?.(path, base, i, bases) === true ? \"[REDACTED]\" : base;\n if (semi === -1) return head;\n return (\n head +\n seg.slice(semi).replace(\n /;([^;=]+)=([^;]*)/g,\n // An empty value is kept, as a query's is: there is nothing to\n // redact, and `\"/x;jsessionid=\" + id` in a script is code that\n // builds one (found in review: it became `=[REDACTED]\" + id`).\n // In a text, the value is its own only (ownValueEnd).\n (m: string, n: string, v: string) => {\n const own =\n rules.spaced === true ? ownValueEnd(v, rules.form) : v.length;\n return own > 0 && isCredentialName(n, rules.kind)\n ? `;${n}=[REDACTED]${v.slice(own)}`\n : m;\n },\n )\n );\n })\n .join(\"/\");\n}\n\n/**\n * A fragment: a hash router's route keeps its path and has its own query\n * scrubbed -- `#/cb?code=...`, and `#/cb&access_token=...`, whose pairs\n * start after the route's first `&` or `;`; a fragment of pairs -- an\n * OAuth implicit grant's `#access_token=...&state=...` -- is scrubbed as a\n * query is. Anything else is read as a path, where no `name=` segment is\n * judged (`#/docs/v=2`, `#!/access_token=...` alike).\n */\nfunction scrubFragment(\n fragment: string,\n rules: UrlRules,\n depth: number,\n path = \"\",\n): string {\n // `depth` rides through, or every `#n=<url>` started the nesting count\n // again and a crafted link recursed until the stack overflowed (review).\n const q = fragment.indexOf(\"?\");\n if (q !== -1) {\n const route = fragment.slice(0, q);\n return `${scrubPath(route, rules)}?${scrubPairs(fragment.slice(q + 1), rules, depth, `${path}/${route}`)}`;\n }\n const eq = fragment.indexOf(\"=\");\n if (eq !== -1 && !fragment.slice(0, eq).includes(\"/\")) {\n return scrubPairs(fragment, rules, depth, path);\n }\n // A route whose pairs follow a `&` or a `;`: `#/cb&access_token=...`,\n // `#/cb/v=1&access_token=...` (an `=` in the route before them, found in\n // review). One with an `=` in its path and no such separator is a route\n // alone (`#/docs/v=2`), as #36's tests require.\n const route = eq === -1 ? null : /^([^&;]*)([&;])/.exec(fragment);\n if (route !== null)\n return `${scrubPath(route[1]!, rules)}${route[2]}${scrubPairs(fragment.slice(route[0].length), rules, depth, `${path}/${route[1]}`)}`;\n return scrubPath(fragment, rules);\n}\n\n/**\n * An absolute URL. The page's URL and the DOM's, with an authority\n * (`https:`, `wss:`, `myapp://`), are parsed as the browser parses them\n * and rebuilt from their parts only when something in them is scrubbed:\n * user info dropped, scheme and host kept as the parser serialises them.\n * Every other URL is spliced (spliceAbsolute). Returned as it came when\n * nothing in it is scrubbed.\n */\nfunction scrubAbsolute(raw: string, rules: UrlRules, depth: number): string {\n // A URL the page's URL rule or the DOM's reads is rebuilt as the browser\n // serialises it, as #36's tests pin. Every other URL -- a request's, one\n // a body holds, one the report prints -- keeps its bytes, and so does one\n // with no authority (`urn:`, `com.example.app:/oauth2redirect`) or one\n // the parser refuses (`https://%HOST%/x`): spliced, never returned\n // unread (found in review: each was recorded or printed as it came).\n if (rules.whole || rules.raw === true || !AUTHORITY.test(raw))\n return spliceAbsolute(raw, rules, depth);\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n return spliceAbsolute(raw, rules, depth);\n }\n const search = url.search.slice(1);\n const hash = url.hash.slice(1);\n const path = scrubPath(url.pathname, rules);\n const query = url.search\n ? scrubPairs(search, rules, depth, url.pathname)\n : \"\";\n const fragment = url.hash\n ? scrubFragment(hash, rules, depth, url.pathname)\n : \"\";\n // Nothing to scrub: the URL exactly as it came -- a trailing `?` or `#`\n // included, which a rebuild from its parts drops.\n if (\n path === url.pathname &&\n query === search &&\n fragment === hash &&\n url.username === \"\" &&\n url.password === \"\"\n ) {\n return raw;\n }\n return (\n `${url.protocol}//${url.host}` +\n path +\n (url.search ? `?${query}` : \"\") +\n (url.hash ? `#${fragment}` : \"\")\n );\n}\n\n/** A scheme a browser reads an authority after: `https:`, `https:/host`, `wss://`, `myapp://`. */\nconst AUTHORITY = /^(?:https?:|[a-z][a-z0-9+.-]*:[/\\\\]{2})/i;\n\n/**\n * An absolute URL scrubbed by its delimiters, every byte the scrub does not\n * replace kept: its scheme, the authority after it (its user info\n * dropped), then its path, query and fragment (scrubRelative).\n */\nfunction spliceAbsolute(raw: string, rules: UrlRules, depth: number): string {\n const head = /^([a-z][a-z0-9+.-]*:)([/\\\\]*)([^/\\\\?#]*)/i.exec(raw)!;\n const [whole, scheme, slashes, authority] = head as unknown as [\n string,\n string,\n string,\n string,\n ];\n const at = slashes === \"\" ? -1 : authority.lastIndexOf(\"@\");\n const out =\n scheme +\n slashes +\n authority.slice(at + 1) +\n scrubRelative(raw.slice(whole.length), rules, depth);\n return out === raw ? raw : out;\n}\n\n/**\n * THE SCRUBBER: one URL as it may be recorded or printed, by `rules`. A\n * URL with a scheme is absolute (scrubAbsolute) -- `https:`, `wss:`,\n * `myapp://`, and one with no authority (`mailto:`, `urn:`,\n * `com.example.app:/oauth2redirect?code=...`) alike -- but for a script's\n * or an inline object's (`javascript:`, `vbscript:`, `data:`, `blob:`),\n * which holds no URL's parts and is kept; anything else is a relative\n * URL, read by its delimiters. Byte for byte as it came when nothing in it\n * is a credential's.\n */\nexport function scrubUrl(value: string, rules: UrlRules): string {\n const lead = value.length - value.trimStart().length;\n const trail = value.length - value.trimEnd().length;\n const url = value.slice(lead, value.length - trail);\n let out: string;\n if (/^(?:javascript|vbscript|data|blob):/i.test(url)) return value;\n if (/^[a-z][a-z0-9+.-]*:/i.test(url)) out = scrubAbsolute(url, rules, 0);\n else out = scrubRelative(url, rules, 0);\n return out === url\n ? value\n : value.slice(0, lead) + out + value.slice(value.length - trail);\n}\n\n/**\n * Where a URL starts in a text -- an HTML, XML, RSC or text body, a JSON\n * string, a form's or a multipart part's value: a scheme with an\n * authority (`https://`, `wss://`, `myapp://`), whatever comes before it\n * (`--https://...`); any value a link's attribute holds, quoted or not\n * (`href=cb#...`); a URL any other attribute holds quoted that a path, a\n * query or a fragment starts, or a scheme as a line's start takes one (a\n * `/` after it, a `.` or `+` in its name, `localhost` and its port, a\n * scheme with no authority) (`data-next=\"/x?next=...\"`, found in review: an attribute\n * off the list kept its link) -- never another quoted value, which is a style or a script's string as often\n * (`style=\"background:url(...)\"`, whose property read as a scheme took\n * the declarations after the URL, found in review), and never an\n * unquoted `name=` in a text, which is code or a pair\n * (`x=y?1:2;token=...`); a meta refresh's `url=`\n * (`content=\"0; url=/x?...\"`, read forward from `content`); and a CSS\n * `url(`. A scheme is at most 32 characters and a name 40, and a name is\n * read from its start, so a start is read at most that far: unbounded, a\n * scheme read from each position of a run of letters cost the square of\n * the run, and so did an attribute read back over a run of spaces (2 s\n * for 64 KB, found in review), and a meta refresh's read back from each\n * `url` (17 s for 256 KB of spaces, found in review). No alternative\n * reads back further than a character, and none has two runs of spaces\n * back to back: `content=` and spaces with no quote between was read\n * once for each place one run could end (found in review).\n */\nconst URL_START =\n /[a-z][a-z0-9+.-]{0,31}:[/\\\\]{2}|(?<attr>\\bcontent\\s*=\\s*(?:[\"']\\s*)?\\d[\\d.]*\\s*[;,]\\s*url\\s*=\\s*[\"']?|\\b(?:href|src|action|formaction|poster|cite|data|background|longdesc|content|data-src|data-href|xlink:href)\\s*=\\s*[\"']?|(?<![\\w:.-])[\\w:.-]{1,40}\\s*=\\s*[\"'](?=\\.{0,2}\\/|[?#]|[a-z][a-z0-9+.-]{0,31}:\\/|[a-z][a-z0-9-]{0,30}[+.][a-z0-9+.-]{0,30}:|localhost:\\d{1,5}[/?#]|(?:mailto|tel|sms|urn|data|javascript|vbscript|blob|about|xmpp|sip|sips|magnet|intent|bitcoin|geo|market|news):)|\\burl\\(\\s*[\"']?)(?=[^\\s\"'<>])/gi;\n\n/** What ends a URL in a text: a space, a quote, a tag, a backslash, a backtick, a brace or a pipe. */\nconst URL_END = /[\\s\"'<>\\\\^`{|}]/;\n\n/** What prose puts after a URL that is no part of it. */\nconst URL_TRAILER = \".,;:!?\";\n\n/**\n * A URL with a scheme and an authority, at `lastIndex`. In a text read\n * for its list (UrlRules' `list`: what a credential's own value leaves\n * after it), a `,` before one ends the URL before it, so each URL of the\n * list is its own (`?token=...,https://b/y?next=...`). A list a query\n * holds elsewhere is the query's value (`?list=https://a,https://b&...`).\n */\nconst NEXT_URL = /[a-z][a-z0-9+.-]{0,31}:\\/\\//iy;\n\n/**\n * Where the URL in `text`'s [start, end) ends, what prose puts after it\n * set aside: a full stop, a comma, and a `)` or `]` at its end the URL\n * does not open -- `(see https://...)` -- but not one it does\n * (`?sig=(...)`, an IPv6 host's `http://[::1]`): stripped, a value's own\n * `)` was left after its marker (found in review). Read once from each\n * end, never as a regex from each position (the square of a run of full\n * stops). What the print sink reads a URL by: a `)` inside a printed key\n * (`?q=:)&token=...`) is the key's.\n */\nexport function urlEnd(text: string, start: number, end: number): number {\n let parens = 0;\n let brackets = 0;\n for (let i = start; i < end; i++) {\n const c = text[i];\n if (c === \"(\") parens++;\n else if (c === \")\") parens--;\n else if (c === \"[\") brackets++;\n else if (c === \"]\") brackets--;\n }\n while (end > start) {\n const c = text[end - 1]!;\n if (c === \")\") {\n if (parens >= 0) break;\n parens++;\n } else if (c === \"]\") {\n if (brackets >= 0) break;\n brackets++;\n } else if (!URL_TRAILER.includes(c)) break;\n end--;\n }\n return end;\n}\n\n/**\n * Where a URL the scan finds at `start` ends: at the first character that\n * ends a URL in a text (URL_END); outside a quoted attribute, also at the\n * first `)` or `]` it does not open -- CSS's\n * `url(https://...?sig=...);color:red`, prose's `(see https://...)` --\n * but not at one it does (`?sig=(...)`, `http://[::1]`); and before what\n * prose puts after it. Read to the next space and stripped at the end\n * only, a CSS declaration after the URL was the URL's, and a credential's\n * value took the `)` and the declarations with it (found in review). A\n * quoted attribute's value ends at its quote, its `)` its own\n * (`href=\"...?q=:)&next=...\"`). One pass forward, one back.\n */\nfunction scanEnd(\n text: string,\n start: number,\n brackets: boolean,\n list: boolean,\n): number {\n let end = start;\n let parens = 0;\n let squares = 0;\n for (; end < text.length; end++) {\n const c = text[end]!;\n if (URL_END.test(c)) break;\n if (list && c === \",\") {\n NEXT_URL.lastIndex = end + 1;\n if (NEXT_URL.test(text)) break;\n }\n if (!brackets) continue;\n if (c === \"(\") parens++;\n else if (c === \"[\") squares++;\n else if (c === \")\" || c === \"]\") {\n if ((c === \")\" ? parens : squares) === 0) break;\n if (c === \")\") parens--;\n else squares--;\n }\n }\n return urlEnd(text, start, end);\n}\n\n/** CSS's `url(` and its quote, at an attribute's value. */\nconst CSS_URL_OPEN = /url\\(\\s*[\"']?/iy;\n\n/** Every URL in `text`, as [start, end) spans, in order; in a text's `list`, a `,` before a URL ends the one before it (NEXT_URL). */\nexport function urlSpans(text: string, list = false): Array<[number, number]> {\n const spans: Array<[number, number]> = [];\n URL_START.lastIndex = 0;\n for (let m = URL_START.exec(text); m !== null; m = URL_START.exec(text)) {\n // A scheme's match is the URL's start; an attribute's or a `url(`'s\n // ends where the URL starts.\n let start = m.index + (m.groups?.[\"attr\"]?.length ?? 0);\n // An attribute's value that is CSS's `url(...)` holds the URL: read\n // from the attribute, the `url(` opened a `(` and the URL took its\n // `)` (`background=\"url(/x?next=...) no-repeat\"`, found in review).\n CSS_URL_OPEN.lastIndex = start;\n const inCssUrl =\n m.groups?.[\"attr\"] !== undefined && CSS_URL_OPEN.test(text);\n if (inCssUrl) start = CSS_URL_OPEN.lastIndex;\n // Read once, to the URL's end: read to the next space first and cut\n // at a `)` after, a run of CSS's `url(...);` was read to its end from\n // each `url(` (2.9 s for 64 KB, found in review). A quoted listed\n // attribute's value, but for a `url(` in it, ends at its quote alone.\n const attr = m.groups?.[\"attr\"] ?? \"\";\n let end = scanEnd(\n text,\n start,\n !/[\"']$/.test(attr) || /^url\\(/i.test(attr) || inCssUrl,\n list,\n );\n // A template literal's `${` starts code, not a value: read as one,\n // `https://x/cb?token=${t}` became `token=[REDACTED]{t}` (found in\n // review).\n if (text[end] === \"{\" && end > start && text[end - 1] === \"$\") end--;\n if (end > start) spans.push([start, end]);\n URL_START.lastIndex = Math.max(end, m.index + m[0].length, start + 1);\n }\n return spans;\n}\n\n/** Each URL in `text` scrubbed by `rules`, as [start, end, replacement] edits for those that changed. */\nexport function urlEdits(\n text: string,\n rules: UrlRules,\n): Array<[number, number, string]> {\n const edits: Array<[number, number, string]> = [];\n for (const [start, end] of urlSpans(text, rules.list === true)) {\n const url = text.slice(start, end);\n const out = scrubUrl(url, rules);\n if (out !== url) edits.push([start, end, out]);\n }\n return edits;\n}\n\n/**\n * A URL read as the replay key reads one (`whole`) under a `param`'s\n * names: what a request's URL and a URL the report prints are scrubbed\n * by, `strict` as asked.\n */\nexport function keyRules(strict: boolean): UrlRules {\n return { kind: \"param\", strict, whole: true };\n}\n\n/**\n * A BODY THE CAPTURE SDK RECORDED CUT, AND SAYS SO.\n *\n * The SDK redacts a body off the page's main thread, in a Web Worker\n * (@keploy/capture-sdk's body-worker.js). Where the page cannot run one\n * -- its CSP refuses the worker's script, the bundler did not emit it,\n * the platform has no Worker -- a body over the SDK's main-thread budget\n * (64 KiB) is not redacted whole on the page's thread: only its first\n * part is, and the rest is dropped. The same holds for a body still in\n * the worker when the page leaves, past what the page's last moment can\n * redact. That body is NOT the response the server sent, so the record\n * carries this note as its first line, naming how much of it is kept\n * (0 when nothing could be redacted in time) and how long it was, and\n * the redacted part follows it.\n *\n * Replay never serves such a body as if it were whole (mock-replay.v7\n * rules.cut): a test that reaches it cannot be proven by it.\n */\nexport function cutBodyNote(kept: number, total: number): string {\n return `[Body cut: ${kept} of ${total} characters kept, unverified]\\n`;\n}\n\n/** True for a body recorded with {@link cutBodyNote}'s first line. */\nexport function isCutBody(body: unknown): boolean {\n return (\n typeof body === \"string\" &&\n /^\\[Body cut: \\d+ of \\d+ characters kept, unverified\\]\\n/.test(body)\n );\n}\n\n/**\n * WHY THE CAPTURE SDK DID NOT CAPTURE A BODY: the reason line a body\n * recorded as {@link notCapturedBodyNote} carries, one per cause, and no\n * other. The SDK records a body only redacted, and the code it redacts\n * one with on the page's main thread is a chunk it asks for at init(),\n * beside rrweb.\n * - `left`: the page left, or the capture stopped, while that chunk was\n * still on its way. A moment after which nothing more is recorded\n * (pagehide, stop()'s bound) cannot wait for it.\n * - `code-failed`: the chunk could not load at all (a CSP that refuses\n * it, a 404 after a deploy, a module without its exports), so the page\n * has no code to redact a body with on its main thread for the rest of\n * its life (KUI_E_BODY_WORKER_UNAVAILABLE names the page's first\n * failed part, once).\n */\nexport const NOT_CAPTURED_WHY = {\n left: \"the page left or the capture stopped before redaction was ready\",\n \"code-failed\": \"the redaction code could not load\",\n} as const;\n\n/** A cause of a body recorded as {@link notCapturedBodyNote}. */\nexport type NotCapturedWhy = keyof typeof NOT_CAPTURED_WHY;\n\n/**\n * A BODY THE CAPTURE SDK DID NOT CAPTURE, AND SAYS WHY: these two lines\n * and nothing else, never the body in the clear. {@link cutBodyNote}\n * with nothing kept, then `[Body not captured: <why>]`, `<why>` being\n * {@link NOT_CAPTURED_WHY}'s line for its cause:\n *\n * [Body cut: 0 of N characters kept, unverified]\n * [Body not captured: the page left or the capture stopped before redaction was ready]\n *\n * [Body cut: 0 of N characters kept, unverified]\n * [Body not captured: the redaction code could not load]\n *\n * The first line is a cut note, so replay never serves it (mock-replay.v7\n * rules.cut) and a test that reaches it is unproven, as for any cut body.\n * The second, which no other body the SDK records has after its note,\n * tells it apart from a body cut at the main thread's budget, and says\n * why (isNotCapturedBody), for a dashboard or a report.\n */\nexport function notCapturedBodyNote(\n total: number,\n why: NotCapturedWhy,\n): string {\n return `${cutBodyNote(0, total)}[Body not captured: ${NOT_CAPTURED_WHY[why]}]\\n`;\n}\n\n/**\n * True for a body recorded as {@link notCapturedBodyNote}, exactly: for\n * the cause `why` when given, else for any cause it documents. A second\n * line naming no documented cause is not one.\n */\nexport function isNotCapturedBody(\n body: unknown,\n why?: NotCapturedWhy,\n): boolean {\n const said =\n typeof body === \"string\" &&\n /^\\[Body cut: 0 of \\d+ characters kept, unverified\\]\\n\\[Body not captured: ([^\\]\\n]*)\\]\\n$/.exec(\n body,\n )?.[1];\n return said\n ? why === undefined\n ? Object.values<string>(NOT_CAPTURED_WHY).includes(said)\n : said === NOT_CAPTURED_WHY[why]\n : false;\n}\n","/* ------------------------------------------------------------------ */\n/* Structural redaction */\n/* ------------------------------------------------------------------ */\n/*\n * Replaces the regex-over-the-whole-body approach, which was a\n * correctness bug rather than a privacy nit:\n *\n * - `/\\b(?:\\d[ -]*?){13,19}\\b/g` matched every 13-digit Date.now(),\n * every snowflake id and every long numeric id.\n * - Replacing inside a serialized JSON number produced INVALID JSON:\n * {\"ts\":1699999999999} became {\"ts\":[REDACTED]}, which no longer\n * parses.\n *\n * The failure mode was especially bad because it looked like a pass: the\n * corruption also destroyed the timestamp nondeterminism it had just\n * created, so a diff of two corrupted captures could still match.\n *\n * Three rules make this deterministic and type-preserving:\n * 1. Parse first. Walk the structure, never the serialization.\n * 2. Only STRING values are scanned. A JSON number is never PII in\n * practice, and scanning numbers is what corrupted timestamps.\n * 3. Redaction is type-preserving and stable: a redacted string stays\n * a string, and the same input always produces the same output, so\n * two recordings of the same logical response stay comparable.\n */\n\nimport {\n decoded,\n holdsCredentialName,\n isCredentialName,\n nameParts,\n scrubUrl,\n urlEdits,\n type UrlRules,\n} from \"@keploy/contract/privacy\";\n\nconst REDACTED = \"[REDACTED]\";\n\n/**\n * Names that are a card's expiry only beside a card field: `expiry` on\n * a token or `expirationDate` on a cookie is a date the page needs back.\n */\nconst CARD_EXPIRY_BESIDE_A_CARD: ReadonlySet<string> = new Set([\n \"expiry\",\n \"expirydate\",\n \"expiration\",\n \"expirationdate\",\n \"expdate\",\n \"exp\",\n]);\n\n/** A field that makes the object it is in a card. */\nconst CARD_FIELDS: ReadonlySet<string> = new Set([\n \"cardnumber\",\n \"creditcard\",\n \"creditcardnumber\",\n \"ccnumber\",\n \"cardnum\",\n \"pan\",\n \"cvv\",\n \"cvc\",\n]);\n\n/** Emitted for a JSON-shaped body that cannot be parsed (usually truncated). */\nexport const TRUNCATED_UNPARSEABLE = \"[UNPARSEABLE_BODY_NOT_REDACTED]\";\n\n/**\n * The notes network.ts writes in place of a body it did not read: a\n * Blob on the XHR path or one over the cap on the fetch path, a buffer\n * over the cap or one that is not UTF-8, a response whose\n * Content-Length is over it, a stream it must not consume, a shape\n * with no name, an XHR responseType it cannot read as text.\n *\n * They are the SDK's own words, not the page's data, and they carry the\n * only record of what the body WAS and how large. They are also not\n * JSON — so under a JSON content-type they went through JSON.parse,\n * failed, and were replaced with the generic refusal below, losing the\n * kind and the size. The docs page records that as a defect: \"with no\n * record of what they were or how large\".\n *\n * Matched whole, anchored, and only for shapes with no free text in\n * them, so a page body that happened to equal one of these would skip\n * redaction — and there would be nothing in it to redact, because the\n * whole body would be that fixed string.\n */\nconst NOT_RECORDED = [\n /^\\[Blob: \\d+ bytes, truncated\\]$/,\n // The XHR path's Blob, which is named rather than read: its body has\n // to be serialised inside send(), and Blob.text() is async.\n /^\\[Blob: \\d+ bytes\\]$/,\n /^\\[Binary: \\d+ bytes\\]$/,\n /^\\[Response body too large: \\d+ bytes\\]$/,\n /^\\[ReadableStream\\]$/,\n /^\\[Unreadable body\\]$/,\n // `[${xhr.responseType} response]` — the XMLHttpRequestResponseType\n // enum: \"\", arraybuffer, blob, document, json, text.\n /^\\[(?:arraybuffer|blob|document|json|text|) response\\]$/,\n];\n\n/** True for a body that IS one of the SDK's own not-recorded notes. */\nexport function isNotRecordedNote(body: string): boolean {\n return NOT_RECORDED.some((re) => re.test(body));\n}\n\n/**\n * A key as the one rule reads a name (@keploy/contract's privacy.ts\n * nameParts), its parts joined: what a rule about a key's context -- a\n * card's fields, a token exchange's -- compares, so no name is read two\n * ways.\n */\nfunction normalizeKey(key: string): string {\n return nameParts(key, \"key\").join(\"\");\n}\n\n/** A plain word, or words joined by `-` or `_`: an app's filter, not an OAuth state. */\nconst PLAIN_WORDS = /^[A-Za-z]+(?:[-_][A-Za-z]+)*$/;\n/** camelCase words: an app's `state=inProgress` (#36's review). */\nconst CAMEL_WORDS = /^[A-Za-z][a-z]+(?:[A-Z][a-z]+)+$/;\n\n/**\n * Whether a state is an app's word rather than OAuth's generated value:\n * letters, or words joined by `-` or `_`, of at most 16 characters --\n * `delivered`, `California`, `in-progress` -- or longer camelCase or\n * joined words. A random run of letters past 16 is not one (review).\n */\nexport function isPlainState(state: string): boolean {\n if (!PLAIN_WORDS.test(state)) return false;\n return (\n state.length <= 16 ||\n CAMEL_WORDS.test(state) ||\n /^[A-Za-z][a-z]+(?:[-_][A-Za-z][a-z]+)+$/.test(state)\n );\n}\n\n/** The grants a token exchange redeems a code for: an authorization code's, and a device flow's (RFC 8628). */\nconst EXCHANGE_GRANTS: ReadonlySet<string> = new Set([\n \"authorization_code\",\n \"urn:ietf:params:oauth:grant-type:device_code\",\n]);\n\n/** The names, normalized, a token exchange carries its code under. */\nconst EXCHANGE_CODES: ReadonlySet<string> = new Set([\"code\", \"devicecode\"]);\n\n/** The names, normalized, an exchange's values are redacted under: its code, and the state beside it. */\nconst EXCHANGE_REDACTED: ReadonlySet<string> = new Set([\n ...EXCHANGE_CODES,\n \"state\",\n]);\n\n/** The names, normalized, an exchange's code is sent or handed out beside. */\nconst EXCHANGE_PEERS: ReadonlySet<string> = new Set([\n \"redirecturi\",\n \"clientid\",\n \"verificationuri\",\n]);\n\n/**\n * Whether a body's names and values are an OAuth token exchange's: a\n * page that finishes an OAuth flow itself (a SPA with PKCE, a backend for\n * the frontend) posts the authorization code it was handed, and `code`\n * is no credential's name anywhere else (an app's `?code=US`, a promo\n * code); a device flow's `device_code` is its code. So a code\n * (EXCHANGE_CODES) goes only beside a grant that redeems one\n * (`grant_type=authorization_code`, the device code grant), a\n * `code_verifier`, a `redirect_uri`, `client_id` or the\n * `verification_uri` a device authorization hands out with its code, or\n * -- beside a code of 10 or more -- a generated state (isGeneratedState):\n * the authorization response itself, which a page may hand its backend.\n * Names normalized.\n */\nfunction isTokenExchange(pairs: ReadonlyArray<[string, string]>): boolean {\n let code = false;\n let peer = false;\n let longCode = false;\n let state = false;\n for (const [name, value] of pairs) {\n if (name === \"granttype\" && EXCHANGE_GRANTS.has(value.trim().toLowerCase()))\n return true;\n if (name === \"codeverifier\") return true;\n if (EXCHANGE_CODES.has(name)) {\n code = true;\n if (value.length >= 10) longCode = true;\n }\n if (EXCHANGE_PEERS.has(name)) peer = true;\n if (name === \"state\" && isGeneratedState(value)) state = true;\n }\n // A generated state beside a code of 10 or more: an authorization\n // response a page hands its backend to redeem, as the URL rule reads one.\n return code && (peer || (state && longCode));\n}\n\n/**\n * An OAuth state as a provider round-trips it: 16 characters or more of a\n * token's alphabet, letters with a digit among them or with both cases\n * (`XK3JF9QZ2LMN8PRT`, `x8Kq2Lm9Np4Rt7Vw`), and no plain word or slug of\n * words and numbers (`in_progress_step2`, `pending-approval-2024`,\n * `ORDER-2024-000123`). An app's own state -- `CA`, `WA-98101`,\n * `delivered`, a timestamp -- is not one.\n */\nfunction isGeneratedState(value: string): boolean {\n return (\n value.length >= 16 &&\n /^[A-Za-z0-9_\\-.~+/=]+$/.test(value) &&\n /[A-Za-z]/.test(value) &&\n (/\\d/.test(value) || (/[a-z]/.test(value) && /[A-Z]/.test(value))) &&\n !isPlainState(value) &&\n !isStateSlug(value)\n );\n}\n\n/**\n * A slug of words and numbers, a word's digits at its end, and one part\n * letters alone: `in_progress_step2`, `ORDER-2024-000123`. With no such\n * part it is a generated token's groups (`Xk9-Pq2-Lm7-Rt4-Zw8`). No part\n * can be read two ways: where a lone capital could, `A-A-...-A1.` took\n * twice as long for each two parts more, 31 s at 30 (MEASURED).\n */\nfunction isStateSlug(value: string): boolean {\n return (\n /^(?:[A-Z]+|[A-Z]?[a-z]+)\\d*(?:[-_](?:(?:[A-Z]+|[A-Z]?[a-z]+)\\d*|\\d+))+$/.test(\n value,\n ) && /(?:^|[-_])[A-Za-z]+(?:[-_]|$)/.test(value)\n );\n}\n\n/**\n * A one-time code's names an app's settings use too: in a JSON body a\n * string or a number under them is the code, and a flag or an object is\n * the app's (`{\"totp\":{\"enabled\":true}}`), which a replay serves back.\n */\nconst BARE_CODE_NAMES: ReadonlySet<string> = new Set([\"passcode\"]);\n\n/** A value under a one-time code's settings name that holds no code itself, but is read on: an object or a list. A flag is kept under every name (redactNode). */\nfunction isSettingsValue(node: JNode): boolean {\n return node.kind === \"object\" || node.kind === \"array\";\n}\n\n/**\n * A JSON key's, a HAR-style pair's or a header's name, read by the one\n * rule (@keploy/contract's privacy.ts isCredentialName) as a `key`.\n */\nexport function isSensitiveKey(key: string): boolean {\n return isCredentialName(key, \"key\");\n}\n\n/**\n * A one-time code's name an app's settings use too: `passcode`\n * (BARE_CODE_NAMES), or a name ending in `otp` -- `otp`, `totp`, an\n * `email_otp`, an `sms_otp`: under it an object is the app's setting\n * (`{\"totp\":{\"enabled\":true}}`), and a code is the code.\n */\nfunction isBareCodeName(key: string): boolean {\n return nameParts(key, \"key\").some(\n (n) => BARE_CODE_NAMES.has(n) || n.endsWith(\"otp\"),\n );\n}\n\n/**\n * Credential names an app's data uses as often for a list, a summary or a\n * method: `{\"credentials\":[{\"id\":1,\"provider\":\"github\"}]}`,\n * `{\"authentication\":{\"providers\":[\"google\"]}}`, a test summary's\n * `{\"pass\":12,\"fail\":3}`. Under them only a string is the credential; any\n * other value is read on, its own credentials redacted by name, so a page\n * that maps over the list is served the list (found in review).\n */\nconst WORD_NAMES: ReadonlySet<string> = new Set([\n \"credentials\",\n \"authentication\",\n \"pass\",\n]);\n\n/** Whether a JSON key is one of WORD_NAMES, read as the one rule reads a key. */\nfunction isWordName(key: string): boolean {\n return nameParts(key, \"key\").some((n) => WORD_NAMES.has(n));\n}\n\n/* ------------------------------------------------------------------ */\n/* Value-level detectors — applied ONLY to strings */\n/* ------------------------------------------------------------------ */\n\n/**\n * Email addresses, found from each `@` rather than by a regex over the\n * whole text.\n *\n * The unanchored `[a-zA-Z0-9._%+-]+@...` retried the whole run from every\n * position inside it, so a long run with no `@` -- a hex digest, a base64\n * blob, a minified bundle -- cost quadratic time ON THE PAGE'S MAIN\n * THREAD: MEASURED 1.8 s for 64K characters and minutes at the 512 KB\n * body cap (review round 1). Anchoring the regex to a run's start made it\n * linear but blind to an address glued onto the previous one\n * (`ada@x.com+bob@y.org`) or ending a long `%20` run -- both of which\n * 3.0.1 caught (review round 2). So the scan starts at each `@`: the local\n * part is the last 64 local characters before it (RFC 5321's limit), not\n * reaching back into the previous match, and the domain is a bounded\n * sticky match after it. Each `@` costs at most 64 + 253 steps: linear.\n */\nconst EMAIL_DOMAIN = /[a-zA-Z0-9.-]{1,253}\\.[a-zA-Z]{2,63}/y;\n\nfunction isEmailLocalChar(code: number): boolean {\n return (\n (code >= 48 && code <= 57) || // 0-9\n (code >= 65 && code <= 90) || // A-Z\n (code >= 97 && code <= 122) || // a-z\n code === 46 || // .\n code === 95 || // _\n code === 37 || // %\n code === 43 || // +\n code === 45 // -\n );\n}\n\n/** The range of every email address in `text`, found from each `@`. */\nfunction emailRanges(text: string, into: Range[]): void {\n let kept = 0; // no match may reach back before this index\n let at = text.indexOf(\"@\");\n while (at !== -1) {\n const floor = Math.max(kept, at - 64);\n let start = at;\n while (start > floor && isEmailLocalChar(text.charCodeAt(start - 1))) {\n start--;\n }\n if (start < at) {\n EMAIL_DOMAIN.lastIndex = at + 1;\n const domain = EMAIL_DOMAIN.exec(text);\n if (domain) {\n kept = at + 1 + domain[0].length;\n into.push([start, kept]);\n at = text.indexOf(\"@\", kept);\n continue;\n }\n }\n at = text.indexOf(\"@\", at + 1);\n }\n}\n\n/**\n * A token whose provider prefix says what it is, whatever key it sits\n * under or text it is in: Keploy's own API keys (`kep_` + 43 base64url\n * characters, api-server's models.GenerateAPIKey), GitHub, GitLab, Slack,\n * Stripe, OpenAI and Anthropic, npm, webhook signing secrets, AWS access\n * key ids (long-lived and temporary) and Google API keys. Each alternative\n * is a literal prefix and a run taken whole (a longer run leaves no tail),\n * started only after a character that is not a letter or digit -- so\n * `x-kep_...` is found and `task_live_...` is not a Stripe key: linear.\n */\nconst KNOWN_TOKEN_RE =\n /(?<![A-Za-z0-9])(?:kep_[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,}|glpat-[A-Za-z0-9_-]{20,}|xox[abprse]-[A-Za-z0-9-]{10,}|[sr]k_(?:live|test)_[A-Za-z0-9]{16,}|sk-(?:proj|ant)-[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{36,}|whsec_[A-Za-z0-9+/=]{24,}|(?:AKIA|ASIA)[0-9A-Z]{16,}|AIza[0-9A-Za-z_-]{35,})/g;\n\nconst SSN_RE = /\\b\\d{3}-\\d{2}-\\d{4}\\b/g;\n// Deliberately strict: a separator or an explicit country code is\n// required. The old \"any 7-digit run\" pattern matched order ids and is\n// what corrupted recorded URLs.\nconst PHONE_RE =\n /(?:\\+\\d{1,3}[ .-]?)?(?:\\(\\d{3}\\)[ .-]?|\\b\\d{3}[ .-])\\d{3}[ .-]\\d{4}\\b/g;\n// Starts only where the previous character is not base64url. `\\b` let a\n// match start after every `-` (a non-word character inside the alphabet),\n// so `eyJ-eyJ-...` rescanned the rest of the run from each `eyJ`:\n// MEASURED 510 ms at 64K characters on the main thread. The cost of the\n// anchor: a token glued straight onto a preceding `-` is not detected; a\n// JWT after a space, `=`, a quote or a colon -- every header, cookie,\n// query and JSON shape -- is.\nconst JWT_RE =\n /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b/g;\n// An IP address is personal data under GDPR. Unlike the card pattern this\n// one is safe: it only ever matches inside a string value, so it cannot\n// turn a JSON number into a bare token.\n// Guarded on both sides so a build/version string is not mistaken for an\n// address: \"1.2.3.4000\" and \"10.0.0.1.5\" must survive untouched.\nconst IPV4_RE =\n /(?<![\\d.])(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(?![\\d.])/g;\n\n/** Luhn check — the standard checksum every real card number satisfies. */\nfunction passesLuhn(digits: string): boolean {\n let sum = 0;\n let double = false;\n for (let i = digits.length - 1; i >= 0; i--) {\n let d = digits.charCodeAt(i) - 48;\n if (d < 0 || d > 9) return false;\n if (double) {\n d *= 2;\n if (d > 9) d -= 9;\n }\n sum += d;\n double = !double;\n }\n return sum % 10 === 0;\n}\n\n/**\n * A real card number: a known issuer prefix, a valid length for that\n * issuer, AND a passing Luhn checksum.\n *\n * All three are required on purpose. Length alone matched timestamps;\n * Luhn alone still admits ~10% of random digit runs. Together the false\n * positive rate on non-card data is negligible, and — critically — a\n * 13-digit millisecond timestamp has no valid issuer prefix.\n */\nfunction isLikelyCardNumber(digits: string): boolean {\n if (digits.length < 13 || digits.length > 19) return false;\n const isVisa =\n digits[0] === \"4\" &&\n (digits.length === 13 || digits.length === 16 || digits.length === 19);\n const isMastercard = /^(5[1-5]|2[2-7])/.test(digits) && digits.length === 16;\n const isAmex = /^3[47]/.test(digits) && digits.length === 15;\n const isDiscover = /^6(?:011|5)/.test(digits) && digits.length === 16;\n const isJcbDiners =\n /^(?:35|3[068])/.test(digits) && digits.length >= 14 && digits.length <= 19;\n if (!(isVisa || isMastercard || isAmex || isDiscover || isJcbDiners))\n return false;\n return passesLuhn(digits);\n}\n\n/** The range of every card-shaped run in `s` that is a real card number. */\nfunction cardRanges(s: string, into: Range[]): void {\n // Candidate runs of digits with optional single spaces/hyphens.\n for (const m of s.matchAll(/\\b(?:\\d[ -]?){12,18}\\d\\b/g)) {\n if (isLikelyCardNumber(m[0].replace(/[^0-9]/g, \"\"))) {\n into.push([m.index, m.index + m[0].length]);\n }\n }\n}\n\n/** Redact card-shaped runs inside a string, preserving everything else. */\nfunction redactCards(s: string): string {\n const ranges: Range[] = [];\n cardRanges(s, ranges);\n return applyRanges(s, ranges);\n}\n\n/** A half-open span of a text to redact: [start, end). */\ntype Range = [number, number] | [number, number, string];\n\n/** The range of every non-empty match of a global pattern. */\nfunction patternRanges(text: string, re: RegExp, into: Range[]): void {\n for (const m of text.matchAll(re)) {\n // An empty match hides nothing: `\\d*` matches the empty string at\n // every position, and a marker at each grew a body tenfold per pass\n // (review r7).\n if (m[0] !== \"\") into.push([m.index, m.index + m[0].length]);\n }\n}\n\n/**\n * Where every detector matches in `text`: the built-ins, then the\n * integrator's patterns (`extra`, compiled global -- see PrivacyEngine).\n *\n * EVERY DETECTOR RUNS OVER THE ORIGINAL TEXT, never over another's\n * output. The scan used to be a chain of replace() calls, each over the\n * last one's result, and both ways of letting a pattern meet a marker were\n * wrong, MEASURED: a pattern that re-scanned the markers rewrote them\n * (`/RED/` -> `[[REDACTED]ACTED]`) and grew a body tenfold per pass\n * (review r7); a pattern that ran only between markers hid only part of\n * its match -- `/Notes: .*\\/` over a phone number, a `<div class=\"notes\">`\n * pattern over an email -- and recorded the rest in clear (review r8,\n * against base 3ce8786, which redacted both). Ranges on the original text\n * have neither failure: see applyRanges.\n */\nfunction detectorRanges(\n text: string,\n extra: readonly RegExp[],\n into: Range[],\n): void {\n patternRanges(text, JWT_RE, into);\n patternRanges(text, KNOWN_TOKEN_RE, into);\n emailRanges(text, into);\n patternRanges(text, SSN_RE, into);\n patternRanges(text, PHONE_RE, into);\n patternRanges(text, IPV4_RE, into);\n cardRanges(text, into);\n for (const re of extra) patternRanges(text, re, into);\n}\n\n/**\n * `text` with every range replaced by one marker, OVERLAPPING ranges\n * merged into one: a pattern that covers a built-in's match covers it\n * whole. Ranges that only touch stay separate markers (two addresses\n * glued together are two). Nothing outside a range changes, and each\n * marker replaces at least one character -- except the one kind of empty\n * range a caller may add on purpose, a sensitive form field's empty value\n * -- so a result is at most ten times its input plus those.\n */\nfunction applyRanges(text: string, ranges: Range[]): string {\n if (ranges.length === 0) return text;\n ranges.sort((a, b) => a[0] - b[0] || b[1] - a[1]);\n let out = \"\";\n let pos = 0;\n let [start, end, with_] = ranges[0];\n for (let k = 1; k <= ranges.length; k++) {\n const next = ranges[k];\n if (next !== undefined && next[0] < end) {\n if (next[1] > end) end = next[1];\n with_ = undefined; // merged: one marker covers them all\n continue;\n }\n out += text.slice(pos, start) + (with_ ?? REDACTED);\n pos = end;\n if (next !== undefined) [start, end, with_] = next;\n }\n return out + text.slice(pos);\n}\n\n/**\n * Apply every value-level detector to one string, then every\n * caller-supplied pattern, all over the string as it came.\n *\n * `extra` is the integrator's `privacy.piiPatterns`, already compiled\n * global (see PrivacyEngine). It rides through every scan the engine\n * makes -- this function is the ONLY string scanner -- so a pattern\n * applies to a JSON string value, a text body and a header value alike.\n * It used to reach header values only, while its documentation said\n * \"matched text is replaced\".\n */\nexport function redactStringValue(\n value: string,\n extra: readonly RegExp[] = [],\n): string {\n if (!value) return value;\n const ranges: Range[] = [];\n detectorRanges(value, extra, ranges);\n return applyRanges(value, ranges);\n}\n\n/**\n * A JSON string's text: each embedded credential pair's value, by the\n * leads a string takes (EMBEDDED_NAME_IN_STRING), and each detector's\n * match replaced. A JSON string is a text -- a message, a log line, a\n * stored form -- and, read by the detectors alone, `see /cb?token=... now`\n * was recorded (found in review).\n */\nfunction redactStringText(value: string, extra: readonly RegExp[]): string {\n if (!value) return value;\n const ranges: Range[] = [];\n embeddedPairRanges(value, ranges, \"string\");\n detectorRanges(value, extra, ranges);\n return applyRanges(value, ranges);\n}\n\n/**\n * The token detectors alone -- a JWT, a provider-prefixed key -- over one\n * string: what the page's own text is read for (privacy.ts scrubDomText).\n * A credential on screen is one whatever text is around it; an email or a\n * phone number in the page's text is the page's content, which balanced\n * records.\n */\nexport function redactTokens(value: string): string {\n return value ? applyRanges(value, tokenRanges(value)) : value;\n}\n\n/**\n * What any token needs somewhere in a value to be one: a JWT's `eyJ` or a\n * provider's prefix. Every attribute and text of a page is asked, and\n * almost none holds one; this is read without the lookbehind the two\n * patterns below start every place with (MEASURED: 18 percent of a\n * snapshot of 80,000 nodes was those patterns finding nothing).\n */\nconst MAYBE_TOKEN =\n /eyJ|kep_|gh[pousr]_|github_pat_|glpat-|xox[abprse]-|[sr]k_(?:live|test)_|sk-(?:proj|ant)-|npm_|whsec_|AKIA|ASIA|AIza/;\n\n/** Where `value`'s JWTs and provider-prefixed keys lie. */\nexport function tokenRanges(value: string): Range[] {\n const ranges: Range[] = [];\n if (!MAYBE_TOKEN.test(value)) return ranges;\n patternRanges(value, JWT_RE, ranges);\n patternRanges(value, KNOWN_TOKEN_RE, ranges);\n return ranges;\n}\n\n/* ------------------------------------------------------------------ */\n/* Structural walk */\n/* ------------------------------------------------------------------ */\n\nconst MAX_DEPTH = 64;\n\n/*\n * JSON IS REDACTED IN ITS OWN TEXT. It was parsed, walked and serialised\n * again, so every byte the walk did not touch could still change: an\n * integer past 2^53 came back rounded (`9007199254740993` recorded as\n * `...992`), whitespace and escapes were normalised -- and a replay\n * serves the recording, so an unchanged app could break on its own\n * snowflake ids. Now JSON.parse only VALIDATES (what it refuses is still\n * refused), a small tokenizer finds each value's span in the text, and\n * only the spans being redacted are rewritten. Every other byte --\n * numbers, whitespace, key order, escapes -- is kept. The tokenizer is\n * the SDK's own, so every engine gives the same answer.\n */\n\n/** A JSON value and where it is in the text. */\ntype JNode =\n | {\n kind: \"object\";\n start: number;\n end: number;\n entries: { key: string; value: JNode }[];\n }\n | { kind: \"array\"; start: number; end: number; items: JNode[] }\n | { kind: \"string\"; start: number; end: number; value: string }\n | { kind: \"scalar\"; start: number; end: number }\n | { kind: \"deep\"; start: number; end: number };\n\nconst ESCAPES: Record<string, string> = {\n '\"': '\"',\n \"\\\\\": \"\\\\\",\n \"/\": \"/\",\n b: \"\\b\",\n f: \"\\f\",\n n: \"\\n\",\n r: \"\\r\",\n t: \"\\t\",\n};\n\n/**\n * The value spans of a JSON text JSON.parse has already accepted, which\n * is why nothing here re-checks the grammar. Read to MAX_DEPTH like the\n * walk below; a value deeper than that is skipped by a scan, not by\n * recursion, so a deep document cannot overflow the stack.\n */\nfunction parseJsonSpans(text: string, base: number): JNode {\n let i = 0;\n const ws = (): void => {\n while (i < text.length) {\n const c = text.charCodeAt(i);\n if (c !== 32 && c !== 9 && c !== 10 && c !== 13) break;\n i++;\n }\n };\n const string = (): string => {\n i++; // the opening quote\n let out = \"\";\n let run = i;\n while (text[i] !== '\"') {\n if (text[i] !== \"\\\\\") {\n i++;\n continue;\n }\n out += text.slice(run, i);\n const e = text[i + 1];\n if (e === \"u\") {\n out += String.fromCharCode(parseInt(text.slice(i + 2, i + 6), 16));\n i += 6;\n } else {\n out += ESCAPES[e];\n i += 2;\n }\n run = i;\n }\n out += text.slice(run, i);\n i++; // the closing quote\n return out;\n };\n // Past MAX_DEPTH: the value's extent only, read by a scan.\n const skip = (): void => {\n let nest = 0;\n do {\n const c = text[i];\n if (c === '\"') {\n i++;\n while (text[i] !== '\"') i += text[i] === \"\\\\\" ? 2 : 1;\n i++;\n } else if (c === \"{\" || c === \"[\") {\n nest++;\n i++;\n } else if (c === \"}\" || c === \"]\") {\n nest--;\n i++;\n } else if (nest === 0 && (c === \",\" || c === \":\")) {\n break;\n } else {\n i++;\n }\n } while (nest > 0 || (i < text.length && !/[\\s,\\]}]/.test(text[i])));\n };\n const value = (depth: number): JNode => {\n ws();\n const start = i;\n if (depth > MAX_DEPTH) {\n skip();\n return { kind: \"deep\", start, end: i };\n }\n const c = text[i];\n if (c === \"{\") {\n i++;\n const entries: { key: string; value: JNode }[] = [];\n ws();\n if (text[i] === \"}\") i++;\n else {\n for (;;) {\n ws();\n const key = string();\n ws();\n i++; // :\n entries.push({ key, value: value(depth + 1) });\n ws();\n if (text[i++] === \"}\") break; // else `,`\n }\n }\n return { kind: \"object\", start, end: i, entries };\n }\n if (c === \"[\") {\n i++;\n const items: JNode[] = [];\n ws();\n if (text[i] === \"]\") i++;\n else {\n for (;;) {\n items.push(value(depth + 1));\n ws();\n if (text[i++] === \"]\") break; // else `,`\n }\n }\n return { kind: \"array\", start, end: i, items };\n }\n if (c === '\"') {\n const v = string();\n return { kind: \"string\", start, end: i, value: v };\n }\n while (i < text.length && !/[\\s,\\]}]/.test(text[i])) i++;\n return { kind: \"scalar\", start, end: i };\n };\n // `base`: the depth this text sits at -- a JSON string inside a body is\n // as deep as the value that holds it, so the cap stays cumulative.\n return value(base);\n}\n\nconst REDACTED_JSON = JSON.stringify(REDACTED);\n\n/* ------------------------------------------------------------------ */\n/* URLs held in a body */\n/* ------------------------------------------------------------------ */\n\n/**\n * A URL a body holds -- a presigned S3, GCS or Azure link an API hands the\n * page, a pagination link, a redirect in a form, a link in an HTML or RSC\n * page -- scrubbed by the one URL scrubber (@keploy/contract's privacy.ts\n * scrubUrl) under a `param`'s names: a credential's value replaced, in\n * its query, its fragment, a path's `;name=` and a URL nested or encoded\n * in a value, its user info dropped, never a paging cursor (a pagination\n * link's `pageToken` is the page's to request again). A body is no replay\n * key, so its pairs are read as the DOM's are, each credential's own value\n * replaced, and a nested URL is written back as it came (`raw`). A\n * scrubbed link is not the one the server sent, so a replay that requests\n * it relies on the replay key treating a redacted value as a wildcard.\n * Every other byte is kept.\n */\nconst BODY_URL_RULES: UrlRules = {\n kind: \"param\",\n strict: false,\n whole: false,\n raw: true,\n};\n\n/**\n * A text body's URLs (an HTML, XML, RSC, CSS, text or multipart body's,\n * read raw) and a header's: BODY_URL_RULES, but a credential's own value\n * ends at the first character the contract's ownValueEnd stops at\n * (whitespace, `,`, `;`, a quote, or a bracket it does not open), the\n * text after it kept (`/api/x?token=... 200 OK`, a CSV row's later\n * columns) and read as a text's (TAIL_URL_RULES).\n */\nconst TEXT_URL_RULES: UrlRules = {\n ...BODY_URL_RULES,\n spaced: true,\n tail: (text) => scrubTextUrls(text, TAIL_URL_RULES),\n};\n\n/**\n * A form body's URLs (readAsForm): a credential's own value ends at its\n * first whitespace, as every body's did before TEXT_URL_RULES, and the\n * form read then takes each value to its `&`. Nothing after it is read\n * again (no `tail`). Read with the text's end, a raw URL's credential\n * value cut at a `,` was left a tail the form read took for the\n * credential's, and the whole value went\n * (`next=https://x/cb?token=abc,def%20ghi` became `next=[REDACTED]`), or\n * the tail was kept (found in review).\n */\nconst FORM_URL_RULES: UrlRules = {\n ...BODY_URL_RULES,\n spaced: true,\n form: true,\n};\n\n/**\n * The text a credential's own value leaves after it in a pair, read as a\n * text's URLs are, each URL of a list its own (`list`): kept unread, a\n * list's next URL kept its nested token and its user info\n * (`?token=...,https://b/y?next=%2Fcb%3Ftoken%3D...`, found in review).\n * Its own credentials' tails are left to the text pair rule, so it is\n * read once.\n */\nconst TAIL_URL_RULES: UrlRules = {\n ...BODY_URL_RULES,\n spaced: true,\n list: true,\n};\n\n/**\n * A line that starts with a URL -- a JSON string that is a link, a form's\n * value, a uri-list's or a log's line -- read whole as a URL is, what\n * follows its start its own (`?markers=red|1,2&signature=...`,\n * `?filter={\"a\":1}&token=...`): a scheme, a `/`, `./` or `../`, then a\n * query or a fragment; a relative path's segments, or none, then a `?` or\n * a `#` and a pair (`cb?jwt=...`, `#access_token=...`), which prose's\n * `Ref#123: ...` and `Q? see ...` are not -- read as a URL, a credential's\n * value took their words to the next `&` (found in review); or a path's\n * parameter (`/cart;jsessionid=...`, a `/` first and no `=` before it,\n * which a form's `a=1;password=...&b=2` is not). Its first word holds no\n * tag, quote, brace or pipe before its first `=`: a stylesheet's\n * `#a{background:url(/x?sig=...)}` and a page's `<style>a{color:#fff}`\n * are texts holding URLs, read as a URL their `)}` and `\">` went with a\n * credential's value (found in review). A scheme is one a `/` follows, one\n * whose name holds a `.` or a `+` (`com.example.app:`), `localhost` and\n * its port (`localhost:3000/`; another one-word host is CSS's\n * `grid-area:1/2` as often), or one of a list that takes no authority\n * (`mailto:`, `tel:`, `xmpp:`, `intent:`, `data:` ...): a CSS property is none,\n * and `background:url(/x?token=...);color:red` read as a URL lost its\n * `);color:red` (found in review). Anything else -- prose, markup, code --\n * is a text holding URLs, each found by the scan.\n */\nconst WHOLE_URL =\n /^(?=[^={}<>\"'\\\\^`|]*(?:=|$))(?:(?:[a-z][a-z0-9+.-]*:\\/|[a-z][a-z0-9-]*[+.][a-z0-9+.-]*:|localhost:\\d{1,5}[/?#]|(?:mailto|tel|sms|urn|data|javascript|vbscript|blob|about|xmpp|sip|sips|magnet|intent|bitcoin|geo|market|news):|\\.{0,2}\\/)[^\\s?#]*[?#]|(?:[\\w.~%-][\\w.~%/-]*)?[?#][^\\s=&#]+=|\\.{0,2}\\/[^\\s?#;=]*;)/i;\n\n/** The start a URL a line starts with is told by (WHOLE_URL): its first word. */\nconst URL_START_WORD = /^\\S*/;\n\n/**\n * Each line of a text, read whole when it starts with a URL: a raw space\n * or tab in a query is its value's (`?q=new york&api_key=...`), and a\n * credential's value ends at its first stop (ownValueEnd, scrubPairs),\n * the line's text after it kept. A URL holds no line break: a uri-list's\n * or a log's lines are each read, and none runs into the next (found in\n * review).\n */\nconst URL_LINE = /^[^\\r\\n]*/gm;\n\n/**\n * `text` -- a body, a JSON string, a form's value -- with every URL it\n * holds scrubbed (BODY_URL_RULES): each line that starts with a URL read\n * whole (WHOLE_URL), then each URL the scan finds in it.\n */\nfunction scrubTextUrls(raw: string, rules = BODY_URL_RULES): string {\n const text = raw.replace(URL_LINE, (line) =>\n WHOLE_URL.test(URL_START_WORD.exec(line)![0])\n ? scrubUrl(line, rules)\n : line,\n );\n const edits = urlEdits(text, rules);\n if (edits.length === 0) return scrubEscapedUrls(text, rules);\n let out = \"\";\n let at = 0;\n for (const [start, end, with_] of edits) {\n out += text.slice(at, start) + with_;\n at = end;\n }\n return scrubEscapedUrls(out + text.slice(at), rules);\n}\n\n/**\n * A URL a script or a JavaScript body writes with its slashes escaped, as\n * JSON and PHP's json_encode write one\n * (`\"https:\\/\\/app\\/cb#access_token=...\"`): the scan finds none, a\n * backslash ending a URL. A scheme read at most 32 characters back, as\n * URL_START's is. It ends at a parenthesis, a bracket (CSS's\n * `url(https:\\/\\/...);background-size:cover` keeps its `)` and the rest)\n * or a plain `/` that ends a regular expression (one its flags and then\n * no word follow, `/.test(`), not one inside a value\n * (`?token=abc/def`, found in review: cut there, `/def` was kept) too: escaped slashes are a regular expression's as often\n * (`/https:\\/\\/x\\/cb#access_token=([^&]+)/`), whose group read as a value\n * left the pattern unbalanced (found in review).\n */\nconst ESCAPED_URL =\n /[a-z][a-z0-9+.-]{0,31}:(?:\\\\\\/|\\\\u002[fF]){2}(?:[^\\s\"'<>\\\\^`{|}()[\\]/]|\\/(?![dgimsuvy]*(?![\\w$]))|\\\\\\/|\\\\u002[fF])*/gi;\n\n/**\n * Each URL `text` writes with its slashes escaped (ESCAPED_URL), read\n * with them unescaped by `rules`: read as written, its credential and a\n * URL nested in it (`?next=%2Fcb%3Ftoken%3D...`) were kept (found in\n * review). It ends at a plain `/` -- a regular expression's closing one,\n * `/https:\\/\\/x\\/cb;jsessionid=.../` -- and only what the read changed\n * is written back, every other byte as it came: written back with every\n * slash escaped, the pattern's closing `/` became `\\/` and the script no\n * longer parsed (found in review).\n */\nfunction scrubEscapedUrls(text: string, rules: UrlRules): string {\n if (!/:(?:\\\\\\/|\\\\u002[fF])/.test(text)) return text;\n return text.replace(ESCAPED_URL, (span) => {\n // The span unescaped, and where in the span each of its characters,\n // and its end, were written.\n let plain = \"\";\n const at: number[] = [];\n for (let i = 0; i < span.length;) {\n at.push(i);\n const escape = ESCAPED_SLASH_AT.exec(span.slice(i, i + 6));\n plain += escape === null ? span[i] : \"/\";\n i += escape === null ? 1 : escape[0].length;\n }\n at.push(span.length);\n const out = scrubUrl(plain, rules);\n if (out === plain) return span;\n // What changed lies between the longest prefix and suffix the two\n // share; only it is written anew, its slashes as the span's first.\n let head = 0;\n while (head < out.length && out[head] === plain[head]) head++;\n let tail = 0;\n while (\n tail < out.length - head &&\n tail < plain.length - head &&\n out[out.length - 1 - tail] === plain[plain.length - 1 - tail]\n )\n tail++;\n const slash = /\\\\\\/|\\\\u002[fF]/.exec(span)![0];\n return (\n span.slice(0, at[head]) +\n out.slice(head, out.length - tail).replace(/\\//g, slash) +\n span.slice(at[plain.length - tail])\n );\n });\n}\n\n/** A slash a script or a JSON text writes escaped (`\\/`, `\\u002f`), at a text's start. */\nconst ESCAPED_SLASH_AT = /^(?:\\\\\\/|\\\\u002[fF])/;\n\n/**\n * Every URL a header's value holds, scrubbed as a text body's URLs are\n * (TEXT_URL_RULES: a credential's own value replaced, ended at its first\n * stop, every other byte kept),\n * and every pair a header's leads start (EMBEDDED_NAME_IN_HEADER), as a\n * relative URL's, which the URL scan does not find, is: a `Referer`, an\n * `X-Redirect-To`, a `Content-Security-Policy`'s `report-uri` absolute or\n * relative (`/csp-report?token=...`). A header is no replay key, so no\n * pair is replaced whole for a name inside it. Only Location,\n * Content-Location, Link and Refresh were read, and a URL any other header\n * carried was recorded as it came (found in review).\n */\nexport function scrubHeaderUrls(value: string): string {\n // A credential's own value ends as a text's does (TEXT_URL_RULES): a\n // header's list is split at `,` and its parameters at `;` (RFC 9110),\n // and a value run to the next pair took a second URL and a CSP's next\n // directive with it (found in review).\n const text = scrubTextUrls(value, TEXT_URL_RULES);\n const ranges: Range[] = [];\n embeddedPairRanges(text, ranges, \"header\");\n return applyRanges(text, ranges);\n}\n\n/**\n * Whether a form value, encoded (`next=https%3A%2F%2Fx%2Fv%3Fjwt%3D...`),\n * holds a URL with a credential in it: such a value goes whole, since its\n * scrubbed URL cannot be written back encoded in place.\n */\nfunction holdsEncodedUrlCredential(raw: string): boolean {\n if (!/[%+]/.test(raw)) return false;\n const value = formDecode(raw);\n if (value === raw) return false;\n // Encoded again (`redirect=https%253A%252F%252F...%253Fjwt%253D...`): no\n // read sees its URL, and no pair search reads it in place. Decoded\n // escape by escape, as holdsCredentialName reads it: all or nothing, a\n // malformed escape beside the name (`%253DS%25zz`) kept it (found in\n // review).\n if (decoded(value) !== value && holdsCredentialName(value, \"param\"))\n return true;\n const scrubbed = scrubTextUrls(value);\n if (scrubbed === value) return false;\n // What the pair search below redacts in place, mapped back to the raw\n // bytes (`redirect=https%3A%2F%2Fx%2Fcb%3Ftoken%3D[REDACTED]`): enough\n // when it is what the URL scrub redacts.\n const inPlace: Range[] = [];\n embeddedPairRanges(value, inPlace);\n return applyRanges(value, inPlace) !== scrubbed;\n}\n\n/**\n * The digits of a JSON number written with a fraction or an exponent\n * that is still an integer (`4242424242424242.0`, `4.242424242424242e15`\n * -- a PAN either way), or null. Plain digits are read as written.\n */\nfunction integerDigits(raw: string): string | null {\n if (!/^-?\\d/.test(raw)) return null; // true, false\n const n = Number(raw);\n return Number.isInteger(n) ? String(n) : null;\n}\n\n/** A flag, or a list of flags: a value that holds no secret under any name. */\nfunction onlyFlags(text: string, node: JNode): boolean {\n if (node.kind === \"scalar\")\n return /^(?:true|false)$/.test(text.slice(node.start, node.end));\n return node.kind === \"array\" && node.items.every((n) => onlyFlags(text, n));\n}\n\n/**\n * One JSON value's redaction, as edits on the text: the decisions the\n * structural walk always made -- a sensitive key takes its whole value,\n * a card number goes even as a number, a string is scanned (and redacted\n * as JSON when it is JSON), a name/value pair goes by its name, past\n * MAX_DEPTH everything goes -- written only where they change something.\n */\nfunction redactNode(\n text: string,\n node: JNode,\n keyHint: string | null,\n depth: number,\n extra: readonly RegExp[],\n edits: Array<[number, number, string]>,\n): void {\n const replace = (with_: string): void => {\n edits.push([node.start, node.end, with_]);\n };\n // Fail CLOSED. Returning the subtree verbatim meant a `password` nested\n // past the cap was emitted in the clear.\n if (node.kind === \"deep\") return replace(REDACTED_JSON);\n // null is kept, under any key: it carries nothing, and a replay that\n // served \"[REDACTED]\" where the app recorded null hands it a string.\n if (node.kind === \"scalar\" && text.startsWith(\"null\", node.start)) return;\n // So is a flag, or a list of flags: a list's item comes here under its\n // key's name without passing the entries loop's guard below.\n if (onlyFlags(text, node)) return;\n // A sensitive key redacts its ENTIRE value, whatever shape it is, but\n // for an object or a list under a name settings use too.\n const bare = keyHint !== null && isBareCodeName(keyHint);\n if (\n keyHint !== null &&\n isSensitiveKey(keyHint) &&\n !(bare && isSettingsValue(node)) &&\n !(node.kind !== \"string\" && isWordName(keyHint))\n ) {\n return replace(REDACTED_JSON);\n }\n if (node.kind === \"scalar\") {\n // Numbers, booleans and null are never scanned -- the rule that stops\n // timestamps and ids being corrupted -- but a card number survives\n // as a JSON number, so the card test reads its digits as written.\n const raw = text.slice(node.start, node.end);\n const digits = /^\\d+$/.test(raw) ? raw : integerDigits(raw);\n if (digits !== null && isLikelyCardNumber(digits)) replace(REDACTED_JSON);\n return;\n }\n if (node.kind === \"string\") {\n const out =\n redactJsonString(node.value, depth, extra) ??\n redactStringText(scrubTextUrls(node.value), extra);\n if (out !== node.value) replace(JSON.stringify(out));\n return;\n }\n if (node.kind === \"array\") {\n for (const item of node.items) {\n redactNode(text, item, keyHint, depth + 1, extra, edits);\n }\n return;\n }\n // A name/value pair whose name is a secret's: a header list\n // (`[{name: \"Authorization\", value: ...}]`, HAR), a test report's\n // header diff (`{key: \"Authorization\", expected, actual}`). The value\n // sits under a generic name, so it goes by its sibling's.\n const pair = node.entries.some(\n ({ key, value }) =>\n PAIR_NAMES.has(key.toLowerCase()) &&\n value.kind === \"string\" &&\n isSensitiveKey(value.value),\n );\n const card = node.entries.some(({ key }) =>\n CARD_FIELDS.has(normalizeKey(key)),\n );\n const exchange = isTokenExchange(\n node.entries.map(\n ({ key, value }) =>\n [normalizeKey(key), value.kind === \"string\" ? value.value : \"\"] as [\n string,\n string,\n ],\n ),\n );\n for (const { key, value } of node.entries) {\n // A flag, or a list of flags, goes under no rule (onlyFlags): it\n // carries no secret, and replaced it became the string \"[REDACTED]\",\n // which an app reads as true -- `{\"hasSignature\":false}` replayed as a\n // signature on file (found in review). Every value a key holds is\n // read here first, a sensitive key's and a context rule's alike.\n if (onlyFlags(text, value)) continue;\n if (card && CARD_EXPIRY_BESIDE_A_CARD.has(normalizeKey(key))) {\n edits.push([value.start, value.end, REDACTED_JSON]);\n } else if (\n ((exchange && EXCHANGE_REDACTED.has(normalizeKey(key))) ||\n (bare && normalizeKey(key) === \"code\")) &&\n !(value.kind === \"scalar\" && text.startsWith(\"null\", value.start))\n ) {\n edits.push([value.start, value.end, REDACTED_JSON]);\n } else if (pair && PAIR_VALUES.has(key.toLowerCase())) {\n edits.push([value.start, value.end, REDACTED_JSON]);\n } else {\n redactNode(\n text,\n value,\n isSensitiveKey(key) ? key : null,\n depth + 1,\n extra,\n edits,\n );\n }\n }\n}\n\n/** `text` with each edit's span replaced; the text itself when there are none. */\nfunction applyEdits(\n text: string,\n edits: Array<[number, number, string]>,\n): string {\n if (edits.length === 0) return text;\n edits.sort((a, b) => a[0] - b[0]);\n let out = \"\";\n let pos = 0;\n for (const [start, end, with_] of edits) {\n out += text.slice(pos, start) + with_;\n pos = end;\n }\n return out + text.slice(pos);\n}\n\n/** A JSON text JSON.parse accepted, redacted in place. */\nfunction redactJsonText(\n text: string,\n depth: number,\n extra: readonly RegExp[],\n): string {\n const edits: Array<[number, number, string]> = [];\n redactNode(text, parseJsonSpans(text, depth), null, depth, extra, edits);\n return applyEdits(text, edits);\n}\n\n/** The field of a name/value pair that names it. */\nconst PAIR_NAMES: ReadonlySet<string> = new Set([\"key\", \"name\", \"header\"]);\n/** The fields of a name/value pair that carry the value. */\nconst PAIR_VALUES: ReadonlySet<string> = new Set([\n \"value\",\n \"values\",\n \"expected\",\n \"actual\",\n]);\n\n/**\n * A string that is itself JSON -- a test case's `header` or `body` as\n * api-server stores them, a GraphQL `variables` string -- redacted as JSON\n * and serialised again, or null when it is not JSON. Returned as it came\n * when nothing in it was redacted, so a JSON string with no secret keeps\n * every byte (its whitespace and key order included).\n */\nfunction redactJsonString(\n s: string,\n depth: number,\n extra: readonly RegExp[],\n): string | null {\n if (!/^\\s*[[{]/.test(s)) return null;\n try {\n JSON.parse(s);\n } catch {\n return null;\n }\n return redactJsonText(s, depth + 1, extra);\n}\n\n/**\n * Redact a captured body.\n *\n * JSON in, valid JSON out — always. A body that is not JSON keeps every\n * byte except what is redacted: a form's credential values and the\n * pattern matches in its other values, or, in any other text, the value\n * of an embedded credential pair and the pattern matches.\n */\nexport function redactBody(\n body: string | null | undefined,\n contentType?: string,\n extra: readonly RegExp[] = [],\n): string | null {\n if (body === null || body === undefined || body === \"\") return body ?? null;\n\n // The SDK's own note in place of a body it never read. Nothing in it\n // came from the page, and it is the only record of what the body was;\n // running it through the JSON branch below flattened it to the\n // refusal and lost the kind and the size. See isNotRecordedNote().\n if (isNotRecordedNote(body)) return body;\n\n const looksJson =\n (contentType ?? \"\").toLowerCase().includes(\"json\") || /^\\s*[[{]/.test(body);\n\n if (looksJson) {\n try {\n JSON.parse(body); // validates: what it refuses is still refused\n } catch {\n // Unparseable but JSON-shaped — almost always a truncated capture,\n // since the transport appends \"...[truncated]\" to oversized bodies.\n //\n // Falling through to the text scanner here is what let the ORIGINAL\n // bug back in: the card regex could match a bare JSON number and\n // emit {\"amount\":[REDACTED]}, which no longer parses. There is no\n // safe way to redact a fragment we cannot parse, so refuse it\n // wholesale rather than emit something corrupt.\n return TRUNCATED_UNPARSEABLE;\n }\n return redactJsonText(body, 0, extra);\n }\n\n // Every URL the body holds, raw -- an HTML, XML, RSC or text body's, a\n // multipart part's, a form value's written as it is -- scrubbed first,\n // the cut marker set aside; the passes below then read the rest. Whether\n // it is read as a form is decided once, here, on its URLs read as a\n // form's (a URL's user info can hold an `&`, and its scrub can drop one:\n // decided on the raw bytes, a form was read as text, found in review).\n // A body that is no form has its URLs read as a text's; when the form\n // read changed nothing, the text read changes nothing either.\n const cut = body.endsWith(TRUNCATED_SUFFIX);\n const raw = cut ? body.slice(0, -TRUNCATED_SUFFIX.length) : body;\n const formHeld = scrubTextUrls(raw, FORM_URL_RULES);\n const asForm = readAsForm(\n cut ? formHeld + TRUNCATED_SUFFIX : formHeld,\n contentType ?? \"\",\n );\n const held =\n asForm || formHeld === raw ? formHeld : scrubTextUrls(raw, TEXT_URL_RULES);\n const text = cut ? held + TRUNCATED_SUFFIX : held;\n\n const multipart = redactMultipartText(text, contentType ?? \"\", extra);\n if (multipart !== null) return multipart;\n // Under a multipart content-type a body is either multipart text or the\n // urlencoded rendering of a FormData's fields (see formDataText). One\n // that is neither -- its boundary not the declared one, or too long to\n // be a boundary -- has parts the form path cannot see: refused whole,\n // never recorded as it came (review r2).\n if (MULTIPART.test(contentType ?? \"\") && !asForm) {\n return UNREADABLE;\n }\n\n const form = redactFormBody(\n text,\n extra,\n asForm,\n /(?:java|ecma)script/i.test(contentType ?? \"\"),\n );\n if (form !== null) return form;\n\n return redactStringValue(text, extra);\n}\n\n/* ------------------------------------------------------------------ */\n/* Form bodies */\n/* ------------------------------------------------------------------ */\n/*\n * A CREDENTIAL IN A FORM BODY IS STILL A CREDENTIAL. Key-based redaction\n * ran on JSON alone, so `password=...` in a form post, an OAuth\n * refresh-token request (form-encoded by RFC 6749), a FormData body or an\n * XHR string body reached the server as typed -- MEASURED on 3.0.1 in\n * Chromium.\n *\n * TWO SHAPES, because a response body is served back to the page at\n * replay and must keep every byte that is not a secret:\n *\n * 1. A FORM -- every segment a pair or a bare name, no whitespace inside\n * a trimmed raw name, at least one real pair. A bare flag\n * (`remember&...`, which the WHATWG parser, Rack and PHP all accept)\n * or a trimmed name no longer takes the whole body off this path, as\n * it did in the first fix (review round 1). A value under a sensitive\n * name is replaced whole; a name is sensitive when it is, or when any\n * bracket or dot part of it is (`password[0]`, `token[value]`,\n * `user[password_confirmation]`), the way a sensitive JSON key\n * redacts its whole subtree. The body is scanned for the patterns as\n * it was sent and decoded -- an email is `ada%40example.com` on the\n * wire -- each decoded match redacting exactly the raw bytes it came\n * from.\n * 2. ANY OTHER TEXT -- HTML, an RSC payload, XML, prose: the value of an\n * embedded credential pair is replaced (see embeddedPairRanges), and the\n * whole text is scanned for the patterns.\n *\n * Everything nothing matched is kept byte for byte: nothing is ever\n * re-encoded, and every detector's ranges are merged before one marker\n * replaces each (see applyRanges).\n */\n\n/**\n * What network.ts appends to a body it cut at the cap. Defined here and\n * imported there, so the form parser and the cut agree on one string.\n */\nexport const TRUNCATED_SUFFIX = \"...[truncated]\";\n\n/**\n * A raw form field name: what a urlencoded serializer or a hand-written\n * `user[password]` leaves -- letters, digits, `%XX`, `+` and `_.-~!*'()[]`.\n * Markup, URLs and prose (`<cfg><url>https://h/x?a`) are not names, so\n * the XML body that holds one is not taken for a form (review round 2).\n * EMPTY IS A NAME: the WHATWG urlencoded parser reads `=x` as one, and\n * refusing it sent a whole form down the embedded-pair path, whose value\n * stops at `(` -- `=x&password=pa(ss` kept `(ss` (review r4, B6).\n */\nconst FORM_NAME = /^[A-Za-z0-9_.~!*'()%+[\\]-]*$/;\n\n/** A form name or value decoded, or as it came when it does not decode. */\nfunction formDecode(raw: string): string {\n if (!/[%+]/.test(raw)) return raw;\n const out = newDecodedText(raw.length);\n appendDecoded(raw, 0, raw.length, out);\n return out.parts.join(\"\");\n}\n\n/** Two hex digits at `i`, as a byte, or -1. */\nfunction hexByte(raw: string, i: number): number {\n if (i + 2 > raw.length) return -1;\n const hi = parseInt(raw[i], 16);\n const lo = parseInt(raw[i + 1], 16);\n return Number.isNaN(hi) || Number.isNaN(lo) ? -1 : hi * 16 + lo;\n}\n\n/** Decoded text, and for each of its code units the raw span it came from. */\ninterface DecodedText {\n parts: string[];\n start: Int32Array;\n end: Int32Array;\n length: number;\n}\n\n/** Room for `capacity` code units: a decoded text is never longer than its raw one. */\nfunction newDecodedText(capacity: number): DecodedText {\n return {\n parts: [],\n start: new Int32Array(capacity),\n end: new Int32Array(capacity),\n length: 0,\n };\n}\n\n/** One decoded code unit `unit`, from raw[from, to). */\nfunction appendUnit(\n out: DecodedText,\n unit: string,\n from: number,\n to: number,\n): void {\n out.parts.push(unit);\n for (let u = 0; u < unit.length; u++) {\n out.start[out.length] = from;\n out.end[out.length] = to;\n out.length++;\n }\n}\n\n/** raw[from, to) as it came, one decoded unit per raw unit. */\nfunction appendRaw(\n raw: string,\n from: number,\n to: number,\n out: DecodedText,\n): void {\n if (from >= to) return;\n out.parts.push(raw.slice(from, to));\n for (let i = from; i < to; i++) {\n out.start[out.length] = i;\n out.end[out.length] = i + 1;\n out.length++;\n }\n}\n\n/**\n * One form name or value decoded as the urlencoded parser decodes it\n * (`+` is a space, `%XX` a UTF-8 byte), appended to `out` with, for every\n * decoded code unit, the span of RAW text it came from -- so a match found\n * in the decoded text is redacted in the raw one, escapes whole, and\n * nothing outside a match is ever re-encoded (re-encoding turned each raw\n * `中` into `%E4%B8%AD`, 7.7x with no pattern at all -- review r8).\n * A part with a malformed escape or bytes that are not UTF-8 is appended\n * as it came, one unit per raw unit, without an exception:\n * decodeURIComponent threw on each, and a thrown URIError per pair cost\n * 0.4-0.8 s on a 512 KB body of them (review round 2).\n */\nfunction appendDecoded(\n raw: string,\n from: number,\n to: number,\n out: DecodedText,\n): void {\n const marks = { parts: out.parts.length, length: out.length };\n let run = from; // the start of a stretch that decodes to itself\n let i = from;\n while (i < to) {\n const c = raw.charCodeAt(i);\n if (c !== 43 && c !== 37) {\n i++; // neither `+` nor `%`\n continue;\n }\n appendRaw(raw, run, i, out);\n if (c === 43) {\n appendUnit(out, \" \", i, i + 1);\n run = ++i;\n continue;\n }\n // A UTF-8 sequence: the lead byte says how many bytes follow; each\n // must be an escaped continuation byte, and the ranges below are\n // exactly the ones decodeURIComponent accepts (no overlong forms, no\n // surrogates, nothing past U+10FFFF).\n const lead = i + 3 <= to ? hexByte(raw, i + 1) : -1;\n let n = -1;\n let lo = 0x80;\n let hi = 0xbf;\n if (lead >= 0 && lead < 0x80) n = 0;\n else if (lead >= 0xc2 && lead <= 0xdf) n = 1;\n else if (lead >= 0xe0 && lead <= 0xef) {\n n = 2;\n if (lead === 0xe0) lo = 0xa0;\n if (lead === 0xed) hi = 0x9f;\n } else if (lead >= 0xf0 && lead <= 0xf4) {\n n = 3;\n if (lead === 0xf0) lo = 0x90;\n if (lead === 0xf4) hi = 0x8f;\n }\n let cp = n <= 0 ? lead : lead & (0x3f >> n);\n for (let k = 1; k <= n && cp >= 0; k++) {\n const at = i + 3 * k;\n const b = at + 3 <= to && raw[at] === \"%\" ? hexByte(raw, at + 1) : -1;\n cp =\n b < (k === 1 ? lo : 0x80) || b > (k === 1 ? hi : 0xbf)\n ? -1\n : (cp << 6) | (b & 0x3f);\n }\n if (n < 0 || cp < 0) {\n // Not UTF-8: the whole part as it came.\n out.parts.length = marks.parts;\n out.length = marks.length;\n appendRaw(raw, from, to, out);\n return;\n }\n const end = i + 3 * (n + 1);\n appendUnit(out, String.fromCodePoint(cp), i, end);\n run = i = end;\n }\n appendRaw(raw, run, to, out);\n}\n\n/**\n * A `name=value` pair embedded in a body that is NOT a form: a query\n * string inside an HTML link (`&token=`), an RSC payload or XML, or a\n * line of prose that holds one. It starts only after `?`, `&`, `;`, a\n * newline, a tag's `>` (`<p>password=...</p>`, found in review), a `#`\n * (a fragment's pair, `Location: /cb#access_token=...`, an unlisted\n * attribute's `data-url=\"/cb#access_token=...\"`, found in review), the start\n * of the body, or a space that follows no bracket and no declaration\n * (`x token=... y`, `user=bob; password=...` and `user=bob, password=...`\n * are text; `var token=`, `if (x) token=` and `{ token=` are code, whose\n * response a replay may run -- and neither in a JavaScript body nor in a\n * `<script>`'s text does a space, a tag or a `#` start a pair: a class's\n * `#token=t` is a private field), its name has no `.` (so minified\n * JS's `e&&e.token=t` is an assignment, not a pair), and its value ends\n * at the first delimiter -- so only the credential is replaced and every\n * other byte of a response that replay serves back is kept. Review round\n * 2 measured the alternative (the value running to the next `&`) deleting\n * the rest of HTML, RSC and XML bodies.\n *\n * The pattern finds a NAME and its `=`, never a value: a match that took\n * the whole pair swallowed every later `?name=` inside its value, so\n * `?next=/b?token=x` in a link, or a form's `redirect=https://x/cb?token=x`,\n * kept the token (review r1 of the port). A value is read only for a\n * sensitive name, and the search resumes after it; any other name's value\n * is searched on from its `=`. Each character is read at most once by the\n * name search and once by a value read: linear. A name's brackets close\n * (`user[password]=`): CSS's `[data-token=x]` selects, and holds no pair.\n * A name found is read by the one rule as a `param`. What is a name is\n * narrower here than in a form: letters, digits, `_`, `-`, `%` and closed\n * brackets, and no `.`, `$` or `+`, which a script's `;e.token=t`,\n * `$token=` and `token+=1` hold -- a JavaScript body or a `<script>`\n * rewritten to `e.token=[REDACTED]` throws when a replay serves it.\n */\nconst EMBEDDED_NAME =\n /(^|[?&;\\n>#]|(?<!\\b(?:var|let|const)|[(){}])[ \\t\\r\\f\\v])([\\w%-]*(?:\\[[\\w%-]*\\][\\w%-]*)*)=/g;\n/**\n * The leads a pair takes in a body that is JavaScript: a start, `?`, `&`,\n * `;`, a newline, or a `#` after a path's character\n * (`\"/cb#access_token=...\"`, found in review) -- its spaces and tags\n * separate code, not pairs, and a `#` after a `.`, a brace, a space or\n * the keyword `static` or `accessor` (`static#token=null`, minified,\n * found in review), or the star and slash that close a block comment\n * (`class A{/**`, `/#token=null}`, found in review), is a private field.\n */\nconst EMBEDDED_NAME_IN_CODE =\n /(^|[?&;\\n]|(?<=[\\w/%~-])(?<!\\*\\/|(?:^|[^\\w$/%~.-])(?:static|accessor))#)([\\w%-]*(?:\\[[\\w%-]*\\][\\w%-]*)*)=/g;\n/**\n * The leads a pair takes in a JSON string, whose content-type says\n * nothing of what it holds -- a message, a stored form, a link, or code,\n * SQL or Markdown: its start, a query's `?` and `&`, and a fragment's `#`\n * after a path (`/cb#access_token=`), never a `;`, a space, a newline or\n * a `#` after a bracket or a dot. Read with a text body's leads, a\n * string's `let a=1;token=getToken()`, `SET password=?` and a class's\n * `#token=null` lost their code (found in review).\n */\nconst EMBEDDED_NAME_IN_STRING =\n /(^|[?&]|(?<=[\\w/%~-])(?<!\\*\\/|(?:^|[^\\w$/%~.-])(?:static|accessor))#)([\\w%-]*(?:\\[[\\w%-]*\\][\\w%-]*)*)=/g;\n/**\n * The leads a pair takes in a header's value (one Location, Content-Location,\n * Link and Refresh are not): a header's parameters are separated by `;`,\n * `,` and spaces (`a=1, token=...`, `0; url=/next?a=1;sig=...`), and\n * hold no code (found in review: each was kept).\n */\nconst EMBEDDED_NAME_IN_HEADER =\n /(^|[?&;,\\s]|(?<=[\\w/%~-])#)([\\w%-]*(?:\\[[\\w%-]*\\][\\w%-]*)*)=/g;\n/** A pair's value: to its first space, quote, backtick, tag, bracket, backslash, `&`, `;`, comma, or a template literal's `${` (code, not a value: `` `/api?token=abc${t}` `` lost its `$`, found in review). */\nconst EMBEDDED_VALUE = /(?:[^\\s&\"'`<>\\\\,;(){}[\\]$]|\\$(?!\\{))+/y;\n/**\n * A JSON string's pair's value: to the next `&` or the string's end. A\n * credential's value there fails closed: ended at a space,\n * `password=correct horse battery staple` kept the words after its first\n * (found in review), and ended at a line break, a PEM key's lines after\n * its first would be kept.\n */\nconst EMBEDDED_VALUE_IN_STRING = /[^&]+/y;\n\n/** Which leads a pair takes: a text body's, a JavaScript body's, a JSON string's, or a header's. */\ntype PairMode = \"text\" | \"code\" | \"string\" | \"header\";\n\n/** The value range of every embedded credential pair in `body`, by `mode`'s leads (EMBEDDED_NAME, EMBEDDED_NAME_IN_CODE, EMBEDDED_NAME_IN_STRING, EMBEDDED_NAME_IN_HEADER) and its value's end (EMBEDDED_VALUE_IN_STRING in a JSON string, EMBEDDED_VALUE elsewhere). */\nfunction embeddedPairRanges(\n body: string,\n into: Range[],\n mode: PairMode = \"text\",\n): void {\n const names =\n mode === \"code\"\n ? EMBEDDED_NAME_IN_CODE\n : mode === \"string\"\n ? EMBEDDED_NAME_IN_STRING\n : mode === \"header\"\n ? EMBEDDED_NAME_IN_HEADER\n : EMBEDDED_NAME;\n // A <script>'s text is code, as a JavaScript body is: a space or a tag\n // there leads no pair (`<script>let a = 1; token=t</script>`).\n const scripts =\n mode !== \"text\" || !/<script/i.test(body) ? [] : scriptRanges(body);\n let r = 0;\n names.lastIndex = 0;\n for (let m = names.exec(body); m !== null; m = names.exec(body)) {\n if (!isCredentialName(m[2], \"param\")) continue;\n // In a <script>, a `#` leads a pair only after a path's character, as\n // in a string (`location.replace(\"/cb#access_token=...\")`, found in\n // review), never after a `.`, a brace, a space, a comment's `*/`,\n // `static` or `accessor` (a private field).\n if (\n scripts.length > 0 &&\n (/^[ \\t\\r\\f\\v>]$/.test(m[1]) ||\n (m[1] === \"#\" &&\n (!/[\\w/%~-]/.test(body[m.index - 1] ?? \"\") ||\n body.startsWith(\"*/\", m.index - 2) ||\n /(?:^|[^\\w$/%~.-])(?:static|accessor)$/.test(\n body.slice(Math.max(0, m.index - 9), m.index),\n ))))\n ) {\n while (r < scripts.length && scripts[r][1] <= m.index) r++;\n if (r < scripts.length && scripts[r][0] <= m.index) continue;\n }\n const valueStart = m.index + m[0].length;\n EMBEDDED_VALUE.lastIndex = valueStart;\n let value = EMBEDDED_VALUE.exec(body);\n if (value === null) continue;\n // A JSON string's value runs on to the next `&` or the string's end,\n // where EMBEDDED_VALUE starts one: one that starts at a space, a\n // quote, a backtick, a bracket, `<`, `>`, `,`, `;` or a backslash is\n // code's, kept (`fetch('/api?token='+t)`, `x='?token='`, found in\n // review), and so is a marker a URL scrub before this one wrote\n // (`?token=[REDACTED]\">link</a>`): the bytes after it are the text's.\n if (mode === \"string\") {\n EMBEDDED_VALUE_IN_STRING.lastIndex = valueStart;\n value = EMBEDDED_VALUE_IN_STRING.exec(body) ?? value;\n }\n const valueEnd = valueStart + value[0].length;\n into.push([valueStart, valueEnd]);\n names.lastIndex = valueEnd;\n }\n}\n\n/**\n * The text of each `<script>` in `body`, to its end tag or the body's\n * end. An open tag is found, then its `>`, each once: a pattern that took\n * the tag whole read to the body's end from every `<script` with no `>`\n * after it, seconds on a 512 KB response (MEASURED in review). With no\n * `>` left, no tag can open.\n */\nfunction scriptRanges(body: string): Range[] {\n const out: Range[] = [];\n const open = /<script\\b/gi;\n const close = /<\\/script\\s*>/gi;\n for (let m = open.exec(body); m !== null; m = open.exec(body)) {\n const gt = body.indexOf(\">\", m.index);\n if (gt === -1) break;\n close.lastIndex = gt + 1;\n const end = close.exec(body);\n const to = end === null ? body.length : end.index;\n out.push([gt + 1, to]);\n open.lastIndex = to;\n }\n return out;\n}\n\n/** A character an embedded pair can follow, as sent or once decoded. */\nconst PAIR_LEAD = /[?;\\n]|%(?:3[FfBb]|26|0[Aa])/;\n\n/**\n * One segment of a form: a pair or a bare name, its trimmed raw name a\n * form name and its value free of raw whitespace (an encoded value\n * carries none; one that does is prose or markup, kept byte for byte on\n * the other path). An empty segment -- a trailing or doubled `&` -- has\n * the empty name, which FORM_NAME accepts.\n */\nfunction formSegment(seg: string): boolean {\n const eq = seg.indexOf(\"=\");\n const name = (eq === -1 ? seg : seg.slice(0, eq)).trim();\n return FORM_NAME.test(name) && (eq === -1 || !/\\s/.test(seg.slice(eq + 1)));\n}\n\n/**\n * The embedded credential pairs inside one form segment, text[from, to).\n *\n * Per segment, and only a segment that holds a character a pair can\n * follow (`?`, `;`, `&` once decoded, a newline): a search over the whole\n * form found every pair of the form itself again and re-checked each name\n * the segment loop had just checked, which doubled the cost of a form of\n * many fields on the page's main thread (512 KB of `a=b&`: 18 -> 35 ms\n * quiet, over a second under load). The check is a walk over the segment\n * alone, so it stays linear. A segment's start counts as a line start.\n */\nfunction spanPairRanges(\n text: string,\n from: number,\n to: number,\n into: Range[],\n): void {\n let lead = false;\n for (let i = from; i < to && !lead; i++) {\n const c = text.charCodeAt(i);\n lead = c === 63 || c === 59 || c === 38 || c === 10; // ? ; & \\n\n }\n if (!lead) return;\n const found: Range[] = [];\n embeddedPairRanges(text.slice(from, to), found);\n for (const [s0, e0] of found) into.push([from + s0, from + e0]);\n}\n\n/**\n * A content-type under which the page itself says the body is a form.\n * multipart is here because network.ts records a FormData -- passed\n * directly or inside a Request -- as the urlencoded pairs of its fields\n * (see formDataText). Multipart TEXT, as a page writes it by hand, is\n * parsed before this is consulted (see redactMultipartText).\n */\nconst DECLARED_FORM =\n /^\\s*(?:application\\/x-www-form-urlencoded|multipart\\/form-data)\\s*(?:;|$)/i;\n\n/**\n * Whether a body is read as a form (redactFormBody), `body` its bytes with\n * its URLs read as a form's and the cut marker, if any, on. The page says\n * so for one it declares x-www-form-urlencoded: it is one whatever its\n * bytes look like, and every\n * value runs to the next `&` -- a hand-built `password=correct horse\n * battery staple` recorded `password=[REDACTED] horse battery staple`\n * while the raw spaces sent it down the embedded-pair path, whose value\n * stops at the first space (review round 3). Under multipart a body that\n * is no multipart text is a FormData's rendering (see formDataText).\n * Otherwise it is one shaped as a form throughout: every segment a pair or\n * a bare name (no whitespace inside a trimmed name), and at least one\n * pair. A cut tail is exempt from the shape test -- the cut may have taken\n * its `=` or split a value -- and may be that pair, so `password=abc(def`\n * cut at the cap keeps its whole value redacted. A cut segment of HTML or\n * a log line taken for a form this way loses nothing: the form path\n * searches every segment for embedded credential pairs as the text path\n * does.\n */\nfunction readAsForm(body: string, contentType: string): boolean {\n if (MULTIPART.test(contentType)) return isFormRendering(body);\n if (DECLARED_FORM.test(contentType)) return true;\n const cut = body.endsWith(TRUNCATED_SUFFIX);\n const text = cut ? body.slice(0, -TRUNCATED_SUFFIX.length) : body;\n const segments = text.split(\"&\");\n const last = segments.length - 1;\n return (\n segments.some((seg) => seg.includes(\"=\")) &&\n segments.every((seg, i) => (cut && i === last) || formSegment(seg))\n );\n}\n\n/** The body redacted as a form, or null when nothing in it applied; `formShaped` is readAsForm's answer. */\nfunction redactFormBody(\n body: string,\n extra: readonly RegExp[],\n formShaped: boolean,\n code = false,\n): string | null {\n // A cut body ends mid-pair: its last segment may have lost its `=`.\n const cut = body.endsWith(TRUNCATED_SUFFIX);\n const text = cut ? body.slice(0, -TRUNCATED_SUFFIX.length) : body;\n const segments = text.split(\"&\");\n if (!formShaped) {\n // Only a body that holds a credential pair takes this path; any other\n // text is the caller's plain scan. The cut marker is the SDK's, not the\n // body's: it is set aside, or a value read up to it took its dots.\n const ranges: Range[] = [];\n embeddedPairRanges(text, ranges, code ? \"code\" : \"text\");\n if (ranges.length === 0) return null;\n detectorRanges(text, extra, ranges);\n return applyRanges(text, ranges) + (cut ? TRUNCATED_SUFFIX : \"\");\n }\n\n // ONE pass of every detector over the body as it came, and one over it\n // decoded, each name and value decoded with a map back to its raw\n // bytes; the `&` and `=` between them stay themselves. No built-in can\n // match across an `&` or an `=` (none of them admits either), so a\n // whole-body scan finds exactly what a scan per name and value found --\n // at one pass instead of six per pair, which cost 100-300x base on a\n // form of many fields (review r8). The integrator's patterns see the\n // whole body too, so one may span `name=value` (`member_id=\\d+`) or\n // several fields (review round 5, H2), as base's scan of the whole body\n // allowed, and one written against the decoded value (`dob=01/02/1990`\n // in a FormData, recorded as `dob=01%2F02%2F1990`) matches it (review\n // r6, B2). PII in the NAME half of a pair is found the same way (review\n // round 4).\n const ranges: Range[] = [];\n detectorRanges(text, extra, ranges);\n // With no `%` and no `+` anywhere, the decoded form IS the form as sent,\n // and a second scan of it would find exactly the same ranges.\n const escaped = /[%+]/.test(text);\n const decoded = newDecodedText(escaped ? text.length : 0);\n // An embedded pair follows `?`, `;` or a newline, raw or escaped, or an\n // `&` that only decoding produces. A form with none of them -- most\n // forms -- skips the pair search below: one pass instead of one per\n // segment.\n const pairsPossible = PAIR_LEAD.test(text);\n // Where each segment sits in the decoded text, for the pair search below.\n const decodedSegments: number[] = [];\n // An OAuth token exchange's `code` (isTokenExchange).\n const exchange = isTokenExchange(\n segments.flatMap((seg) => {\n const eq = seg.indexOf(\"=\");\n return eq === -1\n ? []\n : [\n [\n normalizeKey(formDecode(seg.slice(0, eq))),\n formDecode(seg.slice(eq + 1)),\n ] as [string, string],\n ];\n }),\n );\n // Raw JSON values redacted in their own text, and the scratch result.\n const jsonSpans: Range[] = [];\n let json: Range | null;\n let at = 0;\n for (const seg of segments) {\n const eq = seg.indexOf(\"=\");\n const nameEnd = eq === -1 ? at + seg.length : at + eq;\n const segEnd = at + seg.length;\n const from = decoded.length;\n if (escaped) appendDecoded(text, at, nameEnd, decoded);\n if (eq !== -1 && escaped) {\n appendUnit(decoded, \"=\", nameEnd, nameEnd + 1);\n appendDecoded(text, nameEnd + 1, segEnd, decoded);\n }\n // A sensitive name redacts its value wherever the pair sits, an\n // empty one included.\n if (\n eq !== -1 &&\n (isCredentialName(seg.slice(0, eq), \"param\") ||\n (exchange &&\n EXCHANGE_REDACTED.has(normalizeKey(formDecode(seg.slice(0, eq))))))\n ) {\n ranges.push([nameEnd + 1, segEnd]);\n } else if (\n eq !== -1 &&\n holdsEncodedUrlCredential(text.slice(nameEnd + 1, segEnd))\n ) {\n // A URL a value holds encoded, with a credential in it\n // (holdsEncodedUrlCredential): the value goes whole.\n ranges.push([nameEnd + 1, segEnd]);\n } else if (\n eq !== -1 &&\n (json = jsonFormValue(text, nameEnd + 1, segEnd, extra)) !== null\n ) {\n // A value that is JSON with something in it to redact -- a GraphQL\n // multipart upload's `operations` carries the variables. Written as\n // it came, it is redacted in its own text; URL-encoded, it goes\n // whole, since a redaction inside it cannot be written back without\n // re-encoding the rest.\n if (json.length === 3) jsonSpans.push(json);\n else ranges.push(json);\n } else if (pairsPossible) {\n // A credential pair INSIDE any other segment -- a redirect URL's\n // `?token=` in a value, a `cb?pwd=` in a name -- is found as in any\n // other text, raw here and decoded below.\n spanPairRanges(text, at, segEnd, ranges);\n if (escaped) decodedSegments.push(from, decoded.length);\n }\n at += seg.length;\n if (at < text.length) {\n if (escaped) appendUnit(decoded, \"&\", at, at + 1);\n at++;\n }\n }\n if (escaped) {\n const found: Range[] = [];\n const plain = decoded.parts.join(\"\");\n detectorRanges(plain, extra, found);\n // `redirect=https%3A%2F%2Fx%2Fcb%3Ftoken%3Dabc` holds `?token=abc`\n // only once decoded.\n for (let k = 0; k < decodedSegments.length; k += 2) {\n spanPairRanges(plain, decodedSegments[k], decodedSegments[k + 1], found);\n }\n for (const [s0, e0] of found) {\n ranges.push([decoded.start[s0], decoded.end[e0 - 1]]);\n }\n }\n // A raw JSON value's own redaction already scanned it: a detector's\n // range inside it would merge with it into a bare marker.\n // jsonSpans are in text order and disjoint (one per segment): each\n // range is looked up by binary search, not against every span -- a\n // form of 40,000 JSON fields was quadratic (review).\n const kept = ranges.filter(([a, b]) => !insideSpan(jsonSpans, a, b));\n return (\n applyRanges(text, [...kept, ...jsonSpans]) + (cut ? TRUNCATED_SUFFIX : \"\")\n );\n}\n\n/* ------------------------------------------------------------------ */\n/* Multipart text */\n/* ------------------------------------------------------------------ */\n\nconst MULTIPART = /^\\s*multipart\\/form-data\\s*(?:;|$)/i;\nconst BOUNDARY_PARAM =\n /;\\s*boundary\\s*=\\s*(?:\"([^\"\\r\\n]{1,200})\"|([^\\s;\"]{1,200}))/i;\n/** A part's field name in its Content-Disposition header. */\nconst PART_NAME =\n /^content-disposition\\s*:[^\\n]*?;\\s*name\\s*=\\s*(?:\"([^\"\\r\\n]*)\"|([^\\s;]+))/im;\n/** A part that carries a file: its bytes are never recorded. */\nconst PART_FILE = /^content-disposition\\s*:[^\\n]*?;\\s*filename\\*?\\s*=/im;\n\n/**\n * A multipart body written out as TEXT -- by hand, as a string passed to\n * fetch or XMLHttpRequest, or served as a response -- redacted part by\n * part, or null when the body is not one.\n *\n * Without this such a body took the form path, which knows `&` and `=`\n * and not parts: a `name=\"password\"` part's value was recorded in clear,\n * and a `&password=` inside another part's text redacted everything after\n * it, the closing boundary included (review r1 of the port, M2).\n *\n * The boundary is the content-type's, or -- when the page declared none\n * -- the body's own first line. Each part's value is replaced whole when\n * its name is sensitive (as a form field's is: `password`, `user[token]`)\n * or when the part is a file; every other value, and every header block,\n * is scanned like any other text. Every other byte is kept. A body cut at\n * the cap keeps what it has: its last part runs to the cut.\n */\nfunction redactMultipartText(\n body: string,\n contentType: string,\n extra: readonly RegExp[],\n): string | null {\n if (!MULTIPART.test(contentType)) return null;\n const cut = body.endsWith(TRUNCATED_SUFFIX);\n const text = cut ? body.slice(0, -TRUNCATED_SUFFIX.length) : body;\n const param = BOUNDARY_PARAM.exec(contentType);\n const boundary =\n param !== null\n ? (param[1] ?? param[2])\n : (/^--([^\\r\\n]{1,200})\\r?\\n/.exec(text)?.[1] ?? null);\n if (boundary === null) return null;\n const delimiter = \"--\" + boundary;\n let at = text.startsWith(delimiter) ? 0 : text.indexOf(\"\\n\" + delimiter);\n // Not multipart text: a FormData rendering (pairs) or anything else.\n if (at === -1) return null;\n if (at > 0) at += 1;\n const ranges: Range[] = [];\n scanSpan(text, 0, at, extra, ranges); // a preamble\n for (;;) {\n const after = at + delimiter.length;\n // A close delimiter ends the body only when no delimiter follows it:\n // `--X--` written inside a value must not leave the parts after it\n // to the pattern scan alone (review r2).\n if (\n text.startsWith(\"--\", after) &&\n text.indexOf(\"\\n\" + delimiter, after) === -1\n ) {\n scanSpan(text, after + 2, text.length, extra, ranges); // an epilogue\n break;\n }\n const lineEnd = text.indexOf(\"\\n\", after);\n if (lineEnd === -1) break; // cut inside a delimiter line\n // Headers run to the first empty line.\n let line = lineEnd + 1;\n let valueStart = -1;\n while (line < text.length) {\n const end = text.indexOf(\"\\n\", line);\n if (end === -1) break;\n if (end === line || (end === line + 1 && text[line] === \"\\r\")) {\n valueStart = end + 1;\n break;\n }\n line = end + 1;\n }\n const headersEnd = valueStart === -1 ? text.length : valueStart;\n scanSpan(text, lineEnd + 1, headersEnd, extra, ranges);\n if (valueStart === -1) break; // cut inside a header block\n const next = text.indexOf(\"\\n\" + delimiter, valueStart);\n let valueEnd = next === -1 ? text.length : next;\n if (next !== -1 && valueEnd > valueStart && text[valueEnd - 1] === \"\\r\") {\n valueEnd--;\n }\n const headers = text.slice(lineEnd + 1, headersEnd);\n const name = PART_NAME.exec(headers);\n const fieldName = name === null ? \"\" : (name[1] ?? name[2]);\n const jsonPart =\n PART_FILE.test(headers) || isCredentialName(fieldName, \"param\")\n ? null\n : redactJsonString(text.slice(valueStart, valueEnd), 0, extra);\n if (PART_FILE.test(headers) || isCredentialName(fieldName, \"param\")) {\n ranges.push([valueStart, valueEnd]);\n } else if (\n jsonPart !== null &&\n jsonPart !== text.slice(valueStart, valueEnd)\n ) {\n // A JSON part with something in it to redact (a GraphQL upload's\n // `operations`), redacted in its own text.\n ranges.push([valueStart, valueEnd, jsonPart]);\n } else {\n scanSpan(text, valueStart, valueEnd, extra, ranges);\n }\n if (next === -1) break;\n at = next + 1;\n }\n return applyRanges(text, ranges) + (cut ? TRUNCATED_SUFFIX : \"\");\n}\n\n/** The fail-closed note: a body nothing here can read safely. */\nconst UNREADABLE = \"[Unreadable body]\";\n\n/**\n * True for a body shaped as a FormData's urlencoded rendering, whole or\n * cut: every `&`-segment a form segment. The cut marker holds no `=`, `&`\n * or whitespace, and its dots, brackets and letters are name characters,\n * so it never makes a segment pass that would fail without it, and a\n * rendering cut anywhere, inside a name or a value, still passes. The\n * last segment of a cut body was once let through unread, and a cut body\n * with no `&` is one segment and the last: a multipart body under another\n * boundary than the declared one, cut at the cap, passed for a rendering\n * and went down the form path, which cannot see its parts.\n */\nfunction isFormRendering(body: string): boolean {\n return body.split(\"&\").every(formSegment);\n}\n\n/** True when [a, b) lies inside one of `spans`, which are sorted and disjoint. */\nfunction insideSpan(spans: Range[], a: number, b: number): boolean {\n let lo = 0;\n let hi = spans.length - 1;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n const [c, d] = spans[mid];\n if (a < c) hi = mid - 1;\n else if (a >= d) lo = mid + 1;\n else return b <= d;\n }\n return false;\n}\n\n/**\n * A form value that is JSON with something in it to redact, as the range\n * to write, or null. Written as it came (no `%`, no `+`), its own\n * redaction is the replacement, every other byte kept; URL-encoded, the\n * whole value goes.\n */\nfunction jsonFormValue(\n text: string,\n start: number,\n end: number,\n extra: readonly RegExp[],\n): Range | null {\n const raw = text.slice(start, end);\n if (!/^(?:%7B|%5B|[[{])/i.test(raw)) return null;\n if (/[%+]/.test(raw)) {\n const decoded = formDecode(raw);\n const redacted = redactJsonString(decoded, 0, extra);\n return redacted === null || redacted === decoded ? null : [start, end];\n }\n const redacted = redactJsonString(raw, 0, extra);\n return redacted === null || redacted === raw ? null : [start, end, redacted];\n}\n\n/** text[from, to) scanned like any other text, its ranges shifted back. */\nfunction scanSpan(\n text: string,\n from: number,\n to: number,\n extra: readonly RegExp[],\n into: Range[],\n): void {\n if (from >= to) return;\n const span = text.slice(from, to);\n const found: Range[] = [];\n detectorRanges(span, extra, found);\n embeddedPairRanges(span, found);\n for (const [s0, e0] of found) into.push([from + s0, from + e0]);\n}\n\n/** Exposed for tests and diagnostics. */\nexport const __internals = {\n isSensitiveKey,\n isLikelyCardNumber,\n passesLuhn,\n redactCards,\n};\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - Privacy / PII masking engine */\n/* ------------------------------------------------------------------ */\n\nimport type {\n CaptureConfig,\n NetworkEvent,\n PiiPattern,\n PrivacyConfig,\n} from \"./types\";\nimport {\n decoded,\n decodePart,\n isCredentialParts,\n keyRules,\n nameParts,\n scrubUrl,\n type PairContext,\n type UrlRules,\n} from \"@keploy/contract/privacy\";\nimport type { BodyJob, BodyOut } from \"./body-redact\";\nimport {\n isPlainState,\n isSensitiveKey,\n redactStringValue,\n redactTokens,\n scrubHeaderUrls,\n tokenRanges,\n} from \"./redact\";\n\n/**\n * `url` as a request's URL is recorded: by the one URL scrubber\n * (@keploy/contract's privacy.ts scrubUrl) under the replay key's rules\n * (keyRules) -- a credential's value replaced by name, a pair read from\n * `&` to `&` and replaced whole when anything in it is a credential's (a\n * `;name=` inside it, a URL nested or encoded in it), a path's\n * `;jsessionid=` and its user info scrubbed -- and under strict every\n * query value. The path is otherwise kept, and a value is never judged by\n * its shape: both are the request's identity at replay. Scanning query\n * VALUES corrupted the canonical key: ?orderId=8675309 became\n * ?orderId=%5BREDACTED%5D and replay, which sees the real value, could\n * never match. `url` carries no fragment.\n */\nfunction maskQueryValues(url: string, strict = false): string {\n return scrubUrl(url, strict ? STRICT_KEY_RULES : KEY_RULES);\n}\n\nconst KEY_RULES = keyRules(false);\nconst STRICT_KEY_RULES = keyRules(true);\n\n/*\n * A PAGE URL's credentials, found two ways.\n *\n * BY NAME, where the URL's own structure shows them, by the one rule\n * every name the SDK records is read by (@keploy/contract's privacy.ts\n * isCredentialName, as a `page`), a\n * request's and a URL held in a body included. It must not eat the app's\n * own parameters -- `?state=closed`, `?code=US`, a paging `pageToken` --\n * or the recording names the wrong page (found in review).\n *\n * BY VALUE, everywhere else (pageSecrets): a credential the URL carries --\n * by name, as a link page's `key` or `t`, as an OAuth callback's code, a\n * CAS ticket, a reset or invite link's path token, or inside a nested\n * return-to URL -- is a value, and\n * that value is scrubbed from every event the SDK sends (scrubSecrets). A\n * rule about where URLs sit in a recording could not hold: rrweb makes\n * links absolute by URL resolution and CSS url() by cutting the page URL\n * at a `/`, and a share link or a hidden input copies it encoded (found in\n * review, three times). Only a value that LOOKS GENERATED is scrubbed\n * everywhere (looksRandom): an app's own `state=delivered` or\n * `/activate/two-factor-authentication` scrubbed for the life of the page\n * ate its text, its classes and its request bodies (found in review).\n */\n/**\n * What reading a page URL's `name=value` pairs did, COUNTED rather than\n * timed, as scrubWork is: the units the scan below looked at. Its cost is\n * linear in the text, and the tests hold it by this count -- it was held\n * by a clock (under 2 s for 60 KB), and on a fast machine the scan that\n * reads a run from each of its units, the square of its length, stayed\n * under it (found running the mutation table through the gate).\n */\nexport const urlWork = { scanned: 0 };\n\nconst SLASH = 47;\nconst AMPERSAND = 38;\nconst SEMICOLON = 59;\nconst QUESTION = 63;\nconst HASH = 35;\nconst EQUALS = 61;\n\n/** `/`, `&`, `;`, `?` or `#`: what a pair's name follows, and what ends a run that held none. */\nfunction startsPair(unit: number): boolean {\n return (\n unit === SLASH ||\n unit === AMPERSAND ||\n unit === SEMICOLON ||\n unit === QUESTION ||\n unit === HASH\n );\n}\n\n/**\n * Every `name=` in `text` that a pair can start with, in order: a name\n * starts the text or follows a delimiter (startsPair), holds no delimiter\n * and no `=`, and ends at its `=`. `visit` is given where the name starts\n * and where its `=` stands, and answers where the scan goes on from --\n * past the `=`, or past as much of the value as the pair takes.\n *\n * IN ONE PASS, and counted (urlWork). It was two regular expressions,\n * each anchored to a delimiter for this: unanchored, as the first cut\n * had them, a name was tried from every position of a run with no `=`\n * and the run read to its end each time, so a 30 KB URL state froze the\n * page for a second on every History call (MEASURED in review #7). A\n * scan written out cannot be asked to do that by one character of a\n * pattern, and what it reads can be counted.\n */\nfunction eachPair(\n text: string,\n visit: (start: number, equals: number) => number,\n): void {\n const n = text.length;\n // Where a name may start: the text's start, or just after a delimiter.\n let start = 0;\n while (start <= n) {\n let j = start;\n let unit = 0;\n while (j < n && (unit = text.charCodeAt(j)) !== EQUALS && !startsPair(unit))\n j++;\n urlWork.scanned += j - start + 1;\n // Where the next delimiter is looked for from.\n let next: number;\n if (j < n && unit === EQUALS) {\n // A name and its `=`; or a `=` with no name before it, which is\n // passed.\n next = j > start ? visit(start, j) : j + 1;\n } else {\n // A run that reached a delimiter, or the end, held no name. The\n // scan goes on FROM THERE, never back into the run.\n next = j;\n }\n const from = next;\n while (next < n && !startsPair(text.charCodeAt(next))) next++;\n urlWork.scanned += next - from + 1;\n if (next >= n) return;\n start = next + 1;\n }\n}\n\n/** Where the value that starts at `from` ends: at the next `&`, `;` or `#` -- and `?`, unless `inQuery` -- or the text's end. */\nfunction valueEnd(text: string, from: number, inQuery: boolean): number {\n let stop = from;\n for (; stop < text.length; stop++) {\n const unit = text.charCodeAt(stop);\n if (\n unit === AMPERSAND ||\n unit === SEMICOLON ||\n unit === HASH ||\n (!inQuery && unit === QUESTION)\n )\n break;\n }\n urlWork.scanned += stop - from + 1;\n return stop;\n}\n\n/**\n * Every `name=value` of a page URL, as written: each value runs to the\n * next `&`, `;` or `#`, and holds whatever stands before it -- a `/`, a\n * `?`, another `=`.\n */\nexport function pagePairs(url: string): Array<[string, string]> {\n const pairs: Array<[string, string]> = [];\n eachPair(url, (start, equals) => {\n const stop = valueEnd(url, equals + 1, true);\n pairs.push([url.slice(start, equals), url.slice(equals + 1, stop)]);\n return stop;\n });\n return pairs;\n}\n\n/**\n * How much of a value says it is a URL: read to its end from every name,\n * a value of `t=https://a/` repeated was read once per pair, the square\n * of its length (found in review).\n */\nconst URL_HEAD = 256;\n\n/**\n * Every sensitive `name=value` in `text` -- a path's matrix parameters, a\n * route, a query -- with its value redacted up to the next `&`, `;` or `#`\n * (and `?` outside a query): a token can hold `/` (base64). The value of\n * a pair that is not sensitive is read on for names, after its\n * delimiters: `?next=/reset?token=...`.\n */\nexport function maskPairs(\n text: string,\n inQuery: boolean,\n linkPage = false,\n): string {\n let out = \"\";\n let at = 0;\n eachPair(text, (start, equals) => {\n const names = nameParts(text.slice(start, equals), \"page\");\n const from = equals + 1;\n if (\n !isCredentialParts(names, \"page\") &&\n !(linkPage && linkPageValue(names, text.slice(from, from + URL_HEAD)))\n )\n return from;\n const stop = valueEnd(text, from, inQuery);\n out += text.slice(at, from) + \"[REDACTED]\";\n at = stop;\n return stop;\n });\n return out + text.slice(at);\n}\n\n/** A page URL without its fragment, its sensitive values redacted by name. */\nfunction maskPageUrl(url: string, linkPage: boolean): string {\n const q = url.indexOf(\"?\");\n if (q === -1) return maskPairs(url, false);\n return `${maskPairs(url.slice(0, q), false)}?${maskPairs(url.slice(q + 1), true, linkPage)}`;\n}\n\n/**\n * A fragment that is a hash router's ROUTE (`#/cart`, `#!/cart`) rather\n * than an in-page anchor (`#reviews`) or a value handed to the page in\n * the fragment (`#access_token=…`, the OAuth implicit flow's).\n */\nconst ROUTE_FRAGMENT = /^!?\\//;\n\n/** Values shorter than this are redacted only where a name shows them: scrubbing a short string everywhere would eat the page. */\nconst MIN_SCRUBBED = 8;\n\n/**\n * Whether a value looks generated rather than written: at least\n * MIN_SCRUBBED characters mixing two of lower case, upper case and digits,\n * and not a capitalised word. Only such a value is scrubbed everywhere: a\n * word -- `delivered`, `California`, `required`,\n * `two-factor-authentication` -- also appears in the page's own text,\n * classes and requests. Nor are digits alone: a run of them is also an\n * order number, a price or an id in a response body, which a replacement\n * left unparseable (found in review). A credential that is not\n * generated-looking is still redacted where its name shows it.\n */\nfunction looksRandom(v: string): boolean {\n if (v.length < MIN_SCRUBBED) return false;\n const kinds =\n Number(/[a-z]/.test(v)) + Number(/[A-Z]/.test(v)) + Number(/\\d/.test(v));\n // Nor a slug of words and numbers (`annual-meeting-2024-berlin`): read\n // as generated, an app's own event page was taken for a link's token\n // (found in review). A word is lower-case or capitalised: in any case\n // at all, 1-4% of real base64url tokens, which carry `-` and `_`, read\n // as slugs and were recorded (MEASURED in review).\n // Nor a camel- or PascalCased word (`childNodes`, `textContent`): read as\n // generated, a crafted `?auth_token=childNodes` renamed rrweb's own keys\n // and destroyed the recording (found in review).\n return (\n kinds >= 2 &&\n !/^[A-Z][a-z]+$/.test(v) &&\n !/^[A-Za-z][a-z]*(?:[-_](?:[A-Za-z][a-z]*|\\d+))+$/.test(v) &&\n !/^[A-Za-z][a-z]{2,}(?:[A-Z][a-z]{2,})+$/.test(v)\n );\n}\n\n/**\n * A value that is a URL -- or, with `paths`, a path: an OAuth `state` that\n * carries the return URL, `/projects/42` -- is not a credential: scrubbing\n * it, and its prefixes at each `/`, ate the page's own URLs, origin\n * included, for the rest of the page (found in review). A credential\n * nested in it is found by the nested read. Only an OAuth code or state\n * is exempt as a PATH: a value a credential's NAME shows is a credential\n * even when it begins with `/`, as one standard-base64 token in 64 does\n * (found in review).\n */\nfunction isUrlLike(v: string, paths = true): boolean {\n return (\n paths ? /^(?:\\/|[a-z][a-z\\d+.-]*:\\/\\/)/i : /^[a-z][a-z\\d+.-]*:\\/\\//i\n ).test(decoded(v));\n}\n\n/** A segment's words: split at `-`, `_`, `.` and a lower-to-upper case change, lower-cased. */\nfunction segmentWords(segment: string): string[] {\n return decoded(segment)\n .replace(/([a-z\\d])([A-Z])/g, \"$1 $2\")\n .split(/[\\s\\-_.]+/)\n .filter((w) => w !== \"\")\n .map((w) => w.toLowerCase());\n}\n\n/*\n * A LINK'S PATH TOKEN is told from an app's own id by two things: the words\n * of the segment it follows, and its own shape.\n *\n * THE WORDS. Every word of the segment must be a link's own -- or an app's\n * `/products/apple-magic-mouse/<id>` is a link; a file extension\n * (`reset.php`) is not a word. A STRONG segment names the act: reset,\n * verify, unlock, activate, invite, forgot, recover, a magic or login\n * link, accept an invitation, or confirm an email, account, registration\n * or sign-up named in its segment or the one before it\n * (`/confirm-email/<t>`, `/email/confirm/<t>`); the noun, a confirmation,\n * names a page (`/account/confirmation/<id>`). A WEAK one names a thing\n * that a token or an app's id may follow: a confirmation, an invitation, a\n * verification, an activation, a password, a sign-up, a log-in.\n *\n * THE SHAPE. An ID is digits, a UUID, a 24-hex ObjectId, a ULID, a cuid, a\n * prefixed id (`inv_…`, `cs_test_…`), or a uid -- Django's and Djoser's\n * base64 of a pk -- where one is expected: before a token, or after a\n * strong segment. TOKEN-SHAPED is any other generated-looking value of 16\n * characters or more (20 after a weak segment). After the segment are read\n * short ids, the link's own words (confirm, accept, edit) and ids, up to\n * the first token-shaped value -- the token\n * (`/reset-password/<ObjectId>/<JWT>`, `/account/reset/<customerId>/<t>`)\n * -- or anything else. When the path ends with ids alone after a strong\n * segment, the last of them is the token (`/invite/<uuid>`), but not when\n * a word ends the read (`/invite/<uuid>/members`); after a weak one an id\n * is the token only when an accept or join follows it\n * (`/invitations/<uuid>/accept`), never otherwise\n * (`/admin/invitations/<uuid>/edit`, `/order/confirmation/<uuid>`).\n *\n * Scrubbing an app's id broke every replay of the flow -- in its URL, its\n * requests and its responses -- and missing a token recorded it (both\n * found in review, round after round). An app's own `/invite/<id>` or\n * `/devices/reset/<uuid>` is still taken for a link: neither the words nor\n * the shape tell them apart.\n */\nconst STRONG_WORDS = new Set([\n \"reset\",\n \"resets\",\n \"verify\",\n \"unlock\",\n \"activate\",\n \"invite\",\n \"forgot\",\n \"forgotten\",\n \"recover\",\n \"recovery\",\n]);\nconst STRONG_COMPOUNDS = new Set([\n \"passwordreset\",\n \"passwordresets\",\n \"resetpassword\",\n \"verifyemail\",\n \"emailverification\",\n \"magiclink\",\n \"magiclogin\",\n \"emaillogin\",\n \"loginlink\",\n \"lostpassword\",\n // A new account's first password, set from an emailed link.\n \"setpassword\",\n \"createpassword\",\n]);\n/**\n * The link segments that name a credential outright, joined: what follows\n * `/set-password/` is a token or a page of the link, so a token goes\n * whatever its length or shape (afterCredentialWord). `/invite/friends`,\n * `/unlock/premium` and `/magic-link/sent` read otherwise, and those keep\n * the shape check.\n */\nconst CREDENTIAL_WORDS = new Set([\n \"setpassword\",\n \"createpassword\",\n \"resetpassword\",\n \"passwordreset\",\n \"forgotpassword\",\n \"forgottenpassword\",\n \"lostpassword\",\n \"verifyemail\",\n \"emailverification\",\n]);\n/** What a page after a credential word says of the link, never a token: `/verify-email/sent`, `/reset-password/success`. `confirm` and `confirmed` are a step of the link already (linkStep). */\nconst STEP_WORDS = new Set([\n \"sent\",\n \"done\",\n \"success\",\n \"complete\",\n \"new\",\n \"error\",\n \"expired\",\n \"failed\",\n \"invalid\",\n]);\nconst WEAK_WORDS = new Set([\n \"confirm\",\n \"confirmation\",\n \"confirmations\",\n \"invites\",\n \"invitation\",\n \"invitations\",\n \"verification\",\n \"verifications\",\n \"activation\",\n \"activations\",\n \"password\",\n \"passwords\",\n \"signup\",\n \"login\",\n]);\nconst CONFIRMED_THINGS = new Set([\n \"email\",\n \"account\",\n \"registration\",\n \"registrations\",\n \"signup\",\n]);\nconst LINK_AUX = new Set([\n \"accept\",\n \"link\",\n \"new\",\n \"old\",\n \"sign\",\n \"up\",\n \"email\",\n \"account\",\n \"registration\",\n \"admin\",\n \"change\",\n \"php\",\n \"asp\",\n \"aspx\",\n \"htm\",\n \"html\",\n \"jsp\",\n \"cgi\",\n]);\n\nconst confirms = (words: string[]) =>\n words.some((w) => CONFIRMED_THINGS.has(w)) ||\n words.join(\"\").includes(\"signup\");\n\n/** 2 for a strong link segment, 1 for a weak one, 0 for neither. */\nfunction linkKind(segment: string, previous: string): number {\n let words = segmentWords(segment);\n const joined = words.join(\"\");\n if (STRONG_COMPOUNDS.has(joined)) return 2;\n // A word split in two: `/users/log-in/<t>`.\n if (WEAK_WORDS.has(joined)) words = [joined];\n let kind = 0;\n for (const w of words) {\n if (STRONG_WORDS.has(w)) kind = 2;\n else if (WEAK_WORDS.has(w)) kind ||= 1;\n else if (!LINK_AUX.has(w)) return 0;\n }\n return kind === 1 &&\n (words.includes(\"accept\") ||\n (words.includes(\"confirm\") &&\n (confirms(words) || confirms(segmentWords(previous)))))\n ? 2\n : kind;\n}\n\n/**\n * An id rather than a token: digits, a UUID, a 24-hex ObjectId, a ULID or\n * a cuid -- shapes a random token does not take, each in its own case.\n * WHEN A SHAPE IS AMBIGUOUS IT IS A TOKEN: a prefixed id (`inv_…`, a\n * TypeID) was read as an id, and so was 1-4% of real nanoid and base64url\n * tokens, which were recorded (MEASURED in review); an app's own id taken\n * for a token is kept by privacy.keepRoutes, a recorded credential by\n * nothing.\n */\nfunction isId(segment: string): boolean {\n return (\n /^(?:\\d+|[\\da-f]{24}|[\\da-f]{8}(?:-[\\da-f]{4}){3}-[\\da-f]{12})$/i.test(\n segment,\n ) || /^(?:[0-7][\\dA-HJKMNP-TV-Z]{25}|c[a-z\\d]{24})$/.test(segment)\n );\n}\n\n/**\n * Django's and Djoser's `<uidb64>`: the user's pk base64url-encoded, which\n * decodes to text (`MTIzNA` is 1234), where a token's random bytes do not.\n * It is an id only where a uid is expected -- before a token, or after a\n * strong segment: Ghost's invitation token is base64 of text too, and read\n * as an id it was recorded every time (found in review).\n */\nfunction isUid(segment: string): boolean {\n // A length of 4n+1 is no base64: atob threw on every one-character\n // segment of a crafted path (MEASURED in review: 3 s for 1 MB).\n if (segment.length % 4 === 1 || !/^[\\w-]+$/.test(segment)) return false;\n try {\n return /^[\\x20-\\x7e]+$/.test(\n atob(\n segment.replace(/-/g, \"+\").replace(/_/g, \"/\") +\n \"===\".slice((segment.length + 3) % 4),\n ),\n );\n } catch {\n return false;\n }\n}\n\n/**\n * A segment a link's token may sit behind besides ids: a short one\n * (`/activate/<id>/<token>`) or a word of the link's own (Djoser's\n * `/password/reset/confirm/<uid>/<token>`, `/passwords/<token>/edit`).\n * Anything else ends the search, so a resource id further down the path\n * (`/reset/devices/<id>`) is not taken for the token.\n */\nfunction mayPrecedeToken(segment: string): boolean {\n return segment.length <= 4 || linkStep(segment);\n}\n\n/** A segment of the link's own between its word and its token: `confirm`, `accept`, `edit`. */\nfunction linkStep(segment: string): boolean {\n return segmentWords(segment).every(\n (w) => w.startsWith(\"confirm\") || w === \"accept\" || w === \"edit\",\n );\n}\n\n/**\n * Whether `segments[i]` is what a credential word hands on (CREDENTIAL_WORDS):\n * the segment right after one, whatever its length or shape, unless it is\n * a step of the link (`/reset-password/confirm/<t>`), a page of it\n * (STEP_WORDS), a file (`hero.png`) or an id with more path after it, the\n * user's (`/verify-email/42/<hash>`). The page URL rule\n * and the DOM's both ask here, so they cannot drift apart.\n */\nfunction afterCredentialWord(segments: readonly string[], i: number): boolean {\n const segment = segments[i] ?? \"\";\n return (\n CREDENTIAL_WORDS.has(segmentWords(segments[i - 1] ?? \"\").join(\"\")) &&\n !linkStep(segment) &&\n !STEP_WORDS.has(segment.toLowerCase()) &&\n !/\\.[A-Za-z][A-Za-z\\d]{0,4}$/.test(segment) &&\n !(isId(segment) && (segments[i + 1] ?? \"\") !== \"\")\n );\n}\n\n/** Words of a path an OAuth callback takes (besides any `callback` or `oauth` in it): its lone `code` is the credential. */\nconst CALLBACK_WORDS = new Set([\n \"cb\",\n \"auth\",\n \"sso\",\n \"signin\",\n \"authorize\",\n \"authorized\",\n \"redirect\",\n]);\n\n/**\n * A link segment that names an invitation (`/invite/`, `/invitations/`,\n * `/accept-invite/`): its code may be 8 characters, shorter than any\n * other link's token is taken to be.\n */\nfunction inviteLink(segment: string): boolean {\n return segmentWords(segment).some((w) => w.startsWith(\"invit\"));\n}\n\n/**\n * Whether a URL is a link page: a link word in its path or route, or\n * WordPress's reset link, `wp-login.php?action=rp`. The page URL rule and a\n * DOM link's both read a URL's pairs by this (linkPageValue), so they\n * cannot drift apart.\n */\nfunction isLinkPage(paths: string[][], action: string): boolean {\n return (\n /^(?:rp|resetpass)$/.test(action) ||\n paths.some((segments) => segments.some((s) => linkKind(s, \"\") !== 0))\n );\n}\n\n/** The value of a URL's `action`, as a page URL's names are read. */\nfunction pairValue(pairs: Array<[string, string]>): string {\n return (\n pairs.find(([n]) => nameParts(n, \"page\").includes(\"action\"))?.[1] ?? \"\"\n );\n}\n\n/** A value under a link page's own names for its token, `?key=`, `?t=`, `?hash=`, `?code=` (ASP.NET Identity's): a URL there is a return-to. */\nfunction linkPageValue(names: string[], value: string): boolean {\n return (\n names.some((n) => /^(?:key|t|hash|code)$/.test(n)) &&\n !isUrlLike(value, false)\n );\n}\n\n/** A segment that acts on the id before it: the invitee's `/invitations/<uuid>/accept`. */\nfunction actsOn(segment: string): boolean {\n const words = segmentWords(segment);\n return words.length > 0 && words.every((w) => w === \"accept\" || w === \"join\");\n}\n\n/** What a declared route must be (PrivacyConfig.secretRoutes): KUI_E_PRIVACY_ROUTE_INVALID quotes it. */\nexport const ROUTE_RULE =\n \"a route is `/`-separated segments from the path's start, each a literal, `*` (any one segment) or `:name` (the value it names), with no `?` or `#`; a secret route names at least one `:name`, a keep route has at least one literal\";\n\n/**\n * `route`'s segments, empty ones left out as a path's are, or null when it\n * is outside ROUTE_RULE for its list. Kept with a slash at its end, a\n * route matched nothing a path without one held (found in review).\n */\nexport function parseRoute(route: unknown, keep = false): string[] | null {\n if (typeof route !== \"string\" || !/^\\/[^?#]*$/.test(route)) return null;\n const segments = route.split(\"/\").filter((s) => s !== \"\");\n const name = (s: string) => /^:\\w+$/.test(s);\n return segments.every((s) => s === \"*\" || name(s) || !/[:*]/.test(s)) &&\n segments.some((s) => (keep ? s !== \"*\" && !name(s) : name(s)))\n ? segments\n : null;\n}\n\n/*\n * THE ROUTES INTEGRATORS DECLARE, for the page: page secrets belong to the\n * document, not to one capture, so every capture's routes are kept and a\n * route stays declared for the page's life. Each is kept once -- a\n * continuous capture declares its routes again every session -- and a\n * new one moves the generation, which the recorder's matcher is keyed on.\n */\nconst declared = { secret: [] as string[][], keep: [] as string[][] };\nconst declaredKeys = new Set<string>();\nlet generation = 0;\n\n/** How many times the declared routes have changed. */\nexport function routesGeneration(): number {\n return generation;\n}\n\n/** Adds routes already checked by parseRoute. */\nexport function declareRoutes(secret: string[][], keep: string[][]): void {\n for (const [list, routes] of [\n [declared.secret, secret],\n [declared.keep, keep],\n ] as const) {\n for (const route of routes) {\n const key = `${list === declared.keep}${route.join(\"/\")}`;\n if (declaredKeys.has(key)) continue;\n declaredKeys.add(key);\n list.push(route);\n generation++;\n scanned = [\"\", [], false, null];\n }\n }\n}\n\n/** A route's segment `part` matches a path's `segment`: a literal by its decoded text, in any case. */\nfunction matches(part: string, segment: string): boolean {\n return (\n part === \"*\" ||\n part[0] === \":\" ||\n decoded(segment).toLowerCase() === decoded(part).toLowerCase()\n );\n}\n\n/**\n * The values `route` names in a path's `parts` (its non-empty segments),\n * each with the segment before it (\"\" for the first) and its position, or\n * null when it does not match.\n */\nfunction named(\n route: string[],\n parts: string[],\n): Array<[string, string, number]> | null {\n const found: Array<[string, string, number]> = [];\n return route.every((part, i) => {\n const segment = parts[i];\n if (segment === undefined) return false;\n if (part[0] === \":\") found.push([segment, parts[i - 1] ?? \"\", i]);\n return matches(part, segment);\n })\n ? found\n : null;\n}\n\n/**\n * A keep route names `parts[i]` as a literal of its own, every segment\n * before it matching: an app's own page, at its own position. A secret\n * route's value there is that page's name, not a credential --\n * `/kl/settings/billing` under `/kl/:key` beside `/kl/settings` went out\n * as `/kl/[REDACTED]/billing`, everywhere (found in review) -- while a\n * position the keep route does not name is still the secret route's.\n */\nfunction keptAt(parts: string[], i: number): boolean {\n return declared.keep.some(\n (route) =>\n i < route.length &&\n route[i] !== \"*\" &&\n route[i]![0] !== \":\" &&\n route.slice(0, i + 1).every((part, j) => matches(part, parts[j]!)),\n );\n}\n\n/**\n * What the declared routes say of a path's `parts`: the credentials secret\n * routes name (each with the segment before it), the ids keep routes name,\n * and whether a keep route of literals alone IS the path -- an app's own\n * page under a secret route (`/invites/settings` under `/invites/:key`),\n * whose segments are not credentials at all. Such a route names one page:\n * matched as a prefix, `/account` kept every page under it, a reset link's\n * token included, and outranked the secret routes there (found in review).\n */\nfunction declaredOf(parts: string[]): {\n secret: Array<[string, string]>;\n kept: Set<string>;\n own: boolean;\n} {\n let own = false;\n const kept = new Set<string>();\n for (const route of declared.keep) {\n const values = named(route, parts);\n if (values === null) continue;\n // Literals ALONE: a `*` names nothing, so a route with one is no page\n // of the app's own. Taken for one -- any route with no `:name` that\n // was as long as the path -- `/unlock/<token>/welcome` was scrubbed\n // with no routes declared and left in the recording once a keep route\n // `/unlock/*/welcome` was (found running the gate's whole table).\n if (values.length === 0)\n own ||= route.length === parts.length && !route.includes(\"*\");\n for (const [v] of values) kept.add(v);\n }\n // Not skipped for the app's own page: every segment of such a page is a\n // keep route's literal at its own position, which keptAt excludes.\n const secret: Array<[string, string]> = [];\n for (const route of declared.secret)\n for (const [v, before, i] of named(route, parts) ?? [])\n if (!keptAt(parts, i) && credentialText(v)) secret.push([v, before]);\n return { secret, kept, own };\n}\n\n/**\n * A declared value is a credential only when, decoded as often as it is\n * encoded, it holds a letter or a digit. One that is separators alone --\n * `%2f`, a `/` -- matched every slash of a crafted URL: rrweb writes that\n * URL into each relative link it makes absolute, and a page of 100 links\n * under `/zinv` + 60,000 `/` + `%2f` took 3.4 s and recorded ten times its\n * own size (MEASURED in review). Decoded once, `%252f` is `%2f`, whose\n * hex digits are no credential's either. No credential is spelt that way,\n * and a value no letter or digit is in has no boundary for the rule that\n * holds it to mean anything. One still encoded after MAX_DECODINGS\n * decodings is no credential either: each decoding reads the whole value,\n * and a crafted `%2525...2f` is one more decoding per `25`.\n */\nfunction credentialText(value: string): boolean {\n let v = value;\n for (let n = 0; n <= MAX_DECODINGS; n++) {\n const next = decoded(v);\n if (next === v) return /[\\p{L}\\p{N}]/u.test(v);\n v = next;\n }\n return false;\n}\n\n/** How many encodings deep credentialText reads a value: one encoded this many times is read (one more decoding says it is done), one encoded more is refused. */\nconst MAX_DECODINGS = 16;\n\n/** A path's and a hash router's route's segments: no query, no matrix parameters, no empty ones. */\nfunction pathParts(url: string): string[][] {\n const hashAt = url.indexOf(\"#\");\n const paths = [\n url\n .slice(0, hashAt === -1 ? url.length : hashAt)\n .replace(/^[a-z][a-z\\d+.-]*:\\/\\/[^/?#]*/i, \"\"),\n ];\n const fragment = hashAt === -1 ? \"\" : url.slice(hashAt + 1);\n // A hash-bang route's path starts after its `!`: kept, `#!/invites/<key>`\n // matched no declared route, whose first segment is `invites` (found in\n // review).\n if (ROUTE_FRAGMENT.test(fragment)) paths.push(fragment.replace(/^!/, \"\"));\n // A matrix parameter is not the segment's value: kept on it, its value\n // was redacted by name in the recorded URL and the rest no longer matched\n // the form held, so the segment's own value was recorded (found in\n // review).\n return paths.map((path) =>\n path\n .split(/[?#]/)[0]!\n .split(\"/\")\n .map((segment) => segment.split(\";\")[0]!),\n );\n}\n\n/**\n * At most this many credential values are held from a URL; one carrying\n * more is a crafted one, and is recorded as its origin alone\n * (recordedPageUrl). Held whole, a fragment of 40,000 values made every\n * event pay 40,000 searches (MEASURED in review: 716 ms for 1,000 mouse\n * moves). The read itself is linear, so the parameters are not counted:\n * a dashboard's 300 `var-host`s are a page, not an attack (found in\n * review).\n *\n * A VALUE PAST THE CAP IS NOT HELD, AND WHAT CARRIES IT AGAIN IS SENT\n * WITH IT. The URL as the page's own is recorded as its origin; but a\n * link rrweb made absolute against it, a request to it, or a text that\n * holds the value is scrubbed of the values held and no others.\n * MEASURED: with 33 `k<i>_token=` values in a page's URL the 33rd stays\n * in an `<a href>` of that URL, in a DOM attribute and in a network\n * event's `url`; with 32, none does. The values a declared route names\n * in the URL's own path and route come first and are not counted, so\n * they are always held: what a crafted link can push out is a value the\n * built-in rule found, or one a route names inside a nested URL, never\n * one a route names in the page's own path. The README says so too.\n */\nconst MAX_URL_SECRETS = 32;\n/**\n * And a URL whose recorded part -- path, query, a hash router's route --\n * is longer than this is not read at all. A fragment that is no route (a\n * playground's `#code/…`) is not recorded, so it does not count: it\n * condemned the page (found in review). It is still read, in linear time,\n * for what it hands the page (`#access_token=…`).\n */\nconst MAX_URL_LENGTH = 65536;\n\n/**\n * Notes that a declared route names `value` after the segment `before`. A\n * value two routes name keeps both: kept once, `/k1/<word>?next=/k2/<word>`\n * held the word after `k1` alone, and the `k2` link carried it (found in\n * review). The segment is kept as it is matched (beforeOf), so the ways a\n * URL can spell one segment are one: kept as spelled, a link of\n * `/invites/x`, `/inviteS/x`, `/invite%73/x` ... named one value after\n * 24,576 segments and made every event pay for 122,880 forms of it\n * (MEASURED in review).\n */\nfunction declare(\n sure: Map<string, Set<string>>,\n value: string,\n before: string,\n): void {\n let befores = sure.get(value);\n if (befores === undefined) sure.set(value, (befores = new Set()));\n befores.add(beforeOf(before));\n}\n\n/**\n * A segment as a route matched it: decoded once (matches), and\n * ASCII-lower-cased as the text it is searched in is. wordAt reads a\n * segment in a text the same way, however that text spells it.\n */\nfunction beforeOf(segment: string): string {\n return asciiLower(decoded(segment));\n}\n\n/** The credential values `url` carries, nested return-to URLs included (to `depth` 2). */\nfunction collectSecrets(\n url: string,\n depth: number,\n out: Set<string>,\n sure: Map<string, Set<string>>,\n owned: Map<string, Set<string>>,\n bare: Set<string>,\n): void {\n // A link's path token, in the path and in a route fragment's path\n // (`#/reset-password/<token>`). The scheme and host are not path:\n // `verify.example.com` is a host, not a link.\n const paths = pathParts(url);\n for (const segments of paths) {\n const n = segments.length;\n const { secret, kept, own } = declaredOf(segments.filter((s) => s !== \"\"));\n for (const [value, before] of secret) {\n out.add(value);\n declare(sure, value, before);\n if (depth === 0) declare(owned, value, before);\n }\n // ONE PASS: a read resumes where the last one stopped, and a link word\n // inside it strengthens it rather than starting another. Restarted at\n // every link word, `#/` + `confirm/` x N was quadratic and froze the\n // page -- 13.5 s for `start()` on 24 KB (MEASURED in review).\n for (let i = 0; i < n; i++) {\n let kind = linkKind(segments[i]!, segments[i - 1] ?? \"\");\n if (kind === 0) continue;\n // An invitation's link, whose code may be short (inviteLink).\n const invite = inviteLink(segments[i]!);\n // What a credential word hands on goes whatever it looks like. One\n // that does not look generated is held as this segment alone: a\n // `/reset-password/success` must not take `success` out of the page.\n const handed = segments[i + 1]!;\n if (afterCredentialWord(segments, i + 1) && !kept.has(handed) && !own) {\n out.add(handed);\n if (!looksRandom(decoded(handed))) {\n if (!sure.has(handed)) bare.add(handed);\n declare(sure, handed, segments[i]!);\n }\n }\n let token = \"\";\n let id = \"\";\n let j = i + 1;\n for (; j < n; j++) {\n const segment = segments[j]!;\n const next = segments[j + 1] ?? \"\";\n if (\n isId(segment) ||\n ((kind === 2 || (next.length >= 16 && looksRandom(next))) &&\n isUid(segment))\n ) {\n id = segment;\n continue;\n }\n if (segment.length >= (kind === 2 ? 16 : 20) && looksRandom(segment)) {\n token = segment;\n break;\n }\n // An invitation's short generated code -- `Ab3dE5gH` -- is a\n // token where an id would be one: the last after a strong\n // segment, or the one an accept acts on. A reset's or a verify's\n // short segment is no code (#36's own test keeps one).\n if (invite && looksRandom(segment)) {\n id = segment;\n continue;\n }\n const stronger = linkKind(segment, segments[j - 1]!);\n if (stronger > kind) {\n kind = stronger;\n id = \"\";\n continue;\n }\n if (id !== \"\" && actsOn(segment)) {\n token = id;\n break;\n }\n if (!mayPrecedeToken(segment)) break;\n }\n // Ids alone to the end of the path, after a strong segment: the last\n // is the token. Not when a word ended the read: `/invite/<uuid>/members`\n // is a page of the app's (found in review).\n if (token === \"\" && kind === 2 && j === n) token = id;\n if (token !== \"\" && !kept.has(token) && !own) out.add(token);\n i = token === \"\" ? j - 1 : j;\n }\n }\n // Each name is decoded once.\n const pairs: Array<[string[], string]> = pagePairs(url).map(\n ([name, held]) => [nameParts(name, \"page\"), held],\n );\n const value = (n: string) =>\n pairs.find(([names]) => names.includes(n))?.[1] ?? \"\";\n const linkPage = isLinkPage(paths, value(\"action\"));\n // Auth0's organization invitation: `?invitation=<ticket>&organization=`.\n const auth0 = value(\"organization\") !== \"\";\n // An OAuth callback's code: beside a generated-looking state -- not an\n // app's `?code=US&state=CA` or `?code=ORD-2024-000123&state=delivered`\n // -- or alone, long and generated-looking (GitHub's 20-character code, a\n // PKCE code) on a callback's path: alone anywhere, a promo code\n // `?code=SUMMER2024DISCOUNTCODE` was scrubbed (found in review).\n const code = value(\"code\");\n const state = value(\"state\");\n const callback =\n !isUrlLike(code) &&\n // An OAuth state is generated, not a camel-cased word: an app's\n // `state=inProgress` beside an order code read as a callback's, and\n // both were scrubbed (found in review).\n ((code.length >= 10 &&\n looksRandom(state) &&\n !/^[A-Za-z][a-z]+(?:[A-Z][a-z]+)+$/.test(state) &&\n !isUrlLike(state)) ||\n (code.length >= 20 &&\n looksRandom(code) &&\n paths.some((segments) =>\n segments.some(\n (segment) =>\n /callback|oauth/i.test(segment) ||\n [...segmentWords(segment), segmentWords(segment).join(\"\")].some(\n (w) => CALLBACK_WORDS.has(w),\n ),\n ),\n )));\n for (const [names, raw] of pairs) {\n const oauth =\n callback && (names.includes(\"code\") || names.includes(\"state\"));\n if (\n (oauth ||\n isCredentialParts(names, \"page\") ||\n (linkPage && linkPageValue(names, raw)) ||\n (auth0 && names.includes(\"invitation\")) ||\n (names.includes(\"ticket\") && /^(?:ST|PT|TGT)-/.test(raw))) &&\n !isUrlLike(raw, oauth)\n ) {\n out.add(raw);\n continue;\n }\n // A nested URL is read when it carries a query or a fragment, or is\n // a URL or a path at all: a return-to path, `next=/reset/<token>`,\n // carries a link's token in its path alone.\n const inner = decoded(raw);\n if (depth < 2 && (/[?#=]/.test(inner) || isUrlLike(inner)))\n collectSecrets(inner, depth + 1, out, sure, owned, bare);\n }\n}\n\n/** The origin of `href`, or \"\" when it has none. */\nfunction originOf(href: string): string {\n try {\n return new URL(href).origin;\n } catch {\n return \"\";\n }\n}\n\n/**\n * A credential a page URL carries, as every event is scrubbed of it\n * (scrubSecrets). Kept as a kind beside its value, never as a marker\n * inside it: a NUL marker was also a value's first character once\n * `%00` decoded, so a token went out and an unrelated string was\n * redacted (found in review).\n */\nexport type PageSecret =\n /** Generated-looking: replaced wherever it appears. */\n | { kind: 0; value: string }\n /** Declared, of at least DECLARED_EVERYWHERE characters: replaced in any case wherever no ASCII letter or digit touches it. */\n | { kind: 1; value: string }\n /** Declared, and shorter: replaced only as the path segment after `before`, as beforeOf matches it (DECLARED_EVERYWHERE). */\n | { kind: 2; value: string; before: string };\n\n/**\n * A DECLARED VALUE that does not look generated -- a 6-character invite\n * code -- is a credential all the same, and the page hands it on: to the\n * request that redeems it, to its own text, to a share link. Held as a\n * whole path segment only, it went out in every one of those (found in\n * review). So one of at least this many characters is replaced, in any\n * case, wherever no ASCII letter or digit touches it -- `{\"code\":\"QX7P2K\"}`,\n * `Code: QX7P2K.`, `?code=qx7p2k` -- WHATEVER ITS LETTERS. Told apart from\n * a word by its shape (a digit, or capitals alone), 32% of random\n * 6-character base62 codes, 35% of nanoid's and 15% of lower-case base36's\n * read as words and went out (MEASURED in review), and no shape tells\n * `qxpkzm` from `create`. A credential wins: a page of the app's own that a\n * secret route also matches -- `/invites/notifications` under\n * `/invites/:code` -- has its name scrubbed from the page's events from\n * then on (a single-page app keeps a page's values after it navigates\n * away) until a keep route names it (`/invites/notifications`), which the integrator\n * can do, where a code recorded by mistake cannot be taken back. A shorter\n * value is too short to scrub from text -- `/invites/new` made every `new`\n * in the page `[REDACTED]` (found in review) -- and is replaced only as the\n * segment after the one its route put before it -- `invites/new`, in any\n * case, wherever a URL holds it -- and a route that names a first segment\n * holds it as any whole segment.\n */\nconst DECLARED_EVERYWHERE = 6;\n\n/**\n * The credential values in a page URL that every event is scrubbed of\n * (scrubSecrets): each as it appears, decoded and encoded, and cut at each\n * of its last four `/`. EVERY FORM is held to the rule the value is:\n * generated-looking, not a URL, and not part of the page's own origin -- a\n * form that is a word, or a prefix of an origin, scrubbed the page's own\n * text and URLs for the rest of the page (found in review). A declared\n * value is held by DECLARED_EVERYWHERE's rule instead.\n */\nexport function pageSecrets(href: string): PageSecret[] {\n return scan(href)[0];\n}\n\nlet scanned: [string, PageSecret[], boolean, SecretMatcher | null] = [\n \"\",\n [],\n false,\n null,\n];\n\n/**\n * pageSecrets' forms of `href`, whether it is a crafted URL -- one past\n * MAX_URL_LENGTH or MAX_URL_SECRETS -- and their matcher. The last URL's\n * answer is kept: a router stamping its history state asks again on every\n * call, and each asked the whole scan (found in review).\n */\nfunction scan(href: string): [PageSecret[], boolean, SecretMatcher | null] {\n if (scanned[0] === href) return [scanned[1], scanned[2], scanned[3]];\n const found = new Set<string>();\n const sure = new Map<string, Set<string>>();\n const own = new Map<string, Set<string>>();\n const bare = new Set<string>();\n const hashAt = href.indexOf(\"#\");\n const main = hashAt === -1 ? href : href.slice(0, hashAt);\n const fragment = hashAt === -1 ? \"\" : href.slice(hashAt + 1);\n const route = ROUTE_FRAGMENT.test(fragment);\n const tooLong = main.length + (route ? fragment.length : 0) > MAX_URL_LENGTH;\n if (!tooLong) collectSecrets(href, 0, found, sure, own, bare);\n // Past the cap the URL is not read, but its declared routes still are:\n // the integrator named those values, and they reach the page's DOM\n // whatever the address bar's length (found in review).\n else\n for (const parts of pathParts(href))\n for (const [v, before] of declaredOf(parts.filter((p) => p !== \"\"))\n .secret) {\n found.add(v);\n declare(sure, v, before);\n declare(own, v, before);\n }\n let crafted = tooLong;\n const origin = originOf(href);\n const forms = new Set<string>();\n const secrets: PageSecret[] = [];\n // The values the declared routes name in the URL's own path and route,\n // each after the segment the route puts before it there, come first and\n // are not counted: there are as many as the routes name. Every other\n // value counts toward the cap, and so does every other segment a\n // declared value is named after, since each is a form every event is\n // searched for: counted by value alone, a link naming one value after\n // thousands of segments -- `/*/:code`'s are any text -- froze the page\n // for seconds per snapshot (MEASURED in review). Held past the cap, a\n // crafted link of 60 KB named 6,815 declared values in its fragment's\n // pairs and init() took 4.4 s in Chromium; counted before the URL's own,\n // 40 link tokens in the path left a hash route's declared code unheld\n // (found in review).\n let held = 0;\n const room = (value: string, before: string | null): boolean => {\n if (before !== null && own.get(value)?.has(before) === true) return true;\n if (held < MAX_URL_SECRETS) {\n held++;\n return true;\n }\n crafted = true;\n return false;\n };\n for (const value of [\n ...own.keys(),\n ...[...found].filter((v) => !own.has(v)),\n ]) {\n const named = sure.get(value);\n const befores =\n named === undefined\n ? undefined\n : [...named].filter((before) => room(value, before));\n if (befores?.length === 0 || (befores === undefined && !room(value, null)))\n break;\n if (befores !== undefined) {\n // A declared value's forms, each held by the rule its own text\n // calls for: decoded, a generated-looking value can be a short code\n // (`Q%C3%A9X7P2` is `QéX7P2`), which the generated-looking rule\n // dropped (found in review). Not part of the page's origin either:\n // a run of digits that is also a host's label took the origin out\n // of every recorded URL.\n const plain = decoded(value);\n // WHAT a value is held as is decided by the value, decoded; its forms\n // are only how a text may spell it. Decided form by form, a\n // 2-character `新規`'s 18-character encoded form was held as a code\n // and scrubbed from every query that searched for it (found in\n // review).\n const code = plain.length >= DECLARED_EVERYWHERE && !bare.has(value);\n // As a share link spells it: it encodes the page URL, once per time\n // it is shared on, and a value encoding changes (`QéX7P2`) changes\n // at each. Held as the URL spells it and once more, a link encoding\n // the page URL twice carried it (found in review). As deep as a `/`\n // before a short value is read (SEPARATORS).\n const shared: string[] = [];\n for (let v = value, n = 0; n < SHARE_ENCODINGS; n++)\n shared.push((v = encodeURIComponent(v)));\n for (const v of new Set([\n value,\n plain,\n ...shared,\n encodeURIComponent(plain),\n // As a JSON writer that escapes non-ASCII spells it (`\\u00e9`).\n // A text's escapes are read (scrubAtOnce), so in text the value\n // is found by its own rule without this form. A member's or an\n // attribute's NAME, and CSS outside its data, are not read for\n // escapes: there this spelling is what holds the value (taken\n // out in round 30, whose refutation found it sent from each of\n // those places). A form of its own, it reads as generated-looking\n // and is replaced inside a longer word too, where the same word\n // spelled raw is kept: more is scrubbed, never less.\n plain.replace(\n /[\\u0080-\\uffff]/g,\n (c) => `\\\\u${c.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n ),\n ])) {\n if (v === \"\") continue;\n const outside = !origin.includes(v);\n const random = outside && looksRandom(v) && !isUrlLike(v, false);\n // Generated-looking: as it is, wherever it appears, and in any case\n // where no letter or digit touches it -- held as it is alone, a\n // page that upper-cased an 8-character code sent it.\n if (code && random) secrets.push({ kind: 0, value: v });\n // A code, whatever its letters: told apart from a word by its\n // shape, a random 6-character base62 code read as a word 32% of the\n // time and was sent in the request redeeming it and the page's text\n // (MEASURED in review). A credential wins (DECLARED_EVERYWHERE).\n // (A generated-looking form is one: it is at least MIN_SCRUBBED\n // long and outside the origin.)\n if (code && outside) secrets.push({ kind: 1, value: v });\n else\n for (const before of befores)\n secrets.push({ kind: 2, value: v, before });\n }\n continue;\n }\n forms.add(value);\n // rrweb resolves a CSS url() by cutting the page URL at its last `/`,\n // and at one more for each `../`, which can fall inside a token that\n // holds one: the part before it leaves too. The last four cuts only: a\n // form at every `/` let one crafted link of 2,000 slashes make 2,000\n // forms of 10 MB, and the tab ran out of memory (MEASURED in review).\n for (\n let at = value.lastIndexOf(\"/\"), n = 0;\n at > 0 && n < 4;\n at = value.lastIndexOf(\"/\", at - 1), n++\n ) {\n forms.add(value.slice(0, at));\n }\n // Encoded as the URL carries it too: a share link encodes the whole\n // page URL, so a value that arrived percent-encoded leaves as `%25..`.\n forms.add(encodeURIComponent(value));\n // Decoded as a page reads it: decodeURIComponent, and URLSearchParams,\n // which also reads `+` as a space -- the usual way an app takes a token\n // out of its URL.\n for (const raw of [value, value.replace(/\\+/g, \" \")]) {\n try {\n const decoded = decodeURIComponent(raw);\n forms.add(decoded);\n forms.add(encodeURIComponent(decoded));\n // And cut at its own `/`s, as the value is: decoded, an encoded\n // `%2F` is a `/` a page's text can end the value at.\n for (\n let at = decoded.lastIndexOf(\"/\"), n = 0;\n at > 0 && n < 4;\n at = decoded.lastIndexOf(\"/\", at - 1), n++\n )\n forms.add(decoded.slice(0, at));\n } catch {\n // Not percent-encoding: the value is its own decoded form.\n }\n }\n }\n for (const v of forms)\n if (looksRandom(v) && !isUrlLike(v, false) && !origin.includes(v))\n secrets.push({ kind: 0, value: v });\n // Longest first: the recorder keeps the newest forms (remember), and a\n // value's whole form must outlive its cuts.\n secrets.sort((a, b) => b.value.length - a.value.length);\n scanned = [href, secrets, crafted, secretPattern(secrets)];\n return [secrets, crafted, scanned[3]];\n}\n\n/** The secrets of a page, each by how it is matched: what scrubSecrets is given. */\nexport interface SecretMatcher {\n /** Each generated-looking secret as JSON text spells it inside a string: a quick test of a serialised event. */\n json: string[];\n /** Each declared one, ASCII-lower-cased, as JSON text spells it: a quick test of the event's JSON lower-cased. */\n jsonLower: string[];\n /** Generated-looking secrets, longest first: replaced wherever they appear. */\n plain: string[];\n /** Declared codes, ASCII-lower-cased, longest first: replaced in any case where no ASCII letter or digit touches them. */\n bounded: string[];\n /** Declared short values, ASCII-lower-cased, longest first, each with the segments it is named after (beforeOf): replaced where a URL holds one as the segment after one of them (wordAt). */\n words: Word[];\n}\n\n/** A declared short value and the segments it is named after, with their lengths: what wordAt reads a text for. */\ninterface Word {\n value: string;\n /** The segments, as beforeOf reads them; `\"\"` for a route's first segment, or a segment past MAX_BEFORE. */\n befores: Set<string>;\n /** Their lengths, and the longest of them (`\"\"` aside). */\n lengths: Set<number>;\n longest: number;\n}\n\n/**\n * `s` with A-Z lower-cased and nothing else changed, so every index stays\n * where it was. Unit by unit, not by a replace callback per capital: over\n * a text full of `[REDACTED]` the callback cost 456 ms per 10 MB and held\n * every one-letter string it made, and a crafted URL's 1M redactions ran\n * past 192 MB (MEASURED in review). toLowerCase alone would lower-case\n * non-ASCII letters too, and change a length (`İ` is two units lower-cased).\n */\nfunction asciiLower(s: string): string {\n if (!/[A-Z]/.test(s)) return s;\n scrubWork.lowered += s.length;\n if (!/[^\\0-\\x7f]/.test(s)) return s.toLowerCase();\n const units = new Uint16Array(Math.min(s.length, LOWER_CHUNK));\n let out = \"\";\n for (let at = 0; at < s.length; at += LOWER_CHUNK) {\n const n = Math.min(LOWER_CHUNK, s.length - at);\n for (let i = 0; i < n; i++) {\n const c = s.charCodeAt(at + i);\n units[i] = c >= 65 && c <= 90 ? c + 32 : c;\n }\n // fromCharCode keeps a lone surrogate as it is; a TextDecoder would not.\n out += String.fromCharCode(...units.subarray(0, n));\n }\n return out;\n}\n\n/** How many units asciiLower lower-cases into one string at a time: well under any engine's argument limit. */\nconst LOWER_CHUNK = 8192;\n\n/**\n * Every index `v` starts at in `s`, overlapping ones included, in time\n * linear in both (Knuth-Morris-Pratt): an indexOf after each match that\n * was not on a boundary read the same text again once per overlap, and a\n * crafted link under the 64 KiB cap made start() take 789 ms and each\n * replaceState 145 ms (MEASURED in review).\n */\nexport function indicesOf(s: string, v: string): number[] {\n const fail = new Int32Array(v.length);\n for (let i = 1, k = 0; i < v.length; i++) {\n while (k > 0 && v.charCodeAt(i) !== v.charCodeAt(k)) k = fail[k - 1]!;\n if (v.charCodeAt(i) === v.charCodeAt(k)) k++;\n fail[i] = k;\n }\n const at: number[] = [];\n for (let i = 0, k = 0; i < s.length; i++) {\n while (k > 0 && s.charCodeAt(i) !== v.charCodeAt(k)) k = fail[k - 1]!;\n if (s.charCodeAt(i) === v.charCodeAt(k)) k++;\n if (k === v.length) {\n at.push(i - k + 1);\n k = fail[k - 1]!;\n }\n }\n return at;\n}\n\n/*\n * THE CAP INSIDE ONE STRING. scrubSecrets counts each string's output once\n * it is built; while one is being built these say where in the event it\n * starts (scrubBase) and how many units the event may take (scrubCap), so\n * a scrub stops before building a string that cannot fit: one `srcset`\n * holding the page URL 1,000 times was scrubbed whole first -- 3 s and\n * 2 GB of renderer memory in Chromium -- and only then refused (found in\n * review #22). Module state, as scrubWork is: a scrub is synchronous and\n * never re-entered.\n */\nlet scrubCap = Infinity;\nlet scrubBase = 0;\n\n/**\n * `scrub()` with no cap: a probe whose output is not what is written. Run\n * under it, scrubJson's test of a number -- is a secret in it? -- projected\n * the number's own growth, and an event whose JSON fits exactly once the\n * number became one quoted marker was refused, its atLeast overstated\n * (found in review #23).\n */\nfunction unbudgeted<T>(scrub: () => T): T {\n const cap = scrubCap;\n scrubCap = Infinity;\n try {\n return scrub();\n } finally {\n scrubCap = cap;\n }\n}\n\n/** Stops the scrub when `units`, written from scrubBase on, pass the cap. */\nfunction overBudget(units: number): void {\n if (scrubBase + units > scrubCap)\n throw new ScrubOverCap(scrubBase + units, scrubCap);\n}\n\n/**\n * Whether a scrub could replace the LONG form `f` -- longer than\n * `[REDACTED]`, the only kind every caller asks about -- in a text spelled\n * `text` (lower-cased for a bounded form or a word): `f` is there, or it\n * could stand across a `[REDACTED]` an earlier form writes, which only a\n * form holding a bracket can (one inside `redacted` is too short to ask\n * about). A form a text cannot hold says nothing about it.\n */\nfunction mayReplace(text: string, f: string, marker = \"[redacted]\"): boolean {\n if (text.includes(f)) return true;\n if (!/[[\\]]/.test(f)) return false;\n // Its pieces outside marker text must all be in the text: the first may\n // end in a marker's start, the last begin with a marker's end.\n const parts = f.split(marker);\n const first = parts[0]!;\n const open = first.lastIndexOf(\"[\");\n if (open >= 0 && marker.startsWith(first.slice(open)))\n parts[0] = first.slice(0, open);\n const last = parts[parts.length - 1]!;\n const close = last.indexOf(\"]\");\n if (close >= 0 && marker.endsWith(last.slice(0, close + 1)))\n parts[parts.length - 1] = last.slice(close + 1);\n return parts.every((p) => text.includes(p));\n}\n\n/**\n * What a scrub writes for `s` is at least `s`: no form `s` could hold is\n * longer than `[REDACTED]`, AND NO TWO PLACES IN IT CAN TOUCH OR OVERLAP.\n * Decided over the forms in `s`, not every form of the page: a real\n * `?token=` in the URL, or a crafted `#/invites/%C3%A9`, turned the early\n * stop off for every string, those that hold neither included (found in\n * review #23).\n *\n * The second half was missing. Places that touch or overlap share ONE\n * marker (scrubAtOnce), so a short credential standing back to back does\n * not grow: `Zk3x9Qa7B` a thousand times, 9,000 units, scrubs to one\n * `[REDACTED]` -- and was stopped before it was read, as \"at least\"\n * 9,000, at every cap from 11 to 8,999 (found in review #29: an event\n * that fits, refused, and a bound that was none). Two places can stand\n * so only when a form lets them: a generated-looking value is replaced\n * wherever it stands, back to back with itself or with anything; a\n * declared code is a place only where no letter or digit touches it, and\n * a declared short value only as a whole segment after a separator, so\n * two of those can meet only where one holds a unit that is no letter or\n * digit. A string that holds a form of either kind is not said to only\n * grow: writesAtLeast() counts what its places can take off.\n */\nfunction onlyGrows(matcher: SecretMatcher, s: string): boolean {\n const long = (f: string) => f.length > REDACTED_UNITS;\n if (matcher.plain.some((f) => long(f) && mayReplace(s, f, \"[REDACTED]\")))\n return false;\n if (matcher.plain.some((f) => s.includes(f))) return false;\n const declared = [\n ...matcher.bounded,\n ...matcher.words.map(({ value }) => value),\n ];\n const rest = declared.filter(long);\n const meeting = declared.filter((f) => /[^a-z0-9]/.test(f));\n if (rest.length === 0 && meeting.length === 0) return true;\n const lower = asciiLower(s);\n return (\n !rest.some((f) => mayReplace(lower, f)) &&\n !meeting.some((f) => lower.includes(f))\n );\n}\n\nconst REDACTED_UNITS = \"[REDACTED]\".length;\n\n/**\n * Some form of `matcher` longer than `[REDACTED]`, holding a bracket, can\n * stand across a marker an earlier form writes in `s` -- the rest of it is\n * in `s` (mayReplace) -- at a place no reading of `s` before the scrub can\n * count, and replacing it there shortens what was written. Decided per\n * string: over every form of the page, one `[` in a real token turned the\n * running check off for every string on it, and a srcset was built to\n * 10.9x the cap (found in review #26).\n */\nfunction crossesMarkers(matcher: SecretMatcher, s: string): boolean {\n const long = (f: string) => f.length > REDACTED_UNITS && /[[\\]]/.test(f);\n if (matcher.plain.some((f) => long(f) && mayReplace(s, f, \"[REDACTED]\")))\n return true;\n const lower = asciiLower(s);\n return [...matcher.bounded, ...matcher.words.map(({ value }) => value)].some(\n (f) => long(f) && mayReplace(lower, f),\n );\n}\n\n/**\n * `s` with each occurrence of `v` in `find` -- `s` as matched, of the same\n * length -- that `keep` accepts replaced by `[REDACTED]`, left to right,\n * none overlapping another; and, asked for, `find` replaced at the same\n * places by the marker as it is matched, so the next form is looked for in\n * the new text without lower-casing it again. That copy is built only when\n * a later form is looked for: over a crafted URL holding one short value\n * 28,000 times, building it for the last form that matched was half the\n * scrub (MEASURED). Joined, not concatenated: a string built by `+=` is a\n * rope of a node per piece until something reads it, and the memo keeps\n * every output, so 1,000 links holding a code 8,000 times each held 810\n * MB where the event was 56 MB (MEASURED; 296 MB joined).\n */\nfunction replaceWhere(\n s: string,\n find: string,\n v: string,\n keep: (start: number, end: number) => boolean,\n budgeted = false,\n): [string, () => string] {\n const at: number[] = [];\n let from = 0;\n // Budgeted when no form after this one can shorten the text: what this\n // one writes, s.length + (10 - v.length) per place, is then at least\n // what the string will be, and passing the cap here stops the scrub\n // before it is built.\n const grows = REDACTED_UNITS - v.length;\n for (const i of indicesOf(find, v)) {\n if (i < from || !keep(i, i + v.length)) continue;\n at.push(i);\n from = i + v.length;\n if (budgeted) overBudget(s.length + at.length * grows);\n }\n if (at.length === 0) return [s, () => find];\n const spliced = (text: string, marker: string): string => {\n const pieces: string[] = [];\n let prev = 0;\n for (const i of at) {\n pieces.push(text.slice(prev, i));\n prev = i + v.length;\n }\n pieces.push(text.slice(prev));\n return pieces.join(marker);\n };\n let lower: string | undefined;\n return [\n spliced(s, \"[REDACTED]\"),\n () => (lower ??= spliced(find, \"[redacted]\")),\n ];\n}\n\nconst ALNUM = /[A-Za-z0-9]/;\n\n/**\n * What may stand right before a value as a boundary though it ends in a\n * letter or digit: a percent escape, encoded any number of times (`%2F`,\n * `%252F`), and an escape of a string literal (`\\n`, `\\t`, `\\u003e`) -- a\n * JSON body re-serialised with a newline before the code put an `n`\n * against it, and the code went out (found in review).\n */\nconst ESCAPE_BEFORE =\n /(?:%(?:25)*[\\da-f]{2}|(?:\\\\|%(?:25)*5c)(?:[nrtbf]|u[\\da-f]{4}))$/i;\n\n/** No ASCII letter or digit touches `s` at `start` and `end`, an escape before it not counting as one. */\nfunction boundedAt(s: string, start: number, end: number): boolean {\n return (\n (start === 0 ||\n !ALNUM.test(s[start - 1]!) ||\n ESCAPE_BEFORE.test(s.slice(Math.max(0, start - 16), start))) &&\n (end === s.length || !ALNUM.test(s[end]!))\n );\n}\n\n/**\n * The separators a declared short value may follow the segment before it\n * by, each with how many more times than the URL itself the segment is\n * percent-encoded where it stands: a share link encodes the page URL, `/`\n * and the segment with it, any number of times. Longest first, so `\\/` is\n * read before `/`.\n */\nconst SEPARATORS: Array<[string, number]> = [\n [\"%25252f\", 3],\n [\"%252f\", 2],\n [\"%2f\", 1],\n [\"\\\\/\", 0],\n [\"/\", 0],\n];\n\n/** How many times over a share link may encode the page URL for a declared value to be held in it: as deep as SEPARATORS reads a `/`. */\nconst SHARE_ENCODINGS = Math.max(...SEPARATORS.map(([, level]) => level));\n\n/** A unit no path segment's text holds: where the segment before a value stops. */\nconst SEGMENT_STOP = /[/\\\\?#\\s\"<>`{}|^[\\]]/;\n\n/** A unit a segment may hold that also ends what came before it: a query's `=` and `&`, a matrix's `;`, a userinfo's `@`. */\nconst SEGMENT_SOFT_STOP = /[!$&'()*+,;=:@]/;\n\n/**\n * The most UTF-16 units a segment a short value is named after (beforeOf)\n * may have for wordAt to look for it: a longer one -- only a crafted `*`\n * segment is one -- is read as no segment at all, so the value is held as\n * any whole segment after a separator. It bounds what one place a value\n * stands costs to read: wordAt reads back no more of the segment before it\n * than decodes to this many units (found in review: 27 s for a 60 KB\n * segment read whole at every place it might start).\n */\nconst MAX_BEFORE = 64;\n\n/** The separator, if any, of at most `level` encodings that ends at `at` in `lower`. */\nfunction separatorEndingAt(\n lower: string,\n at: number,\n level: number,\n): [string, number] | undefined {\n return SEPARATORS.find(\n ([sep, l]) =>\n l <= level && at >= sep.length && lower.startsWith(sep, at - sep.length),\n );\n}\n\n/**\n * A segment's matrix parameters start at `at`: `;` however many times, up\n * to `level`, it is encoded there -- a share link's encoder that leaves\n * `;` as it is cut nothing, and a code after `%2F...;x=1%2F` was recorded\n * (found in review).\n */\nfunction matrixAt(lower: string, at: number, level: number): boolean {\n if (lower[at] === \";\") return true;\n for (let k = 1; k <= level; k++)\n if (lower.startsWith(`%${\"25\".repeat(k - 1)}3b`, at)) return true;\n return false;\n}\n\n/**\n * A run of separators ending at `at` -- `//`, `%2F%2F` -- begins an\n * authority (`https://host`, a protocol-relative `//host`) rather than an\n * empty segment: it follows a scheme's `:`, as written or encoded, or\n * stands where no path segment does.\n */\nfunction authorityAt(lower: string, at: number): boolean {\n return (\n at === 0 ||\n SEGMENT_STOP.test(lower[at - 1]!) ||\n SEGMENT_SOFT_STOP.test(lower[at - 1]!) ||\n /(?::|%(?:25)*3a)$/.test(lower.slice(Math.max(0, at - 9), at))\n );\n}\n\n/**\n * What the scrub did, COUNTED rather than timed: the pieces wordAt decoded,\n * the strings it scrubbed, the units its scans read and the units it\n * lower-cased. Its cost is held by these counts -- a budget in\n * milliseconds holds nothing on a loaded machine and fails on one\n * (MEASURED: 89 ms locally, 2,068 ms in the CI image, one test).\n */\nexport const scrubWork = { pieces: 0, strings: 0, scanned: 0, lowered: 0 };\n\n/**\n * Where the run of separators of at most `level` encodings that ends at\n * `at` begins (`at` itself for none).\n *\n * READ AT EVERY PLACE A VALUE STANDS, AND EACH RUN STILL ONCE: two places\n * of one value could share a run only if the first stood inside it, and\n * no value that is held does. A place starts where a separator ends and\n * ends before a unit that is no letter or digit, so inside a run it is\n * whole separators -- and a value that decodes to separators alone is no\n * credential (credentialText). It was not always so: a declared `%2f`\n * was held, stood at every unit of a run of slashes, and each place\n * stepped back over the whole run before it -- the square of the run,\n * 2.6 s for 16 KB (MEASURED in review #18) -- so the runs, and the\n * segment before each, were memoised by position. Review #20 stopped\n * holding such a value, and the memo outlived what it was for with no\n * text able to reach it: with either half switched off the whole suite\n * stayed green (found running the mutation table through the gate).\n * What holds the cost now is credentialText, and the count that found\n * the square still runs against it (privacy-declared-routes.test.ts).\n */\nfunction runStartOf(lower: string, at: number, level: number): number {\n let stop = at;\n for (;;) {\n const more = separatorEndingAt(lower, stop, level);\n if (more === undefined) return stop;\n stop -= more[0].length;\n scrubWork.scanned++;\n }\n}\n\n/**\n * `lower` holds a declared short value at [start, end) as the path\n * segment after one of `word.befores` (beforeOf): no letter, digit, `-`,\n * `_` or `~` continues it, a separator stands before it, and the segment\n * before that -- empty segments stepped over; read back to whatever ends\n * it, or from any `=`, `&` or the like inside it; without its matrix\n * parameters -- decoded once more than the separator is encoded, is one of\n * them; for a route that names the path's first segment (`\"\"`), any whole\n * segment after a separator. Never a host: a value right after\n * `scheme://` is the page's origin, and a first-segment route took it out\n * of every recorded URL (found in review). Compared as the route matched\n * it rather than against a list of spellings: a URL spells a segment in\n * more ways than a list holds, and `/invite%73/<code>`, or a `*` segment of\n * `%C3%A9@x`, left a short code in the recorded URL (found in review).\n *\n * LINEAR in the text. The segment before is read back to its start --\n * a separator of at most this one's encoding, or a unit no segment holds\n * -- so each segment is read for the one place a value can follow it, at\n * each encoding level; and each place the segment may start (`from`, or\n * after a soft stop) is decoded as the piece it adds to the one after it,\n * once, the pieces' decodings joined from the right, until they decode to\n * more than any of `word.befores` -- `decoded` is escape by escape, and a\n * soft stop is no part of an escape, so a decoded join is the join's\n * decoding. Read whole at each such place, and only so far back, a\n * crafted link froze init() for 27 s and then for 10 s (MEASURED in\n * review); with the 512 units of matrix parameters and the 16 empty\n * segments that bounded it, a longer one left the code in the URL.\n */\nfunction wordAt(\n lower: string,\n start: number,\n end: number,\n word: Word,\n): boolean {\n if (end !== lower.length && /[a-z0-9_~-]/.test(lower[end]!)) return false;\n const found = separatorEndingAt(lower, start, 3);\n if (found === undefined) return false;\n const [sep, level] = found;\n // Separators doubled before the value: an authority, or empty segments\n // to step over.\n const stop = runStartOf(lower, start - sep.length, level);\n if (stop !== start - sep.length && authorityAt(lower, stop)) return false;\n if (word.befores.has(\"\")) return true;\n if (word.longest === 0) return false;\n return segmentBefore(lower, stop, level, word);\n}\n\n/** The segment ending at `stop`, read back to its start, decoded `level` + 1 times, is one of `word.befores` (wordAt). */\nfunction segmentBefore(\n lower: string,\n stop: number,\n level: number,\n word: Word,\n): boolean {\n let from = stop;\n while (\n from > 0 &&\n !SEGMENT_STOP.test(lower[from - 1]!) &&\n separatorEndingAt(lower, from, level) === undefined\n )\n from--;\n scrubWork.scanned += stop - from;\n // Right to left. Each candidate start is `from` or follows a soft stop,\n // and its segment ends where its matrix parameters begin, the nearest\n // at or after it; `joined` is the decoding of that segment, grown a\n // piece [s, pieceEnd) at a time.\n let pieceEnd = stop;\n let joined = \"\";\n let spent = false;\n for (let s = stop; s >= from; s--) {\n if (s < stop && matrixAt(lower, s, level)) {\n pieceEnd = s;\n joined = \"\";\n spent = false;\n }\n if (spent || (s !== from && !SEGMENT_SOFT_STOP.test(lower[s - 1]!)))\n continue;\n let piece = lower.slice(s, pieceEnd);\n for (let k = 0; k <= level; k++) piece = decoded(piece);\n scrubWork.pieces++;\n joined = asciiLower(piece) + joined;\n pieceEnd = s;\n if (joined.length > word.longest) spent = true;\n else if (word.lengths.has(joined.length) && word.befores.has(joined))\n return true;\n }\n return false;\n}\n/**\n * `s` with every secret of `matcher` replaced by `[REDACTED]`, each by its\n * own rule. A string that is a JSON object or array is scrubbed as JSON\n * (scrubJson), so it still parses.\n */\nfunction scrubText(s: string, matcher: SecretMatcher): string {\n if (!mayHold(s, matcher)) return s;\n if (/^[ \\t\\n\\r]*[{[]/.test(s)) {\n const json = scrubJson(s, matcher);\n if (json !== null) return json;\n }\n return scrubPlain(s, matcher);\n}\n\n/**\n * A request or response body: scrubbed as JSON whenever it is JSON, a\n * bare number or string included -- scrubbed as text, a body `482913`\n * became `[REDACTED]`, which is no JSON (found in review) -- and as text\n * otherwise. Only a body: the page's text `482913` is text.\n */\nfunction scrubBody(s: string, matcher: SecretMatcher): string {\n if (!mayHold(s, matcher)) return s;\n return scrubJson(s, matcher) ?? scrubPlain(s, matcher);\n}\n\n/** Some secret of `matcher` is in `s`, by its plain text: what every scrub tests first. */\nfunction mayHold(s: string, matcher: SecretMatcher): boolean {\n if (heldIn(s, matcher)) return true;\n // A text holding JSON may spell a secret with escapes (jsonUnescaped).\n return s.includes(\"\\\\\") && heldIn(jsonUnescaped(s), matcher);\n}\n\n/** Some form of `matcher` is in `s` as it is written. */\nfunction heldIn(s: string, matcher: SecretMatcher): boolean {\n if (matcher.plain.some((f) => s.includes(f))) return true;\n if (matcher.bounded.length === 0 && matcher.words.length === 0) return false;\n const lower = asciiLower(s);\n return (\n matcher.bounded.some((f) => lower.includes(f)) ||\n matcher.words.some(({ value }) => lower.includes(value))\n );\n}\n\n/**\n * `matcher` with only the forms the JSON text `s` holds, as written or as\n * a JSON writer spells them (`\\u00e9`, `\\\"`): what each of its tokens --\n * decoded -- is tested against.\n */\nfunction narrowed(s: string, matcher: SecretMatcher): SecretMatcher {\n const lower = asciiLower(s);\n const plain = s.includes(\"\\\\\") ? asciiLower(jsonUnescaped(s)) : lower;\n const held = (f: string) =>\n lower.includes(asciiLower(f)) ||\n lower.includes(asciiLower(jsonSpelling(f))) ||\n plain.includes(asciiLower(f));\n return {\n ...matcher,\n plain: matcher.plain.filter(held),\n bounded: matcher.bounded.filter(held),\n words: matcher.words.filter(({ value }) => held(value)),\n };\n}\n\n/**\n * `s` with every JSON `\\uXXXX` and `\\/` escape read, at any depth of\n * escaping: what a text that holds JSON spells, however its writer chose to\n * escape it. A token written by a writer that escapes `+` (`\\u002B`,\n * System.Text.Json's default) or `/` (`\\/`, PHP's json_encode) passed the\n * scrub's tests unseen and was recorded (found in review).\n */\nfunction jsonUnescaped(s: string): string {\n return s\n .replace(/\\\\+u([0-9a-fA-F]{4})/g, (_, hex: string) =>\n String.fromCharCode(parseInt(hex, 16)),\n )\n .replace(/\\\\+\\//g, \"/\");\n}\n\n/** `f` as a JSON string writer that escapes every unit past ASCII spells it, without the quotes. */\nfunction jsonSpelling(f: string): string {\n return JSON.stringify(f)\n .slice(1, -1)\n .replace(\n /[\\u0080-\\uffff]/g,\n (c) => `\\\\u${c.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\n/** A JSON string, a JSON number as JSON.parse reads one, or an object's brace. */\nconst JSON_TOKEN =\n /\"(?:[^\"\\\\]|\\\\[\\s\\S])*\"|-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?|[{}]/g;\n\n/** What follows a JSON string that is a member's name. */\nconst NAME_ENDS = /[ \\t\\n\\r]*:/y;\n\n/**\n * `s`, when it parses as JSON, with every secret replaced TOKEN BY TOKEN;\n * null when it does not parse. A string -- a member's name included -- is\n * scrubbed as the text it decodes to, a JSON text in it as JSON again,\n * and written back as JSON.stringify writes it; a number a secret is in\n * becomes the string `\"[REDACTED]\"`; every token no secret is in is kept\n * byte for byte, a large integer's digits included. Two names of one\n * object that become one are both kept, the second suffixed `#2`. Each\n * token is tested against the forms the whole text holds, not all of\n * them: tested against all, a crafted link's 640 forms made a 1 MB JSON\n * body cost 550 ms against 9 ms as text (MEASURED in review). Replaced as\n * text, a declared `482913` made `{\"code\":[REDACTED]}` of the request\n * redeeming it; quoted wherever it looked like a number,\n * `\"list\":\"[482913]\"` and `\"{\\\"code\\\":482913}\"` in a string no longer\n * parsed (found in review).\n */\nfunction scrubJson(s: string, matcher: SecretMatcher): string | null {\n try {\n JSON.parse(s);\n } catch {\n return null;\n }\n const forms = narrowed(s, matcher);\n // Every object's names, read first: a name renamed to one the object\n // holds LATER collided with it, and parsed, the body kept one of the two\n // values (found in review).\n const held: Array<Set<string>> = [];\n const open: number[] = [];\n for (const m of s.matchAll(JSON_TOKEN)) {\n const token = m[0];\n if (token === \"{\") {\n open.push(held.length);\n held.push(new Set());\n } else if (token === \"}\") open.pop();\n else if (token[0] === '\"' && open.length > 0) {\n NAME_ENDS.lastIndex = m.index + token.length;\n if (NAME_ENDS.test(s))\n held[open[open.length - 1]!]!.add(JSON.parse(token) as string);\n }\n }\n // What is written is final as it is written -- out only grows -- so the\n // cap is checked after each token, and each string token is scrubbed\n // from where it is written: with no stop, a data attribute holding 1,000\n // page URLs was built to 29x the cap before it was refused (found in\n // review #25).\n const base = scrubBase;\n let out = \"\";\n let at = 0;\n let opened = 0;\n const names: Array<Set<string>> = [];\n for (const m of s.matchAll(JSON_TOKEN)) {\n const token = m[0];\n if (token === \"{\") {\n names.push(new Set(held[opened++]));\n continue;\n }\n if (token === \"}\") {\n names.pop();\n continue;\n }\n let written = token;\n if (token[0] === '\"') {\n const text = JSON.parse(token) as string;\n scrubBase = base + out.length + (m.index - at);\n let scrubbed: string;\n try {\n scrubbed = scrubText(text, forms);\n } finally {\n scrubBase = base;\n }\n NAME_ENDS.lastIndex = m.index + token.length;\n const own = NAME_ENDS.test(s) ? names[names.length - 1] : undefined;\n if (own !== undefined && scrubbed !== text) {\n const name = scrubbed;\n for (let n = 2; own.has(scrubbed); n++) scrubbed = `${name}#${n}`;\n own.add(scrubbed);\n }\n if (scrubbed !== text) written = JSON.stringify(scrubbed);\n } else if (unbudgeted(() => scrubPlain(token, forms)) !== token) {\n written = '\"[REDACTED]\"';\n }\n if (written === token) continue;\n out += s.slice(at, m.index) + written;\n at = m.index + token.length;\n overBudget(out.length);\n }\n return out + s.slice(at);\n}\n\n/**\n * The places in `s` its JSON `\\uXXXX` and `\\/` escapes stand, as\n * jsonUnescaped reads them: `text` is that reading, and `escapes` holds,\n * per escape, the unit's index in `text` and where its spelling ends in\n * `s` -- so a range of `text` is a range of `s`.\n */\nfunction unescapedMap(s: string): { text: string; escapes: number[] } {\n let text = \"\";\n const escapes: number[] = [];\n let last = 0;\n for (const m of s.matchAll(/\\\\+u([0-9a-fA-F]{4})|\\\\+\\//g)) {\n text += s.slice(last, m.index);\n escapes.push(text.length, m.index + m[0].length);\n text += m[1] === undefined ? \"/\" : String.fromCharCode(parseInt(m[1], 16));\n last = m.index + m[0].length;\n }\n return { text: text + s.slice(last), escapes };\n}\n\n/** Where the boundary `at` of unescapedMap's `text` stands in its `s`. */\nfunction spelledAt(escapes: number[], at: number): number {\n let lo = 0;\n let hi = escapes.length / 2;\n // The last escape whose unit lies wholly before `at`.\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (escapes[mid * 2]! < at) lo = mid + 1;\n else hi = mid;\n }\n if (lo === 0) return at;\n const k = (lo - 1) * 2;\n return escapes[k + 1]! + (at - escapes[k]! - 1);\n}\n\n/**\n * Where each form of `matcher` stands in `text`, by its own rule: per form,\n * its starts, ascending, in a typed array, and its length. Kept as one\n * `[start, end]` pair per match and sorted, a crafted text's ranges took\n * 4 s and 2.9 GB at 22 MB, and ran out of memory at 56 MB (found in review\n * #23).\n *\n * And `slack`: the most the later pass can shorten what these ranges'\n * markers leave. A long declared form (a value or word longer than\n * `[REDACTED]`) a letter or digit touched is no range here; once a marker\n * stands beside it, it is bounded, and scrubPlain's later pass replaces it\n * -- shorter by its length less the marker's. Uncounted, the running check\n * refused events that fit and said they were larger than they were (found\n * in review #26: a 12-digit code after each of 3000 tokens, an event of\n * 63,000 refused at caps up to 68,999). The places are taken across every\n * long form at once: where they overlap -- one form's own, as indicesOf\n * finds them, or several forms' -- the replacements the later pass makes\n * there are disjoint and each writes a marker, so a run of overlapping\n * places of total length U shortens by U less one marker at most. Counted\n * per form, 31 codes of one digit overlapping in one run took off many\n * times what the run could shrink, and the running check stopped nothing\n * (found in review #27).\n *\n * With `all`, every place of a long form counts, kept or not, and no list\n * is made: what the later pass can take off a string read as it is\n * SPELLED, where it finds forms this pass, reading the unescaped text,\n * does not (scrubAtOnce).\n */\nfunction secretRanges(\n text: string,\n matcher: SecretMatcher,\n all = false,\n): { lists: Array<{ at: Int32Array; length: number }>; slack: number } {\n const lists: Array<{ at: Int32Array; length: number }> = [];\n // Where a long form a letter or digit touched stands, as [start, end)\n // pairs: what the later pass may yet replace, shorter.\n const left: number[] = [];\n const add = (\n found: number[],\n length: number,\n keep: (a: number) => boolean,\n ): void => {\n const at = new Int32Array(found.length);\n let n = 0;\n const long = length > REDACTED_UNITS;\n // This form's overlapping places, as one run [runStart, runEnd).\n let runStart = -1;\n let runEnd = -1;\n for (const a of found) {\n if (!all && keep(a)) at[n++] = a;\n else if (long) {\n if (a < runEnd) {\n runEnd = a + length;\n } else {\n if (runStart >= 0) left.push(runStart, runEnd);\n runStart = a;\n runEnd = a + length;\n }\n }\n }\n if (runStart >= 0) left.push(runStart, runEnd);\n if (n > 0) lists.push({ at: at.subarray(0, n), length });\n };\n for (const f of matcher.plain) add(indicesOf(text, f), f.length, () => true);\n const lower = asciiLower(text);\n for (const f of matcher.bounded)\n add(indicesOf(lower, f), f.length, (a) => boundedAt(text, a, a + f.length));\n for (const word of matcher.words)\n add(indicesOf(lower, word.value), word.value.length, (a) =>\n wordAt(lower, a, a + word.value.length, word),\n );\n return { lists, slack: unionSlack(left) };\n}\n\n/**\n * The most the later pass can shorten `[start, end)` places that may\n * overlap, across forms: each run of overlapping places, of total length U,\n * shortens by U less one marker at most, since the replacements made in it\n * are disjoint and each writes one.\n */\nexport function unionSlack(spans: number[]): number {\n if (spans.length === 0) return 0;\n const order = Array.from({ length: spans.length / 2 }, (_, i) => i).sort(\n (x, y) => spans[2 * x]! - spans[2 * y]!,\n );\n let slack = 0;\n let start = spans[2 * order[0]!]!;\n let end = spans[2 * order[0]! + 1]!;\n const close = (): void => {\n if (end - start > REDACTED_UNITS) slack += end - start - REDACTED_UNITS;\n };\n for (const i of order) {\n const a = spans[2 * i]!;\n const b = spans[2 * i + 1]!;\n if (a < end) {\n if (b > end) end = b;\n } else {\n close();\n start = a;\n end = b;\n }\n }\n close();\n return slack;\n}\n\n/**\n * `s` with every secret replaced where it stands in the text AS IT WAS\n * RECORDED: each form's places are found first, by its own rule, and then\n * replaced together. Replaced a form at a time, each form was looked for\n * in what the forms before it had left. A declared short value is held as\n * the segment after the one before it (wordAt), and where that segment\n * was a secret too -- `/join/:team/:pin`, or a token the built-in rule\n * reads before a declared pin -- it read `[REDACTED]` by then: the pin\n * went out in the page's URL, and in every link and event that carried\n * it (found refuting review #30's removals). Only a text holding a JSON\n * escape, or one near the cap, was read this way before; every text is\n * now.\n *\n * Read through its JSON escapes (unescapedMap), so what is replaced is\n * the spelling as it stands: a token in an HTML or script body that a\n * JSON writer had escaped -- `\\u002B` for `+`, `\\/` for `/` -- was found\n * (mayHold reads the escapes) and recorded whole, or its tail after the\n * slash (found in review).\n *\n * The ranges are taken in order of where they start -- a later rule's\n * range can stand before an earlier one's (found in review) -- merged from\n * each form's own ascending list, one marker for ranges that overlap or\n * touch. This pass replaces every place of every form, so what it writes\n * is final as it is written -- nothing after it can shorten it unless a\n * long form can stand across a marker (crossesMarkers), or a long declared\n * form a letter or digit touched here is bounded by a marker later, which\n * the check takes off what was written (secretRanges' `slack`) -- and the\n * cap is checked as it grows: built whole first, a 22 MB text took 4 s and 2.9\n * GB before it was refused (found in review #23), and checked only when\n * no long form was in the string, a srcset holding a real `?token=` was\n * built to 11x the cap (found in review #25).\n *\n * Checked only for a string whose scrub COULD pass the cap -- a marker is\n * at most `[REDACTED]`'s length per unit read, so one that fits at ten\n * times its length cannot -- since deciding the check lower-cases the\n * string once more (crossesMarkers). For one that could, with an escape\n * or without, it is checked as it is written rather than split and joined\n * whole: the lower bound startsOver asks first cannot count markers\n * (adjacent places share one), and a run of `/b` passed it below about\n * twice the cap (found in review #25).\n */\nfunction scrubAtOnce(s: string, matcher: SecretMatcher): string {\n const capped =\n scrubCap !== Infinity && scrubBase + REDACTED_UNITS * s.length > scrubCap;\n const { text, escapes } = s.includes(\"\\\\\")\n ? unescapedMap(s)\n : { text: s, escapes: [] as number[] };\n const ranges = secretRanges(text, matcher);\n const { lists } = ranges;\n if (lists.length === 0) return s;\n const budget = capped && !crossesMarkers(matcher, s);\n // The later pass reads the string as it is SPELLED, and a form can stand\n // there that the unescaped text does not hold -- a credential with a\n // literal backslash, or one across an escape's own digits. What it can\n // take off those places is slack too: uncounted, an event that fit was\n // refused and said larger than it was (found in review #28).\n const slack =\n ranges.slack +\n (budget && escapes.length > 0 ? secretRanges(s, matcher, true).slack : 0);\n const next = new Int32Array(lists.length);\n const startOf = (k: number): number => lists[k]!.at[next[k]!]!;\n // The lists, as a heap by where each one's next range starts.\n const heap: number[] = [];\n const swap = (i: number, j: number): void => {\n const t = heap[i]!;\n heap[i] = heap[j]!;\n heap[j] = t;\n };\n const down = (i: number): void => {\n for (;;) {\n const l = 2 * i + 1;\n let m = i;\n if (l < heap.length && startOf(heap[l]!) < startOf(heap[m]!)) m = l;\n if (l + 1 < heap.length && startOf(heap[l + 1]!) < startOf(heap[m]!))\n m = l + 1;\n if (m === i) return;\n swap(i, m);\n i = m;\n }\n };\n for (let k = 0; k < lists.length; k++) heap.push(k);\n for (let i = (heap.length >> 1) - 1; i >= 0; i--) down(i);\n const out: string[] = [];\n let from = 0;\n let marked = false;\n let written = 0;\n while (heap.length > 0) {\n const k = heap[0]!;\n const start = startOf(k);\n const a = spelledAt(escapes, start);\n const b = spelledAt(escapes, start + lists[k]!.length);\n next[k] = next[k]! + 1;\n if (next[k]! >= lists[k]!.at.length) {\n heap[0] = heap[heap.length - 1]!;\n heap.pop();\n }\n if (heap.length > 0) down(0);\n if (b <= from) continue;\n if (marked && a <= from) {\n from = b;\n continue;\n }\n written += a - from + REDACTED_UNITS;\n if (budget) overBudget(written - slack);\n out.push(s.slice(from, a), \"[REDACTED]\");\n from = b;\n marked = true;\n }\n // And the whole of it, the tail included: final, as every unit before\n // it, but for what the later pass can still take off.\n if (budget) overBudget(written + s.length - from - slack);\n out.push(s.slice(from));\n return out.join(\"\");\n}\n\n/**\n * `s` with every secret of `matcher` replaced by `[REDACTED]` as text:\n * nothing but the secret changes. Every form where it stands in the text\n * as recorded first (scrubAtOnce); then a form at a time, for what that\n * pass does not read -- a form the string spells that its unescaped text\n * does not hold, one that stands across a marker, and a declared value\n * a letter or digit touched that a marker now bounds.\n */\nfunction scrubPlain(s: string, matcher: SecretMatcher): string {\n s = scrubAtOnce(s, matcher);\n for (const f of matcher.plain)\n if (s.includes(f)) s = s.split(f).join(\"[REDACTED]\");\n // Lower-cased once: each replacement keeps `lower` in step (replaceWhere).\n // Lower-cased again after every form that matched, a crafted URL's\n // redactions were read once per form (found in review).\n const first = asciiLower(s);\n let lower = (): string => first;\n // Which forms no later form can undo the growth of: a form is budgeted\n // when neither it nor any after it that this text could hold is longer\n // than `[REDACTED]` -- decided over the text's forms, not the page's\n // (found in review #23).\n const forms = [\n ...matcher.bounded,\n ...matcher.words.map(({ value }) => value),\n ];\n const budgeted: boolean[] = new Array<boolean>(forms.length);\n for (let i = forms.length - 1, ok = true; i >= 0; i--) {\n const f = forms[i]!;\n ok = ok && (f.length <= REDACTED_UNITS || !mayReplace(first, f));\n budgeted[i] = ok;\n }\n let form = 0;\n for (const f of matcher.bounded) {\n if (lower().includes(f)) {\n const text = s;\n [s, lower] = replaceWhere(\n s,\n lower(),\n f,\n (a, b) => boundedAt(text, a, b),\n budgeted[form],\n );\n }\n form++;\n }\n for (const word of matcher.words) {\n if (lower().includes(word.value)) {\n const text = lower();\n [s, lower] = replaceWhere(\n s,\n text,\n word.value,\n (a, b) => wordAt(text, a, b, word),\n budgeted[form],\n );\n }\n form++;\n }\n return s;\n}\n\n/**\n * Each place CSS carries data -- a comment (an unclosed one runs to the\n * end), a `url(...)` (its argument unquoted up to the first `)`, or one\n * quoted string, with whitespace around it), a quoted string -- as\n * `at(start, end)`, left to right, leftmost first and in that order of\n * kinds where two start at one place. A string or url() that does not\n * close is no place, and the scan goes on from the unit after its start.\n *\n * IN ONE PASS, counted in scrubWork.scanned. It was a regular expression,\n * and `url(` followed by a run of whitespace with no `)` -- where its\n * three quantifiers all match whitespace -- cost the cube of the run: a\n * crafted inline style froze a page for 13 s at 4 KB (reproduced in\n * review). Where each string body ends, and the next `)`, `\"` or `'`\n * after a point, are worked out once and remembered, so a run of\n * unclosed `'a\\` or `url(` reads each unit a bounded number of times.\n */\nexport function cssData(\n s: string,\n at: (start: number, end: number) => void,\n): void {\n const n = s.length;\n // The end of a string body starting at i (its closing quote's index +\n // 1), -1 when it does not close; worked out at most once per index.\n const ends: Record<string, Int32Array> = {};\n const bodyEnd = (i: number, quote: string): number => {\n const memo = (ends[quote] ??= new Int32Array(n + 2).fill(-2));\n const path: number[] = [];\n let j = i;\n let end = -1;\n for (;;) {\n if (j >= n) break;\n if (memo[j]! !== -2) {\n end = memo[j]!;\n break;\n }\n path.push(j);\n scrubWork.scanned++;\n const c = s[j]!;\n if (c === quote) {\n end = j + 1;\n break;\n }\n j += c === \"\\\\\" ? 2 : 1;\n }\n for (const p of path) memo[p] = end;\n return end;\n };\n // The first `)`, `\"` or `'` at or after i; asked at points that only\n // grow, so the run between them is read once.\n let stop = -1;\n const nextStop = (i: number): number => {\n if (stop < i) stop = i;\n while (stop < n && !\")\\\"'\".includes(s[stop]!)) {\n scrubWork.scanned++;\n stop++;\n }\n return stop;\n };\n // Past the whitespace run at i. Each run is read once: one after a\n // `url(` holds no other `url(`, and two string bodies never end at one\n // quote (a quote that opens one after `url(` and its whitespace is\n // unescaped, so it would have ended the other).\n const pastSpace = (i: number): number => {\n let j = i;\n while (j < n && /\\s/.test(s[j]!)) {\n scrubWork.scanned++;\n j++;\n }\n return j;\n };\n let i = 0;\n while (i < n) {\n scrubWork.scanned++;\n const c = s[i]!;\n if (c === \"/\" && s[i + 1] === \"*\") {\n const close = s.indexOf(\"*/\", i + 2);\n const end = close < 0 ? n : close + 2;\n scrubWork.scanned += end - i;\n at(i, end);\n i = end;\n continue;\n }\n if (\n (c === \"u\" || c === \"U\") &&\n s.slice(i, i + 4).toLowerCase() === \"url(\"\n ) {\n const open = pastSpace(i + 4);\n const q = s[open];\n let end = -1;\n if (q === '\"' || q === \"'\") {\n const body = bodyEnd(open + 1, q);\n if (body >= 0) {\n const close = pastSpace(body);\n if (s[close] === \")\") end = close + 1;\n }\n } else {\n const close = nextStop(i + 4);\n if (s[close] === \")\") end = close + 1;\n }\n if (end >= 0) {\n at(i, end);\n i = end;\n continue;\n }\n }\n if (c === '\"' || c === \"'\") {\n const end = bodyEnd(i + 1, c);\n if (end >= 0) {\n at(i, end);\n i = end;\n continue;\n }\n }\n i++;\n }\n}\n\n/** A CSS comment with its text scrubbed and its delimiters kept; one the text ends inside stays open. */\nfunction scrubCssComment(c: string, matcher: SecretMatcher): string {\n const closed = c.length >= 4 && c.endsWith(\"*/\");\n return `/*${scrubPlain(c.slice(2, closed ? -2 : undefined), matcher)}${closed ? \"*/\" : \"\"}`;\n}\n\n/**\n * CSS text with every secret replaced where CSS carries data -- a url()\n * (rrweb makes each absolute against the page, so it can hold the page's\n * path), a quoted string and a comment -- and a generated-looking one\n * anywhere. A\n * declared value is never replaced in CSS's own syntax: a crafted\n * `#/invites/display` made `style=\"display: none\"` into\n * `[REDACTED]: none` (found in review).\n */\nfunction scrubCss(s: string, matcher: SecretMatcher): string {\n if (!mayHold(s, matcher)) return s;\n for (const f of matcher.plain)\n if (s.includes(f)) s = s.split(f).join(\"[REDACTED]\");\n // A comment is read as ONE piece of data -- an apostrophe in one opened\n // a \"string\" that swallowed the CSS after it (found in review) -- and\n // scrubbed inside its delimiters: it carries no syntax, and a\n // replacement only ever inserts `[REDACTED]`, so it cannot end one.\n // Each piece written is final -- a later one only adds -- so the cap is\n // checked as the text is built: one <style> of 1,000 url()s under a\n // crafted page URL was scrubbed whole, then refused (found in review).\n let out = \"\";\n let from = 0;\n cssData(s, (start, end) => {\n const data = s.slice(start, end);\n out +=\n s.slice(from, start) +\n (data.startsWith(\"/*\")\n ? scrubCssComment(data, matcher)\n : scrubPlain(data, matcher));\n overBudget(out.length);\n from = end;\n });\n return out + s.slice(from);\n}\n\n/**\n * One matcher for every one of `secrets`, longest first in each rule so a\n * longer form wins over one inside it; null for none.\n */\nexport function secretPattern(\n secrets: readonly PageSecret[],\n): SecretMatcher | null {\n if (secrets.length === 0) return null;\n const longestFirst = (a: string, b: string) => b.length - a.length;\n const plain: string[] = [];\n const bounded: string[] = [];\n const named = new Map<string, Set<string>>();\n for (const secret of secrets) {\n const value = asciiLower(secret.value);\n if (secret.kind === 0) plain.push(secret.value);\n else if (secret.kind === 1) bounded.push(value);\n else {\n let befores = named.get(value);\n if (befores === undefined) named.set(value, (befores = new Set()));\n befores.add(secret.before.length > MAX_BEFORE ? \"\" : secret.before);\n }\n }\n plain.sort(longestFirst);\n bounded.sort(longestFirst);\n const words: Word[] = [...named]\n .map(([value, befores]) => {\n const lengths = new Set(\n [...befores].filter((b) => b !== \"\").map((b) => b.length),\n );\n return {\n value,\n befores,\n lengths,\n longest: lengths.size === 0 ? 0 : Math.max(...lengths),\n };\n })\n .sort((a, b) => b.value.length - a.value.length);\n return {\n // One includes() per form, not one alternation over all of them: over\n // 20 KB of forms the alternation took 300 ms on a 1.4 MB snapshot, and\n // every event is tested (MEASURED in review: 18 ms this way for 256\n // forms of 250 characters).\n json: plain.map((f) => JSON.stringify(f).slice(1, -1)),\n // The declared ones in any case: tested against the JSON lower-cased,\n // a short value with the separator wordAt requires before it.\n jsonLower: [\n ...bounded,\n ...words.flatMap(({ value }) => SEPARATORS.map(([sep]) => sep + value)),\n ].map((f) => JSON.stringify(f).slice(1, -1)),\n // And no regular expression over the forms at all: one alternation\n // over a crafted link's forms ran the tab out of memory compiling it\n // (MEASURED in review).\n plain,\n bounded,\n words,\n };\n}\n\n/**\n * Some secret of `matcher` is in the JSON text `text`: each as JSON spells\n * it, and -- when the text holds escapes -- each as it reads once every\n * `\\uXXXX` and `\\/` is (jsonUnescaped). One includes() per form.\n */\nfunction mayHoldJson(text: string, matcher: SecretMatcher): boolean {\n if (matcher.json.some((f) => text.includes(f))) return true;\n const lower = asciiLower(text);\n if (matcher.jsonLower.some((f) => lower.includes(f))) return true;\n if (!text.includes(\"\\\\\")) return false;\n const plain = jsonUnescaped(text);\n if (matcher.plain.some((f) => plain.includes(f))) return true;\n const plainLower = asciiLower(plain);\n return (\n matcher.bounded.some((f) => plainLower.includes(f)) ||\n matcher.words.some(({ value }) => plainLower.includes(value))\n );\n}\n\n/** What an event's `data` is: rrweb's event, the SDK's network record, or an integrator's own payload. */\nexport type EventShape = \"dom\" | \"network\" | \"custom\";\n\n/**\n * The longest key V8 hashes by its content: past 16,383 UTF-16 units a\n * string is hashed by its length alone (MEASURED on Node 24: 1,000\n * distinct keys sharing a prefix cost 9 ms in a Map at 8 KB, 645 ms just\n * past this and 3.8 s at 60 KB).\n */\nexport const LONGEST_HASHED_KEY = 16_383;\n\n/**\n * The memo key of `s` scrubbed as `how`: the string itself when V8 hashes\n * it, else its length and a hash of its own (FNV-1a), compared whole only\n * on a match. Keyed by the string alone, a page whose crafted URL rrweb\n * writes into 1,000 distinct `href=\"#...\"` made every lookup collide with\n * every earlier one: 3.1 s for one snapshot (found in review).\n */\nexport function memoKey(how: string, s: string): string {\n const key = `${how}\\u0000${s}`;\n if (key.length <= LONGEST_HASHED_KEY) return key;\n let h = 0x811c9dc5;\n for (let i = 0; i < s.length; i++) {\n h ^= s.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return `${how}\\u0001${s.length}\\u0000${h >>> 0}`;\n}\n\n/** rrweb's IncrementalSource.StyleDeclaration: `set: {property, value}`, `remove: {property}`. */\nconst STYLE_DECLARATION = 13;\n\n/** rrweb's IncrementalSource.StyleSheetRule: `adds: [{rule}]`, and a sheet's whole text as `replace` or `replaceSync`. */\nconst STYLE_SHEET_RULE = 8;\n\n/**\n * Attributes whose values are HTML's own vocabulary -- an input's `type`,\n * a link's `rel` -- and never the page's data: a crafted\n * `/invites/checkbox` made every checkbox `type=\"[REDACTED]\"`, which a\n * replay renders as a text box (found in review).\n */\nconst HTML_VOCABULARY = new Set([\n \"type\",\n \"rel\",\n \"method\",\n \"enctype\",\n \"autocomplete\",\n \"inputmode\",\n \"enterkeyhint\",\n \"dir\",\n \"role\",\n \"crossorigin\",\n \"referrerpolicy\",\n \"loading\",\n \"decoding\",\n \"fetchpriority\",\n \"contenteditable\",\n \"draggable\",\n \"spellcheck\",\n \"translate\",\n]);\n\n/** How a string of an event is scrubbed: not at all (the event's own structure), as CSS, as a body, or as text. */\n/** rrweb's numbers for an element node, a text node, a full snapshot, an incremental one and a DOM mutation. */\nconst RR_ELEMENT = 2;\nconst RR_TEXT = 3;\nconst RR_FULL_SNAPSHOT = 2;\nconst RR_INCREMENTAL = 3;\nconst RR_MUTATION = 0;\n\n/**\n * The text nodes of the page's `<style>` elements, by rrweb's node id, so\n * the CSS a style's text holds is scrubbed as CSS. rrweb 2 marks none of\n * them -- its serialized text node carries no `isStyle`, which rrweb 1's\n * did -- so text written into a style after the snapshot (a theme switch's\n * `style.textContent = ...`, a CSS-in-JS dev build, HMR) was scrubbed as\n * text, and `/n0/invites/display` made `.b{display:block}` into\n * `.b{[REDACTED]:block}` (found in review). One per capture: observe()\n * reads every DOM event's JSON copy, in order, before it is scrubbed, and\n * a full snapshot starts it over. rrweb's ids do NOT start over -- its\n * mirror outlives a snapshot, and a node removed and added again keeps\n * its id (MEASURED in review on rrweb 2.1.6) -- which is why an add says\n * afresh what a node is.\n */\n/**\n * What the page says of rrweb's node ids, for the styles' observer. A node\n * is NOTED when the observer starts following its id -- the moment rrweb\n * has just serialised it, so its mirror holds it -- and asked about by\n * that node from then on, not by the id: rrweb's mirror forgets an id\n * that is still in the page. Recording a same-origin frame with an\n * observer of its own, it writes a <style> moved out of the frame into the\n * page as the page's add and THEN the frame's remove, and on that remove\n * deletes the id from its id-to-node map (removeNodeFromMap) although the\n * node is in the page (MEASURED in Chromium with rrweb 2.1.6: the add,\n * two removes naming the frame's head, then the style's next text added\n * under its id).\n */\nexport interface NodePresence {\n /** Keep the node `id` names now. */\n note(id: number): void;\n /** The node kept for `id` is still in the page. */\n present(id: number): boolean;\n /** Stop keeping the node for `id`. */\n forget(id: number): void;\n}\n\nexport class StyleTexts {\n /** Each style's text nodes, by the style's id. */\n private readonly styles = new Map<number, Set<number>>();\n /** Each style text node's style, by the text's id. */\n private readonly texts = new Map<number, number>();\n\n /**\n * `present` says whether rrweb's node `id` is still in the page. rrweb\n * writes a remove for the top of a removed subtree alone, so a style\n * inside a removed container, shadow host or frame is named by no\n * remove at all, and each such cycle left its ids followed for the\n * session (found in review: +1,200 ids over 600 container cycles, +400\n * over 200 shadow hosts). And a remove is not always the node leaving:\n * a <style> moved from a frame into the page arrives as the page's add\n * and THEN the frame's remove (NodePresence), and read as \"gone\" by\n * that remove, a style still in the page was forgotten and its next text\n * scrubbed as text (`.c{display:flex}` posted as `.c{[REDACTED]:flex}`,\n * reproduced in review in Chromium). So with `page`, a removed node is\n * forgotten only when it is no longer in the page; without one -- no\n * DOM to ask -- the remove says so, and nothing is pruned.\n */\n constructor(private readonly page?: NodePresence) {}\n\n /** `id` has left the page: as `page` says, or, with none, as the remove that names it does. */\n private gone(id: number): boolean {\n return this.page === undefined || !this.page.present(id);\n }\n\n /** How many ids are followed, a style's set of texts included: what a long session's churn must not grow. */\n get size(): number {\n let members = 0;\n for (const texts of this.styles.values()) members += texts.size;\n return this.styles.size + this.texts.size + members;\n }\n\n private addText(text: number, style: number): void {\n this.dropText(text);\n this.texts.set(text, style);\n this.styles.get(style)?.add(text);\n this.page?.note(text);\n }\n\n private dropText(text: number): void {\n const style = this.texts.get(text);\n if (style !== undefined) this.styles.get(style)?.delete(text);\n if (this.texts.delete(text)) this.page?.forget(text);\n }\n\n /**\n * A removed node is no style, nor a style's text -- and a removed\n * style's texts go with it: rrweb writes a remove for the style alone,\n * and each add and remove of one left its text's id followed for the\n * session (found in review: 2,000 ids after 2,000 cycles).\n */\n private drop(id: number): void {\n const texts = this.styles.get(id);\n if (texts !== undefined)\n for (const t of texts) if (this.texts.delete(t)) this.page?.forget(t);\n if (this.styles.delete(id)) this.page?.forget(id);\n this.dropText(id);\n }\n\n observe(event: unknown): void {\n if (!isPlainRecord(event) || !isPlainRecord(event[\"data\"])) return;\n const data = event[\"data\"];\n if (event[\"type\"] === RR_FULL_SNAPSHOT) {\n for (const id of [...this.styles.keys(), ...this.texts.keys()])\n this.page?.forget(id);\n this.styles.clear();\n this.texts.clear();\n this.walk(data[\"node\"], null);\n return;\n }\n if (event[\"type\"] !== RR_INCREMENTAL || data[\"source\"] !== RR_MUTATION)\n return;\n // A node removed is no style's, nor a style's text, until an add\n // says so again: rrweb moves a node as a remove and an add, and text\n // moved out of a style into a <p> was still scrubbed as CSS -- a code\n // in it recorded in clear (found in review).\n const removes = Array.isArray(data[\"removes\"]) ? data[\"removes\"] : [];\n for (const r of removes)\n if (isPlainRecord(r) && typeof r[\"id\"] === \"number\" && this.gone(r[\"id\"]))\n this.drop(r[\"id\"]);\n const adds = Array.isArray(data[\"adds\"])\n ? data[\"adds\"].filter(isPlainRecord)\n : [];\n // Styles first: an add of a style's text may come before the style's.\n for (const add of adds) this.walk(add[\"node\"], null);\n for (const add of adds) {\n const node = add[\"node\"];\n if (\n isPlainRecord(node) &&\n node[\"type\"] === RR_TEXT &&\n typeof node[\"id\"] === \"number\"\n ) {\n if (\n typeof add[\"parentId\"] === \"number\" &&\n this.styles.has(add[\"parentId\"])\n )\n this.addText(node[\"id\"], add[\"parentId\"]);\n else this.dropText(node[\"id\"]);\n }\n }\n if (removes.length > 0 && this.page !== undefined) this.prune();\n }\n\n /** Stops following every id `present` says is gone: once per mutation that removes, over the ids followed. */\n private prune(): void {\n for (const id of this.styles.keys()) if (this.gone(id)) this.drop(id);\n for (const id of this.texts.keys()) if (this.gone(id)) this.dropText(id);\n }\n\n private walk(root: unknown, inStyle: number | null): void {\n const pending: Array<[unknown, number | null]> = [[root, inStyle]];\n // A node seen is not walked again: the event is read in place, and an\n // integrator's own (recorder.emitEvent is public) can hold a cycle.\n const seen = new Set<unknown>();\n while (pending.length > 0) {\n const [node, styled] = pending.pop()!;\n if (seen.has(node)) continue;\n seen.add(node);\n if (!isPlainRecord(node) || typeof node[\"id\"] !== \"number\") continue;\n const id = node[\"id\"];\n const style =\n node[\"type\"] === RR_ELEMENT &&\n typeof node[\"tagName\"] === \"string\" &&\n node[\"tagName\"].toLowerCase() === \"style\";\n if (style && !this.styles.has(id)) {\n this.styles.set(id, new Set());\n this.page?.note(id);\n }\n if (node[\"type\"] === RR_TEXT && styled !== null) this.addText(id, styled);\n if (Array.isArray(node[\"childNodes\"]))\n for (const child of node[\"childNodes\"])\n pending.push([child, style ? id : null]);\n }\n }\n\n /** The records in an event (one observe() read, or a copy of it) whose `textContent` or `value` is a style's text. */\n recordsIn(event: unknown): Set<unknown> {\n const found = new Set<unknown>();\n if (!isPlainRecord(event) || !isPlainRecord(event[\"data\"])) return found;\n const data = event[\"data\"];\n const pending: unknown[] = [];\n if (event[\"type\"] === RR_FULL_SNAPSHOT) pending.push(data[\"node\"]);\n else if (\n event[\"type\"] === RR_INCREMENTAL &&\n data[\"source\"] === RR_MUTATION\n ) {\n if (Array.isArray(data[\"adds\"]))\n for (const add of data[\"adds\"])\n if (isPlainRecord(add)) pending.push(add[\"node\"]);\n if (Array.isArray(data[\"texts\"]))\n for (const text of data[\"texts\"])\n if (\n isPlainRecord(text) &&\n typeof text[\"id\"] === \"number\" &&\n this.texts.has(text[\"id\"])\n )\n found.add(text);\n }\n while (pending.length > 0) {\n const node = pending.pop();\n if (!isPlainRecord(node)) continue;\n if (\n node[\"type\"] === RR_TEXT &&\n typeof node[\"id\"] === \"number\" &&\n this.texts.has(node[\"id\"])\n )\n found.add(node);\n if (Array.isArray(node[\"childNodes\"]))\n pending.push(...(node[\"childNodes\"] as unknown[]));\n }\n return found;\n }\n}\n\ntype Scrub = \"keep\" | \"css\" | \"body\" | \"text\";\n\n/**\n * A scrub that stopped because what it had written passed `cap` units:\n * the event could never be sent (scrubSecrets), and is dropped and said\n * as KUI_E_EVENT_OVERSIZED_SCRUBBING. `atLeast` is a lower bound of the\n * scrubbed event's size: what it had written, less what a later\n * replacement could still take off it (secretRanges' slack).\n */\nexport class ScrubOverCap extends Error {\n constructor(\n readonly atLeast: number,\n readonly cap: number,\n ) {\n super(`the scrubbed event passed ${cap} units (at least ${atLeast})`);\n this.name = \"ScrubOverCap\";\n }\n}\n\n/**\n * How many times `v` stands in `s`, overlapping places counted: the KMP\n * of indicesOf, counting rather than keeping each place.\n */\nfunction countOf(s: string, v: string): number {\n if (v.length === 0) return 0;\n const fail = new Int32Array(v.length);\n for (let i = 1, k = 0; i < v.length; i++) {\n while (k > 0 && v.charCodeAt(i) !== v.charCodeAt(k)) k = fail[k - 1]!;\n if (v.charCodeAt(i) === v.charCodeAt(k)) k++;\n fail[i] = k;\n }\n let n = 0;\n for (let i = 0, k = 0; i < s.length; i++) {\n while (k > 0 && s.charCodeAt(i) !== v.charCodeAt(k)) k = fail[k - 1]!;\n if (s.charCodeAt(i) === v.charCodeAt(k)) k++;\n if (k === v.length) {\n n++;\n k = fail[k - 1]!;\n }\n }\n return n;\n}\n\n/**\n * At least what scrubbing `s` writes, or null where nothing is known\n * before it is read. Each place a form stands is replaced by a marker\n * that can absorb it whole, and each escape folds into the one unit it\n * spells, so the scrub writes no less than `s` without its escapes' extra\n * units and without every unit every form's places cover (overlapping\n * places counted twice: more taken off, never less). The places are\n * counted in BOTH readings of a string that holds an escape, unescaped and\n * as it is spelled: the later pass replaces a form where it is spelled,\n * and counted in the unescaped text alone, a credential with a literal\n * backslash had no place at all -- an event that scrubbed to 8,600 units\n * was refused as at least 13,200 (found in review #28). Not for a long\n * form that can stand across a marker an earlier form writes: it has no\n * places here to count.\n */\nfunction writesAtLeast(s: string, matcher: SecretMatcher): number | null {\n if (crossesMarkers(matcher, s)) return null;\n const escaped = s.includes(\"\\\\\");\n const text = escaped ? unescapedMap(s).text : s;\n const readings = escaped ? [text, s] : [text];\n let least = text.length;\n for (const reading of readings) {\n const lower = asciiLower(reading);\n for (const f of matcher.plain) least -= countOf(reading, f) * f.length;\n for (const f of matcher.bounded) least -= countOf(lower, f) * f.length;\n for (const { value } of matcher.words)\n least -= countOf(lower, value) * value.length;\n }\n return least;\n}\n\n/**\n * Stops the scrub BEFORE reading `s` when what it would write cannot fit.\n * When no form can shorten it -- every form it could hold is no longer\n * than `[REDACTED]`, and it holds no escape -- the scrub writes at least\n * `s`. Otherwise at least writesAtLeast(): all-or-nothing, a string\n * holding one escape, or one long form, was read and built whole before\n * it was refused -- 2 s and 1 GB in Chromium for a crafted srcset (found\n * in review #24). Asked only of a string whose own length could pass\n * what is left of the cap. Not for JSON: scrubJson replaces a whole\n * number that holds a value with one quoted `[REDACTED]`, which can be\n * shorter (`123456.78901234567`).\n *\n * NOR FOR CSS THAT HOLDS A BACKSLASH, of which nothing is known before\n * it is read. scrubCss replaces a generated-looking value wherever the\n * text SPELLS it, and only then reads each piece of data through its\n * escapes: so the second step reads a text the first has changed. A\n * credential ending in a backslash, followed by one with a letter\n * written `\\u005a`, is in neither reading of the text as it stands --\n * its backslash and the next one's `u0041` read as one escape -- and\n * both are replaced: the first as spelled, the second once the first\n * is gone. writesAtLeast() counted one of them, and 11,618 units that\n * scrub to 4,218 were refused at every cap up to 6,417 as \"at least\"\n * 6,418 (found in review #29). Such CSS is stopped as it is written,\n * piece by piece (scrubCss), not before.\n */\nfunction startsOver(s: string, how: Scrub, matcher: SecretMatcher): void {\n if (scrubCap === Infinity || scrubBase + s.length <= scrubCap) return;\n if (how === \"body\" || (how === \"text\" && /^[ \\t\\n\\r]*[{[]/.test(s))) return;\n // Nor for CSS that holds a backslash: it is read two ways in turn, and\n // neither reading of it as it stands is what the scrub reads (scrubCss).\n if (how === \"css\" && s.includes(\"\\\\\")) return;\n if (!s.includes(\"\\\\\") && onlyGrows(matcher, s)) {\n overBudget(s.length);\n return;\n }\n const least = writesAtLeast(s, matcher);\n if (least !== null) overBudget(least);\n}\n\n/**\n * `value` -- an event's `data`, of `shape` -- with every secret in its\n * DATA replaced by `[REDACTED]`: a fresh copy when anything matched,\n * `value` itself when nothing did.\n *\n * DATA, NOT STRUCTURE. What the event's reader parses is left as it is:\n * a member's name is renamed only for a generated-looking secret, and\n * never one rrweb writes for itself (`rr_*`); an attribute whose NAME\n * holds one is dropped, since no name a DOM accepts holds `[REDACTED]`;\n * rrweb's `tagName`, the network record's `method` and `type`, and a\n * style declaration's property are never touched; CSS is scrubbed where\n * it carries data (scrubCss); a request or response body as JSON when it\n * is JSON (scrubBody). Renamed by a declared word, a crafted\n * `#/invites/childNodes` made every node's `childNodes` `[REDACTED]` and\n * the replay threw, `#/invites/button` every `<button>` a tag no DOM\n * accepts, and `#/invites/source` left the flow engine no action -- with\n * no keep route that could stop it, since the link names the word (found\n * in review).\n *\n * NEVER WRITTEN: the value can be an integrator's own object\n * (recorder.emitEvent is public), and an in-place walk hung the tab on a\n * cycle, threw on a frozen object or a throwing getter, and rewrote the\n * app's objects (found in review). Only a DOM event's styles are read in\n * place (StyleTexts.observe: read-only, a cycle walked once, as\n * scrubDomUrls reads the event before this). Its JSON -- what is sent -- is tested,\n * and only when a secret is in it is a fresh copy parsed from that JSON\n * and walked: acyclic, plain, and this function's own. The replacement is\n * in DECODED strings, so it can never land inside an escape sequence and\n * leave the JSON unparseable, and no regular expression runs over the\n * whole serialised text, which overflowed the stack on an 8 MB string\n * (found in review). Two names that become one are both kept, the second\n * suffixed. A value JSON refuses is returned as it is, and the transport\n * drops it unsent (KUI_E_EVENT_UNSERIALISABLE).\n */\nexport function scrubSecrets<T>(\n value: T,\n matcher: SecretMatcher | null,\n shape: EventShape = \"custom\",\n styles?: StyleTexts,\n cap?: number,\n): T {\n // A DOM event is observed for its styles' text whether or not a secret\n // is in it -- the next one may need what this one added -- in place and\n // read-only: StyleTexts' walk keeps each node it has seen, so a cycle\n // ends it (an integrator's cyclic event walked in place never returned,\n // found in review). It was observed in a copy parsed back from the\n // event's JSON, which cost a serialisation and a parse of every DOM\n // event with no secret to look for (MEASURE.md, uic-sdk-perf: on a\n // 22.5k-node page, more than the observation). The event is serialised\n // once, by the transport, when there is no secret to look for.\n if (shape === \"dom\") styles?.observe(value);\n if (matcher === null) return value;\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n return value;\n }\n const text = json;\n if (text === undefined || !mayHoldJson(text, matcher)) return value;\n const copy: unknown = JSON.parse(text);\n if (typeof copy === \"string\") {\n scrubWork.strings++;\n return budgeted(0, () => {\n startsOver(copy, \"text\", matcher);\n return scrubText(copy, matcher);\n }) as T;\n }\n // The text of a <style>, by the node that holds it (StyleTexts): CSS.\n const styleText =\n shape === \"dom\" && styles !== undefined\n ? styles.recordsIn(copy)\n : new Set<unknown>();\n const declaration =\n shape === \"dom\" &&\n isPlainRecord(copy) &&\n copy[\"type\"] === 3 &&\n isPlainRecord(copy[\"data\"]) &&\n copy[\"data\"][\"source\"] === STYLE_DECLARATION;\n const scrubOf = (\n record: Record<string, unknown>,\n key: string,\n css: boolean,\n attributes: boolean,\n root: boolean,\n ): Scrub => {\n if (shape === \"network\")\n return root && (key === \"method\" || key === \"type\")\n ? \"keep\"\n : root && (key === \"requestBody\" || key === \"responseBody\")\n ? \"body\"\n : \"text\";\n if (shape !== \"dom\") return \"text\";\n if (\n key === \"tagName\" ||\n (declaration && key === \"property\") ||\n (attributes && HTML_VOCABULARY.has(key))\n )\n return \"keep\";\n if (\n css ||\n (attributes && key === \"style\") ||\n key === \"_cssText\" ||\n key === \"rule\" ||\n ((key === \"replace\" || key === \"replaceSync\") &&\n record[\"source\"] === STYLE_SHEET_RULE) ||\n (declaration && key === \"value\") ||\n ((key === \"textContent\" || key === \"value\") && styleText.has(record))\n )\n return \"css\";\n return \"text\";\n };\n /*\n * ONCE per distinct string and rule: rrweb writes the page's URL into\n * every `href=\"#...\"` it makes absolute, so a page of 100 such links\n * carried one crafted URL 100 times and scrubbed it 100 times (found in\n * review).\n */\n const memo = new Map<string, Array<[string, string]>>();\n /*\n * A text is scrubbed as the parts before and from its first `#` when no\n * secret's spelling holds one: `#` stops every rule that reads around a\n * value (a segment's back-scan, a code's \"no letter or digit touches\n * it\"), so the two parts scrub as the whole does -- a differential test\n * holds that. rrweb writes the page's URL into each `href=\"#...\"` it\n * makes absolute, so a crafted URL of 60 KB under 1,000 distinct\n * fragments was scrubbed in full 1,000 times (4.6 s under a declared\n * route, found in review); its part before `#` is now one string, and\n * the memo scrubs it once. Not a JSON text, which is parsed whole. A\n * text holding a `\\\\` was kept whole as well, while it alone was read\n * through its escapes and the rest a form at a time: the two halves\n * then scrubbed by different rules. Every text is read through its\n * escapes now (scrubAtOnce), no escape spells a `#` that is split at,\n * and the differential test holds the split for such a text as for any\n * other.\n */\n const splitsAtHash = ![\n ...matcher.plain,\n ...matcher.bounded,\n ...matcher.words.map((w) => w.value),\n ].some((f) => f.includes(\"#\"));\n /*\n * AT MOST `cap` UNITS ARE WRITTEN: past it the event is one no batch can\n * carry -- a string's UTF-16 units are never more than its UTF-8 bytes,\n * and the event's JSON holds every one of them -- so the scrub stops\n * there (ScrubOverCap) instead of writing the rest. A credential is\n * replaced by `[REDACTED]`, so a short value repeated through a crafted\n * URL grows every link rrweb resolves against it: 1,000 links under\n * `/b` x 28,000 took 4 s and 1 GB of heap in Chromium to scrub an event\n * the transport then dropped (MEASURED in review).\n */\n let written = 0;\n const counted = (out: string): string => {\n written += out.length;\n if (cap !== undefined && written > cap)\n throw new ScrubOverCap(written, cap);\n return out;\n };\n /** `scrub` with the cap and where its string starts in the event set for it. */\n function budgeted(base: number, scrub: () => string): string {\n scrubCap = cap ?? Infinity;\n scrubBase = base;\n try {\n return scrub();\n } finally {\n scrubCap = Infinity;\n scrubBase = 0;\n }\n }\n const scrubbed = (s: string, how: Scrub): string => {\n if (how === \"keep\") return s;\n if (how === \"text\" && splitsAtHash) {\n const hash = s.indexOf(\"#\");\n if (hash > 0 && !/^[ \\t\\n\\r]*[{[]/.test(s))\n return scrubbed(s.slice(0, hash), how) + scrubbed(s.slice(hash), how);\n }\n startsOver(s, how, matcher);\n const key = memoKey(how, s);\n const bucket = memo.get(key);\n const hit = bucket?.find(([seen]) => seen === s);\n if (hit !== undefined) return hit[1];\n scrubWork.strings++;\n const out =\n how === \"css\"\n ? scrubCss(s, matcher)\n : how === \"body\"\n ? scrubBody(s, matcher)\n : scrubText(s, matcher);\n if (bucket !== undefined) bucket.push([s, out]);\n else memo.set(key, [[s, out]]);\n return out;\n };\n /*\n * Whose NAMES a record holds: the page's -- an element's attributes, a\n * style's properties, a request's headers -- or the integrator's, in a\n * custom event; or the event's own, which are never renamed. Renamed\n * wherever a generated-looking secret was found, a crafted\n * `?auth_token=parentId` renamed every mutation's `parentId` and the\n * replay added none of the page's nodes (found in review).\n */\n const pending: Array<{\n node: unknown;\n css: boolean;\n attributes: boolean;\n names: boolean;\n root: boolean;\n }> = [\n {\n node: copy,\n css: false,\n attributes: false,\n names: shape === \"custom\",\n root: true,\n },\n ];\n while (pending.length > 0) {\n const { node, css, attributes, names, root } = pending.pop()!;\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) {\n const v: unknown = node[i];\n if (typeof v === \"string\")\n node[i] = counted(\n budgeted(written, () => scrubbed(v, css ? \"css\" : \"text\")),\n );\n else if (v !== null && typeof v === \"object\")\n pending.push({\n node: v,\n css,\n attributes: false,\n names: shape === \"custom\",\n root: false,\n });\n }\n continue;\n }\n if (!isPlainRecord(node)) continue;\n for (const key of Object.keys(node)) {\n const v = node[key];\n // An attribute whose NAME holds a secret is dropped -- no name a DOM\n // accepts holds `[REDACTED]`, and renamed to one, the replay threw\n // (found in review #15) -- and dropped HERE, before its value is\n // scrubbed or counted: counted, a page under the cap was refused for\n // a value it never sent (found in review #22).\n if (\n shape === \"dom\" &&\n names &&\n !key.startsWith(\"rr_\") &&\n key !== \"_cssText\" &&\n matcher.plain.some((f) => key.includes(f))\n ) {\n delete node[key];\n continue;\n }\n const how = scrubOf(node, key, css, attributes, root);\n if (typeof v === \"string\")\n node[key] = counted(budgeted(written, () => scrubbed(v, how)));\n else if (v !== null && typeof v === \"object\") {\n const elements = shape === \"dom\" && key === \"attributes\";\n pending.push({\n node: v,\n css: how === \"css\",\n attributes: elements,\n names:\n shape === \"custom\" ||\n elements ||\n (shape === \"dom\" && attributes && key === \"style\") ||\n (shape === \"network\" &&\n root &&\n (key === \"requestHeaders\" || key === \"responseHeaders\")),\n root: false,\n });\n }\n // rrweb's own attribute names -- `rr_*`, `_cssText` -- are its\n // structure even inside an element's attributes: dropped by a crafted\n // `?auth_token=_cssText`, a replay's <style> came back empty (found\n // in review).\n if (!names || key.startsWith(\"rr_\") || key === \"_cssText\") continue;\n let renamed = key;\n for (const f of matcher.plain)\n if (renamed.includes(f)) renamed = renamed.split(f).join(\"[REDACTED]\");\n if (renamed === key) continue;\n const kept = node[key];\n delete node[key];\n let name = renamed;\n for (let n = 2; Object.prototype.hasOwnProperty.call(node, name); n++)\n name = `${renamed}#${n}`;\n node[name] = kept;\n }\n }\n return copy as T;\n}\n\n/** A JSON object that is not an array. */\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** The page's URL as a recording carries it (Meta events and session metadata). */\nexport function recordedPageUrl(href: string): string {\n // Sensitive values redacted by name where the URL shows them, and every\n // credential value it carries (pageSecrets) wherever else it sits. The\n // fragment is kept only when it is a route -- the page a hash router is\n // on -- up to a second `#`; any other fragment is dropped, so scrolling to\n // an anchor is not a change of page. A crafted URL is its origin alone:\n // what it carries past the caps is not read, so it cannot be scrubbed.\n const [, crafted, matcher] = scan(href);\n if (crafted) return `${originOf(href)}/[REDACTED]`;\n const hashAt = href.indexOf(\"#\");\n const linkPage = isLinkPage(pathParts(href), pairValue(pagePairs(href)));\n let url = maskPageUrl(hashAt === -1 ? href : href.slice(0, hashAt), linkPage);\n if (hashAt !== -1) {\n const fragment = href.slice(hashAt + 1).split(\"#\")[0]!;\n if (ROUTE_FRAGMENT.test(fragment))\n url += `#${maskPageUrl(fragment, linkPage)}`;\n }\n return matcher === null ? url : scrubText(url, matcher);\n}\n\n/** Case-insensitive content-type lookup over a header bag. */\nfunction findContentType(\n headers?: Record<string, string> | null,\n): string | undefined {\n if (!headers) return undefined;\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === \"content-type\") return v;\n }\n return undefined;\n}\n\n/* ------------------------------------------------------------------ */\n/* Built-in PII regex patterns */\n/* ------------------------------------------------------------------ */\n\n/*\n * phone_us: every leading group used to be optional, reducing it to \"any\n * 7-digit run\": it matched order ids, invoice numbers, timestamps and\n * Content-Length values. A separator or explicit country code is now\n * required.\n *\n * credit_card was removed from this list. The pattern\n * /\\b(?:\\d[ -]*?){13,19}\\b/ matched every 13-digit Date.now() and every\n * long numeric id, and replacing inside a serialized number produced\n * invalid JSON. Card numbers are now detected in redact.ts against string\n * values only, requiring issuer prefix + length + Luhn.\n *\n * (Above the array, not inside it: a comment inside an expression ships\n * in the bundle.)\n */\nconst BUILTIN_PII_PATTERNS: PiiPattern[] = [\n // No email entry: maskText runs redactStringValue first, whose email\n // scan (redact.ts emailRanges) is linear. A regex here was a second,\n // quadratic copy of it: a long run with no `@` cost seconds on the\n // page's main thread.\n {\n name: \"phone_us\",\n pattern:\n /(?:\\+\\d{1,3}[ .-]?)?(?:\\(\\d{3}\\)[ .-]?|\\b\\d{3}[ .-])\\d{3}[ .-]\\d{4}\\b/g,\n },\n {\n name: \"ssn\",\n pattern: /\\b\\d{3}-\\d{2}-\\d{4}\\b/g,\n },\n {\n name: \"ipv4\",\n pattern:\n /\\b(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\b/g,\n },\n];\n\n/**\n * Default sensitive headers whose values are always redacted in network\n * captures regardless of other config.\n */\nconst DEFAULT_SENSITIVE_HEADERS: string[] = [\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n \"x-auth-token\",\n \"proxy-authorization\",\n];\n\n/* ------------------------------------------------------------------ */\n/* Page URLs */\n/* ------------------------------------------------------------------ */\n/*\n * THE PAGE'S OWN URL, AND THE PAGE'S LINKS, CARRY CREDENTIALS TOO. The\n * page URL's rule above (recordedPageUrl, by name; pageSecrets and\n * scrubSecrets, by value) decides what the page's own URL keeps: an\n * app's `?code=SUMMERSALE24`, `?key=PROJ-1` and `?state=delivered` stay,\n * and its resource ids stay in its paths, so the page recorded is the\n * page visited. What follows runs after it and never undoes it: it adds\n * what that rule leaves -- strict mode's every query value, a value\n * shaped like a token or holding a PII pattern, a JWT path segment, a\n * URL nested in a value -- and it is the scrub of every OTHER URL the\n * DOM rrweb records holds: a link, a form action, a media URL, by the\n * page URL's names and the same shapes.\n */\n\n/** A URL parameter's name as the one rule reads it (nameParts), its parts joined: what the OAuth and id rules compare. */\nfunction normalizeName(name: string): string {\n return nameParts(name, \"page\").join(\"\");\n}\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst JWT = /^eyJ[\\w-]+\\.[\\w-]+\\.[\\w-]*$/;\n/** A slug: two or more hyphen-separated words of three letters or more. */\nconst SLUG = /(?:^|-)[A-Za-z]{3,}-(?:[A-Za-z0-9]+-)*[A-Za-z]{3,}(?:-|$)/;\n\n/**\n * A query value that is a token whatever it is called: a JWT, or 32 or\n * more characters of a token alphabet mixing letters and digits that is\n * not a slug (`apple-iphone-15-pro-max-256gb`) and not a canonical UUID\n * (an id a flow's pages are told apart by). Only query and fragment-pair\n * VALUES are judged by shape; a path segment is a token only when it is a\n * JWT, since slugs, digests and file names live there.\n */\nfunction isTokenShaped(value: string): boolean {\n if (JWT.test(value)) return true;\n if (value.length < 32 || UUID.test(value) || SLUG.test(value)) return false;\n return (\n /^[A-Za-z0-9_\\-.~+/=]+$/.test(value) &&\n /[0-9]/.test(value) &&\n /[A-Za-z]/.test(value)\n );\n}\n\n/** What any built-in pattern needs somewhere in a value to match it. */\nconst MAYBE_PII = /@|\\d[\\d .()-]{5,}\\d|\\d\\.\\d|eyJ/;\n\n/*\n * AN OAUTH AUTHORIZATION RESPONSE IS REDACTED IN EVERY MODE (founder\n * ruling on the rebase onto #36). The page URL rule's pageSecrets\n * redacts a code beside a generated-looking state, or a long\n * generated-looking code on a callback's path; a provider's short code,\n * or a state that is short or holds a dash, passed it. So a `code` and\n * the `state` beside it are replaced here when the code is not a path or\n * a URL and either the URL's path (or a hash router's route) is a\n * callback's -- `callback` or `oauth` in a segment, or a segment of\n * CALLBACK_WORDS -- or the state is not a plain word: an app's own\n * `?code=ORD-2024-000123&state=delivered` and `?code=US&state=CA` stay,\n * as #36's tests require. A `state` beside an id, access or refresh token\n * is the implicit grant's and goes too; the tokens go by name.\n */\n\n/** Whether a path, or a hash router's route, is an OAuth callback's. */\nfunction isCallbackPath(path: string): boolean {\n return path.split(\"/\").some((segment) => {\n if (/callback|oauth/i.test(segment)) return true;\n const words = segmentWords(segment);\n return [...words, words.join(\"\")].some((w) => CALLBACK_WORDS.has(w));\n });\n}\n\n/** The names an OAuth authorization response is read by (oauthPairs). */\nconst OAUTH_NAMES: ReadonlySet<string> = new Set([\n \"code\",\n \"state\",\n \"accesstoken\",\n \"idtoken\",\n \"refreshtoken\",\n]);\n\n/** The names whose values an OAuth authorization response's pairs hold here. */\nfunction oauthPairs(pairs: string[], callback: boolean): Set<string> {\n // Every occurrence: a second `code=` must not hide behind a first that\n // is a path (review). One pass, a value decoded only under a name asked\n // for: five passes decoded every name five times, for a query that\n // holds none of them.\n const found = new Map<string, string[]>();\n for (const pair of pairs) {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) continue;\n const n = normalizeName(decodePart(pair.slice(0, eq)));\n if (!OAUTH_NAMES.has(n)) continue;\n const list = found.get(n);\n const value = decodePart(pair.slice(eq + 1));\n if (list === undefined) found.set(n, [value]);\n else list.push(value);\n }\n const values = (n: string): string[] => found.get(n) ?? [];\n const out = new Set<string>();\n const codes = values(\"code\").filter((c) => c !== \"\" && !isUrlLike(c));\n const states = values(\"state\").filter(\n (s) => s !== \"\" && !isPlainState(s) && !isUrlLike(s),\n );\n if (codes.length > 0 && (callback || states.length > 0)) {\n out.add(\"code\");\n out.add(\"state\");\n out.add(\"sessionstate\");\n }\n if (\n values(\"accesstoken\").length > 0 ||\n values(\"idtoken\").length > 0 ||\n values(\"refreshtoken\").length > 0\n ) {\n out.add(\"state\");\n out.add(\"sessionstate\");\n }\n return out;\n}\n\n/**\n * The page URL's credentials as the credential scrub holds them\n * (secretsOf), while one DOM event is scrubbed: scrubDomTree and\n * scrubDomAttributes set it and put it back. Empty for a page URL, and for\n * a DOM URL when the page's URL carries none.\n */\nlet known: readonly string[] = [];\n\n/** True while a DOM event's URLs are scrubbed, as `known` is set: see pageRules' `head`. */\nlet inDom = false;\n\n/** True while a URL a visitor goes to is scrubbed, not one the page loads: a credential word's rule is for those. */\nlet navigating = false;\n\n/** scrubUrlValue with `navigating` set as asked and put back whatever happens: a throw (ScrubOverCap) must not leave the next resource read as a link. */\nfunction scrubUrlAs(navigation: boolean, value: string, strict: boolean) {\n const outer = navigating;\n navigating = navigation;\n try {\n return scrubUrlValue(value, strict);\n } finally {\n navigating = outer;\n }\n}\n\n/** Whether an attribute takes the visitor somewhere: an `<a>`'s or an `<area>`'s `href`, or a form's. Unknown, as a change's tag is, it may. */\nfunction isNavigation(name: string, tag: string): boolean {\n if (name === \"href\" || name === \"xlink:href\")\n return tag === \"\" || tag === \"a\" || tag === \"area\";\n return name === \"action\" || name === \"formaction\";\n}\n\n/** A word a reset, invite, verify or magic link puts before its token: the prefilter before linkPathTokens. */\nconst LINK_WORD =\n /reset|verif|confirm|activat|invit|magic|log-?in|passw|unlock|forgot|recover|sign-?up/i;\n\n/**\n * The token segments of a link's path, as the page URL rule tells them\n * from an app's own ids for the page's own URL (pageSecrets): after a\n * reset, invite, verify or magic-link word, a generated-looking value --\n * `/reset-password/<t>`, `/invitations/<uuid>/accept` -- and not\n * `/order/confirmation/<uuid>` or `/products/apple-magic-mouse/<id>`.\n */\nfunction linkPathTokens(path: string): Set<string> {\n const tokens = new Set<string>();\n const at = path.startsWith(\"/\") ? path : `/${path}`;\n for (const secret of pageSecrets(`https://link.invalid${at}`))\n tokens.add(secret.value);\n return tokens;\n}\n\n/**\n * A link's token as the DOM is read for one: a UUID, or a value with a\n * part that looks generated (looksRandom: 8 or more characters mixing two\n * of lower case, upper case and digits, and no word) -- an invitation's\n * 8-character code among them. pageSecrets also takes a slug of words\n * and numbers after a sign-in word for a token\n * (`/login/apple-iphone-15-pro-max-256gb`), which for the page's own URL\n * it may; in the DOM, where every product and article link is read, a\n * link keeps it.\n */\nfunction isLinkToken(segment: string): boolean {\n const v = decoded(segment);\n if (UUID.test(v)) return true;\n return v.split(/[-_.~]+/).some(looksRandom);\n}\n\n/**\n * How much of `raw` is one of the page URL's credentials followed by a\n * path, or 0: rrweb resolves a CSS url() against the page's URL by\n * cutting it at a `/`, so on a page reached with `?token=X`, `url(img.png)`\n * becomes `?token=X/img.png`. The credential goes and the file name rrweb\n * appended stays -- known by the credential's VALUE, never by marker text\n * found in the input, so a `[REDACTED]` the page wrote itself shields\n * nothing.\n */\nfunction knownPrefix(raw: string): number {\n let longest = 0;\n // Lower-cased once, and only when a declared code is asked for: up to\n // 256 credentials are held, and a value is read against each.\n let lower: string | null = null;\n for (const secret of known) {\n if (secret.length <= longest || raw.charAt(secret.length) !== \"/\") continue;\n if (raw.startsWith(secret)) {\n longest = secret.length;\n continue;\n }\n if (lower === null) lower = asciiLower(raw);\n if (lower.startsWith(secret)) longest = secret.length;\n }\n return longest;\n}\n\n/** The runs of a value a token could be: what lies between characters no token holds. */\nfunction tokenRuns(value: string): string[] {\n return value.split(/[^A-Za-z0-9_\\-.~+/=]+/);\n}\n\n/**\n * Whether a query value holds a token: the value whole, or, when it is\n * not a URL, any run of token characters in it -- so text around a token\n * (a `[REDACTED]` the page wrote, a label) hides nothing. A URL -- an\n * http(s) URL or a path, with none of the characters a URL cannot hold\n * (a space, a bracket, a quote) -- is scrubbed one level down instead\n * (scrubNestedUrl): read as runs, a return URL's path was one long run,\n * and went whole.\n */\nfunction holdsToken(value: string): boolean {\n if (isTokenShaped(value)) return true;\n if (/^(?:https?:|\\/)[^\\s\"<>\\\\^`{|}[\\]]*$/i.test(value)) return false;\n return tokenRuns(value).some(isTokenShaped);\n}\n\n/** Whether a link is a link page, read as the page URL rule reads one (isLinkPage): only for a pair under a link page's names. */\nfunction linkPairs(path: string, pairs: string[]): boolean {\n const named = pairs.map((p): [string, string] => {\n const eq = p.indexOf(\"=\");\n return eq === -1 ? [p, \"\"] : [p.slice(0, eq), p.slice(eq + 1)];\n });\n return isLinkPage(\n [path.split(\"/\").map((s) => s.split(\";\")[0]!)],\n pairValue(named),\n );\n}\n\n/* ------------------------------------------------------------------ */\n/* URLs in the DOM rrweb records */\n/* ------------------------------------------------------------------ */\n/*\n * The page's links carry the same tokens its own URL does: a reset link\n * in `<a href>`, a session in `<form action>`, a signed media URL in\n * `src`/`srcset`/`poster`. rrweb serialises every attribute into the\n * full snapshot and every attribute change into a mutation, so each\n * URL-valued attribute goes through the page-URL scrub.\n */\n\n/** Attributes whose value is a URL (`srcset` a list of them). */\nconst URL_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"href\",\n \"xlink:href\",\n \"src\",\n \"action\",\n \"formaction\",\n \"srcset\",\n \"poster\",\n \"cite\",\n \"data\",\n // Lazy loaders keep the real (often signed) URL here until it loads.\n \"data-src\",\n \"data-href\",\n \"background\",\n \"longdesc\",\n]);\n\n/**\n * The attributes whose value is text a person reads, or a value one set:\n * read for PII as well as tokens (scrubAttributeText). Any other -- a URL,\n * CSS, a srcdoc (whose text is the page's, as a text node's is), an `id`\n * or a reference to one, an SVG path's or a viewBox's numbers -- is read\n * for tokens alone: `d=\"M 100 200 1234\"` is no phone number, and a\n * replay draws what it says.\n */\nconst TEXT_ATTRIBUTES: ReadonlySet<string> = new Set([\n \"title\",\n \"alt\",\n \"placeholder\",\n \"label\",\n \"content\",\n \"summary\",\n \"abbr\",\n \"aria-label\",\n \"aria-description\",\n \"aria-valuetext\",\n \"aria-placeholder\",\n \"aria-roledescription\",\n \"aria-braillelabel\",\n \"aria-brailleroledescription\",\n]);\n\n/** The elements whose `value` is what a person typed or chose: governed by `privacyMode`'s mask map, not read for PII. */\nconst FIELD_TAGS: ReadonlySet<string> = new Set([\n \"input\",\n \"textarea\",\n \"select\",\n]);\n\n/**\n * An attribute that holds text: one of TEXT_ATTRIBUTES, a `data-*` that\n * is no URL (`data-clipboard-text`, `data-email`), or the `value` of an\n * element `tag` names that is no field (a button's, an option's). A\n * field's value is what the mask map decides -- `off` records a typed\n * email, as its README row says -- and a value an attribute change sets,\n * whose element the change does not name, is read for tokens alone.\n */\nfunction isTextAttribute(name: string, tag: string): boolean {\n if (name === \"value\") return tag !== \"\" && !FIELD_TAGS.has(tag);\n return (\n TEXT_ATTRIBUTES.has(name) ||\n (name.startsWith(\"data-\") &&\n !URL_ATTRIBUTES.has(name) &&\n name !== \"data-srcset\")\n );\n}\n\n/*\n * STRICT RECORDS NO PAGE TEXT (README, Privacy): every attribute value is\n * blanked but those strict's ALLOW-LIST keeps (strict-attributes.ts, which\n * says why each name is there), those with their own rule (OWN_RULE: CSS,\n * a srcset, a srcdoc) and a URL-named one holding a URL. The allow-list is\n * a CHUNK OF ITS OWN, about 954 B gzipped that only strict needs: the\n * recorder loads it beside rrweb under strict and starts no recording\n * until it is installed here (recorder.ts loadRecorder). Not installed --\n * no path records so, but a future one would -- strict FAILS CLOSED:\n * every value is blanked but those two rules'.\n */\nlet strictKept: typeof import(\"./strict-attributes\").kept | undefined;\n/** Installs strict's allow-list, once its chunk has loaded (recorder.ts). */\nexport function keepStrict(kept: typeof strictKept): void {\n strictKept = kept;\n}\n/** Read by their own rule under strict, on every element: CSS, a srcset, a ping, a srcdoc. */\nconst OWN_RULE =\n /^(?:style|_csstext|srcset|data-srcset|imagesrcset|ping|srcdoc)$/;\n\n/** A value that can be a URL: no whitespace, quote, brace or angle bracket. */\nconst URLISH = /^[^\\s\"'`<>{}]*$/;\n\n/** Under strict, the value an attribute is recorded with when strict blanks it; undefined when strict keeps it (and its own rule reads it). */\nfunction blanked(\n name: string,\n value: string,\n tag: string,\n attributes?: Record<string, unknown>,\n svg = false,\n): string | undefined {\n if (\n name === \"content\"\n ? strictKept?.(name, tag, svg, attributes)\n : OWN_RULE.test(name) ||\n strictKept?.(name, tag, svg) ||\n // A URL-named attribute keeps a URL (its query the URL rule's), not\n // text: `<x-card src=\"Jane Doe\">`, `data='{\"q\":...}'` (review).\n (URL_ATTRIBUTES.has(name) && URLISH.test(decoded(value)))\n )\n return undefined;\n return /[^*\\s]/.test(value) ? \"\" : value;\n}\n\n/** `<meta http-equiv=refresh content=\"5; url=...\">`: the URL part. */\nconst REFRESH = /^(\\s*[\\d.]*\\s*[;,]\\s*(?:url\\s*=\\s*)?)(['\"]?)(.*?)(\\2\\s*)$/is;\n\n/** Nothing in a value the scrub could change: no query, fragment, path parameter, user info or JWT. */\nconst MAYBE_SCRUBBED = /[?#;@]|eyJ/;\n\n/**\n * Whether a URL may hold anything the DOM URL scrub replaces: a query, a\n * fragment, a path parameter, user info or a JWT -- or, in a DOM URL, a\n * link word, whose path is read for a token (linkPathTokens). Asked\n * before any scrub, so a page of plain links costs a regex test each.\n */\nfunction maybeScrubbed(value: string): boolean {\n return MAYBE_SCRUBBED.test(value) || (inDom && LINK_WORD.test(value));\n}\n\n/*\n * THE PAGE'S AND THE DOM'S RULES for the one URL scrubber (@keploy/contract's\n * privacy.ts scrubUrl): what a URL is made of is read there, as for every\n * URL the SDK records, and these are the value rules only the page's URL\n * and the DOM's take -- a URL that is no replay key, read by a `page`'s\n * names. In order: an OAuth authorization response's code and state\n * (oauthPairs), a link page's key (linkPageValue), and a page credential\n * at a value's head with a path after it (knownPrefix); then, after the\n * name rule, a value by its shape (holdsToken, isTokenShaped) or a PII\n * pattern; a bare name by its shape; a path's JWT segment and a link's\n * token segment (linkPathTokens).\n */\n\n/** The OAuth response's names and the link-page reading of one query, each read once: read for each pair, a 32 KB href of `t=1&` took 5.5 s on the page's thread (MEASURED in review). */\nconst queryReads = new WeakMap<\n readonly string[],\n { oauth: Set<string>; linkPage?: boolean }\n>();\n\nfunction readOf(ctx: PairContext): { oauth: Set<string>; linkPage?: boolean } {\n let read = queryReads.get(ctx.pairs);\n if (read === undefined) {\n read = { oauth: oauthPairs([...ctx.pairs], isCallbackPath(ctx.path)) };\n queryReads.set(ctx.pairs, read);\n }\n return read;\n}\n\nfunction pageBefore(strict: boolean) {\n return (name: string, raw: string, ctx: PairContext): string | null => {\n const read = readOf(ctx);\n if (read.oauth.has(normalizeName(decodePart(name)))) return \"[REDACTED]\";\n if (\n linkPageValue(nameParts(name, \"page\"), raw) &&\n (read.linkPage ??= linkPairs(ctx.path, [...ctx.pairs]))\n )\n return \"[REDACTED]\";\n // A page URL credential at the head of the value and a path after\n // it, under any name: the cut rrweb makes of a CSS url()\n // (knownPrefix). The credential goes and the path stays, unless a\n // PII pattern touches it; then the value goes whole.\n const cut = strict ? 0 : knownPrefix(raw);\n if (cut > 0) {\n const rest = decodePart(raw.slice(cut));\n if (!MAYBE_PII.test(rest) || redactStringValue(rest) === rest)\n return `[REDACTED]${raw.slice(cut)}`;\n }\n return null;\n };\n}\n\nfunction pageRules(strict: boolean): UrlRules {\n // The segments of the last DOM path the head rule read, and its link's\n // tokens: one reading for each scrubPath call, known by its segments'\n // array, which each call makes anew. Known by the path's text, an equal\n // path compared whole at each segment cost the square of a repeat (1.6 s\n // for a 256 KB link scrubbed twice, found in review).\n let headBases: readonly string[] | undefined;\n let headTokens: Set<string> | null = null;\n return {\n kind: \"page\",\n strict,\n whole: false,\n before: pageBefore(strict),\n value: (name, raw, value) => {\n // A value under an `*id`/`*ids` name is an id however it looks\n // (a Relay id, a 32-hex id): judged by name only (review). A name\n // with brackets (`filter[id]`, `ids[]`) is none.\n const idParts = nameParts(name, \"key\");\n const idName =\n !/[[\\]]/.test(decoded(name)) && /ids?$/.test(idParts[0] ?? \"\");\n return (\n (!idName && (holdsToken(value) || isTokenShaped(raw))) ||\n // An email, a phone number, a card: the built-in patterns. A page\n // URL is no replay key, so a value they touch goes whole. Only a\n // value that could hold one is scanned: every pattern needs an\n // `@`, a run of digits, `digit.digit` or `eyJ`, and a snapshot of\n // a page of links scans thousands of values.\n (MAYBE_PII.test(value) && redactStringValue(value) !== value)\n );\n },\n bare: (pair) => isTokenShaped(pair) || isTokenShaped(decodePart(pair)),\n segment: (seg) => JWT.test(seg),\n // A link's path token (DOM URLs only: the page's own URL has been\n // through the page URL rule already), a segment judged without the `;`\n // parameters it may carry (`/reset/<token>;v=1`).\n // Read once for each path, a DOM URL's only: read for each segment, a\n // path of many segments was read whole for each (9 s for 256 KB of\n // `/`, found in review), and a reading kept here whatever asked was\n // the page URL's when a DOM URL of that path asked (found in review).\n head: (path, base, i, bases) => {\n if (!inDom) return false;\n if (bases !== headBases) {\n headBases = bases;\n headTokens = LINK_WORD.test(path) ? linkPathTokens(path) : null;\n }\n const tokens = headTokens;\n return (\n tokens !== null &&\n tokens.has(base) &&\n (isLinkToken(base) || (navigating && afterCredentialWord(bases, i)))\n );\n },\n };\n}\n\nconst PAGE_RULES = pageRules(false);\nconst STRICT_PAGE_RULES = pageRules(true);\n\n/**\n * One URL-valued attribute value as it may be recorded, by the one URL\n * scrubber under the page's rules: an absolute URL (`https:`, `wss:`,\n * `myapp://`, `mailto:`) and a relative one alike; a script's or an\n * inline object's (`javascript:`, `data:`, `blob:`) is kept.\n * Byte-identical when nothing in it is scrubbed.\n */\nfunction scrubUrlValue(value: string, strict: boolean): string {\n if (!maybeScrubbed(value)) return value;\n return scrubUrl(value, strict ? STRICT_PAGE_RULES : PAGE_RULES);\n}\n\n/** `url 1x, url 2x`: each candidate's URL scrubbed, its descriptor kept. */\nfunction scrubSrcset(value: string, strict: boolean): string {\n if (!maybeScrubbed(value)) return value;\n const out = value\n .split(\",\")\n .map((candidate) => {\n const m = /^(\\s*)(\\S+)([\\s\\S]*)$/.exec(candidate);\n return m === null ? candidate : m[1] + scrubUrlValue(m[2], strict) + m[3];\n })\n .join(\",\");\n return out === value ? value : out;\n}\n\n/** A CSS identifier, its escapes included: what a function's name is read as. */\nconst IDENT =\n /(?:[A-Za-z0-9_-]|[\\u0080-\\uffff]|\\\\(?:[0-9A-Fa-f]{1,6}[ \\t\\n]?|[^\\n0-9A-Fa-f]))+/y;\n\n/** Where the CSS identifier at `at` ends, or `at` when none starts there. */\nfunction identEnd(css: string, at: number): number {\n IDENT.lastIndex = at;\n return IDENT.test(css) ? IDENT.lastIndex : at;\n}\n\n/** CSS's escapes in a string or a `url()`: `\\` and 1-6 hex digits (and one space after), or `\\` and any other character. */\nfunction cssUnescape(text: string): string {\n return text.replace(\n /\\\\(?:([0-9A-Fa-f]{1,6})[ \\t\\n]?|([\\s\\S]))/g,\n (_m: string, hex: string | undefined, char: string | undefined) => {\n if (hex === undefined) return char === \"\\n\" ? \"\" : (char ?? \"\");\n const code = parseInt(hex, 16);\n return code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)\n ? \"�\"\n : String.fromCodePoint(code);\n },\n );\n}\n\n/** A URL written back into CSS read through its escapes: what would end a string (`quoted`) or a `url()` escaped again. */\nfunction cssEscape(text: string, quoted: boolean): string {\n return text.replace(quoted ? /[\\\\\"'\\n]/g : /[\\\\\"'()\\s]/g, (c) =>\n /\\s/.test(c) ? `\\\\${c.charCodeAt(0).toString(16)} ` : `\\\\${c}`,\n );\n}\n\n/**\n * CSS text -- a style attribute, a `<style>`'s, the stylesheet rrweb\n * inlines for a `<link>`, a rule a script inserted, a declaration it set\n * -- each URL in it scrubbed, every other byte kept: a `url(...)`, quoted\n * or not, closed or not (CSS reads an unclosed one to the end), and every\n * other quoted string, which CSS names a URL with in `@import \"...\"`,\n * `image-set(\"...\" 1x)` and `src(\"...\")`; a string that is not a URL\n * comes back as it was. Read through CSS's escapes, and past its\n * comments, so an apostrophe in `/* don't *\\/` opens no string. Scanned\n * by hand, once, left to right: a regex with three whitespace-matching\n * quantifiers in a row took cubic time on an unclosed `url(` (MEASURED by\n * review: 2,000 spaces, 618 ms), on every snapshot and mutation.\n */\nfunction scrubCssUrls(value: string, strict: boolean): string {\n if (!/url\\(|[\"'\\\\]/i.test(value)) return value;\n if (!maybeScrubbed(value) && !value.includes(\"\\\\\")) return value;\n const len = value.length;\n const space = /[\\t\\n\\f\\r ]/;\n let out = \"\";\n let pos = 0;\n // The URL at [from, to), scrubbed, and written back as it was spelled.\n const take = (from: number, to: number, quoted: boolean): void => {\n const raw = value.slice(from, to);\n const text = raw.includes(\"\\\\\") ? cssUnescape(raw) : raw;\n const scrubbed = scrubUrlValue(text, strict);\n if (scrubbed === text) return;\n out +=\n value.slice(pos, from) +\n (text === raw ? scrubbed : cssEscape(scrubbed, quoted));\n pos = to;\n };\n let i = 0;\n while (i < len) {\n const c = value[i];\n if (c === \"/\" && value[i + 1] === \"*\") {\n const end = value.indexOf(\"*/\", i + 2);\n i = end === -1 ? len : end + 2;\n } else if (value.startsWith(\"<!--\", i)) {\n // CSS's CDO token: no identifier's start, so a `url(` after it is one.\n i += 4;\n } else if (c === '\"' || c === \"'\") {\n // To its closing quote, a newline (CSS's bad string), or the end.\n let end = i + 1;\n while (end < len && value[end] !== c && value[end] !== \"\\n\")\n end += value[end] === \"\\\\\" ? 2 : 1;\n end = Math.min(end, len);\n take(i + 1, end, true);\n i = end + 1;\n } else {\n // An identifier, read through its escapes: `u\\72l(` is `url(` to a\n // browser. Any other is passed over whole, as is any other character.\n const name = identEnd(value, i);\n if (name === i) {\n i++;\n continue;\n }\n if (\n value[name] !== \"(\" ||\n cssUnescape(value.slice(i, name)).toLowerCase() !== \"url\"\n ) {\n i = name;\n continue;\n }\n let from = name + 1;\n while (from < len && space.test(value[from])) from++;\n // A quoted url()'s URL is its string, read as any string is.\n if (value[from] === '\"' || value[from] === \"'\") {\n i = from;\n continue;\n }\n // Unquoted: to its `)` (an escaped one does not close it) or the end.\n let end = from;\n while (end < len && value[end] !== \")\")\n end += value[end] === \"\\\\\" ? 2 : 1;\n end = Math.min(end, len);\n let to = end;\n while (to > from && space.test(value[to - 1])) to--;\n take(from, to, false);\n i = end + 1;\n }\n }\n return pos === 0 ? value : out + value.slice(pos);\n}\n\n/**\n * The character references for an ASCII character, by name: each one\n * HTML names that a URL's delimiters, or text around them, can be\n * written with. `&`, `<`, `>` and `"`, in either case, are\n * read without their `;` too (decodeHtml).\n */\nconst HTML_NAMED: Readonly<Record<string, string>> = {\n Tab: \"\\t\",\n NewLine: \"\\n\",\n excl: \"!\",\n quot: '\"',\n QUOT: '\"',\n num: \"#\",\n dollar: \"$\",\n percnt: \"%\",\n amp: \"&\",\n AMP: \"&\",\n apos: \"'\",\n lpar: \"(\",\n rpar: \")\",\n ast: \"*\",\n midast: \"*\",\n plus: \"+\",\n comma: \",\",\n period: \".\",\n sol: \"/\",\n colon: \":\",\n semi: \";\",\n lt: \"<\",\n LT: \"<\",\n equals: \"=\",\n gt: \">\",\n GT: \">\",\n quest: \"?\",\n commat: \"@\",\n lsqb: \"[\",\n lbrack: \"[\",\n bsol: \"\\\\\",\n rsqb: \"]\",\n rbrack: \"]\",\n Hat: \"^\",\n lowbar: \"_\",\n UnderBar: \"_\",\n grave: \"`\",\n DiacriticalGrave: \"`\",\n lcub: \"{\",\n lbrace: \"{\",\n verbar: \"|\",\n vert: \"|\",\n VerticalLine: \"|\",\n rcub: \"}\",\n rbrace: \"}\",\n nbsp: \" \",\n NonBreakingSpace: \" \",\n};\n\n/**\n * An attribute value as a browser reads it out of markup: numeric\n * character references, any number of digits long (`=` is `=`),\n * the named ones for ASCII (HTML_NAMED), and `&`, `<`, `>` and\n * `"` in either case without their `;` where no letter, digit or `=`\n * follows. A reference it does not know is left as written.\n */\nfunction decodeHtml(value: string): string {\n if (!value.includes(\"&\")) return value;\n return value.replace(\n /&(?:#(\\d+);?|#[xX]([0-9A-Fa-f]+);?|([A-Za-z][A-Za-z0-9]*);|(amp|AMP|lt|LT|gt|GT|quot|QUOT)(?![A-Za-z0-9=]))/g,\n (\n m: string,\n dec: string | undefined,\n hex: string | undefined,\n named: string | undefined,\n legacy: string | undefined,\n ) => {\n if (dec !== undefined || hex !== undefined) {\n const code = dec !== undefined ? Number(dec) : parseInt(hex!, 16);\n return code === 0 ||\n code > 0x10ffff ||\n (code >= 0xd800 && code <= 0xdfff)\n ? \"�\"\n : String.fromCodePoint(code);\n }\n return HTML_NAMED[named ?? legacy ?? \"\"] ?? m;\n },\n );\n}\n\n/** A value written back into markup between `quote`s (none: unquoted), so a browser reads it as it was scrubbed. */\nfunction encodeHtml(value: string, quote: string): string {\n const amp = value.replace(/&/g, \"&\");\n if (quote === '\"') return amp.replace(/\"/g, \""\");\n if (quote === \"'\") return amp.replace(/'/g, \"'\");\n // Unquoted, a value ends at a space or `>`, and a quote would open one.\n return amp.replace(/[\\s\"'`>]/g, (c) => `&#${c.charCodeAt(0)};`);\n}\n\n/** Elements whose text a browser reads as text, never as tags, up to their end tag. */\nconst RAW_TEXT: ReadonlySet<string> = new Set([\n \"script\",\n \"style\",\n \"textarea\",\n \"title\",\n \"xmp\",\n \"iframe\",\n \"noembed\",\n \"noframes\",\n]);\n\n/** An attribute the DOM scrub reads -- a URL, a style, a srcdoc -- anywhere in markup, its value quoted or not: the second read of a srcdoc (scrubHtml). */\nconst HTML_URL_ATTRIBUTE =\n /(^|[\\s/\"'])(href|xlink:href|src|action|formaction|poster|cite|data|background|longdesc|data-src|data-href|srcset|imagesrcset|data-srcset|ping|content|style|srcdoc)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'>]+))/gi;\n\n/**\n * An `iframe`'s `srcdoc`: a whole document in one attribute, read twice.\n * First as a browser's tokenizer reads it: comments, `<!...>` and `<?...>`\n * passed over, an end tag's attributes read and left, a raw-text\n * element's text (`<script>`, `<textarea>`, `<title>`) passed over to its\n * end tag, a `<style>`'s scrubbed as CSS; in a start tag, an attribute\n * after a `/` or straight after a closing quote, a value quoted or not,\n * character references decoded (decodeHtml), and each attribute\n * scrubbed as the DOM's own are (a `style` and a nested `srcdoc`\n * included). Then, in what that read passed over, each URL-valued\n * attribute found by its shape alone, so markup it takes otherwise than\n * a browser does -- foreign content's CDATA, a tag it misreads -- hides\n * no link. A value scrubbed is written back with its references encoded;\n * the rest of the markup is kept byte for byte.\n */\nfunction scrubHtml(html: string, strict: boolean): string {\n if (!strict && !maybeScrubbed(html) && !/url\\(/i.test(html)) return html;\n const len = html.length;\n const space = /[\\t\\n\\f\\r ]/;\n // Replacements, and the values the first read took, by their range.\n const edits: Array<[number, number, string]> = [];\n const read = new Set<string>();\n // One attribute value at [from, to), scrubbed by its name.\n const value = (\n name: string,\n from: number,\n to: number,\n quote: string,\n tag = \"\",\n ) => {\n const text = decodeHtml(html.slice(from, to));\n const scrubbed =\n (strict ? blanked(name, text, tag) : undefined) ??\n scrubAttributeValue(name, text, strict, \"\");\n if (scrubbed !== text) edits.push([from, to, encodeHtml(scrubbed, quote)]);\n };\n // A tag's attributes from `start`, each scrubbed when `scrub`: where it ends (its `>`, or the end).\n const attributes = (start: number, scrub: boolean, tag = \"\"): number => {\n let i = start;\n for (;;) {\n while (i < len && (space.test(html[i]) || html[i] === \"/\")) i++;\n if (i >= len || html[i] === \">\") return i;\n const nameAt = i;\n // A name's first character may be `=`; after it, `=` ends the name.\n i++;\n while (i < len && !space.test(html[i]) && !\"/>=\".includes(html[i])) i++;\n const name = html.slice(nameAt, i).toLowerCase();\n let j = i;\n while (j < len && space.test(html[j])) j++;\n if (html[j] !== \"=\") {\n i = j;\n continue;\n }\n j++;\n while (j < len && space.test(html[j])) j++;\n const quote = html[j] === '\"' || html[j] === \"'\" ? html[j] : \"\";\n const from = quote === \"\" ? j : j + 1;\n let to = from;\n if (quote !== \"\") {\n to = html.indexOf(quote, from);\n if (to === -1) to = len;\n i = Math.min(to + 1, len);\n } else {\n while (to < len && !space.test(html[to]) && html[to] !== \">\") to++;\n i = to;\n }\n if (scrub) {\n read.add(`${from}:${to}`);\n value(name, from, to, quote, tag);\n }\n }\n };\n // Under strict, the text between tags and in every raw-text element\n // but a <style> (a <title>, a <textarea>, a <script>), a comment's, a\n // CDATA section's -- masked as rrweb masks a text node's: each\n // character but whitespace an asterisk.\n const mask = (from: number, to: number): void => {\n const text = html.slice(from, to);\n if (strict && /\\S/.test(text))\n edits.push([from, to, text.replace(/\\S/g, \"*\")]);\n };\n let text = 0;\n let i = html.indexOf(\"<\");\n while (i !== -1 && i < len) {\n let next: number;\n let tagged = true;\n if (html.startsWith(\"<!--\", i)) {\n // A comment: `<!-->` and `<!--->` end at once; else at `-->` or `--!>`.\n if (html.startsWith(\">\", i + 4)) next = i + 5;\n else if (html.startsWith(\"->\", i + 4)) next = i + 6;\n else {\n const end = /--!?>/g;\n end.lastIndex = i + 4;\n const m = end.exec(html);\n next = m === null ? len : m.index + m[0].length;\n mask(i + 4, m === null ? len : m.index);\n }\n } else if (html[i + 1] === \"!\" || html[i + 1] === \"?\") {\n const end = html.indexOf(\">\", i + 2);\n next = end === -1 ? len : end + 1;\n // A CDATA section or a bogus comment holds text; a doctype does not.\n if (!/^<!doctype/i.test(html.slice(i, i + 9)))\n mask(i + 2, end === -1 ? len : end);\n } else if (html[i + 1] === \"/\" && /[A-Za-z]/.test(html[i + 2] ?? \"\")) {\n // An end tag: its attributes read, so a quote in one is not taken\n // for text, and left as they are.\n let j = i + 2;\n while (j < len && !space.test(html[j]) && !\"/>\".includes(html[j])) j++;\n next = attributes(j, false) + 1;\n } else if (/[A-Za-z]/.test(html[i + 1] ?? \"\")) {\n let j = i + 1;\n while (j < len && !space.test(html[j]) && !\"/>\".includes(html[j])) j++;\n const tag = html.slice(i + 1, j).toLowerCase();\n const close = attributes(j, true, tag);\n next = close + 1;\n if (RAW_TEXT.has(tag) && close < len) {\n // Its text, up to its end tag: CSS for a <style>, text otherwise.\n const end = new RegExp(`</${tag}[\\\\t\\\\n\\\\f\\\\r />]`, \"gi\");\n end.lastIndex = close + 1;\n const m = end.exec(html);\n const to = m === null ? len : m.index;\n if (tag === \"style\") {\n const css = html.slice(close + 1, to);\n const scrubbed = scrubCssUrls(css, strict);\n if (scrubbed !== css) edits.push([close + 1, to, scrubbed]);\n } else mask(close + 1, to); // strict: a script's text too\n next = to;\n }\n } else {\n // A `<` that opens no tag is text.\n next = i + 1;\n tagged = false;\n }\n if (tagged) {\n mask(text, i);\n text = next;\n }\n i = html.indexOf(\"<\", next);\n }\n mask(text, len);\n // In order: a tag's attribute edits are pushed before the text in front\n // of it is masked, and the second read below takes them as sorted -- a\n // value it found inside masked text would undo the mask (found in review).\n edits.sort((a, b) => a[0] - b[0]);\n // The second read: every URL-valued attribute by its shape alone, each\n // match read again from its value on, so a name=value inside another's\n // value -- where the first read and a browser parted -- is found too. A\n // value the first read took is not read twice, nor text it replaced.\n const firstEdits = edits.length;\n const shape = new RegExp(HTML_URL_ATTRIBUTE.source, \"gi\");\n let e = 0;\n let after = 0;\n for (let m = shape.exec(html); m !== null; m = shape.exec(html)) {\n const raw = m[3] ?? m[4] ?? m[5] ?? \"\";\n const to = m.index + m[0].length - (m[5] === undefined ? 1 : 0);\n const from = to - raw.length;\n shape.lastIndex = from;\n while (e < firstEdits && edits[e][1] <= from) e++;\n if (\n read.has(`${from}:${to}`) ||\n (e < firstEdits && edits[e][0] < to) ||\n from < after\n )\n continue;\n const quote = m[3] !== undefined ? '\"' : m[4] !== undefined ? \"'\" : \"\";\n const before = edits.length;\n value(m[2].toLowerCase(), from, to, quote);\n if (edits.length > before) after = to;\n }\n if (edits.length === 0) return html;\n edits.sort((a, b) => a[0] - b[0]);\n let out = \"\";\n let pos = 0;\n for (const [from, to, text] of edits) {\n out += html.slice(pos, from) + text;\n pos = to;\n }\n return out + html.slice(pos);\n}\n\n/**\n * A `content` attribute: a refresh's URL (`5; url=/reset?token=...`), or\n * a whole URL (`og:url`), scrubbed; any other content kept.\n */\nfunction scrubContent(value: string, strict: boolean): string {\n if (!maybeScrubbed(value)) return value;\n const refresh = REFRESH.exec(value);\n if (refresh !== null && refresh[3] !== \"\") {\n const url = scrubUrlAs(true, refresh[3], strict);\n return url === refresh[3]\n ? value\n : refresh[1] + refresh[2] + url + refresh[4];\n }\n return /^\\s*https?:\\/\\//i.test(value) ? scrubUrlValue(value, strict) : value;\n}\n\n/**\n * An element's attributes as rrweb serialised them, each URL-valued one\n * scrubbed IN PLACE (a value is replaced only when the scrub changed it).\n * A value that is not a string (a style object, a removed attribute's\n * null) is left alone.\n */\nexport function scrubDomAttributes(\n attributes: Record<string, unknown>,\n strict: boolean,\n secrets: readonly string[] = [],\n tag = \"\",\n svg = false,\n): void {\n const outer = [known, inDom] as const;\n known = secrets;\n inDom = true;\n try {\n scrubAttributes(attributes, strict, tag, svg);\n } finally {\n [known, inDom] = outer;\n }\n}\n\nfunction scrubAttributes(\n attributes: Record<string, unknown>,\n strict: boolean,\n tag = \"\",\n svg = false,\n): void {\n for (const key of Object.keys(attributes)) {\n const value = attributes[key];\n const name = key.toLowerCase();\n // Which radio or option the visitor chose: rrweb writes `checked: true`\n // (a boolean), and the attribute's presence is the choice (review).\n if (strict && (name === \"checked\" || name === \"selected\")) {\n delete attributes[key];\n continue;\n }\n if (typeof value !== \"string\") {\n if (name === \"style\" && isPlainRecord(value))\n scrubStyleObject(value, strict);\n continue;\n }\n const out =\n (strict ? blanked(name, value, tag, attributes, svg) : undefined) ??\n scrubAttributeText(\n name,\n scrubAttributeValue(name, value, strict, tag),\n tag,\n );\n if (out !== value) attributes[key] = out;\n }\n}\n\n/**\n * A style changed through `element.style`, as rrweb records it: an object\n * of the properties changed, each a value, `[value, priority]` for an\n * `!important` one, or `false` for one removed. Each value is CSS, read as\n * a style attribute's is (scrubCssUrls); a script's lazy-loaded, signed\n * background image is set exactly this way.\n */\nfunction scrubStyleObject(style: Record<string, unknown>, strict: boolean) {\n const css = (value: string) =>\n scrubAttributeText(\"style\", scrubCssUrls(value, strict), \"\");\n for (const property of Object.keys(style)) {\n const value = style[property];\n if (typeof value === \"string\") {\n const out = css(value);\n if (out !== value) style[property] = out;\n } else if (Array.isArray(value) && typeof value[0] === \"string\") {\n const out = css(value[0]);\n if (out !== value[0]) style[property] = [out, ...value.slice(1)];\n }\n }\n}\n\n/**\n * An attribute's value read as text, in every mode: a provider's token\n * or a JWT anywhere in it -- a `data-clipboard-text` holding a minted\n * key -- and, in an attribute that holds text (isTextAttribute: `title`,\n * `aria-label`, `alt`, `value`, `data-*`, a meta `content`), each built-in\n * PII pattern. A URL keeps its host and path for the replay to load it\n * by, and is scrubbed as a URL; rrweb's own `rr_*` attributes (a canvas's\n * image data) are not the page's text.\n */\nfunction scrubAttributeText(name: string, value: string, tag: string): string {\n if (name.startsWith(\"rr_\")) return value;\n if (isTextAttribute(name, tag) && MAYBE_PII.test(value))\n return redactStringValue(value);\n return redactTokens(value);\n}\n\n/**\n * The page's own text -- a text node in a snapshot or a node added after\n * it, a text change, a value typed under `off` -- with each provider's\n * token and JWT in it replaced, in every mode: the dashboard shows a\n * freshly minted key as text, once. Other text, an email or a phone\n * number among it, is the page's content and is recorded as rrweb masks\n * it.\n */\nexport function scrubDomText(text: string): string {\n return redactTokens(text);\n}\n\n/** One attribute's value, by its lower-cased name: see scrubDomAttributes. */\nfunction scrubAttributeValue(\n name: string,\n value: string,\n strict: boolean,\n tag: string,\n): string {\n let out = value;\n if (name === \"srcset\" || name === \"data-srcset\" || name === \"imagesrcset\") {\n out = scrubSrcset(value, strict);\n } else if (name === \"style\" || name === \"_csstext\") {\n // `_cssText`: the stylesheet rrweb inlines for a `<link>`.\n out = scrubCssUrls(value, strict);\n } else if (name === \"ping\") {\n // A space-separated list of URLs.\n out = value.replace(/\\S+/g, (url) => scrubUrlValue(url, strict));\n } else if (name === \"srcdoc\") out = scrubHtml(value, strict);\n else if (name === \"content\") out = scrubContent(value, strict);\n else if (URL_ATTRIBUTES.has(name)) {\n out = scrubUrlAs(isNavigation(name, tag), value, strict);\n } else if (WHOLLY_URL.test(value)) {\n out = scrubUrlAs(false, value, strict);\n }\n return out;\n}\n\n/**\n * The value of an attribute off URL_ATTRIBUTES that is wholly a URL -- a\n * `data-next=\"/x?next=...\"`, an input's `value=\"/cb?access_token=...\"`:\n * a scheme or a path (`/`, `./`, `../`) first and a query, a fragment or\n * a path's parameter after it, or a query or a fragment first\n * (`?next=...`), and no space anywhere. A scheme is one WHOLE_URL in\n * redact.ts takes: a `/` after it, a `.` or `+` in its name, or one that\n * takes no authority -- never a CSS property's name\n * (`background:url(...);color:red`, found in review). Read as a listed one is (found in\n * review: such a value kept its credential). A class list, a title's\n * prose and a word are never one; a URL inside prose, and a relative one\n * with no `/` first (`cb?access_token=...`), are not read. The text up to\n * the first `?`, `#` or `;` is read once: `\\S*` there, then `\\S*` after,\n * read a run of `?` back from each (6 s for 128 KB, found in review).\n */\nconst WHOLLY_URL =\n /^(?:(?:[a-z][a-z0-9+.-]{0,31}:\\/|[a-z][a-z0-9-]{0,30}[+.][a-z0-9+.-]{0,30}:|localhost:\\d{1,5}[/?#]|(?:mailto|tel|sms|urn|data|javascript|vbscript|blob|about|xmpp|sip|sips|magnet|intent|bitcoin|geo|market|news):|\\.{0,2}\\/)[^\\s?#;]*[?#;]|[?#])\\S*$/i;\n\n/**\n * CSS a DOM event carries outside an attribute -- a `<style>`'s text\n * changed after it was added, a rule a script inserted or replaced\n * through the CSSOM, a declaration it set, an adopted stylesheet -- its\n * URLs scrubbed as a style attribute's are, with the page URL's\n * credentials known (`secrets`, as scrubDomTree takes them).\n */\nexport function scrubDomCss(\n css: string,\n strict: boolean,\n secrets: readonly string[] = [],\n): string {\n const outer = [known, inDom] as const;\n known = secrets;\n inDom = true;\n try {\n return scrubCssUrls(css, strict);\n } finally {\n [known, inDom] = outer;\n }\n}\n\n/**\n * Every element in an rrweb-serialised subtree -- a full snapshot's\n * document, a mutation's added node -- its attributes scrubbed in place.\n * Iterative, so a deep page cannot overflow the stack, and each node\n * once: emitEvent is public, and a DOM event handed in whose node holds\n * itself in its childNodes would otherwise never return (main's\n * recorder-navigation test hands one in).\n */\n/** A serialised text node, and rrweb's numbers for the kinds of node a run reads. */\ninterface TextNode {\n textContent: string;\n}\nconst TEXT_NODE = 3;\nconst COMMENT_NODE = 5;\n\n/**\n * Text nodes side by side read as one: a framework renders `{a}{b}` as\n * two, a key shown in groups is two or more, and each alone is no token.\n * A token across them goes: the first node it touches holds the marker,\n * and each other loses its part.\n */\nfunction scrubTextRun(run: TextNode[]): void {\n const text = run.map((node) => node.textContent).join(\"\");\n const ranges = tokenRanges(text).sort((a, b) => a[0] - b[0]);\n let r = 0;\n let at = 0;\n for (const node of run) {\n const end = at + node.textContent.length;\n let out = \"\";\n let pos = at;\n while (r < ranges.length && ranges[r]![0] < end) {\n const [from, to] = ranges[r]!;\n if (from >= pos) out += `${text.slice(pos, from)}[REDACTED]`;\n pos = Math.max(pos, Math.min(to, end));\n if (to > end) break;\n r++;\n }\n node.textContent = out + text.slice(pos, end);\n at = end;\n }\n}\n\nfunction isTextNode(node: unknown): node is TextNode {\n const n = node as { type?: unknown; textContent?: unknown } | null;\n return n?.type === TEXT_NODE && typeof n.textContent === \"string\";\n}\n\n/** Each run of a node's text children, a comment between them read past: server-rendered React writes `<!-- -->` there. */\nfunction scrubTextRuns(children: unknown[]): void {\n let run: TextNode[] = [];\n for (const child of children) {\n if (isTextNode(child)) run.push(child);\n else if ((child as { type?: unknown } | null)?.type !== COMMENT_NODE) {\n if (run.length > 1) scrubTextRun(run);\n run = [];\n }\n }\n if (run.length > 1) scrubTextRun(run);\n}\n\n/**\n * The same, for the nodes one mutation adds: each is an entry of its own,\n * and `nextId` says which follows which. Linear: each chain is read once,\n * from its head. A text beside a node already on the page is not in the\n * batch, so it is read alone.\n */\nexport function scrubAddedTextRuns(adds: unknown[]): void {\n type Added = { nextId?: unknown; node?: { id?: unknown; type?: unknown } };\n const byId = new Map<unknown, Added>();\n for (const add of adds as Array<Added | null>) {\n const type = add?.node?.type;\n if (type === TEXT_NODE || type === COMMENT_NODE)\n byId.set(add!.node!.id, add!);\n }\n const followers = new Set<Added | undefined>();\n for (const add of byId.values()) followers.add(byId.get(add.nextId));\n for (const add of byId.values()) {\n if (followers.has(add)) continue;\n const run: TextNode[] = [];\n for (let at: Added | undefined = add; at; at = byId.get(at.nextId))\n if (isTextNode(at.node)) run.push(at.node);\n if (run.length > 1) scrubTextRun(run);\n }\n}\n\nexport function scrubDomTree(\n root: unknown,\n strict: boolean,\n secrets: readonly string[] = [],\n): void {\n const outer = [known, inDom] as const;\n known = secrets;\n inDom = true;\n try {\n scrubTree(root, strict);\n } finally {\n [known, inDom] = outer;\n }\n}\n\nfunction scrubTree(root: unknown, strict: boolean): void {\n const stack: unknown[] = [root];\n const seen = new Set<object>();\n while (stack.length > 0) {\n const node = stack.pop() as {\n attributes?: unknown;\n tagName?: unknown;\n childNodes?: unknown;\n isStyle?: unknown;\n isSVG?: unknown;\n textContent?: unknown;\n type?: unknown;\n } | null;\n if (node === null || typeof node !== \"object\" || seen.has(node)) continue;\n seen.add(node);\n // A `<style>`'s text, as rrweb serialises it: its url()s; any other\n // text -- a text node, a comment -- its tokens.\n if (typeof node.textContent === \"string\") {\n // A comment under strict: blank (rrweb masks no comment).\n const text =\n node.isStyle === true\n ? scrubCssUrls(node.textContent, strict)\n : strict && node.type === COMMENT_NODE\n ? \"\"\n : scrubDomText(node.textContent);\n if (text !== node.textContent) node.textContent = text;\n }\n const attributes = node.attributes;\n if (attributes !== null && typeof attributes === \"object\") {\n scrubAttributes(\n attributes as Record<string, unknown>,\n strict,\n typeof node.tagName === \"string\" ? node.tagName.toLowerCase() : \"\",\n node.isSVG === true,\n );\n }\n if (Array.isArray(node.childNodes)) {\n scrubTextRuns(node.childNodes);\n for (const child of node.childNodes) stack.push(child);\n }\n }\n}\n\n/**\n * A URL as it may be recorded -- the page's own, after the page URL rule\n * (recordedPageUrl), or one in the DOM: query and fragment-pair values\n * scrubbed by name (the one rule's, as a `page`) and by shape (a\n * token, a PII pattern), a JWT path segment and a sensitive `;name=`\n * path parameter replaced, a URL inside a value scrubbed one level down,\n * user info dropped. Under\n * `strict` every query and fragment-pair VALUE is replaced and every name\n * kept: the founder's rule for public sites is that no typed text is\n * recorded, and a search box puts what was typed in `?q=`. Not an http(s)\n * URL: returned as it is. A URL with nothing to scrub is returned exactly\n * as it came.\n */\nexport function scrubPageUrl(raw: string, strict = false): string {\n if (!raw) return raw;\n return scrubUrl(raw, strict ? STRICT_PAGE_RULES : PAGE_RULES);\n}\n\n/* ------------------------------------------------------------------ */\n/* Defaults */\n/* ------------------------------------------------------------------ */\n\n/**\n * A header whose value is a URL (Location, Content-Location) or carries\n * them (each `<...>` target of a Link, the `url=` of a Refresh), with\n * those URLs' query values redacted as a request URL's are (maskUrl): by\n * name, and every one under strict -- the page requests a redirect's or a\n * link's target next, and its key is read so. A `Link: <...?q=ada&page=3>`\n * names the search a person typed. Every other header has each URL it\n * holds scrubbed as a body's URLs are (scrubHeaderUrls).\n */\nfunction maskHeaderUrls(\n name: string,\n value: string,\n maskUrl: (url: string) => string,\n): string {\n switch (name) {\n case \"location\":\n case \"content-location\":\n return maskUrl(value);\n case \"link\":\n return value.replace(\n /<([^>]*)>/g,\n (_, url: string) => `<${maskUrl(url)}>`,\n );\n case \"refresh\": {\n // Its delay is optional (`url=/x?token=...`, found in review: one\n // without was returned as it came); one that names no URL is read\n // as any other header's value is.\n const at = /^\\s*(?:\\d[\\d.]*\\s*[;,]\\s*)?url\\s*=\\s*/i.exec(value);\n if (at === null) return scrubHeaderUrls(value);\n const rest = value.slice(at[0].length);\n const quoted = /^([\"'])(.*)\\1$/.exec(rest);\n return quoted\n ? `${at[0]}${quoted[1]}${maskUrl(quoted[2])}${quoted[1]}`\n : `${at[0]}${maskUrl(rest)}`;\n }\n }\n return scrubHeaderUrls(value);\n}\n\n/**\n * The header values strict mode keeps: ones that describe the exchange,\n * never the person -- what a body is and how it travels and is cached.\n * Under strict every other value is replaced and its name kept: a header\n * the page's own code fills from what a person typed (`x-search-term`)\n * is typed text, which strict promises not to record.\n */\nconst STRICT_HEADERS: ReadonlySet<string> = new Set([\n \"accept\",\n \"accept-encoding\",\n \"accept-ranges\",\n \"age\",\n \"cache-control\",\n \"connection\",\n \"content-encoding\",\n \"content-language\",\n \"content-length\",\n \"content-type\",\n \"date\",\n \"etag\",\n \"expires\",\n \"keep-alive\",\n \"last-modified\",\n \"pragma\",\n \"transfer-encoding\",\n \"vary\",\n]);\n\n/**\n * A header whose NAME says its value is a credential, besides the six in\n * `sensitiveHeaders` by default: any name the body redaction reads as a\n * credential's (isSensitiveKey, the one rule: `*token`, `*apikey`,\n * `*secret`, `*password` and the rest -- `X-Access-Token`,\n * `X-Csrf-Token`, `Api-Key`, `X-Goog-Api-Key`, `X-Amz-Security-Token`),\n * or one whose last word, or last two read as one, the rule takes (a\n * vendor's prefix before a `csrf`, a `sid`, an `auth key`, an `mfa code`,\n * a `session id`, a `jwt assertion`). A word\n * that only describes one stays: `X-Session-Timeout`,\n * `X-Tokens-Remaining`, `X-Password-Policy`, `X-Request-Id`. No replay\n * needs a credential's value: a mock keeps `content-type` and\n * `cache-control` alone, and the replay key is the method, URL and body.\n */\nfunction isCredentialHeader(name: string): boolean {\n // CORS names a credential's kind, not one: `Access-Control-Allow-Credentials`.\n if (name.startsWith(\"access-control-\")) return false;\n if (isSensitiveKey(name)) return true;\n const words = name.split(/[-_\\s]+/).filter((w) => w !== \"\");\n if (words.length > 1 && /^v?\\d+$/.test(words[words.length - 1]!)) words.pop();\n const last = words[words.length - 1] ?? \"\";\n const before = words[words.length - 2] ?? \"\";\n // A vendor's prefix before the credential's own name: `X-Csrf`,\n // `X-Sid`, `X-Auth-Key`, `X-Mfa-Code`, `X-Session-Id`,\n // `X-Jwt-Assertion` -- the one rule's names, read at the name's last\n // word and its last two.\n return (\n isSensitiveKey(last) || (before !== \"\" && isSensitiveKey(before + last))\n );\n}\n\nexport function defaultPrivacyConfig(): PrivacyConfig {\n return {\n maskSelectors: [],\n unmaskSelectors: [],\n blockSelectors: [],\n maskNetworkBodies: false,\n sensitiveHeaders: [...DEFAULT_SENSITIVE_HEADERS],\n piiPatterns: [],\n secretRoutes: [],\n keepRoutes: [],\n };\n}\n\n/* ------------------------------------------------------------------ */\n/* PrivacyEngine */\n/* ------------------------------------------------------------------ */\n\n/**\n * Merge an integrator's overrides into the defaults.\n *\n * LISTS OF PROTECTIONS EXTEND; THEY DO NOT REPLACE. `sensitiveHeaders`\n * was spread straight over the defaults, so an integrator adding one\n * header of their own un-redacted authorization, cookie, set-cookie,\n * x-api-key, x-auth-token and proxy-authorization in every capture\n * from then on. There is deliberately no way to remove a built-in\n * header: no redacted header value is ever needed for replay — the\n * canonical key carries no headers, and the mock generator keeps only\n * content-type and cache-control (test-generator's mocks.ts) — so an\n * opt-out would only ever be a leak.\n */\nfunction mergePrivacyConfig(\n base: PrivacyConfig,\n partial: Partial<PrivacyConfig>,\n): PrivacyConfig {\n // An explicit `undefined` must not erase a default: `{...base, ...partial}`\n // would copy it over the base value.\n const defined = Object.fromEntries(\n Object.entries(partial).filter(([, v]) => v !== undefined),\n ) as Partial<PrivacyConfig>;\n const merged: PrivacyConfig = { ...base, ...defined };\n if (defined.sensitiveHeaders) {\n const seen = new Set<string>();\n merged.sensitiveHeaders = [\n ...DEFAULT_SENSITIVE_HEADERS,\n ...base.sensitiveHeaders,\n ...defined.sensitiveHeaders,\n ].filter((h) => {\n const k = h.toLowerCase();\n if (seen.has(k)) return false;\n seen.add(k);\n return true;\n });\n }\n return merged;\n}\n\n/**\n * Compile a caller's pattern so that `String.prototype.replace` hits\n * every occurrence. A pattern written without the `g` flag replaced\n * its first match and left the rest in the clear.\n */\nfunction compileGlobal(patterns: readonly PiiPattern[]): RegExp[] {\n return patterns.map(({ pattern }) =>\n pattern.flags.includes(\"g\")\n ? new RegExp(pattern.source, pattern.flags)\n : new RegExp(pattern.source, pattern.flags + \"g\"),\n );\n}\n\n/**\n * The body code (body-redact.ts) on this thread, once the capture has\n * loaded it (body-jobs.ts): what maskNetworkData redacts with when the\n * caller passes no bodies.\n */\nexport const bodyCode: { redact?: (job: BodyJob) => BodyOut } = {};\n\n/** What a body masked whole is recorded as (maskNetworkData); one that was absent stays null. */\nexport const MASKED = \"[MASKED]\";\n\nexport class PrivacyEngine {\n private config: PrivacyConfig;\n private builtinPatterns: RegExp[];\n /** The integrator's piiPatterns, compiled global once. */\n private userPatterns: RegExp[];\n /** `privacyMode: \"strict\"`: no body, and no query value, is recorded. */\n private readonly strict: boolean;\n\n /**\n * `privacyMode` is the capture's (CaptureConfig.privacyMode). Only\n * `strict` changes what this engine does: it records no request or\n * response body -- `maskNetworkBodies` is forced on, here and through\n * every updateConfig() -- and replaces every query value of a network\n * URL. KeployCapture refuses an explicit `maskNetworkBodies: false`\n * beside strict (KUI_E_PRIVACY_CONFLICT) before it builds one of these;\n * an engine built directly has no onError to say that to, so strict\n * wins, which is the direction that cannot leak.\n */\n constructor(\n config: Partial<PrivacyConfig> = {},\n privacyMode: CaptureConfig[\"privacyMode\"] = \"balanced\",\n ) {\n this.strict = privacyMode === \"strict\";\n this.config = this.settle(\n mergePrivacyConfig(defaultPrivacyConfig(), config),\n );\n this.builtinPatterns = compileGlobal(BUILTIN_PII_PATTERNS);\n this.userPatterns = compileGlobal(this.config.piiPatterns);\n }\n\n /** The merged config, with what strict mode forces. */\n private settle(config: PrivacyConfig): PrivacyConfig {\n return this.strict ? { ...config, maskNetworkBodies: true } : config;\n }\n\n /* -------------------------------------------------------------- */\n /* Text masking */\n /* -------------------------------------------------------------- */\n\n /**\n * Replace every occurrence of known PII patterns in `text` with\n * `[REDACTED]`. Returns the scrubbed string.\n */\n maskText(text: string): string {\n if (!text) return text;\n\n // Card numbers go through the structural detector (issuer prefix +\n // length + Luhn) rather than a length-only regex, which matched every\n // 13-digit timestamp. The user's patterns ride inside the same call.\n let result = redactStringValue(text, this.userPatterns);\n for (const re of this.builtinPatterns) {\n // replace() with a global regex always starts from index 0, so a\n // compiled pattern is safe to reuse across calls.\n result = result.replace(re, \"[REDACTED]\");\n }\n return result;\n }\n\n /**\n * Redact a URL without disturbing the parts that carry request identity.\n *\n * By the one URL scrubber (maskQueryValues): the path is kept -- it is\n * what the canonical key is computed from, and rewriting it makes the\n * recording unreplayable -- but for a `;name=` parameter that names a\n * credential (`;jsessionid=`), whose value goes.\n * Query values are redacted by parameter NAME (the one rule, read as a\n * `param`), and by nothing else: no regex, built-in or user-supplied,\n * runs over a value. A pair is what follows a `&`, as the key reads one,\n * and its whole value is replaced when anything in it is a credential's\n * -- a `;name=` inside it, a URL nested or encoded in it -- so a redacted\n * value is `[REDACTED]`, which canonical-key.v2's match rule matches any\n * live value against; canonical-key.v1 drops only its own names from a\n * key. The user info is dropped. Every other value and every name is\n * kept, because they are part of identity too -- except under\n * `privacyMode: \"strict\"`, which replaces every value. An earlier\n * version of this method scanned every value (maskQueryValues records\n * what that did to the key); this comment said so and outlived the fix.\n */\n maskUrl(rawUrl: string): string {\n if (!rawUrl) return rawUrl;\n\n const hashAt = rawUrl.indexOf(\"#\");\n return maskQueryValues(\n hashAt === -1 ? rawUrl : rawUrl.slice(0, hashAt),\n this.strict,\n );\n }\n\n /* -------------------------------------------------------------- */\n /* Network data masking */\n /* -------------------------------------------------------------- */\n\n /**\n * Returns a deep-copy of the given {@link NetworkEvent} with sensitive\n * headers redacted and (optionally) bodies masked.\n */\n maskNetworkData(event: NetworkEvent, bodies?: BodyOut): NetworkEvent {\n const masked: NetworkEvent = { ...event };\n\n // --- headers ---\n masked.requestHeaders = this.maskHeaders(event.requestHeaders);\n masked.responseHeaders = this.maskHeaders(event.responseHeaders);\n\n // --- bodies ---\n const job = this.bodyJob(event);\n // Structural redaction (redact.ts redactBody): parse, walk,\n // re-serialize; running regexes over the serialized form corrupted\n // numbers into invalid JSON. It is not in this bundle: the capture\n // hands a body to a Web Worker and passes its answer in as `bodies`\n // (body-jobs.ts). Called with none, the bodies are redacted by the\n // code the capture loaded, and recorded masked whole until it has.\n const out =\n job &&\n (bodies ??\n bodyCode.redact?.(job) ?? {\n requestBody: event.requestBody ? MASKED : null,\n responseBody: event.responseBody ? MASKED : null,\n });\n masked.requestBody = out\n ? out.requestBody\n : event.requestBody\n ? MASKED\n : null;\n masked.responseBody = out\n ? out.responseBody\n : event.responseBody\n ? MASKED\n : null;\n\n // The URL is scrubbed STRUCTURALLY: sensitive query parameters by\n // NAME, path untouched, and NO regex — built-in or user-supplied.\n //\n // Running the PII patterns over the whole URL corrupted the recorded\n // key and guaranteed a replay deny. `phone_us` made every leading\n // group optional, so it reduced to \"any 7-digit run\":\n // /api/v1/orders/8675309 -> /api/v1/orders/[REDACTED]\n // The recorded key became GET /api/v1/orders/[REDACTED] while replay\n // computed GET /api/v1/orders/:id, so the mock could never match.\n // Query VALUES are part of that key too (canonkey.ts keeps them\n // verbatim), which is why piiPatterns stop at the URL boundary.\n masked.url = this.maskUrl(event.url);\n\n return masked;\n }\n\n /**\n * The bodies of `event` to redact, with what their redaction reads (the\n * content-types and the integrator's piiPatterns, which run on string\n * values inside the structure, so JSON stays valid), or null when the\n * config masks bodies whole and there is nothing to redact.\n */\n bodyJob(event: NetworkEvent): BodyJob | null {\n return this.config.maskNetworkBodies\n ? null\n : {\n requestBody: event.requestBody,\n responseBody: event.responseBody,\n requestType: findContentType(event.requestHeaders),\n responseType: findContentType(event.responseHeaders),\n patterns: this.userPatterns,\n };\n }\n\n /* -------------------------------------------------------------- */\n /* Config accessors */\n /* -------------------------------------------------------------- */\n\n getConfig(): Readonly<PrivacyConfig> {\n return this.config;\n }\n\n updateConfig(partial: Partial<PrivacyConfig>): void {\n this.config = this.settle(mergePrivacyConfig(this.config, partial));\n this.userPatterns = compileGlobal(this.config.piiPatterns);\n }\n\n /* -------------------------------------------------------------- */\n /* Internals */\n /* -------------------------------------------------------------- */\n\n private maskHeaders(headers: Record<string, string>): Record<string, string> {\n const result: Record<string, string> = {};\n const sensitiveSet = new Set(\n this.config.sensitiveHeaders.map((h) => h.toLowerCase()),\n );\n\n for (const [key, value] of Object.entries(headers)) {\n const name = key.toLowerCase();\n if (sensitiveSet.has(name) || isCredentialHeader(name)) {\n result[key] = \"[REDACTED]\";\n } else if (this.strict && !STRICT_HEADERS.has(name)) {\n result[key] = \"[REDACTED]\";\n } else {\n result[key] = this.maskText(\n maskHeaderUrls(name, value, (url) => this.maskUrl(url)),\n );\n }\n }\n return result;\n }\n}\n","/**\n * THE SERVER'S RULE FOR A SESSION ID, CHECKED BEFORE A BYTE IS SENT.\n *\n * The ingest route refuses a session id outside this shape with a 400\n * whose only diagnosis is `issues: [{path: \"sessionId\", ...}]`. The SDK\n * mints its own ids as UUIDs, which always pass; the one integrator-\n * supplied value on the wire is what `sessionIdGenerator` returns, and\n * a `user:42/session 1`-style correlation id -- exactly what the option\n * invites -- used to reach onError as \"Invalid request\" with a remedy\n * blaming a version mismatch. Now the recorder refuses to start with\n * it, and names the value and the rule (KUI_E_SESSION_ID_INVALID).\n *\n * THE RULE IS THE SERVER'S, VERBATIM: api-server\n * pkg/uicapture/sdkwire.ValidSessionID and the sidecar router's\n * SafeIdSchema enforce `^[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*$` at 1-200\n * characters. spec/session-id.v1.json is emitted from this module and\n * executed against it, so a rule that loosens or tightens here without\n * the server following is a red vector, not a 400 in production.\n */\n\n/** `MaxSessionIDLen` in api-server sdkwire; `.max(200)` in the sidecar's SafeIdSchema. */\nexport const SESSION_ID_MAX_LENGTH = 200;\n\n/** Every dot-separated segment non-empty and made of [A-Za-z0-9_-]. */\nexport const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*$/;\n\n/**\n * The rule as one sentence: BYTE FOR BYTE the `issues[].message` the\n * server sends on the 400 this check pre-empts (sdkwire.Parse), so what\n * the SDK says locally is what the server would have said, and a Go\n * twin can compare the two strings rather than two paraphrases.\n */\nexport const SESSION_ID_RULE =\n `must be 1-${SESSION_ID_MAX_LENGTH} characters of letters, digits, dot, dash and underscore, ` +\n \"with no empty dot-separated segment\";\n\n/** Whether the server would accept `value` as a session id (or a batch id, which has the same shape). */\nexport function isValidSessionId(value: unknown): value is string {\n return (\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= SESSION_ID_MAX_LENGTH &&\n SESSION_ID_PATTERN.test(value)\n );\n}\n","/**\n * THE SDK'S TERMINAL FAILURES, AS AN AGENT CAN ACT ON THEM.\n *\n * A rejected ingest key, a wrong endpoint, a session-id collision and an\n * over-sized batch used to reach the integrator's onError as one prose\n * Error -- \"[keploy] capture stopped: the server rejected this batch\n * with 401 ...\" -- readable by a human and useless to an agent, which\n * cannot tell \"mint a key\" from \"fix the URL\" without parsing English.\n * Every terminal failure now carries a `code` from the contract's error\n * corpus, the server's own sentence as `serverMessage`, its `issues[]`\n * when the body had them, and the link to the code's remedy, so a\n * program reading onError can branch on `code` alone.\n *\n * THIS TABLE IS A BRIEF OF THE CORPUS, AND IS HELD TO IT BY A TEST. The\n * SDK's only runtime dependency is rrweb (its README says so and a test\n * holds the bundle size), so it cannot import @keploy/contract's corpus\n * at runtime: the one part of the contract it bundles is the zod-free\n * `@keploy/contract/privacy` module, which tsup inlines. It used to carry each entry's summary and remedy verbatim,\n * and with it the CommonJS build was over its budget (MEASURED as\n * bundle-size.test.ts measures: ESM 30,129 and CJS 30,832 bytes gzipped\n * against 30,720). The founder ruled on 2026-10-08: error codes and a\n * docs link in the bundle, the remedy prose in the contract corpus and\n * on the docs page. So each entry carries its code, `summary` -- what\n * happened, in a sentence or two, a field of the tables this package\n * exports since 3.0 -- and `remedy.docs`, the corpus's own link for the\n * code, where the remedy is. An error's message says what happened;\n * KUI_E_DOM_RECORDER_UNAVAILABLE's, which used to spell out the remedy,\n * names that link instead. No remedy sentence is carried: `remedy.manual`,\n * which 3.0 filled with the corpus's prose, now holds the same link, so\n * code written against 3.0 still reads a string. Taking the ten remedy\n * sentences out saved 1,494 bytes of the build, 559 (ESM) and 567 (CJS)\n * gzipped -- MEASURED as bundle-size.test.ts measures, with nothing else\n * changed. errors-drift.test.ts\n * imports the contract as a dev dependency and requires, per code:\n * `docs` and `command` equal to the corpus's, `manual` equal to `docs`,\n * every backticked name in the summary to be one the corpus entry names\n * (a summary cannot point at an option, a field or a route the corpus\n * does not), the summary under a length cap, and the evidence field sets\n * equal -- and\n * builds a CaptureError of every code and hands its evidence to the\n * corpus's own makeToolError, so the fields the SDK sends are the\n * fields the corpus declares. The corpus's `alternatives` and\n * `autofixable` are not carried: nothing in the SDK reads them.\n *\n * THE STATUS MAPPING IS THE TRANSPORT'S TERMINAL PREDICATE, not a\n * parallel copy of one: the transport calls codeForStatus on every\n * response and stops capture exactly when it answers a code.\n * spec/sdk-errors.v3.json is emitted from it and executed from the file\n * by sdk-errors.test.ts, which executes the frozen versions 1 and 2\n * too. JS-only: the SDK runs in the browser, and the\n * Go side answers these statuses rather than consuming this mapping.\n *\n * ONE CODE IS RAISED BEFORE A BYTE IS SENT. The session id is the one\n * integrator-supplied VALUE on the wire (`sessionIdGenerator`; the\n * other integrator option that shapes a batch, `batchSize`, is clamped\n * to the server's cap by the transport), and the server's 400 for a bad\n * one -- \"Invalid request\", `issues: [{path: \"sessionId\"}]` -- came\n * with a remedy blaming a version mismatch. The recorder now checks\n * the value against the server's own rule (session-id.ts,\n * spec/session-id.v1.json) and refuses to start with\n * KUI_E_SESSION_ID_INVALID, naming what the generator produced -- a\n * string outside the rule, a non-string, or a throw -- and the rule.\n *\n * TWO CLASSES, ONE BASE, SO `err.code` NARROWS `err.evidence`. The\n * remedies tell a program to read `evidence.rule` or `evidence.issues`;\n * with one class carrying a union evidence type, a TypeScript handler\n * that branched on `code` and then did as told got TS2339 on every\n * field. IngestRejection and SessionIdRefusal each declare `code` as\n * the literal(s) they carry, and onError receives their union.\n */\n\nimport { SESSION_ID_RULE } from \"./session-id\";\nimport { ROUTE_RULE } from \"./privacy\";\n\n/** The four codes the server's status can produce. */\nexport type ServerAnsweredCode =\n | \"KUI_E_INGEST_KEY_REJECTED\"\n | \"KUI_E_INGEST_ENDPOINT_NOT_FOUND\"\n | \"KUI_E_SESSION_CONFLICT\"\n | \"KUI_E_INGEST_REJECTED\";\n\n/** The ten codes the SDK raises. Everything else it retries or ignores. */\nexport type CaptureErrorCode =\n | ServerAnsweredCode\n | \"KUI_E_SESSION_ID_INVALID\"\n | \"KUI_E_DOM_RECORDER_UNAVAILABLE\"\n | \"KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE\"\n | \"KUI_E_PRIVACY_ROUTE_INVALID\"\n | \"KUI_E_CAPTURE_DECLINED\"\n | \"KUI_E_PRIVACY_CONFLICT\";\n\nexport interface CaptureRemedy {\n /** null on every code: this build has no verb that mints a key, edits a config, rotates a session, shrinks a batch or installs a bundler. */\n command: null;\n /**\n * The same link as `docs`. In 3.0 this was the corpus's remedy prose; the\n * remedy is now only on the page at `docs`.\n * @deprecated Read `docs`.\n */\n manual: string;\n /** The corpus's page for this code: `https://keploy.io/docs/ui-capture/errors#<code>`, lower case, `-` for `_`. */\n docs: string;\n}\n\nexport interface CaptureErrorEntry {\n summary: string;\n remedy: CaptureRemedy;\n /** The evidence fields a CaptureError of this code always carries; the corpus declares the same set. */\n evidence: readonly string[];\n /** The fields it carries only when it has them; the corpus declares the same set. */\n optionalEvidence: readonly string[];\n}\n\n/** One entry of the server's `issues[]`: which field, and what was wrong with it. */\nexport interface ServerIssue {\n readonly path: string;\n readonly message: string;\n}\n\n/**\n * What every server-answered code carries. `issues` is the server's\n * own list when its body had one (the ingest route sends it on a 400\n * only; the SDK forwards it whatever the status), so it is\n * `optionalEvidence` on all four.\n */\nconst SERVER_EVIDENCE = [\n \"status\",\n \"serverMessage\",\n \"endpoint\",\n \"sessionId\",\n] as const;\nconst SERVER_OPTIONAL_EVIDENCE = [\"issues\"] as const;\n\n/**\n * The corpus's page for every code, as @keploy/contract's docsFor()\n * builds it (DOCS_BASE, `/errors#`, the code in lower case with `-` for\n * `_`); errors-drift.test.ts holds each entry's `remedy.docs` to the\n * corpus's own link.\n */\nconst DOCS = \"https://keploy.io/docs/ui-capture/errors#\";\n\n/** One entry as written below; `remedy.docs` is derived from its code. */\ninterface Brief {\n summary: string;\n evidence: readonly string[];\n optionalEvidence?: readonly string[];\n}\n\nfunction withDocs<C extends string>(\n briefs: Record<C, Brief>,\n): Record<C, CaptureErrorEntry> {\n const table = {} as Record<C, CaptureErrorEntry>;\n for (const code of Object.keys(briefs) as C[]) {\n const b = briefs[code];\n const docs = DOCS + code.toLowerCase().replace(/_/g, \"-\");\n table[code] = {\n summary: b.summary,\n remedy: { command: null, manual: docs, docs },\n evidence: b.evidence,\n optionalEvidence: b.optionalEvidence ?? [],\n };\n }\n return table;\n}\n\nexport const SDK_ERRORS: Record<CaptureErrorCode, CaptureErrorEntry> =\n withDocs<CaptureErrorCode>({\n KUI_E_INGEST_KEY_REJECTED: {\n summary:\n \"The ingest server refused the SDK's API key (401 or 403). Capture has stopped.\",\n evidence: SERVER_EVIDENCE,\n optionalEvidence: SERVER_OPTIONAL_EVIDENCE,\n },\n KUI_E_INGEST_ENDPOINT_NOT_FOUND: {\n summary:\n \"The ingest server answered 404 or 405: nothing at `endpoint` accepts a POST. Capture has stopped.\",\n evidence: SERVER_EVIDENCE,\n optionalEvidence: SERVER_OPTIONAL_EVIDENCE,\n },\n KUI_E_SESSION_CONFLICT: {\n summary:\n \"The ingest server answered 409: this session id is already claimed, or a batchId was re-used. Capture has stopped.\",\n evidence: SERVER_EVIDENCE,\n optionalEvidence: SERVER_OPTIONAL_EVIDENCE,\n },\n KUI_E_INGEST_REJECTED: {\n summary:\n \"The ingest server refused a batch with a terminal 4xx (400, 413 or 415). Capture has stopped.\",\n evidence: SERVER_EVIDENCE,\n optionalEvidence: SERVER_OPTIONAL_EVIDENCE,\n },\n KUI_E_SESSION_ID_INVALID: {\n summary:\n \"The configured `sessionIdGenerator` did not produce a session id the ingest server would accept. Capture did not start.\",\n evidence: [\"sessionId\", \"received\", \"rule\"],\n },\n KUI_E_DOM_RECORDER_UNAVAILABLE: {\n summary:\n \"The capture SDK could not load rrweb, the library it records the page with. The capture ended before anything was sent.\",\n evidence: [\"reason\"],\n },\n KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE: {\n summary:\n \"Under strict, the capture SDK could not load its attribute allow-list. The capture ended before anything was recorded or sent.\",\n evidence: [\"reason\"],\n },\n KUI_E_PRIVACY_ROUTE_INVALID: {\n summary:\n \"A route in `privacy.secretRoutes` or `privacy.keepRoutes` is not one the SDK can match. Capture did not start.\",\n evidence: [\"option\", \"received\", \"rule\"],\n },\n KUI_E_CAPTURE_DECLINED: {\n summary:\n \"The browser sent Do Not Track or Global Privacy Control, and `honorPrivacySignals` is on. Capture did not start; nothing was recorded or sent.\",\n evidence: [\"signal\"],\n },\n KUI_E_PRIVACY_CONFLICT: {\n summary:\n '`privacyMode: \"strict\"` records no body, and `privacy.maskNetworkBodies` is `false`, which asks for them. Capture did not start.',\n evidence: [\"privacyMode\", \"option\"],\n },\n });\n\n/**\n * The codes the SDK writes to the console; the capture continues. Three\n * are for a DROPPED event; two drop nothing: KUI_E_NAVIGATION_UNWRAPPED\n * (the page made a method the SDK wraps impossible to replace, so it\n * wrapped none: recorder.ts wrapHistory) and KUI_E_REQUEST_TERM_FAILED\n * (a request recorded without its canonical-key.v2 term, because\n * computing it threw, or body:* because its chunk did not load:\n * network.ts termFor).\n */\nexport type CaptureWarningCode =\n | \"KUI_E_EVENT_UNSERIALISABLE\"\n | \"KUI_E_EVENT_OVERSIZED\"\n | \"KUI_E_EVENT_OVERSIZED_SCRUBBING\"\n | \"KUI_E_NAVIGATION_UNWRAPPED\"\n | \"KUI_E_REQUEST_TERM_FAILED\"\n | \"KUI_E_BODY_WORKER_UNAVAILABLE\";\n\n/**\n * THE SIX WARNING ENTRIES, briefed and held to the corpus by\n * errors-drift.test.ts like SDK_ERRORS. These never reach onError --\n * that channel is terminal-only, and a dropped event ends nothing, nor\n * does a page the SDK could not wrap (KUI_E_NAVIGATION_UNWRAPPED) or a\n * request it recorded without its term (KUI_E_REQUEST_TERM_FAILED) --\n * so the console line is their only surface, and it names the code so\n * the corpus's own scanner (\"an agent that finds KUI_E_... in a log can\n * resolve it\") can find it. Before this table the two lines carried no\n * code, and a dropped rrweb FullSnapshot of a huge page left a\n * recording whose selectors could not resolve with a line nothing\n * could look up. Each is said once per capture: the four the transport\n * writes once per Transport, KUI_E_REQUEST_TERM_FAILED once per\n * NetworkInterceptor (network.ts); a later init() starts a new count.\n * KUI_E_BODY_WORKER_UNAVAILABLE is said once per PAGE (body-jobs.ts): the\n * worker and the body chunk load once per page, and so fail once.\n */\nexport const SDK_WARNINGS: Record<CaptureWarningCode, CaptureErrorEntry> =\n withDocs<CaptureWarningCode>({\n KUI_E_EVENT_UNSERIALISABLE: {\n summary:\n \"The SDK dropped one captured event because it could not be serialised to JSON. The capture continues without it.\",\n evidence: [\"eventId\", \"eventType\", \"reason\"],\n },\n KUI_E_EVENT_OVERSIZED: {\n summary:\n \"The SDK dropped one captured event that alone is over the ingest server's decoded cap (`evidence.cap` bytes). The capture continues without it.\",\n evidence: [\"eventId\", \"eventType\", \"bytes\", \"cap\"],\n },\n KUI_E_EVENT_OVERSIZED_SCRUBBING: {\n summary:\n \"The SDK dropped one captured event whose scrub of the page URL's credentials passed the ingest server's decoded cap (`evidence.cap` bytes). The capture continues without it.\",\n evidence: [\"eventType\", \"atLeast\", \"cap\"],\n },\n KUI_E_NAVIGATION_UNWRAPPED: {\n summary:\n \"The page made a History or Navigation API method the SDK wraps (`evidence.method`) impossible to replace and put back, so the SDK wrapped none of them. The capture continues.\",\n evidence: [\"method\"],\n },\n KUI_E_REQUEST_TERM_FAILED: {\n summary:\n \"The SDK recorded a request without its canonical-key.v2 term (computing it threw: `evidence.reason`), or body:* (its term code did not load). The page's request was unaffected.\",\n evidence: [\"method\", \"reason\"],\n },\n KUI_E_BODY_WORKER_UNAVAILABLE: {\n summary:\n \"No body worker or chunk (`evidence.part`): no worker, a body over 64 KiB is recorded cut; no chunk, one the main thread redacts keeps nothing; tests over them are unproven.\",\n evidence: [\"part\", \"reason\"],\n },\n });\n\n/**\n * The console line for a request recorded without its term: the code\n * first, a fixed sentence, then the evidence as JSON -- the same shape\n * as warningLine's, for the same scanners. `reason` (what threw) rides\n * in the JSON only, never in the prose before the marker.\n */\nexport function termWarningLine(method: string, reason: string): string {\n return noticeLine(\n { code: \"KUI_E_REQUEST_TERM_FAILED\", method, reason },\n \"recorded a request without its term, or body:*: computing it failed; the request itself was not affected. \" +\n \"The capture continues; any further such requests in this capture are recorded that way, silently.\",\n );\n}\n\n/**\n * The console line for a page whose body worker or body chunk could not\n * load, of termWarningLine's shape: what failed (`part`) and what the\n * browser said (`reason`), in the JSON only.\n */\nexport function bodyWorkerWarningLine(part: string, reason: string): string {\n return noticeLine(\n { code: \"KUI_E_BODY_WORKER_UNAVAILABLE\", part, reason },\n \"could not run the body worker or load the body chunk (evidence.part): without the worker, a body over 64 KiB is recorded cut; without the chunk, a body the main thread must redact is recorded with nothing kept; replay reports a test over a cut body unproven. \" +\n \"Allow worker-src 'self' in the page's CSP, use a bundler that emits the worker (or copy dist/body-worker.js beside the bundle), serve it from the page's origin, or serve the SDK's dist/ as it is. Said once per page for each part.\",\n );\n}\n\n/** The evidence a warning line carries: exactly the corpus entry's `evidence` fields. */\nexport type CaptureWarningEvidence =\n | {\n code: \"KUI_E_EVENT_UNSERIALISABLE\";\n eventId: string;\n eventType: string;\n reason: string;\n }\n | {\n code: \"KUI_E_EVENT_OVERSIZED\";\n eventId: string;\n eventType: string;\n bytes: number;\n cap: number;\n }\n | {\n code: \"KUI_E_EVENT_OVERSIZED_SCRUBBING\";\n eventType: string;\n atLeast: number;\n cap: number;\n }\n | {\n code: \"KUI_E_NAVIGATION_UNWRAPPED\";\n method: string;\n }\n | {\n code: \"KUI_E_REQUEST_TERM_FAILED\";\n method: string;\n reason: string;\n }\n | {\n code: \"KUI_E_BODY_WORKER_UNAVAILABLE\";\n part: string;\n reason: string;\n };\n\n/** Free text on one line: whitespace runs, newlines included, become one space. */\nfunction oneLine(text: string): string {\n return text.replace(/\\s+/g, \" \").trim();\n}\n\n/**\n * The console line for a dropped event: the code first, as a token the\n * corpus scanner matches, then the prose a human reads, then the\n * evidence as JSON so a program that only has the log can still read\n * the fields the remedy names. `prose` is the caller's sentence about\n * this drop; the \"once per capture\" tail is the same on both lines.\n *\n * ONE LINE, LITERALLY, AND NOTHING INTEGRATOR-SUPPLIED BEFORE THE\n * MARKER. A log reader is line-oriented, and the JSON has to be on the\n * line that carries the code; and \"parse the JSON after the first\n * `evidence=`\" is only a rule if nothing before that marker can contain\n * the marker. So the id and the type of the event ride in the JSON\n * ONLY -- a first version wrote `dropped event <id> (<type>)` in the\n * prose, and an id of `evidence={\"fake\":1}` (any string, through the\n * exported Transport) sat before the real marker, and a type with a\n * newline made two lines. The prose is the caller's fixed sentence\n * (never free text such as `reason`; the JSON carries it, escaped) and\n * is collapsed to single spaces in case it ever is not.\n */\nexport function warningLine(\n evidence: CaptureWarningEvidence,\n prose: string,\n): string {\n const { code, ...fields } = evidence;\n return (\n `[keploy] ${code}: dropped an event: ${oneLine(prose)} ` +\n `The capture continues; any further such events in this capture are dropped silently. ` +\n `evidence=${evidenceJson(fields)}`\n );\n}\n\n/**\n * The console line for a warning that drops nothing\n * (KUI_E_NAVIGATION_UNWRAPPED, KUI_E_REQUEST_TERM_FAILED), by warningLine's rules: one line, the code\n * first, then the SDK's fixed sentence, then the evidence as JSON after the\n * first `evidence=`.\n */\nexport function noticeLine(\n evidence: CaptureWarningEvidence,\n prose: string,\n): string {\n const { code, ...fields } = evidence;\n return `[keploy] ${code}: ${oneLine(prose)} evidence=${evidenceJson(fields)}`;\n}\n\n/**\n * The evidence as JSON, and this does not throw for any value\n * JSON.stringify refuses on its own account -- a cycle, a BigInt, a\n * throwing getter or toJSON. The report path runs inside enqueue(),\n * which promises the emitter that a dropped event is dropped in\n * silence -- nothing queued, nothing thrown -- and the one thing\n * JSON.stringify refuses here is a field that is not the string the\n * type says: through the exported Transport a JS caller can pass a\n * cyclic object or a BigInt as an event's id, and MEASURED, a first\n * version then threw \"Converting circular structure to JSON\" out of\n * enqueue, where the old template rendered `[object Object]` and went\n * on. So a field JSON refuses is rendered by describeValue instead\n * and the line still parses. (A Proxy whose `get` trap throws defeats\n * describeValue's own `constructor.name` read as well -- MEASURED --\n * and is not an id anything produces; it is the contract's function,\n * held to the corpus byte for byte, so that edge is its to close.)\n */\nfunction evidenceJson(fields: Record<string, unknown>): string {\n try {\n return JSON.stringify(fields);\n } catch {\n const rendered: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(fields)) {\n rendered[key] =\n typeof value === \"string\" || typeof value === \"number\"\n ? value\n : describeValue(value);\n }\n return JSON.stringify(rendered);\n }\n}\n\n/**\n * The code for an ingest response status, or null when the status is\n * not terminal. THIS IS THE TRANSPORT'S PREDICATE: it stops capture iff\n * this answers a code, so 429 and every 5xx (retried) and every 2xx\n * (not an error) are null here and nowhere else.\n *\n * 401 and 403 are both the key -- the route answers 403 to a personal\n * access token however it is scoped, and 401 to a key it does not know.\n * 404 and 405 are the endpoint: the SDK only ever POSTs to the ingest\n * route, so nothing accepting the POST means the URL is wrong. 409 is\n * every way one session id can be claimed twice. Every other terminal\n * 4xx is the server refusing the bytes, and says why in its body.\n */\nexport function codeForStatus(status: number): ServerAnsweredCode | null {\n if (status === 401 || status === 403) return \"KUI_E_INGEST_KEY_REJECTED\";\n if (status === 404 || status === 405) {\n return \"KUI_E_INGEST_ENDPOINT_NOT_FOUND\";\n }\n if (status === 409) return \"KUI_E_SESSION_CONFLICT\";\n if (status >= 400 && status < 500 && status !== 429) {\n return \"KUI_E_INGEST_REJECTED\";\n }\n return null;\n}\n\n/** What the server said, out of its body: the sentence and, on a 400, which fields it refused. */\nexport interface ServerError {\n readonly message: string | null;\n readonly issues: readonly ServerIssue[] | null;\n}\n\nconst NO_SERVER_ERROR: ServerError = { message: null, issues: null };\n\n/** Strings are cut at this many characters, sentence and issues alike, whatever the body's shape. */\nconst SERVER_TEXT_LIMIT = 500;\n\n/**\n * The server's explanation out of its response body. The ingest route\n * answers `{\"error\": \"...\"}` plus `issues: [{path, message}]` on a 400;\n * the sentence and the issues are what an agent should read, not the\n * JSON around them, and the raw body sliced at 500 characters could cut\n * that JSON mid-string. A body that is not that shape -- a proxy's\n * HTML, a plain-text 404 -- is kept as text, trimmed to 500 characters.\n * An empty or blank body, or an empty `error`, is null: \"no message\",\n * not a message of spaces.\n */\nexport function parseServerError(body: string | null): ServerError {\n if (body === null) return NO_SERVER_ERROR;\n const text = body.trim();\n if (text === \"\") return NO_SERVER_ERROR;\n try {\n const parsed: unknown = JSON.parse(text);\n if (parsed !== null && typeof parsed === \"object\") {\n const shaped = parsed as { error?: unknown; issues?: unknown };\n if (typeof shaped.error === \"string\") {\n const sentence = shaped.error.trim();\n return {\n message:\n sentence === \"\" ? null : sentence.slice(0, SERVER_TEXT_LIMIT),\n issues: issuesOf(shaped.issues),\n };\n }\n }\n } catch {\n // Not JSON; the text itself is the message.\n }\n return { message: text.slice(0, SERVER_TEXT_LIMIT), issues: null };\n}\n\n/**\n * The server's machine-readable `reason` out of its JSON body, or null.\n *\n * The ingest route answers 409 for three different conditions (a session\n * it has completed, a capture identity that conflicts, a batchId reused\n * with different events) and the status alone cannot tell them apart; only\n * the first means \"start the next session\" (found in review). A server\n * that predates the field answers null, and the response stays terminal.\n */\nexport function serverReason(body: string | null): string | null {\n if (body === null) return null;\n try {\n const parsed: unknown = JSON.parse(body);\n const reason = (parsed as { reason?: unknown } | null)?.reason;\n return typeof reason === \"string\" ? reason.slice(0, 100) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * At most this many issues are kept. The server validates every event\n * of a batch and a 5000-event batch can answer thousands of `issues`;\n * evidence has to stay readable, and the first hundred name the\n * pattern as well as the rest would.\n */\nconst ISSUES_LIMIT = 100;\n\n/** The `{path, message}` items of `issues`, and only those; null when there are none. */\nfunction issuesOf(raw: unknown): readonly ServerIssue[] | null {\n if (!Array.isArray(raw)) return null;\n const out: ServerIssue[] = [];\n for (const item of raw as unknown[]) {\n if (out.length === ISSUES_LIMIT) break;\n if (item === null || typeof item !== \"object\") continue;\n const { path, message } = item as { path?: unknown; message?: unknown };\n if (typeof path !== \"string\" || typeof message !== \"string\") continue;\n out.push({\n path: path.slice(0, SERVER_TEXT_LIMIT),\n message: message.slice(0, SERVER_TEXT_LIMIT),\n });\n }\n return out.length > 0 ? out : null;\n}\n\n/**\n * A value of unknown shape, rendered for a message. The same table as\n * @keploy/contract's describeValue (errors-drift.test.ts holds the two\n * to each other on the inputs that matter here), copied because the SDK\n * cannot import the contract: `String(value)` turns every plain object\n * into `[object Object]`, which names nothing, and THROWS on an object\n * with no prototype -- MEASURED, a `sessionIdGenerator` returning\n * `Object.create(null)` made the SDK's own hardening path throw.\n */\nexport function describeValue(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value instanceof Error) return `${value.name}: ${value.message}`;\n if (typeof value === \"function\") return `[function ${value.name}]`;\n if (typeof value !== \"object\" || value === null) return String(value);\n try {\n return JSON.stringify(value);\n } catch {\n const ctor = (value as { constructor?: { name?: unknown } }).constructor;\n const name = typeof ctor?.name === \"string\" ? ctor.name : \"object\";\n return `[${name} not JSON-serialisable]`;\n }\n}\n\n/** What every server-answered code carries as evidence; `issues` only when the server sent them. */\nexport type IngestEvidence = Readonly<{\n status: number;\n serverMessage: string | null;\n endpoint: string;\n sessionId: string | null;\n issues?: readonly ServerIssue[];\n}>;\n\n/** What KUI_E_SESSION_ID_INVALID carries: the string returned (or null), what was produced, and the rule. */\nexport type SessionIdEvidence = Readonly<{\n sessionId: string | null;\n received: string;\n rule: string;\n}>;\n\n/** What KUI_E_DOM_RECORDER_UNAVAILABLE carries: the error the browser gave for rrweb's import. */\nexport type DomRecorderEvidence = Readonly<{ reason: string }>;\n\n/** What KUI_E_PRIVACY_ROUTE_INVALID carries: the list, the entry as received, and the rule. */\nexport type PrivacyRouteEvidence = Readonly<{\n option: \"secretRoutes\" | \"keepRoutes\";\n received: string;\n rule: string;\n}>;\n\n/** What KUI_E_CAPTURE_DECLINED carries: the privacy signal the browser sent. */\nexport type CaptureDeclinedEvidence = Readonly<{\n signal: PrivacySignal;\n}>;\n\n/** A browser privacy signal the SDK honours. */\nexport type PrivacySignal = \"doNotTrack\" | \"globalPrivacyControl\";\n\n/** What KUI_E_PRIVACY_CONFLICT carries: the mode, and the option that contradicts it. */\nexport type PrivacyConflictEvidence = Readonly<{\n privacyMode: \"strict\";\n option: \"privacy.maskNetworkBodies\";\n}>;\n\nexport type CaptureEvidence =\n | IngestEvidence\n | SessionIdEvidence\n | DomRecorderEvidence\n | PrivacyRouteEvidence\n | CaptureDeclinedEvidence\n | PrivacyConflictEvidence;\n\n/** How many issues the prose names before \"(+N more)\"; `issues` itself is cut at ISSUES_LIMIT. */\nconst ISSUES_IN_PROSE = 5;\n\n/**\n * What onError receives when capture stops (or did not start). This is\n * the BASE: every handler can read `code`, `remedy`, `message` and\n * `evidence` on it, and `instanceof CaptureError` is true of both\n * subclasses. A handler that branches on `code` gets the subclass, and\n * with it the evidence shape the remedy tells it to read (see\n * AnyCaptureError). `message` is the prose a human reads; it is\n * composed by the subclass from the same fields the evidence carries,\n * so what the console says and what the program gets cannot drift.\n */\nexport class CaptureError extends Error {\n readonly code: CaptureErrorCode;\n /** The HTTP status that produced this, or null for a code raised before anything was sent. */\n readonly status: number | null;\n /** The server's own sentence (the `error` field of its body, or the body's text), or null when there was none. */\n readonly serverMessage: string | null;\n /** The server's `issues[]` -- which fields it refused -- or null when its body carried none. */\n readonly issues: readonly ServerIssue[] | null;\n readonly remedy: CaptureRemedy;\n readonly evidence: CaptureEvidence;\n\n protected constructor(\n code: CaptureErrorCode,\n message: string,\n status: number | null,\n server: ServerError,\n evidence: CaptureEvidence,\n ) {\n super(message);\n this.name = \"CaptureError\";\n this.code = code;\n this.remedy = SDK_ERRORS[code].remedy;\n this.status = status;\n this.serverMessage = server.message;\n this.issues = server.issues;\n this.evidence = evidence;\n }\n}\n\n/** What the transport builds from a terminal response. */\nexport interface IngestRejectionInit {\n code: ServerAnsweredCode;\n status: number;\n server: ServerError;\n endpoint: string;\n sessionId: string | null;\n}\n\n/** The server answered a batch with a terminal 4xx: one of the four server-answered codes. */\nexport class IngestRejection extends CaptureError {\n declare readonly code: ServerAnsweredCode;\n declare readonly status: number;\n declare readonly evidence: IngestEvidence;\n\n constructor(init: IngestRejectionInit) {\n const { message, issues } = init.server;\n let text =\n `[keploy] capture stopped: the server rejected this batch with ${init.status} and will ` +\n `reject the rest, so capture has stopped (${init.code}). ` +\n `${message === null ? \"(no response body)\" : message}`;\n if (issues !== null) {\n const named = issues\n .slice(0, ISSUES_IN_PROSE)\n .map((i) => `${i.path === \"\" ? \"body\" : i.path}: ${i.message}`)\n .join(\"; \");\n const more = issues.length - ISSUES_IN_PROSE;\n text += ` -- ${named}${more > 0 ? ` (+${more} more)` : \"\"}`;\n }\n super(init.code, text, init.status, init.server, {\n status: init.status,\n serverMessage: message,\n endpoint: init.endpoint,\n sessionId: init.sessionId,\n ...(issues !== null ? { issues } : {}),\n });\n }\n}\n\n/** What the recorder builds when sessionIdGenerator does not produce a session id. */\nexport interface SessionIdRefusalInit {\n /** The string the generator returned, or null when it returned no string or threw. */\n sessionId: string | null;\n /** `string <value>`, `number 42`, `object {}`, `threw Error: boom` -- see describeReceived(). */\n received: string;\n}\n\n/** The SDK refused to start: KUI_E_SESSION_ID_INVALID, raised before a byte was sent. */\nexport class SessionIdRefusal extends CaptureError {\n declare readonly code: \"KUI_E_SESSION_ID_INVALID\";\n declare readonly status: null;\n declare readonly evidence: SessionIdEvidence;\n\n constructor(init: SessionIdRefusalInit) {\n const what =\n init.sessionId !== null\n ? `returned ${JSON.stringify(init.sessionId)}, which the ingest server would refuse`\n : init.received.startsWith(\"threw \")\n ? init.received\n : `returned ${init.received}, which is not a session id`;\n super(\n \"KUI_E_SESSION_ID_INVALID\",\n `[keploy] capture did not start: sessionIdGenerator ${what} ` +\n `(KUI_E_SESSION_ID_INVALID). A session id ${SESSION_ID_RULE}.`,\n null,\n NO_SERVER_ERROR,\n {\n sessionId: init.sessionId,\n received: init.received,\n rule: SESSION_ID_RULE,\n },\n );\n }\n}\n\n/**\n * The SDK refused a strict capture: KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE,\n * raised in a browser when strict's attribute allow-list, a chunk of its\n * own (strict-attributes.ts), could not be loaded -- at init(), or, for a\n * page started offline, once the network is back -- before anything is\n * recorded or sent. Strict records no page text: without the list it\n * cannot tell an attribute holding the page's structure from one holding\n * the visitor's search, and blanking every one would leave a recording no\n * selector or replay can use, so it records nothing. The evidence is\n * DomRecorderRefusal's: the error the browser gave for the import.\n */\nexport class StrictAttributesRefusal extends CaptureError {\n declare readonly code: \"KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE\";\n declare readonly status: null;\n declare readonly evidence: DomRecorderEvidence;\n\n constructor(init: { reason: string }) {\n super(\n \"KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE\",\n `[keploy] capture ended before anything was recorded: privacyMode \"strict\" could not load its attribute allow-list ` +\n `(KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE): ${init.reason}. ` +\n `What to do: ${SDK_ERRORS.KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE.remedy.docs}`,\n null,\n NO_SERVER_ERROR,\n { reason: init.reason },\n );\n }\n}\n\n/**\n * The SDK refused the capture: KUI_E_DOM_RECORDER_UNAVAILABLE, raised in a\n * browser when rrweb could not be imported -- at init(), or, for a page\n * started offline, once the network is back and the import still fails --\n * and either way before a byte of the capture is sent (its transport is\n * held until rrweb lands: Transport.hold).\n *\n * NOT A SILENT NO-OP ANY MORE. The recorder's import of rrweb failed\n * quietly -- the catch said \"rrweb unavailable (SSR/test)\" -- and init()\n * resolved with a session id and recorded no DOM. MEASURED on a page\n * loading the ESM build without a bundler: the bare `import(\"rrweb\")`\n * throws, no DOM event is ever posted (a page that makes requests posts\n * those alone), and the integrator sees success and flows with no steps. Outside a browser (SSR) there is no page to\n * record and that stays silent.\n */\nexport class DomRecorderRefusal extends CaptureError {\n declare readonly code: \"KUI_E_DOM_RECORDER_UNAVAILABLE\";\n declare readonly status: null;\n declare readonly evidence: DomRecorderEvidence;\n\n constructor(init: { reason: string }) {\n super(\n \"KUI_E_DOM_RECORDER_UNAVAILABLE\",\n `[keploy] capture ended before anything was sent: rrweb, the library the SDK records the page with, could not be loaded ` +\n `(KUI_E_DOM_RECORDER_UNAVAILABLE): ${init.reason}. ` +\n `What to do: ${SDK_ERRORS.KUI_E_DOM_RECORDER_UNAVAILABLE.remedy.docs}`,\n null,\n NO_SERVER_ERROR,\n { reason: init.reason },\n );\n }\n}\n\n/**\n * The SDK refused to start: KUI_E_PRIVACY_ROUTE_INVALID, raised before a\n * byte was sent, when a declared privacy route is outside ROUTE_RULE. A\n * route the SDK cannot match protects nothing, and recording on in that\n * belief sends what it was meant to keep.\n */\nexport class PrivacyRouteRefusal extends CaptureError {\n declare readonly code: \"KUI_E_PRIVACY_ROUTE_INVALID\";\n declare readonly status: null;\n declare readonly evidence: PrivacyRouteEvidence;\n\n constructor(init: {\n option: \"secretRoutes\" | \"keepRoutes\";\n received: string;\n }) {\n super(\n \"KUI_E_PRIVACY_ROUTE_INVALID\",\n `[keploy] capture did not start: privacy.${init.option} has ${init.received}, which is no route ` +\n `(KUI_E_PRIVACY_ROUTE_INVALID). ${ROUTE_RULE}.`,\n null,\n NO_SERVER_ERROR,\n { option: init.option, received: init.received, rule: ROUTE_RULE },\n );\n }\n}\n\n/**\n * The SDK did not start because the browser sent a privacy signal:\n * KUI_E_CAPTURE_DECLINED, raised before anything was recorded or sent.\n * Not a failure -- the person using the page declined -- so it is\n * logged with console.info, not console.error.\n */\nexport class CaptureDeclined extends CaptureError {\n declare readonly code: \"KUI_E_CAPTURE_DECLINED\";\n declare readonly status: null;\n declare readonly evidence: CaptureDeclinedEvidence;\n\n constructor(signal: PrivacySignal) {\n super(\n \"KUI_E_CAPTURE_DECLINED\",\n `[keploy] capture did not start: the browser sent ${\n signal === \"doNotTrack\" ? \"Do Not Track\" : \"Global Privacy Control\"\n }, and honorPrivacySignals is on (KUI_E_CAPTURE_DECLINED). Nothing was recorded or sent.`,\n null,\n NO_SERVER_ERROR,\n { signal },\n );\n }\n}\n\n/**\n * The SDK refused to start because two privacy options contradict each\n * other: KUI_E_PRIVACY_CONFLICT, raised before anything was recorded or\n * sent. `privacyMode: \"strict\"` records no body and an explicit\n * `privacy.maskNetworkBodies: false` asks for them. Neither silently\n * wins: strict is a promise the site makes to the people using it,\n * which an option set somewhere else must not undo, and an option the\n * integrator wrote must not be dropped without a word.\n */\nexport class PrivacyConflict extends CaptureError {\n declare readonly code: \"KUI_E_PRIVACY_CONFLICT\";\n declare readonly status: null;\n declare readonly evidence: PrivacyConflictEvidence;\n\n constructor() {\n super(\n \"KUI_E_PRIVACY_CONFLICT\",\n '[keploy] capture did not start: privacyMode \"strict\" records no request or response body, and privacy.maskNetworkBodies is false, which asks for them (KUI_E_PRIVACY_CONFLICT). Remove privacy.maskNetworkBodies, or use privacyMode \"balanced\".',\n null,\n NO_SERVER_ERROR,\n { privacyMode: \"strict\", option: \"privacy.maskNetworkBodies\" },\n );\n }\n}\n\n/**\n * Every CaptureError a handler can receive, as a union its `code`\n * discriminates: after `if (err.code === \"KUI_E_SESSION_ID_INVALID\")`\n * the evidence is SessionIdEvidence, after\n * `\"KUI_E_DOM_RECORDER_UNAVAILABLE\"` or\n * `\"KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE\"` DomRecorderEvidence, after\n * `\"KUI_E_PRIVACY_ROUTE_INVALID\"` PrivacyRouteEvidence, after\n * `\"KUI_E_CAPTURE_DECLINED\"` CaptureDeclinedEvidence, after\n * `\"KUI_E_PRIVACY_CONFLICT\"` PrivacyConflictEvidence, and otherwise\n * IngestEvidence.\n */\nexport type AnyCaptureError =\n | IngestRejection\n | SessionIdRefusal\n | DomRecorderRefusal\n | StrictAttributesRefusal\n | PrivacyRouteRefusal\n | CaptureDeclined\n | PrivacyConflict;\n\n/**\n * What a sessionIdGenerator produced, for the evidence: the type and\n * the value, so a number 42 cannot be mistaken for the string \"42\"\n * (which the server would accept), and a throw is named as one.\n *\n * ONE RULE MORE THAN describeValue, which was built for CLI values: an\n * object is named by its class. describeValue renders a Promise, a\n * Map and a prototype-less object identically as `{}` -- MEASURED, an\n * `async () => \"abc\"` generator (the most plausible non-string\n * mistake) came back as `object {}`, and a reader looking for an empty\n * object was looking for the wrong bug. A thenable is called what it\n * is, with the fix: the generator must return synchronously.\n */\nexport function describeReceived(\n outcome: { returned: unknown } | { threw: unknown },\n): string {\n if (\"threw\" in outcome) return `threw ${describeValue(outcome.threw)}`;\n const value = outcome.returned;\n if (typeof value === \"object\" && value !== null) {\n if (typeof (value as { then?: unknown }).then === \"function\") {\n return \"a Promise (sessionIdGenerator must return a string synchronously)\";\n }\n const ctor = (value as { constructor?: { name?: unknown } }).constructor;\n const name = typeof ctor?.name === \"string\" ? ctor.name : \"\";\n if (name !== \"\" && name !== \"Object\") {\n return `object ${name} ${describeValue(value)}`;\n }\n }\n return `${typeof value} ${describeValue(value)}`;\n}\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - the page's leave, and the SDK's lazy loads */\n/* ------------------------------------------------------------------ */\n\n/*\n * A LEAVE IS NOT A FAILURE, AND A LEAVING PAGE STARTS NO LOAD. Every chunk\n * the SDK loads (module-of.ts's ownChunk: the body chunk, the worker's\n * start, the GraphQL term chunk, each with its fallback beside the SDK)\n * and the body worker itself (body-jobs.ts) go through the one gate here,\n * `staying`:\n *\n * - WebKit cancels a page's loads as a navigation starts, after\n * beforeunload and before pagehide, and rejects every load the page\n * starts from then on; Firefox cancels them too (MEASURED in Playwright\n * 1.63's WebKit 26.6 and Firefox 155, repro6 and probe8). Each rejects as\n * a 404 or a refused chunk does, and was judged so: a body recorded\n * `code-failed` and KUI_E_BODY_WORKER_UNAVAILABLE said for a page that\n * only left (CI pipeline 366). So a load that fails while the page is\n * leaving is not judged: it is HELD, and asked for once more when the\n * leave ends. Asked again, a module the browser keeps as failed in the\n * page's module map rejects at once, and ownChunk then asks for its\n * fallback beside the SDK, a URL never asked for.\n * - And a load is never STARTED while the page is leaving: none is of use\n * to a page on its way out, WebKit rejects each, and Firefox keeps one\n * started then on the network past the leave: the next page's load\n * event waited for it (probe8: ownChunk's fallback, asked for once\n * Firefox had cancelled the chunk's import, held the next page at\n * `interactive` for as long as its server held the file, 3.2 s there).\n * It is held, as whenOnline holds a load asked for offline.\n *\n * THE PAGE IS LEAVING from beforeunload, or from the Navigation API's\n * navigate to another document (iOS Safari may fire no beforeunload;\n * Chromium and Firefox fire navigate first, WebKit beforeunload: nav9) --\n * unless the app took it over: it fires with destination.sameDocument\n * false all the same for an SPA's route (MEASURED in all three engines,\n * rev8). Each navigate is JUDGED BY WHAT BECAME OF IT IN THIS DOCUMENT, a\n * task after its dispatch (undo): the app cancelled it (defaultPrevented),\n * or it COMMITTED here -- an intercepted navigate commits as its dispatch\n * ends, before its handler runs (currententrychange, all three engines,\n * probe11), an intercepted reload too, with no new entry (its\n * navigationType says so: REVIEW-s4 B2, P3) -- or its transition is still\n * under way (a commit the app deferred: precommitHandler). A navigation\n * to another document commits nothing here while the page lives. Never\n * the transition alone: a route whose handler has\n * settled by then has none (probe11), and read so, every route of such an\n * SPA, and in WebKit every intercepted link, left the page leaving for\n * good (#74). Never a signal's abort: Chromium aborts a navigation to\n * another document at an app's route, and commits it all the same\n * (probe11). A same-document navigate (pushState, a hash) and a download\n * are no leave at all. And an app's route ends no leave a navigation\n * already began: it may not cancel that navigation, so the page stays\n * leaving.\n *\n * AND IT ENDS ON PROOF THAT THE PAGE STAYED, something a navigation still\n * on its way cannot produce, never a clock (MEASURED in all three\n * engines, probe10):\n * - Chromium aborts the leaving navigate's signal at a prompt the user\n * cancelled. A link clicked twice, or Enter pressed twice, aborts it too,\n * and fires the new navigate in the same task, and so does the page's\n * own replaceState in its beforeunload (vue-router saves its scroll so),\n * with a same-document navigate (rev10): the abort is read a task later,\n * and ends the leave only if no navigate of any kind, and no leave,\n * came since.\n * - pageshow from the back/forward cache, or a capture's start (the\n * page's script alive and starting one) -- never the one the visitor's\n * input starts, a continuous capture's next session (index.ts).\n * Never navigatesuccess: the page's own pushState or replaceState fires\n * one, trusted in Chromium and Firefox, while a real navigation still\n * loads, and Firefox, asked for a load then, held the next page (rev10).\n * Never the visitor's input: after a prompt the user ACCEPTED, and while a\n * real navigation is still loading, the old page gets every click and key\n * (all three engines), and a load asked for then was refused by WebKit and\n * judged failed, or started by Firefox mid-leave, holding the next page\n * (rev9). So a prompt the user cancelled in Firefox or WebKit, a 204, a\n * download and Chromium's mailto: (each fires nothing more) keep the page\n * leaving until one of those: its bodies are recorded as the page having\n * left, and nothing is said. What was held is then asked for. A body\n * recorded while the page was leaving stays recorded so: fail closed.\n * And NOTHING WAITS ON A LOAD THE LEAVE HOLDS (unlessHeld): start() for\n * rrweb's import, so no promise the app awaits hangs, and each GraphQL\n * request for the term code (network.ts), whose event and bodies a leave\n * that never ends kept for the page's life, one more each request.\n *\n * TWO STATES, EACH DEFINED HERE ONCE, and read by every consumer:\n * - HOLDING (isHolding): from the leave's first sign, a navigate's dispatch\n * or beforeunload. No load starts (staying), which protects the next\n * page (#74). Nothing is judged by it alone.\n * - STANDING (isStanding): the leave survived its check, a task after its\n * sign's dispatch -- a navigate's, the task in which an intercepted or\n * cancelled one is undone (undo), and beforeunload's too: WebKit fires\n * beforeunload before an app's route as well, whose navigate in the same\n * task takes the leave over and is judged by its commit. Stood at once,\n * it failed closed in every WebKit route's window: the route's own data\n * request, sent from its handler, recorded body:* (REVIEW-s4 B1, P1). A\n * beforeunload no navigate took over (the address bar, a bookmark: no\n * navigate at all) stands at its check as a navigation under way, which\n * no later route ends. Only a standing leave fails closed: a term\n * recorded body:* (network.ts), a body noted `left` (body-jobs.ts), a\n * wait ended (unlessHeld).\n * EACH NAVIGATE HAS A CHECK OF ITS OWN, a task after its dispatch. The\n * newest navigate judges the leave: the page stayed, or it stands. One a\n * newer navigate came after judges only itself: taken over by the page\n * (an SPA's route its guard redirects: it committed before the redirect),\n * nothing; otherwise a navigation under way (a link clicked twice, a\n * navigation an app's route came after), and the leave stands. Once one\n * stands, no later check undoes it (`went`): an app's route ends no leave\n * a navigation began. Judged by the first's check, a guard's redirect\n * stood the leave until the next capture start -- every term body:*,\n * every body `left`, on a page that never left. Each navigate's check is\n * queued at its dispatch, so a window that holds several ends with the\n * newest one's task.\n * Inside a window a consumer waits for the check (whenJudged)\n * and then goes on with its load (an SPA's route: the page stayed) or\n * fails closed (the leave stands). An SPA's route sends its data request\n * from the navigate's own dispatch, inside the window, and recorded it\n * body:* when the leave was judged at its first sign (sdk-leave.spec.ts,\n * Chromium: its check's task ran after the route's request). No clock: the\n * window ends with the check's task, FIFO behind the dispatch.\n *\n * Watched from a capture's start to the last capture's stop, and between\n * a continuous capture's sessions while the next waits (index.ts), never\n * for the page's life.\n */\n\nlet leaving = false;\n/** HOLDING: the page is leaving, from the leave's first sign; no load starts. */\nexport const isHolding = (): boolean => leaving;\n/** The leave survived its check (stand): set only while `leaving`. */\nlet stands = false;\n/** STANDING: the leave survived its check; what fails closed reads this. */\nexport const isStanding = (): boolean => stands;\n/** What waits for the leave's check, inside a navigate's window (whenJudged). */\nlet judging: Array<() => void> = [];\n/** Leaves begun so far: a body answered during this one is told from one the page was still reading as it began (body-jobs.ts). */\nlet leaves = 0;\nexport const leaveMark = (): number => leaves;\n/** What began the leave: a navigate's is undone if the app intercepted or cancelled it. */\nlet leftBy: Event | undefined;\n/** The newest navigate since the leave began, of any kind. */\nlet going: Event | undefined;\n/** The newest navigate with a check of its own: it judges the leave, any before it only itself. */\nlet last: Event | undefined;\n/**\n * Navigates the page took over by COMMITTING them in this document, each\n * the newest navigate as it committed: an app's route, the page's\n * pushState. Weak: kept only while the event is.\n */\nconst landed = new WeakSet<Event>();\n/** A navigate's check found it going to another document; see undo(). */\nlet went = false;\n/** Loads held for the leave's end. */\nlet held: Array<() => void> = [];\nlet watched = false;\n/**\n * Called as the page stays, before what was held is asked for, `cancelled`\n * true after a leave that may have cancelled its loads (one a navigation\n * began: not a navigate the app intercepted or cancelled): body-jobs.ts's\n * worker not yet running, whose script's load the leave cancelled unsaid,\n * and the running one it kept for the leave.\n */\nexport const stays: Array<(cancelled: boolean) => void> = [];\n\n/**\n * The page stayed: the leave is over, and every load it held is asked for\n * once more -- in a task of its own, never inside the visitor's input that\n * proved it (a worker's start posts every body held), and held again if\n * the page has begun to leave by then.\n */\nexport function stayed(cancelled = true): void {\n if (!leaving) return;\n // While still leaving: what they hold waits with the rest.\n for (const stay of stays) stay(cancelled);\n leaving = stands = went = false;\n leftBy = going = last = undefined;\n const due = held;\n held = [];\n // Judged: the page stayed, and each goes on with its load.\n judge();\n setTimeout(() => {\n for (const run of due) if (!whenStayed(run)) run();\n }, 0);\n}\n\n/**\n * What awaits a load besides its answer, each told as the leave next holds\n * one; see unlessHeld(). One a load still on its way, never the page's\n * life: a promise every start() raced, settled only at a leave, kept each\n * race (about 300 B) until one came -- unbounded on a page that never left.\n */\nconst waiting = new Set<() => void>();\n/**\n * `load`'s answer (its failure rejects), or undefined as the leave next\n * holds a load: what awaits one awaits it no longer (recorder.ts's\n * start(), so init() never hangs on a held load; network.ts's term). And\n * undefined at once for a load not yet `answered` asked for while the page\n * is leaving: held, or held as it is asked for, or cancelled as the page\n * goes -- a leave that never ends (a 204, a download) tells nothing more,\n * and each wait it kept, a request's or a session's, stayed for the\n * page's life. Losing it fails closed.\n */\nexport const unlessHeld = <T>(\n load: Promise<T>,\n answered?: boolean,\n): Promise<T | undefined> =>\n new Promise((settle, fail) => {\n const wait = (): void => {\n if (stands && !answered) return settle(undefined);\n const held = (): void => settle(undefined);\n waiting.add(held);\n void load.then(\n (done) => (waiting.delete(held), settle(done)),\n (err: unknown) => (waiting.delete(held), fail(err)),\n );\n };\n // Inside a navigate's window, the check first: an SPA's route, whose\n // request is sent there, has its load once the page has stayed.\n if (answered || !whenJudged(wait)) wait();\n });\n\n/** End every wait (unlessHeld): the leave that stands holds a load. */\nfunction tell(): void {\n for (const told of waiting) told();\n waiting.clear();\n}\n\n/**\n * Run `run` once the leave has been judged -- it stands, or the page\n * stayed -- when the page is HOLDING and not yet STANDING (the window up to\n * the newest sign's check, a task after it): true when it waits. No clock.\n */\nexport function whenJudged(run: () => void): boolean {\n const wait = leaving && !stands;\n if (wait) judging.push(run);\n return wait;\n}\n\n/** Run what waits for the leave's check (whenJudged). */\nfunction judge(): void {\n const due = judging;\n judging = [];\n for (const run of due) run();\n}\n\n/**\n * The leave survived its check: STANDING from now until the page stays.\n * What a load held in the window kept waiting is told now, and what waits\n * for the check fails closed.\n */\nfunction stand(): void {\n if (!leaving || stands) return;\n stands = true;\n if (held.length) tell();\n judge();\n}\n\n/** Hold `run` until the page has stayed; true when it waits (the page is leaving). */\nexport function whenStayed(run: () => void): boolean {\n if (leaving) {\n held.push(run);\n // Only a leave that stands ends a wait: one in a navigate's window may\n // be an SPA's route (stand() tells them if it stands).\n if (stands) tell();\n }\n return leaving;\n}\n\n/**\n * `get()`, a lazy load, through the leave gate: started only while the\n * page is not leaving, and, refused or cancelled while it is, asked for\n * once more when it has stayed. Rejects with a failure judged outside a\n * leave: a real one.\n */\nexport function staying<T>(get: () => T | PromiseLike<T>): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const go = (): void =>\n void new Promise<T>((started) => started(get())).then(\n resolve,\n (err: unknown) => {\n if (!whenStayed(go)) reject(err);\n },\n );\n if (!whenStayed(go)) go();\n });\n}\n\ntype Navigation = EventTarget & {\n transition?: unknown;\n currentEntry?: unknown;\n};\n/** The Navigation API, where the browser has it. */\nconst nav = (): Navigation | undefined =>\n (globalThis as { navigation?: Navigation }).navigation;\n\n/**\n * A task from now, the page stayed if no leave began since `by` and\n * `yes()`. An aborted navigation's check (no `own`) never makes a leave\n * stand. A navigate's own check (`own`, `yes()` its transition still under\n * way): taken over by the page if the app cancelled it or it committed\n * here. The newest navigate judges the leave: the page stayed, or it\n * STANDS. One a newer navigate came after judges only itself: taken over,\n * nothing; otherwise a navigation under way, which an app's route may not\n * cancel, and it STANDS. No later check undoes a leave that stands so\n * (`went`).\n */\nfunction undo(\n by: Event | undefined,\n yes: () => unknown,\n cancelled: boolean,\n own?: Event & { signal?: AbortSignal },\n): void {\n const leave = leaves;\n setTimeout(() => {\n if (!own) {\n if (leftBy === by && yes()) stayed(cancelled);\n return;\n }\n // Over (the page stayed, or a new leave began), or judged already.\n if (went || leave !== leaves || !leaving) return;\n // Taken over by the page: cancelled, or committed here (an app's route).\n const kept = own.defaultPrevented || landed.has(own);\n if (own === last && leftBy === own && (kept || yes()))\n return stayed(cancelled);\n // Superseded: taken over, it judges nothing -- never by its abort.\n if (own !== last && kept) return;\n went = true;\n stand();\n }, 0);\n}\n\nfunction onLeave(event: Event): void {\n const type = event.type;\n const go = event as Event & {\n destination?: { sameDocument?: boolean };\n downloadRequest?: string | null;\n signal?: AbortSignal;\n from?: unknown;\n navigationType?: string | null;\n };\n // A commit in this document: the newest navigate's own (an app's route,\n // the page's pushState, an intercepted reload: no new entry, its type\n // \"reload\"), never a change of the entry's state alone (updateCurrentEntry:\n // `from` is the current entry still, and no navigationType).\n if (type === \"currententrychange\") {\n if (going && (go.from !== nav()?.currentEntry || go.navigationType))\n landed.add(going);\n return;\n }\n // A proof: the browser's own (trusted) pageshow from the back/forward\n // cache -- never the page's script's, nor the leaving page's own first\n // load ending.\n if (type === \"pageshow\") {\n if (event.isTrusted && (event as PageTransitionEvent).persisted) stayed();\n return;\n }\n if (!leaving) going = undefined;\n const was = leaving;\n // Every navigate is the newest, a same-document one (pushState, a hash)\n // or a download's too, though either leaves nothing.\n if (type === \"navigate\") going = event;\n if (go.destination?.sameDocument || go.downloadRequest != null) return;\n if (!was) leaves++;\n leaving = true;\n leftBy = event;\n // beforeunload: judged a task later, as a navigate is. WebKit fires it\n // first even for an app's route, whose navigate in this task takes the\n // leave over (leftBy) and is judged by its commit. One no navigate took\n // over stands, as a navigation under way (`went`): no later route ends it.\n if (type !== \"navigate\")\n setTimeout(() => {\n if (leftBy === event) {\n went = true;\n stand();\n }\n }, 0);\n else {\n // Taken over or not: known once every listener has had it and the\n // app's handler has run, a task later (not yet at a microtask: nav9),\n // each navigate by a check of its own. A leave that stood may have\n // cancelled loads; one still in a navigate's window has not.\n undo(event, () => nav()?.transition, was && stands, (last = go));\n // Aborted, as Chromium does at a prompt the user cancelled: the page\n // stays, unless a navigate or a leave came since.\n go.signal?.addEventListener(\"abort\", () =>\n undo(leftBy, () => going === event, false),\n );\n }\n}\n\nconst LEAVE = [\"beforeunload\", \"pageshow\"];\n\n/**\n * Watch the page's leave (`on`, at a capture's start, which is itself\n * proof that the page stayed unless the visitor's input started it:\n * `proof`) or stop watching it (at the last capture's stop). A load still\n * held then waits for the next capture's start.\n */\nexport function watchLeave(on: boolean, proof = on): void {\n if (proof) stayed();\n if (watched === on || typeof addEventListener !== \"function\") return;\n watched = on;\n const options = { capture: true, passive: true };\n const listen = (target: EventTarget | undefined, types: string[]): void => {\n for (const type of types)\n if (on) target?.addEventListener(type, onLeave, options);\n else target?.removeEventListener(type, onLeave, options);\n };\n listen(globalThis as unknown as EventTarget, LEAVE);\n listen(nav(), [\"navigate\", \"currententrychange\"]);\n}\n\n/** Exposed for tests. */\nexport const __leave = {\n /** Forget the leave, what it held and the watch. */\n reset(): void {\n watchLeave(false);\n leaving = stands = went = false;\n leftBy = going = last = undefined;\n held = [];\n judging = [];\n waiting.clear();\n },\n leaving: isHolding,\n /** The leave stands (isStanding). */\n stands: isStanding,\n /** What waits for the leave's check (whenJudged). */\n judging: (): number => judging.length,\n /** Loads held for the leave's end. */\n held: (): number => held.length,\n /** What awaits a load besides its answer (unlessHeld). */\n waiting: (): number => waiting.size,\n};\n","{\n \"name\": \"@keploy/capture-sdk\",\n \"version\": \"3.1.0-rc.2\",\n \"description\": \"Lightweight SDK to capture UI flows from real users - DOM recording, network interception, PII masking\",\n \"main\": \"dist/index.js\",\n \"module\": \"dist/index.bundler.mjs\",\n \"unpkg\": \"dist/index.mjs\",\n \"jsdelivr\": \"dist/index.mjs\",\n \"types\": \"dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./request-term\": {\n \"types\": \"./dist/request-term.d.ts\",\n \"import\": \"./dist/request-term.mjs\",\n \"require\": \"./dist/request-term.js\"\n },\n \"./strict-attributes\": {\n \"types\": \"./dist/strict-attributes.d.ts\",\n \"import\": \"./dist/strict-attributes.mjs\",\n \"require\": \"./dist/strict-attributes.js\"\n },\n \"./body-redact\": {\n \"types\": \"./dist/body-redact.d.ts\",\n \"import\": \"./dist/body-redact.mjs\",\n \"require\": \"./dist/body-redact.js\"\n },\n \"./body-worker-start\": {\n \"types\": \"./dist/body-worker-start.d.ts\",\n \"import\": \"./dist/body-worker-start.mjs\",\n \"require\": \"./dist/body-worker-start.js\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"request-term/package.json\",\n \"strict-attributes/package.json\",\n \"body-redact/package.json\",\n \"body-worker-start/package.json\",\n \"LICENSE\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"node scripts/build-main.mjs && node scripts/build-worker.mjs && tsc -p tsconfig.build.json\",\n \"dev\": \"node scripts/build-main.mjs --watch\",\n \"test\": \"vitest run\",\n \"clean\": \"rm -rf dist\",\n \"typecheck\": \"tsc --noEmit\",\n \"prepublishOnly\": \"pnpm run clean && turbo run build --filter=@keploy/capture-sdk --force\"\n },\n \"dependencies\": {\n \"rrweb\": \"^2.1.6\"\n },\n \"devDependencies\": {\n \"@keploy/contract\": \"workspace:*\",\n \"@types/node\": \"~24.13.5\",\n \"jsdom\": \"^30.1.0\",\n \"terser\": \"5.51.2\",\n \"tsup\": \"^8.3.0\",\n \"typescript\": \"^7.0.2\",\n \"vitest\": \"^5.0.1\"\n },\n \"peerDependencies\": {},\n \"keywords\": [\n \"keploy\",\n \"ui-testing\",\n \"session-recording\",\n \"e2e\",\n \"capture\"\n ],\n \"browser\": {\n \"./dist/body-worker-unbundled.mjs\": \"./dist/body-worker-none.mjs\"\n },\n \"alias\": {\n \"@keploy/capture-sdk/body-worker-start\": \"./dist/body-worker-start.mjs\"\n },\n \"license\": \"Apache-2.0\",\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n","import { version } from \"../package.json\";\nimport { staying } from \"./leave\";\n\n/**\n * The module an import() resolved to, whichever way the page's bundler\n * hands it over. A bundler that takes the target as CommonJS gives an ES\n * module that imports it only `{ default: module.exports }`: MEASURED with\n * webpack 4.47.0 and babel-loader (Create React App 4's setup) on the\n * packed SDK, rrweb and the request-term chunk both arrived so --\n * `rrweb.record` was undefined and init() rejected with `TypeError: r is\n * not a function`, and every GraphQL call was recorded with no term. The\n * namespace is passed in whole, never read member by member at the\n * import(): Parcel 2 checks each member read off an import()'s namespace\n * against the module's exports, and neither module has a `default`.\n */\nexport function moduleOf<T>(namespace: T): T {\n // `in`, not a read: a module system that throws on a missing export\n // (vitest's mocks do) must not see `default` asked for.\n return \"default\" in (namespace as object)\n ? (namespace as { default: T }).default\n : namespace;\n}\n\n/**\n * One of the SDK's own chunks: `bare`, an import() of the package's own\n * name -- what a bundler resolves (webpack 4 through the subpath's\n * package.json) and an import map may map -- or, when that rejects,\n * `beside`, an import() of the built file by its path beside\n * dist/index.mjs. AN UNBUNDLED PAGE RESOLVES NO BARE NAME IT DOES NOT\n * MAP: MEASURED on SDK be157850 with the journey-chain probe's pages (an\n * import map naming `rrweb` alone, as enterprise-ui's e2e page and the\n * README's no-bundler install have it), every response body was recorded\n * `[Body cut: 0 of N characters kept, unverified]` in Chromium, Firefox\n * and WebKit, privacy off included, where 3.1.0-rc.1, the redactor in its\n * bundle, recorded all 7 whole (sdk-unbundled.spec.ts holds it). A\n * relative import() is resolved against the module that makes it,\n * dist/index.mjs wherever the page serves it from, so no entry is needed.\n *\n * ONLY dist/index.mjs HAS `beside` (`__BESIDE__`, scripts/build-main.mjs):\n * the build a page with no bundler loads, and modern bundlers through the\n * `exports` map, which bundle each path, as written, into the chunk the\n * name loads, so no native import() reaches their output.\n * dist/index.bundler.mjs (the `module` field: webpack 4, Parcel by\n * default) and dist/index.js (CommonJS: Nuxt 2's and Angular Universal's\n * server builds) have none: webpack 4 cannot parse the worker start's\n * `import.meta`, and for node reads no `browser` field; and for an .mjs\n * file it resolves the name and the path to two files, each chunk twice.\n * When both loads fail, both errors are reported: the first says why in a bundled build, the\n * second on a page with no bundler.\n *\n * A CHUNK OF ANOTHER VERSION IS A FAILED LOAD. Each chunk exports the\n * version it was built as (the package's, as transport.ts reads it), and\n * one that is not the SDK's own is refused, so the file beside the SDK is\n * asked for. MEASURED on 3.1.0-rc.1 (CDN-FINDINGS.txt): unpkg's\n * `?module` rewrites the SDK's import of its own name to\n * `https://unpkg.com/@keploy/capture-sdk@latest/<chunk>?module` -- the\n * package does not depend on itself, so the CDN knows no version for it\n * -- which loads whatever version is latest, never the page's. A chunk\n * that exports no version (3.0.x's) is another version too.\n *\n * EACH LOAD GOES THROUGH THE LEAVE GATE (leave.ts, staying): never started\n * while the page is leaving, and, refused or cancelled by the leave, asked\n * for once more when the page has stayed -- so a bare import cancelled by\n * a leave never asks for `beside` mid-leave, and one the module map keeps\n * as failed falls to `beside` once the page has stayed. Every chunk the\n * SDK loads is one of these.\n */\nexport function ownChunk<T>(\n bare: () => Promise<T>,\n beside?: () => Promise<T>,\n): Promise<T> {\n const own = (namespace: T): T => {\n const code = moduleOf(namespace);\n const built = (code as { version?: unknown }).version;\n if (built !== version)\n throw new Error(\n `a chunk of version ${String(built)}, not the SDK's ${version}`,\n );\n return code;\n };\n // The file beside is refused as the name's was, so its refusal is\n // caught with its failed load: both errors, whichever way it failed.\n return staying(bare)\n .then(own)\n .catch((err: unknown) =>\n beside\n ? staying(beside)\n .then(own)\n .catch((near: unknown) =>\n Promise.reject(\n new Error(`${String(err)}; beside the SDK: ${String(near)}`, {\n cause: err,\n }),\n ),\n )\n : Promise.reject(err),\n );\n}\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - where a body is redacted */\n/* ------------------------------------------------------------------ */\n\n/*\n * A BODY IS REDACTED IN A WEB WORKER, NEVER ON THE PAGE'S THREAD WHEN IT\n * CAN BE HELPED. MEASURED (uic-sdk-perf MEASURE.md): redaction on the main\n * thread took 42-58 ms per 512 KB JSON body (150 ms at a phone's speed),\n * and with it moved to a task after the page's (#65) a burst still\n * starved the page's timers, Firefox's text() could still resolve behind\n * it, and back-to-back 256 KB POSTs paid it in full. So:\n *\n * - THE WORKER, dist/body-worker.js, is started when a capture that\n * records bodies to redact starts -- in the page's next idle period, as\n * rrweb loads at start, and at the latest the task after its first\n * exchange leaves; never inside init()'s task, and before the page's\n * burst when an idle period comes first (otherwise in the task after\n * its first request leaves, while its responses may still arrive);\n * never for a capture that masks\n * bodies whole -- and once per page: a start that fails online is not\n * retried; one the browser could not make offline is made once it is\n * back online, its jobs held meanwhile.\n * Every body goes to it; its answers come back in the order the bodies\n * went, and each event keeps the place (seq) and the time it was given\n * when it was reported (network.ts), so the recording's order is the\n * one #65 recorded.\n * - THE MAIN THREAD'S CODE, dist/body-redact.{mjs,js}, is loaded once,\n * for the moments that cannot wait for the worker (now()): asked for\n * in init()'s own task, beside rrweb (askForCode, KeployCapture.start),\n * so it is there once its fetch is over, while the page's network is\n * recorded from the start as it always was. A body the main thread\n * must redact with no code to do it with is recorded as\n * @keploy/contract's notCapturedBodyNote, saying why -- never in the\n * clear, and told apart from a body cut at the budget: `left` when a\n * moment that cannot wait (pagehide, settle()'s bound) finds it with\n * the code still on its way, `code-failed` when the code could not\n * load at all (noted).\n * - WITH NO WORKER -- a CSP that refuses it, a bundler that did not emit\n * it (webpack 4), a platform without Worker, a worker that failed --\n * each body is redacted on the main thread in a task of its own, and\n * only up to MAIN_THREAD_BODY_BUDGET: a body over it is recorded cut,\n * under @keploy/contract's cutBodyNote, which replay never serves as a\n * whole body (mock-replay.v7 rules.cut).\n *\n * Nothing is lost on the way: a job is held until it is recorded, and\n * now() records every job still held at the\n * moments that cannot wait (pagehide, settle()'s bound): whole within\n * the budget, cut past it. A load that fails never throws into the page.\n */\n\nimport { notCapturedBodyNote } from \"@keploy/contract/privacy\";\nimport type { BodyJob, BodyOut } from \"./body-redact\";\nimport { bodyWorkerWarningLine, describeValue } from \"./errors\";\nimport {\n __leave,\n isHolding,\n isStanding,\n leaveMark,\n staying,\n stays,\n whenJudged,\n whenStayed,\n} from \"./leave\";\nimport { ownChunk } from \"./module-of\";\nimport { bodyCode } from \"./privacy\";\n\ntype BodyCode = typeof import(\"./body-redact\");\ntype WorkerStart = typeof import(\"./body-worker-start\");\n\n/**\n * UTF-16 units of body the main thread redacts in one go: a body with no\n * worker, and all the bodies a moment that cannot wait redacts together.\n * 64 KiB is about 6-10 ms of redaction at desktop speed (MEASURED: 5.7 ms\n * for a 64 KB JSON in Chromium, 6 in Firefox, 8 in WebKit), and the most\n * a page-unload flush can carry anyway (transport.ts, the keepalive\n * quota). Founder's ruling, 2026-11-11.\n */\nexport const MAIN_THREAD_BODY_BUDGET = 65_536;\n\n/*\n * The two chunks, by the package's own name (see network.ts's term chunk),\n * or -- in dist/index.mjs alone (`__BESIDE__`) -- by their files beside the\n * SDK's own, on a page that maps no such name (ownChunk). `as string` keeps\n * TypeScript from resolving a built file's path; the build keeps each one\n * external, as written, and a bundler bundles it as the chunk the name\n * loads. An unbundled page's worker start is dist/body-worker-unbundled.mjs,\n * the worker's start again: it names the worker beside itself, so neither\n * the chunk nor the worker needs an import-map entry. The package's\n * `browser` field sends a bundler building for the browser from it to the\n * stub; it starts the worker by the name `bare` imports.\n */\nconst importCode = (): Promise<BodyCode> =>\n ownChunk(\n () => import(\"@keploy/capture-sdk/body-redact\"),\n // oxlint-disable-next-line no-undef -- a constant of the build (scripts/build-main.mjs), declared in build-flags.d.ts: true in dist/index.mjs alone\n __BESIDE__ ? () => import(\"./body-redact.mjs\" as string) : undefined,\n );\nconst importStart = (): Promise<WorkerStart> =>\n ownChunk(\n () => import(\"@keploy/capture-sdk/body-worker-start\"),\n // oxlint-disable-next-line no-undef -- a constant of the build (scripts/build-main.mjs), declared in build-flags.d.ts: true in dist/index.mjs alone\n __BESIDE__\n ? () => import(\"./body-worker-unbundled.mjs\" as string)\n : undefined,\n );\nlet load = { code: importCode, start: importStart };\n\n/** The main thread's code, once loaded. */\nlet code: BodyCode | undefined;\n/** Settles when the code has loaded, or failed to load for good. */\nlet codeLoad: Promise<void> | undefined;\n/** The code's load waits for the browser to be back online (whenOnline). */\nlet codeOffline = false;\n/** The code failed to load for good: there will be none on this page. */\nlet codeFailed = false;\n/** The worker: undefined until it has started (or while a start is due), null when there is none. */\nlet worker: Worker | null | undefined;\n/** A start is under way, or waits for the page to be back online. */\nlet workerStarting = false;\n/** The worker that has said it runs (its script's first act, body-worker.ts). */\nlet running: Worker | undefined;\n/**\n * Asked for and not yet started: posted once it is, or redacted here if it\n * never is. A job leaves it as it is recorded (BodyJobs.answer): a capture's\n * end records every job it held, and nothing it recorded stays here.\n */\nlet starting = new Set<Held>();\n/** Posted to the worker and not yet answered, by id. */\nconst posted = new Map<number, Held>();\nlet ids = 0;\n\ninterface Held {\n job: BodyJob | null;\n owner: BodyJobs;\n /** Its bodies as recorded, once known (undefined: not yet). */\n out?: BodyOut | null;\n /** The relay is over (see network.ts): the main thread redacts after it. */\n after?: Promise<void>;\n /** Posted already, at report (a browser with no idle periods; see redact). */\n sent?: boolean;\n /** leave.ts's leaveMark() as its exchange was answered (ofTheLeave). */\n mark: number;\n}\n\n/** A body answered since the leave under way began (leave.ts's leaveMark()). */\nconst sinceTheLeave = (held: Held): boolean => held.mark === leaveMark();\n\n/**\n * A body of the leave that STANDS (leave.ts's isStanding()): answered\n * since it began. One the page was still reading as the leave began --\n * answered before it, then cut by the leave (Firefox and WebKit abort a\n * document's fetches as it navigates, before pagehide) or ended during it\n * -- is not: it is one of a set fixed as the leave began, and it is cut\n * where the page left, as pagehide cuts one still arriving (now()),\n * redacted by the code.\n */\nconst ofTheLeave = (held: Held): boolean => isStanding() && sinceTheLeave(held);\n\n/** Run `fn` in an idle period where the browser has them (at most 1 s later), else the next task. */\nfunction later(fn: () => void): void {\n (\n (typeof requestIdleCallback !== \"undefined\"\n ? requestIdleCallback\n : setTimeout) as (run: () => void, options: object) => void\n )(\n // setTimeout reads the options as its delay: 0 (no NaN warning).\n fn,\n { timeout: 1_000, valueOf: () => 0 },\n );\n}\n\n/** The parts KUI_E_BODY_WORKER_UNAVAILABLE has been said for: each once per page, as each loads once per page. */\nlet warned = \"\";\n\n/**\n * Tell the integrator, once per page for each, that the worker (`part`\n * \"worker\") or the body chunk (\"code\") is not available, `why` saying\n * what the browser said: without the worker a body over 64 KiB is\n * recorded cut; without the chunk a body the main thread must redact\n * keeps nothing. The console is the only surface: nothing ends, and\n * onError is terminal-only. EACH PART IS SAID: said once per page\n * whatever failed, a page whose CSP refuses the worker and whose chunk\n * did not load (or was refused as another version's, ownChunk) was told\n * of the worker alone -- bodies over 64 KiB cut, its fix worker-src --\n * while every body the main thread redacted kept nothing, said nowhere.\n */\nfunction warn(part: \"code\" | \"worker\", why: unknown): void {\n if (warned.includes(part)) return;\n warned += part;\n try {\n // console.warn, as every warning: nothing ends.\n console.warn(\n bodyWorkerWarningLine(\n part,\n typeof Event !== \"undefined\" && why instanceof Event\n ? // A worker's error event: a refused, missing or broken script\n // says nothing more (Chromium fires a plain Event).\n (why as ErrorEvent).message ||\n \"the worker's script did not load or run (refused by the page's CSP, a 404, or a script that does not parse)\"\n : describeValue(why),\n ),\n );\n } catch {\n // A console that throws is not the page's problem either.\n }\n}\n\n/** Callbacks waiting for the browser to be back online, or undefined when none waits. */\nlet online: Array<() => void> | undefined;\n/** Stops the wait for `online` (its listener and poll), while one waits. */\nlet unwait: (() => void) | undefined;\n\n/**\n * Whether a service worker controls the page, which may answer offline:\n * read guarded, as recorder.ts's workerInControl reads it. A frame\n * sandboxed without allow-same-origin throws a SecurityError from\n * `navigator.serviceWorker` itself, and init() asks for the chunk in its\n * own task (askForCode): read bare, it rejected init() there.\n */\nfunction controlled(): boolean {\n try {\n return Boolean(navigator.serviceWorker?.controller);\n } catch {\n return false;\n }\n}\n\n/**\n * OFFLINE IS NOT A FAILURE, AND NOTHING IS ASKED FOR WHILE OFFLINE. A page\n * that starts capturing offline cannot fetch the chunk or the worker's\n * script, and main recorded its bodies (redacted in the bundle) all the\n * same. A module import asked for offline cannot simply be asked again:\n * Chromium keeps a failed import for the life of the page (MEASURED for\n * rrweb, recorder.ts). So while the browser says it is offline -- and no\n * service worker controls the page, which may serve both -- the loads\n * are not started at all; their jobs are held, and `run` is called once\n * the browser is back online: at its `online` event, or at the next\n * second's look at navigator.onLine (a page's own listener can stop the\n * event, as the recorder found). True when `run` waits.\n */\nfunction whenOnline(run: () => void): boolean {\n if (\n typeof navigator === \"undefined\" ||\n navigator.onLine !== false ||\n controlled() ||\n typeof addEventListener !== \"function\"\n )\n return false;\n if (!online) {\n online = [];\n const back = (): void => {\n if (navigator.onLine === false) return;\n unwait?.();\n const waiting = online ?? [];\n online = undefined;\n for (const fn of waiting) fn();\n };\n addEventListener(\"online\", back);\n const poll = setInterval(back, 1_000);\n unwait = () => {\n removeEventListener(\"online\", back);\n clearInterval(poll);\n unwait = undefined;\n };\n }\n online.push(run);\n return true;\n}\n\n/** The main thread's code, loading once per page, and not before the browser is online. */\nfunction loadCode(): Promise<void> {\n return (codeLoad ??= new Promise<void>((resolve) => {\n const go = (): void => {\n codeOffline = false;\n // Through the leave gate (ownChunk): a failure that reaches here was\n // judged outside a leave.\n void load\n .code()\n .then((loaded) => {\n // A module without the export -- a stale or wrong file served at\n // the chunk's path -- is a chunk that failed for good too: there\n // is nothing in it to redact with.\n if (typeof loaded.redactBodies !== \"function\")\n throw new TypeError(\"the body chunk has no redactBodies export\");\n return loaded;\n })\n .then(\n (loaded) => {\n code = loaded;\n // PrivacyEngine.maskNetworkData, called by the integrator,\n // redacts with it from now on (bodies masked until then).\n bodyCode.redact = (job) => loaded.redactBodies(job);\n resolve();\n },\n (err: unknown) => {\n codeFailed = true;\n warn(\"code\", err);\n resolve();\n },\n );\n };\n if (!(codeOffline = whenOnline(go))) go();\n }));\n}\n\n/**\n * THE CODE AS SOON AS THE CAPTURE STARTS: the main thread's code, asked\n * for now -- in init()'s own task, beside rrweb's import, never in an\n * idle period or after the first exchange -- so the window in which a\n * page that leaves finds a body held without it is the chunk's fetch.\n * The page's network is recorded meanwhile, as it always was; a body\n * that meets a moment that cannot wait before the code has arrived is\n * recorded as notCapturedBodyNote(N, \"left\") (now()). Offline it\n * is asked for once the browser is back (whenOnline), as before.\n */\nexport function askForCode(): void {\n void loadCode();\n}\n\n/** Start the worker, once per page, and not before the browser is online. */\nfunction startWorker(): void {\n if (workerStarting || worker !== undefined) return;\n workerStarting = true;\n const go = (): void =>\n void load\n .start()\n // The worker itself through the leave gate too: never started while\n // the page leaves, its start module having arrived meanwhile.\n .then((start) => staying(() => start.startBodyWorker()))\n .then((started) => {\n started.onmessage = ({\n data,\n }: MessageEvent<{ id: number; out: BodyOut | null }>) => {\n running = started;\n const held = posted.get(data.id);\n if (!held) return;\n posted.delete(data.id);\n held.owner.answered(held, data.out);\n };\n // A script the page's CSP refused, a 404, one that does not\n // parse: each fails the worker here, after jobs were posted to it.\n started.onerror = (event) => fail(started, event);\n worker = started;\n workerStarting = false;\n const waiting = starting;\n starting = new Set();\n for (const held of waiting) post(held);\n })\n // A start that threw (no Worker, a CSP that throws, webpack 4's\n // stub, a CommonJS build with no import.meta) or a chunk that did\n // not load.\n .catch((err: unknown) => fail(null, err));\n if (!whenOnline(go)) go();\n}\n\n/**\n * Start loading the main thread's code and the worker, once per page: at\n * a capture's start, in a task of its own (prepareSoon). For a capture\n * KeployCapture started the code is asked for already (askForCode).\n */\nexport function prepare(): void {\n void loadCode();\n startWorker();\n}\n\n/** prepare() is due in an idle period, and in a next task. */\nlet soonIdle = false;\nlet soonTask = false;\n\n/**\n * prepare() in a task of its own, never beside the page's own work: at a\n * capture's start in the page's next idle period (as rrweb loads at\n * start), and at the latest in the task after its first exchange leaves.\n * So the chunk and the worker are there before a burst of the page's\n * requests when an idle period comes first after the capture starts;\n * otherwise they are asked for in the task after its first request\n * leaves, queued behind the requests that task made, while their\n * responses may still be arriving. MEASURED, WebKit 26.6, one\n * box, 9 interleaved reps, 50 x 64 KB with the loads asked for beside the\n * burst's first request: time to headers +1.8 ms and the burst +3.3 ms\n * against main, both past main's spread.\n */\nexport function prepareSoon(idle = false): void {\n // Nothing to do once both are there (a worker released at stop() is\n // started again: prepare() is idempotent).\n if (codeLoad && worker !== undefined) return;\n // An idle period at start; the next task (which no hidden tab withholds)\n // once an exchange is waiting, whether or not the idle one has come.\n if (idle ? soonIdle : soonTask) return;\n if (idle) soonIdle = true;\n else soonTask = true;\n (idle ? later : (run: () => void) => setTimeout(run, 0))(() => {\n if (idle) soonIdle = false;\n else soonTask = false;\n prepare();\n });\n}\n\n/** Post `held` to the worker, once it has started. */\nfunction post(held: Held): void {\n // Recorded already (a capture that stopped while the worker's start was\n // held): nothing to send.\n if (!held.owner.has(held)) return;\n // WHILE THE PAGE LEAVES, A BODY OF THAT LEAVE WAITS ON NOTHING THE LEAVE\n // HOLDS (ofTheLeave: not one the page was reading as it began): with no\n // worker running (one not yet started, whose start the leave holds, or\n // one whose script's load it may have cancelled, never to answer), it is\n // recorded at once as the page having left, and its string goes now.\n // Nothing waits for a held start, page-wide, for as long as a leave that\n // never ends lasts (a 204, a download), and nothing goes to the main\n // thread's budget because of a leave. A page with no worker at all redacts\n // here as ever, once its code is there (alone()). Inside a navigate's\n // window -- the leave not yet judged, perhaps an SPA's route -- it waits\n // for the check (one task): posted as ever once the page has stayed, or\n // noted so once the leave stands (whenJudged).\n const ready = worker ? worker === running : worker === null && code;\n if (!ready && sinceTheLeave(held) && whenJudged(() => post(held))) return;\n if (!ready && ofTheLeave(held)) {\n held.owner.answered(held, noted(held.job!));\n held.job = null;\n return;\n }\n if (worker) {\n posted.set(++ids, held);\n try {\n worker.postMessage({ id: ids, job: held.job });\n } catch {\n // A job the worker cannot be handed (a pattern that does not clone).\n posted.delete(ids);\n held.owner.alone(held);\n }\n } else if (worker === null) {\n held.owner.alone(held);\n } else {\n starting.add(held);\n prepare();\n }\n}\n\n/**\n * The worker did not start, or failed. A worker whose script could not be\n * fetched because the browser went offline is started again, once, when\n * it is back online, and one that failed while the page was leaving (its\n * script's load cancelled by the leave) once the page has stayed (leave.ts),\n * its jobs held meanwhile (still starting: no exchange starts another);\n * otherwise there is no worker for the rest of the page's life, and every\n * job held is redacted here.\n */\nfunction fail(failed: Worker | null, why: unknown): void {\n if (failed && worker !== failed) return;\n try {\n failed?.terminate();\n } catch {\n // Nothing a failed worker does is the page's problem.\n }\n // Those not yet recorded: one recorded while posted is answered no more.\n const orphans = [...posted.values(), ...starting].filter((held) =>\n held.owner.has(held),\n );\n posted.clear();\n worker = undefined;\n starting = new Set(orphans);\n // Still starting while it waits: no exchange meanwhile starts another.\n workerStarting = true;\n const again = (): void => {\n workerStarting = false;\n startWorker();\n };\n if (whenOnline(again) || whenStayed(again)) return;\n workerStarting = false;\n worker = null;\n starting = new Set();\n warn(\"worker\", why);\n for (const held of orphans) held.owner.alone(held);\n}\n\n/**\n * Set while the running worker is kept for the page's leave (releaseWorker):\n * whether a capture is live or a next session waits for it (index.ts),\n * read whenever it may go.\n */\nlet kept: (() => boolean) | undefined;\n\n/** Let the page's worker go, unless a job is still posted to it. */\nfunction letGo(): void {\n kept = undefined;\n if (!worker || posted.size > 0) return;\n try {\n worker.terminate();\n } catch {\n // Nothing a worker does on its way out is the page's problem.\n }\n worker = undefined;\n}\n\n/**\n * The worker kept for the leave goes as the leave ends (this, the stays\n * hook), when no capture is live and none waits; the integrator's stop()\n * lets it go itself (releaseWorker). Never while one is: that capture takes it over as its own, for a\n * worker let go and started again costs the page's thread its start for\n * nothing (the founder's no-slowdown rule). Its own end lets it go, as ever.\n */\nconst gone = (): void => {\n if (kept && !kept()) letGo();\n};\n\n/**\n * AT PAGEHIDE THE KEPT WORKER GOES, WHATEVER WAITS FOR IT: a dedicated\n * worker alive in a page entering the back/forward cache risks the page's\n * place there, which would slow the visitor's way back. What was posted to\n * it is pagehide's to record (now()), and a body after a persisted pageshow\n * starts one again (post).\n */\nconst hidden = (): void => {\n if (!kept) return;\n posted.clear();\n letGo();\n};\n\n/*\n * A WORKER NOT YET RUNNING WHEN THE PAGE STAYS after a leave that may have\n * cancelled its loads is started again, its jobs held for it: its script's\n * load was the leave's to cancel, and Firefox fires no error when it does\n * (MEASURED, Firefox 155, final9a and check9: a worker whose script was\n * loading as a link answered 204 began to leave never ran and never said\n * so), which left every later body posted to a worker that would never\n * answer. One that ran (body-worker.ts's first act) is kept.\n */\nstays.push((cancelled) => {\n if (cancelled && worker && worker !== running) fail(worker, \"left\");\n // The worker kept for the leave (releaseWorker) goes as it ends, unless a\n // capture is live or waits: then it is that capture's.\n gone();\n});\n\n/**\n * Let the page's worker go when a capture stops and nothing is posted to\n * it: an idle thread for the rest of the page's life otherwise. The next\n * capture starts one again from its start (the chunk is the module\n * the page already loaded; the script, the bundler's file, is cached). A\n * page that has no worker (null) keeps having none. And, when no capture\n * is live (`last`), stop waiting for the network: nothing asks then, and\n * the wait's look a second would outlive the capture\n * (dom-recorder-offline-unsaid.test.ts). Never while one is: a capture\n * started during this one's settle() holds its bodies in the same wait.\n * Every body of the capture that ended was recorded by its settle().\n * `wanted`: whether a capture is live or a next session waits for the\n * visitor's input (a continuous capture's), which a running worker is kept\n * for while the page leaves; read again whenever the kept worker may go.\n */\nexport function releaseWorker(\n last = true,\n wanted: () => boolean = () => false,\n): void {\n if (last && online) {\n unwait?.();\n online = undefined;\n if (codeOffline) codeLoad = undefined;\n if (worker === undefined) workerStarting = false;\n starting = new Set();\n }\n // A RUNNING WORKER IS KEPT WHILE THE PAGE LEAVES, for a capture still live\n // or a next session that waits (`next`, a continuous capture's): started\n // again, it would be held until the leave ends (leave.ts), and every body\n // of that session recorded as the page having left (post). It already\n // runs, so keeping it costs nothing new, and its bodies are redacted as\n // ever. It goes when no capture is live and none waits (gone), and at\n // pagehide (hidden).\n if (wanted() && running !== undefined && worker === running && isHolding()) {\n kept = wanted;\n addEventListener(\"pagehide\", hidden);\n return;\n }\n letGo();\n}\n\n/**\n * Each of `job`'s bodies as not captured (notCapturedBodyNote), there\n * being no code here to redact it with, and saying why: `code-failed`\n * when the code failed to load for good (a CSP that refuses it, a 404, a\n * module without its exports: there will be none on this page), `left`\n * while it is still on its way -- the page left, or the capture stopped,\n * before it arrived, or the page's leave holds its load (leave.ts).\n * Never the bare cut note a body cut at the budget carries.\n */\nfunction noted(job: BodyJob): BodyOut {\n const note = (body: string | null) =>\n body &&\n notCapturedBodyNote(body.length, codeFailed ? \"code-failed\" : \"left\");\n return {\n requestBody: note(job.requestBody),\n responseBody: note(job.responseBody),\n };\n}\n\n/**\n * `job` redacted on this thread, the request body up to `limit` units and\n * the response's up to `responseLimit`; null (the exchange is not\n * recorded, as when the worker's redaction throws) on a throw, which\n * never reaches the page.\n */\nfunction mainThread(\n job: BodyJob,\n limit: number,\n responseLimit = limit,\n): BodyOut | null {\n try {\n return code!.redactBodies(job, limit, responseLimit);\n } catch {\n return null;\n }\n}\n\n/** UTF-16 units in `job`'s bodies. */\nfunction size(job: BodyJob | null): number {\n return (job?.requestBody?.length ?? 0) + (job?.responseBody?.length ?? 0);\n}\n\n/**\n * One capture's bodies on their way to the recording. `record` is called\n * once per job, with its bodies as recorded, or null for a job whose\n * redaction threw (the exchange is not recorded, as when redaction threw\n * on the main thread).\n */\nexport class BodyJobs {\n /** Jobs not yet recorded, in the order they were handed over. */\n private held = new Map<Held, (out: BodyOut | null) => void>();\n\n /**\n * Redact `job`'s bodies, off the main thread, and call `record` with\n * them. A null job has nothing to redact (bodies masked whole), and is\n * recorded in a task of its own.\n */\n redact(\n job: BodyJob | null,\n record: (out: BodyOut | null) => void,\n after?: Promise<void>,\n mark = leaveMark(),\n ): void {\n const held: Held = { job, owner: this, after, mark };\n // Held from now, so now() records it whichever way it goes.\n this.held.set(held, record);\n // Nothing to redact -- bodies masked whole, or none (a failed request,\n // a 204) -- needs neither the worker nor the code: offline, or with\n // both refused, it is recorded as main recorded it, in its task.\n if (!job || (!job.requestBody && !job.responseBody)) {\n held.out = {\n requestBody: job ? job.requestBody : null,\n responseBody: job ? job.responseBody : null,\n };\n }\n // A browser with no idle periods (Safari: later() is the next task,\n // inside the page's burst all the same) gets the body at once, as the\n // SDK has read it, so the burst pays no task of its own for the copy.\n // MEASURED, WebKit 26.6, 50 x 64 KB, time to body against main: +0.6 ms\n // with the copy at once; +6.6 to +18.2 ms (3 runs) with it in a task.\n else if (typeof requestIdleCallback === \"undefined\") {\n held.sent = true;\n post(held);\n }\n // Its task, as #65's: once the relay is over (`after`), in an idle\n // period where the browser has one. That is where main redacted it,\n // and where its bodies go to the worker: never inside the page's own\n // burst of responses, which then pays no copy either. MEASURED at 4x\n // CPU throttling, with each body posted at once and each answer\n // recorded the moment it came: the burst's time to body 99 -> 110 ms\n // and its longest freeze 50 -> 101 ms against main. The moments that\n // cannot wait for the worker -- the network back online, a hidden\n // tab, stop(), pagehide -- record it there (now()).\n void Promise.resolve(after).then(() =>\n later(() => {\n if (!this.held.has(held)) return;\n if (held.out !== undefined) this.answer(held, held.out);\n else if (!held.sent) post(held);\n }),\n );\n }\n\n /** True while a job is held. */\n holds(): boolean {\n return this.held.size > 0;\n }\n\n /** True while `held` is held: not yet recorded. */\n has(held: Held): boolean {\n return this.held.has(held);\n }\n\n /**\n * The worker's answer for `held`: kept, and recorded in an idle period\n * of its own (the event's headers, URL and serialisation run on this\n * thread, never beside the page's work); now() records it at once.\n */\n answered(held: Held, out: BodyOut | null): void {\n if (!this.held.has(held)) return;\n held.out = out;\n // After the relay too (`after`): never while the page reads the rest\n // of a body past the cap, on any path.\n void Promise.resolve(held.after).then(() =>\n later(() => this.answer(held, out)),\n );\n }\n\n /** Record `held` with `out`, once. */\n answer(held: Held, out: BodyOut | null): void {\n const record = this.held.get(held);\n if (!record) return;\n this.held.delete(held);\n // Recorded: out of the page-wide wait at once, and its bodies with it,\n // though a worker that never answers keeps it posted.\n starting.delete(held);\n held.job = null;\n record(out);\n }\n\n /**\n * With no worker: redact `held` here, in a task of its own once the relay\n * is over, each body up to the budget (the founder's rule is per body: a\n * body of 64 KiB or less is redacted whole, as it always was).\n */\n alone(held: Held): void {\n void Promise.all([loadCode(), held.after]).then(() =>\n later(() => {\n if (!this.held.has(held)) return;\n const job = held.job!;\n // No code either (neither chunk loaded): nothing to redact with,\n // so the body is recorded as not captured, the code having failed.\n this.answer(\n held,\n code ? mainThread(job, MAIN_THREAD_BODY_BUDGET) : noted(job),\n );\n }),\n );\n }\n\n /**\n * Record now, on this thread, the jobs still held, within\n * MAIN_THREAD_BODY_BUDGET units in all: those that fit whole first, in\n * the order handed over, then the rest; each keeps its place (seq). `final` is\n * a moment after which nothing more is recorded (pagehide, settle()'s\n * bound): a job past the budget is recorded cut, and one whose code has\n * not loaded as not captured (noted: `left` while the code is on its\n * way, `code-failed` when it failed for good), so the exchange is never\n * lost and no body is recorded in the clear. Other\n * moments (a hidden tab's drain, stop()) record only what fits whole,\n * and leave the rest to the worker.\n */\n now(final: boolean): void {\n let left = MAIN_THREAD_BODY_BUDGET;\n // First every job that fits whole, in the order handed over -- a\n // login's small response is not spent on a large body ahead of it --\n // then, at a moment after which nothing is recorded, the rest, cut to\n // what is left of the budget: the request body first, the response\n // after it, never more than `left` units between them.\n for (const pass of final ? [true, false] : [true]) {\n for (const held of [...this.held.keys()]) {\n // Answered by the worker, waiting for its task: nothing to redact.\n if (held.out !== undefined) {\n this.answer(held, held.out);\n continue;\n }\n const job = held.job;\n if (!job) {\n this.answer(held, { requestBody: null, responseBody: null });\n continue;\n }\n const units = size(job);\n if (pass && !(code && units <= left)) continue;\n const request = Math.min(job.requestBody?.length ?? 0, left);\n this.answer(\n held,\n code ? mainThread(job, request, left - request) : noted(job),\n );\n left -= pass ? units : left;\n }\n }\n }\n}\n\n/** Exposed for tests: the chunk loaders, and the page's worker forgotten. */\nexport const __bodyJobs = {\n /** Load the code and the worker's start with these from now on (the page's import() when none), forgetting any worker so far. */\n loaders(\n codeLoader?: () => Promise<BodyCode>,\n startLoader?: () => Promise<WorkerStart>,\n ): void {\n try {\n worker?.terminate();\n } catch {\n // A fake worker may not implement it.\n }\n // Through ownChunk, as the page's own: the leave gate holds them too.\n load = {\n code: codeLoader ? () => ownChunk(codeLoader) : importCode,\n start: startLoader ? () => ownChunk(startLoader) : importStart,\n };\n unwait?.();\n code = codeLoad = worker = running = online = undefined;\n soonIdle = soonTask = false;\n kept = undefined;\n warned = \"\";\n workerStarting = false;\n starting = new Set();\n posted.clear();\n codeOffline = codeFailed = false;\n __leave.reset();\n },\n /** The worker as it stands: undefined (not asked for), null (none), or the worker. */\n worker: (): Worker | null | undefined => worker,\n /** prepare() is due in a task of its own (prepareSoon's idle or next task). */\n soon: (): boolean => soonIdle || soonTask,\n /** Jobs not yet recorded that wait for the worker's start, in the page-wide wait (starting). */\n starting: (): number =>\n [...starting].filter((held) => held.owner.has(held)).length,\n /** Every job in the page-wide wait, recorded or not. */\n waiting: (): number => starting.size,\n /** UTF-16 units of body the page's worker plumbing still holds (the wait, and jobs posted): none once recorded. */\n retained: (): number =>\n [...starting, ...posted.values()].reduce(\n (units, held) => units + size(held.job),\n 0,\n ),\n};\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - could a body be a GraphQL request? */\n/* ------------------------------------------------------------------ */\n/*\n * The term code (request-term.ts: the lexer, the document check, the\n * hash) is a chunk of its own, loaded only for a body that passes\n * couldBeGraphql(); every other body is recorded here, at once, and the\n * chunk is never fetched. So the check must be a SUPERSET of what the\n * term code gives a term: a GraphQL body it missed would be recorded ''\n * while replay computes its term from postData(), and the keys would\n * differ.\n *\n * DERIVED FROM THE TERM CODE'S OWN ENTRY CONDITIONS (spec/canonical-\n * key.v2.json rules.term and rules.document; request-term.ts prepare()),\n * not from examples. A body has a term only when:\n * 1. it parses as ONE JSON value with nothing but JSON's whitespace\n * (U+0020, U+0009, U+000A, U+000D) before it -- a byte order mark\n * is refused -- and that value is an OBJECT, so the first character\n * that is not JSON whitespace is `{`; and\n * 2. it has a documentId, which needs a member named `query` (a string\n * that is a document) or a member named `persistedQuery` (inside\n * `extensions`). A member name is a JSON string: written with no\n * escape it is exactly `\"query\"`, quotes included, or holds\n * `persistedQuery`; written with any escape it holds `\\u`, the only\n * JSON escape that yields a letter.\n * So a batch (`[...]`), a raw application/graphql document (`{ me { id\n * } }`, `query Q { ... }`), a form and plain text have no term on either\n * side, and a GET has no body to read (the live term is\n * term(request.postData())). __tests__/term-candidate.test.ts runs every\n * term vector and every e2e GraphQL body through the check.\n */\n\n/** Longer bodies (UTF-16 units) are recorded \"body:*\": bounded work, and no literal long enough to strain a regex engine. */\nexport const MAX_TERM_BODY = 4 * 1024 * 1024;\n\n/** Text that starts as a JSON object does: JSON whitespace, then `{` (condition 1 above). */\nexport const OBJECT_START = /^[\\t\\n\\r ]*\\{/;\n\n/** The first character that is not JSON whitespace. */\nexport const NOT_SPACE = /[^\\t\\n\\r ]/;\n\n/** True when `text` could be a body the term code gives a term (see above). */\nexport function couldBeGraphql(text: string): boolean {\n return (\n OBJECT_START.test(text) &&\n (text.includes('\"query\"') ||\n text.includes(\"persistedQuery\") ||\n text.includes(\"\\\\u\"))\n );\n}\n\n/**\n * The requestTerm of a body AS THE APP HANDED IT to fetch or XHR when it\n * needs no term code: '' for no body, a form, or text that cannot be a\n * GraphQL request; \"body:*\" for a body that is not text (a Blob, a\n * buffer, a stream, a Document) or is longer than MAX_TERM_BODY. null\n * when the body could be a GraphQL request: the term code decides it.\n */\nexport function termBeforeLoad(body: unknown): string | null {\n if (body == null || body === \"\") return \"\";\n if (typeof body === \"string\")\n return body.length > MAX_TERM_BODY\n ? \"body:*\"\n : couldBeGraphql(body)\n ? null\n : \"\";\n // Sent as form text, which is never a JSON object.\n if (\n body instanceof URLSearchParams ||\n (typeof FormData !== \"undefined\" && body instanceof FormData)\n )\n return \"\";\n return \"body:*\";\n}\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - Network interceptor */\n/* ------------------------------------------------------------------ */\n\nimport { askForCode, BodyJobs, prepareSoon } from \"./body-jobs\";\nimport { ownChunk } from \"./module-of\";\nimport type {\n CaptureConfig,\n NetworkEvent,\n NetworkEventCallback,\n PrivacyConfig,\n} from \"./types\";\nimport { MASKED, PrivacyEngine } from \"./privacy\";\n// What a cut body is marked with, so the recording says it was cut; the\n// form redactor reads the same marker.\nimport { TRUNCATED_SUFFIX } from \"./redact\";\nimport { MAX_TERM_BODY, NOT_SPACE, termBeforeLoad } from \"./term-candidate\";\nimport { describeValue, termWarningLine } from \"./errors\";\nimport { leaveMark, unlessHeld } from \"./leave\";\n\n/*\n * THE TERM CODE IS A CHUNK OF ITS OWN: request-term.ts (the lexer, the\n * document check, the hash), loaded the first time a body could be a\n * GraphQL request (termBeforeLoad() answers every other body at once),\n * and once per page: the promise is kept, a failed load included. It is\n * imported by the package's own name, which the package's exports map\n * resolves to dist/request-term.{mjs,js}, as a consumer's bundler\n * resolves import(\"rrweb\") -- the build cannot split a CommonJS build,\n * so a relative import() of the source would be inlined -- or, on a page\n * that maps no such name, by its built file beside the SDK's (ownChunk),\n * a path the build keeps external, through the leave gate (leave.ts:\n * never asked for while the page leaves, and asked for once more when a\n * leave cut it short). A load\n * that fails (a CSP, offline, a 404 on the chunk) records such a body\n * as body:* -- as a page with no SubtleCrypto does -- and says\n * KUI_E_REQUEST_TERM_FAILED once per capture (termFor()). One the leave\n * holds records it body:* too, at once and unsaid (unlessHeld): a leave\n * is no failure, and one that never ends (a 204, a download) kept every\n * later request's event, never recorded, for the page's life.\n */\ntype TermCode = typeof import(\"./request-term\");\nlet termCode: Promise<TermCode> | undefined;\n/** The term code has loaded: no leave holds it (termFor). */\nlet termLoaded = false;\nconst pageImport = (): Promise<TermCode> =>\n ownChunk(\n () => import(\"@keploy/capture-sdk/request-term\"),\n // oxlint-disable-next-line no-undef -- a constant of the build (scripts/build-main.mjs), declared in build-flags.d.ts: true in dist/index.mjs alone\n __BESIDE__ ? () => import(\"./request-term.mjs\" as string) : undefined,\n );\nlet importTermCode = pageImport;\nconst loadTermCode = (): Promise<TermCode> => {\n if (!termCode) {\n termCode = importTermCode().then((code) => ((termLoaded = true), code));\n // Handled from its creation: a load first asked for while the leave\n // stands has no waiter (unlessHeld), and, failing for real once the\n // page has stayed, it rejected unhandled -- \"Uncaught (in promise)\" on\n // the page. The next request that waits on it says why (termFor()).\n termCode.catch(() => {});\n }\n return termCode;\n};\n\n/* ------------------------------------------------------------------ */\n/* Helpers */\n/* ------------------------------------------------------------------ */\n\n/** Resolve a URL the way the browser will, so two spellings compare equal. */\nfunction absolute(url: string): string {\n try {\n const base = typeof document !== \"undefined\" ? document.baseURI : undefined;\n return new URL(url, base).href;\n } catch {\n return url;\n }\n}\n\nfunction headersToRecord(\n headers: Headers | HeadersInit | undefined | null,\n): Record<string, string> {\n const result: Record<string, string> = {};\n if (!headers) return result;\n\n if (headers instanceof Headers) {\n headers.forEach((value, key) => {\n result[key] = value;\n });\n } else if (Array.isArray(headers)) {\n for (const [key, value] of headers) {\n result[key] = value;\n }\n } else {\n Object.assign(result, headers);\n }\n return result;\n}\n\n/**\n * Cut a recorded body at `maxBodySize`.\n *\n * ONE RULE IN ONE PLACE. The cap was written out at six call sites and\n * missed the seventh: an XHR FormData body was assembled and recorded\n * WHOLE, however large. An upload form with a base64 field put\n * megabytes into one event — past the queue's byte accounting, and far\n * past the 32 KiB the page-unload flush can carry, so it held back\n * everything behind it there too.\n *\n * THE CAP COUNTS UTF-16 CODE UNITS, not bytes: the unit a JS string is\n * measured in, equal to bytes for ASCII and up to 2x under it for\n * multi-byte text. `maxBodySize` is a bound on what is RECORDED, not an\n * exact byte budget, and counting bytes would mean a TextEncoder pass\n * over every body the page sends. The option's docs say so.\n */\nfunction truncate(text: string, maxSize: number): string {\n return text.length > maxSize\n ? text.slice(0, maxSize) + TRUNCATED_SUFFIX\n : text;\n}\n\n/**\n * A FormData rendered as text, so it can be cut like any other body.\n *\n * FORM-ENCODED, so it parses back into the pairs it came from. It was\n * `key=value` raw, and a value holding `&` or `=` then split into pairs\n * that were not there: `password=ab&cd` read as a redacted `password`\n * and a bare `cd`, which is the second half of the password in clear.\n */\nfunction formDataText(body: FormData): string {\n const enc = (text: string) => encodeURIComponent(text).replace(/%20/g, \"+\");\n const parts: string[] = [];\n body.forEach((value, key) => {\n parts.push(\n typeof value === \"string\"\n ? `${enc(key)}=${enc(value)}`\n : // Encoded like every other value: raw spaces here made the\n // whole rendering not a form, and a password beside a file\n // then kept everything after its first `(` or `'`.\n `${enc(key)}=${enc(`[File: ${value.name}, ${value.size} bytes]`)}`,\n );\n });\n return parts.join(\"&\");\n}\n\n/**\n * The body an XHR was sent with, as it is recorded.\n *\n * Exported through `__internals` because the only other way to reach it\n * is a real XMLHttpRequest against a real server, and the rules under\n * test — that every shape faces the cap, and that a shape the SDK does\n * not read is named with its kind and its size — are about this\n * function.\n *\n * EVERY SHAPE, NOT ONE. This returned `[Binary/Document body]` for a\n * Blob, an ArrayBuffer, a view and a Document alike: no kind, no size,\n * and a string the npm page never listed among the notes it promised.\n * `xhr.send(blob)` with a 2 MB Blob therefore recorded strictly less\n * than `fetch` recorded for the same Blob, which answered `[Blob: N\n * bytes, truncated]`.\n *\n * A BLOB IS NAMED, NOT READ, and that is the one place this path\n * cannot match fetch's: Blob.text() is async and the body must be\n * serialised inside send(), before the request goes out.\n */\nfunction serializeXhrBody(\n body: Document | XMLHttpRequestBodyInit | null | undefined,\n maxSize: number,\n): string | null {\n if (body == null) return null;\n if (typeof body === \"string\") return truncate(body, maxSize);\n if (body instanceof FormData) return truncate(formDataText(body), maxSize);\n if (body instanceof URLSearchParams)\n return truncate(body.toString(), maxSize);\n if (typeof Blob !== \"undefined\" && body instanceof Blob)\n return `[Blob: ${body.size} bytes]`;\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body))\n return binaryBody(body, maxSize);\n if (typeof Document !== \"undefined\" && body instanceof Document) {\n // What the browser sends for a Document IS its serialisation, so\n // there is text here and it faces the cap like any other text.\n try {\n return truncate(new XMLSerializer().serializeToString(body), maxSize);\n } catch {\n return \"[Unreadable body]\";\n }\n }\n // Fail closed. XMLHttpRequestBodyInit has no other member today; a\n // body this function cannot name is never passed through.\n return \"[Unreadable body]\";\n}\n\n/**\n * A buffer body: its text if it is text and fits, otherwise a note.\n *\n * FATAL, DELIBERATELY. A default TextDecoder never throws — it\n * substitutes U+FFFD — so a protobuf or a gzip payload under the cap\n * was recorded as a run of replacement characters, the catch below was\n * unreachable, and the recording kept neither the bytes nor the fact\n * that it was binary. `fatal: true` makes \"this is not text\" an answer\n * the note can carry.\n *\n * THE VIEW, NOT ITS BUFFER. `body.buffer` is the whole allocation a\n * view looks into. MEASURED in body-size.test.ts: a 4-byte view onto a\n * 256-byte pool — what a slice of a preallocated buffer is — was\n * recorded as `[Binary: 256 bytes]`, a note whose size is wrong, and\n * under a larger cap it decoded the entire pool: a body the request\n * never sent.\n */\nfunction binaryBody(\n body: ArrayBuffer | ArrayBufferView,\n maxSize: number,\n): string {\n const bytes =\n body instanceof ArrayBuffer\n ? new Uint8Array(body)\n : new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n if (bytes.byteLength > maxSize) return `[Binary: ${bytes.byteLength} bytes]`;\n try {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n return `[Binary: ${bytes.byteLength} bytes]`;\n }\n}\n\nasync function serializeBody(\n body: BodyInit | null | undefined,\n maxSize: number,\n): Promise<string | null> {\n if (body == null) return null;\n\n try {\n if (typeof body === \"string\") return truncate(body, maxSize);\n if (body instanceof URLSearchParams)\n return truncate(body.toString(), maxSize);\n if (body instanceof FormData) return truncate(formDataText(body), maxSize);\n if (body instanceof Blob) {\n if (body.size > maxSize) return `[Blob: ${body.size} bytes, truncated]`;\n const text = await body.text();\n return text;\n }\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body))\n return binaryBody(body, maxSize);\n // ReadableStream - we don't consume it (would break the request).\n return \"[ReadableStream]\";\n } catch {\n return \"[Unreadable body]\";\n }\n}\n\n/*\n * BODIES MASKED WHOLE ARE NEVER READ. Under `maskNetworkBodies` (which\n * `privacyMode: \"strict\"` always sets) a body is recorded MASKED\n * whatever it holds, and null when there is none (PrivacyEngine\n * maskNetworkData). The SDK used to read every body all the same -- a\n * Blob's text(), a buffer's decode, a FormData's encoding, and every\n * response through its relay -- and then threw what it read away. It is\n * decided instead from what the body IS, before anything touches it, so\n * the page's request and Response are the page's own: nothing read,\n * cloned, teed or relayed.\n */\n\n/**\n * A request body as recorded when bodies are masked whole: null when\n * serializeBody (fetch) or serializeXhrBody (`xhr`) would have answered\n * none or \"\", MASKED for any other answer -- from the body's kind and\n * size, never its content.\n */\nfunction maskedSent(body: unknown, xhr: boolean): string | null {\n if (body == null) return null;\n try {\n if (typeof body === \"string\") return body === \"\" ? null : MASKED;\n // Rendered `k=v&...`: empty only with no pair at all.\n if (body instanceof URLSearchParams || body instanceof FormData)\n return body.keys().next().done ? null : MASKED;\n // An XHR's Blob is named, `[Blob: 0 bytes]`, however small.\n if (body instanceof Blob) return xhr || body.size > 0 ? MASKED : null;\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body))\n return body.byteLength > 0 ? MASKED : null;\n // An XHR's Document is its serialisation: \"\" only with no node in it.\n if (xhr && typeof Document !== \"undefined\" && body instanceof Document)\n return body.hasChildNodes() ? MASKED : null;\n } catch {\n // Recorded as the fail-closed note: a body.\n }\n // A stream or any other shape: a note, `[ReadableStream]` or\n // `[Unreadable body]`.\n return MASKED;\n}\n\n/**\n * A fetch response's body as recorded when bodies are masked whole,\n * decided from its body's presence and its headers (a HEAD's, a 204's, a\n * 205's and a 304's are decided before it, in every mode: recorded\n * empty): null when there is no body (a null body), or the network\n * declared it empty (Content-Length 0), or it is locked (the relay could\n * not have read it); MASKED otherwise, a body too large to read included.\n * A body whose length was not declared is MASKED unread: recorded as a\n * body, which it is unless it turns out empty. (A fetch polyfill's\n * Response has no `body` at all, undefined: decided by its headers as any\n * other.)\n */\nfunction maskedResponse(response: Response): string | null {\n const none =\n response.body === null ||\n response.body?.locked ||\n /^\\s*0+\\s*$/.test(response.headers.get(\"content-length\") ?? \"\");\n return none ? null : MASKED;\n}\n\n/** An XHR's response body as recorded when bodies are masked whole (see maskedResponse). */\nfunction maskedXhrResponse(xhr: XMLHttpRequest): string | null {\n // responseText throws for any other type: recorded `[json response]`.\n if (xhr.responseType !== \"\" && xhr.responseType !== \"text\") return MASKED;\n try {\n // The text the browser already holds: only whether it is empty is asked.\n return xhr.responseText ? MASKED : null;\n } catch {\n return MASKED;\n }\n}\n\n/**\n * Brand check, not `instanceof`: a Request made in another realm (a\n * same-origin iframe calling the top page's fetch) is not an instance of\n * this realm's Request, and would be consumed below like any other.\n */\nfunction isRequest(value: unknown): value is Request {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { [Symbol.toStringTag]?: unknown })[Symbol.toStringTag] ===\n \"Request\"\n );\n}\n\n/** A content-type under which a body is multipart form data. */\nconst MULTIPART_TYPE = /^\\s*multipart\\/form-data\\s*(?:;|$)/i;\n\n/**\n * The body inside a Request, from the SDK's copy, UNCUT: the caller cuts\n * what it records and computes canonical-key.v2's term over this text.\n *\n * A MULTIPART one is parsed back into its fields and rendered as a\n * FormData passed directly is, so its values are redacted by name and the\n * recording does not carry the per-request boundary. Never recorded raw:\n * one that does not parse REJECTS, and the caller records the fail-closed\n * note and keys it body:* -- its text is unknown here, and replay\n * computes a term from it (a JSON body sent under a multipart type has\n * one).\n *\n * Any other is read only as far as it is needed: to the cap, and past it\n * only while the text could still be a GraphQL request (a JSON object:\n * JSON whitespace only so far, or then `{`), up to the term's own bound\n * (MAX_TERM_BODY), since a term over a cut body is wrong. Firefox has no\n * `body` on a Request at all; its body is in memory there (no streamed\n * uploads), and only as much of it is decoded as that needs (three bytes\n * per UTF-16 unit). Answers undefined for no body (Firefox: an empty\n * Blob) and null for one that cannot be read.\n *\n * MASKED (`masked`, bodies masked whole): the text is read only for the\n * term, and a body whose first character that is not JSON whitespace is\n * not `{` has the term '' and is recorded MASKED whatever follows, so it\n * is read no further than that character (stops()). A multipart body is\n * still parsed: whether it parses decides its term ('' or body:*).\n */\nfunction readRequestBody(\n copy: Request,\n maxSize: number,\n masked = false,\n): Promise<string | null | undefined> {\n if (MULTIPART_TYPE.test(copy.headers.get(\"content-type\") ?? \"\"))\n return copy.formData().then(formDataText);\n const body = copy.body;\n if (body) return readRequestCopy(body, maxSize, masked);\n const cap = maxSize * 3 + 4;\n return copy\n .blob()\n .then(async (blob) => {\n // No body at all: none, as in every other engine (recorded null,\n // keyed ''), never unreadable.\n if (blob.size === 0) return;\n if (masked) {\n const start = await decoded(blob.slice(0, 1024));\n if (stops(start, maxSize)) return start;\n }\n const head = await decoded(blob.slice(0, cap));\n // Still an object's start: JSON whitespace only so far, or then `{`.\n return blob.size > cap && /^[\\t\\n\\r ]*(?:\\{|$)/.test(head)\n ? decoded(blob.slice(0, MAX_TERM_BODY * 3 + 4))\n : head;\n })\n .catch(() => null);\n}\n\n/**\n * UTF-8 that KEEPS a leading byte order mark. Replay computes the live\n * term over Playwright's postData(), which keeps it, and a body that\n * starts with one has no term (JSON allows nothing before its value); a\n * default decoder, Blob.text() included, drops it, and the SDK then\n * recorded a GraphQL term the live request never has.\n */\nconst utf8 = (): TextDecoder => new TextDecoder(\"utf-8\", { ignoreBOM: true });\n\n/**\n * Whether a masked body read so far as `text` is known enough: its first\n * character that is not JSON whitespace is there and is not `{`, so its\n * term is '' (or body:* past MAX_TERM_BODY, which a cap under it decides\n * the same way) and it is recorded MASKED.\n */\nconst stops = (text: string, maxSize: number): boolean =>\n maxSize < MAX_TERM_BODY && (NOT_SPACE.exec(text)?.[0] ?? \"{\") !== \"{\";\n\n/** A Blob's bytes as text (utf8()). */\nconst decoded = async (blob: Blob): Promise<string> =>\n utf8().decode(await blob.arrayBuffer());\n\n/**\n * Read a Request copy's stream as text, uncut: to `maxSize` UTF-16 units,\n * past it only while it could be a GraphQL request, to MAX_TERM_BODY\n * (readRequestBody). null when it cannot be read.\n */\nasync function readRequestCopy(\n body: ReadableStream<Uint8Array>,\n maxSize: number,\n masked: boolean,\n): Promise<string | null> {\n const reader = body.getReader();\n const decoder = utf8();\n let text = \"\";\n // The first character that is not JSON whitespace, once read. Only the\n // newly decoded part is scanned, so each character is looked at at most\n // once however the body arrives: scanning the whole text read so far\n // made a body streamed in small chunks quadratic (a concatenated string\n // is flattened for each scan).\n let first = \"\";\n try {\n for (;;) {\n const next = await reader.read();\n if (next.done) return text + decoder.decode();\n const part = decoder.decode(next.value, { stream: true });\n if (!first) first = NOT_SPACE.exec(part)?.[0] ?? \"\";\n text += part;\n if (masked && stops(first, maxSize)) {\n void reader.cancel().catch(() => {});\n return text;\n }\n // Past the cap only while it could be a JSON object (whitespace\n // only so far, or then `{`), up to the term's bound.\n if (\n text.length > maxSize &&\n (text.length > MAX_TERM_BODY || (first !== \"\" && first !== \"{\"))\n ) {\n void reader.cancel().catch(() => {});\n return text;\n }\n }\n } catch {\n return null;\n }\n}\n\n/**\n * Text the SDK stopped reading before its end -- the page left, settle()\n * ended, the body failed -- marked as cut. Always under the cap: a body\n * past it has already been recorded, cut at the cap.\n */\nfunction cutText(text: string): string {\n return text + TRUNCATED_SUFFIX;\n}\n\n/**\n * A body chunk as the platform takes one: a Uint8Array (from any realm),\n * else a TypeError -- what `text()` and the other readers answer for a\n * page-built body that enqueues anything else, without the SDK too.\n */\nfunction bytesOf(value: unknown): Uint8Array {\n // The platform's own TypedArray tag getter: it reads the object's real\n // type (any realm, subclasses included) and runs no code of the page's,\n // where its Symbol.toStringTag could be faked or throw.\n if (typedArrayName(value) === \"Uint8Array\") return value as Uint8Array;\n throw new TypeError(\"a response body chunk is not a Uint8Array\");\n}\n\n/** `%TypedArray%.prototype[Symbol.toStringTag]`'s getter: a typed array's name, else undefined. */\nconst typedArrayTag: unknown = Reflect.get(\n Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(Uint8Array.prototype) as object,\n Symbol.toStringTag,\n ) ?? {},\n \"get\",\n);\nfunction typedArrayName(value: unknown): unknown {\n return typeof typedArrayTag === \"function\"\n ? Reflect.apply(typedArrayTag, value, [])\n : undefined;\n}\n\n/** The underlying-source type of a byte stream. */\nconst BYTE_SOURCE = \"bytes\";\n\n/** What the relay calls on its page stream's controller, default or byte. */\ninterface PageController {\n enqueue(chunk: Uint8Array): void;\n close(): void;\n error(reason?: unknown): void;\n readonly byobRequest?: { respond(bytesWritten: number): void } | null;\n}\n\n/** The members a Response the SDK builds takes from the network's own: what `new Response()` cannot set. */\nconst NETWORK_MEMBERS = [\"url\", \"redirected\", \"type\", \"headers\"] as const;\n\n/**\n * Give `page` the network's url, redirected, type and headers, and a\n * clone() whose result has them too. Own, non-enumerable accessors on\n * that one object: a constructed Response has no URL list, type\n * \"default\" and a mutable Headers, and the page must read the network's.\n */\nfunction dress(page: Response, network: Response): void {\n for (const name of NETWORK_MEMBERS) {\n Object.defineProperty(page, name, {\n get: () => network[name],\n configurable: true,\n });\n }\n // Read by descriptor: it is called with an explicit receiver.\n const clone = Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(page) as object,\n \"clone\",\n )?.value as ((this: Response) => Response) | undefined;\n if (!clone) return;\n Object.defineProperty(page, \"clone\", {\n value: function (this: Response): Response {\n const copy = clone.call(this);\n dress(copy, network);\n return copy;\n },\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * A response body, recorded by the SDK as the ONE reader of the\n * network's body and handed on to the page through a stream of the\n * SDK's own, in a Response the page gets as soon as the headers are in.\n *\n * WHY NOT A CLONE. The interceptor read every response from\n * `response.clone()` and handed the page its Response only when that\n * read had finished, so a streamed response -- SSE over fetch, NDJSON,\n * an LLM's tokens, a live log view -- reached the page only when it\n * ended, and an endless one never. Handing the Response over first and\n * reading the clone beside it is not enough either: in Chromium a clone\n * of a network body is a tee that reads the network as fast as it\n * delivers, whatever either branch reads (MEASURED: a page reading a\n * 300 MB chunked body slowly held +332 MB with the SDK, +83 MB without),\n * and a tee cancels its source only when BOTH branches cancel, so a\n * page's \"Stop generating\" never reached the server while the SDK's copy\n * read on.\n *\n * So the SDK reads the network's body itself, once, and passes each\n * chunk on to the page as the page asks for it:\n *\n * - The page's stream has a high-water mark of 0: a chunk is handed over\n * when the page reads, the moment the network delivers it.\n * - The SDK reads AHEAD of the page only until it has the recording --\n * the whole body, or more than `maxSize` units of it -- so a body the\n * page never reads is still recorded, as it always was, and what is\n * held for a slow page is bounded by the cap. Past that, a read of the\n * network happens only for a page read: the network's backpressure is\n * the page's.\n * - The page's cancel IS the network's: cancel(), a reader's cancel(), a\n * for-await `break`, a pipe that stops -- every way the page can stop\n * reaches this stream's cancel and goes straight on to the network.\n * - An error or an abort of the network's body is the page's at once.\n *\n * What is recorded: the body as `text()` decodes it, cut at `maxSize`\n * with the marker -- the same value as before -- when the network's body\n * ends or passes the cap, whichever comes first. A page that stops\n * reading before either is recorded with exactly what IT read, unmarked:\n * that is what the page saw of the exchange, and a page that cancels\n * after its last byte (a reader that stops at `data: [DONE]`) is\n * recorded whole whether or not the network's end came first.\n *\n * Returns null, leaving the network's Response untouched, when there is\n * no body to relay or the platform will not build one around it.\n */\nfunction relayResponse(\n network: Response,\n maxSize: number,\n report: (body: string | null) => void,\n): { page: Response; cut: () => void; done: Promise<void> } | null {\n const body = network.body;\n if (!body) return null;\n // The platform's own classes, read off the objects the network made: a\n // page that loads a streams or fetch polyfill replaces the globals, and\n // the network's body and Response are still the platform's.\n const Stream = (Object.getPrototypeOf(body) as ReadableStream)\n .constructor as typeof ReadableStream;\n const PageResponse = (Object.getPrototypeOf(network) as Response)\n .constructor as typeof Response;\n\n const decoder = new TextDecoder();\n /** The body as decoded so far (`stream: true`), until it passes the cap. */\n let text = \"\";\n /** The recording is past the cap, and reported. */\n let over = false;\n let ended = false;\n let stopped = false;\n let reported = false;\n let reading = false;\n /** Chunks read and not yet handed to the page, each with the text length once it is decoded. */\n const queue: Array<{ chunk: Uint8Array; textEnd: number }> = [];\n /** How much of `text` the page has been handed. */\n let pageText = 0;\n /** A page read waiting for a chunk. */\n let waiting: (() => void) | null = null;\n let controller: PageController | null = null;\n /** The relay is over: the network's body ended, failed, or the page cancelled. */\n let finished!: () => void;\n const done = new Promise<void>((resolve) => (finished = resolve));\n\n const once = (value: string | null): void => {\n if (reported) return;\n reported = true;\n report(value);\n };\n\n const hand = (): void => {\n if (!waiting || !controller) return;\n const next = queue.shift();\n if (next) {\n // A byte stream's enqueue() transfers (detaches) the chunk's buffer,\n // which the body's source may still hold -- a pooled buffer, or a\n // constant chunk a page-built body enqueues again and again. The\n // page is handed a copy; the source's buffer is never taken.\n // Copied by the constructor, not by the chunk's own slice(): a\n // Buffer polyfill's slice() is a view onto the same memory.\n controller.enqueue(new Uint8Array(next.chunk));\n pageText = next.textEnd;\n } else if (ended) {\n controller.close();\n // A BYOB read waiting at the end is answered with no bytes.\n controller.byobRequest?.respond(0);\n } else {\n return;\n }\n const resolve = waiting;\n waiting = null;\n resolve();\n };\n\n const pump = (): void => {\n if (reading || ended || stopped) return;\n // Ahead of the page only until the recording is had.\n if (over && !waiting) return;\n reading = true;\n reader.read().then(\n (next) => {\n reading = false;\n if (stopped) return;\n try {\n if (next.done) {\n ended = true;\n finished();\n if (!over) once(truncate(text + decoder.decode(), maxSize));\n } else {\n const chunk = bytesOf(next.value);\n // An empty chunk (a page-built body may enqueue one) is nothing\n // to hand over: a byte stream refuses it.\n if (chunk.byteLength > 0) {\n if (!over) {\n text += decoder.decode(chunk, { stream: true });\n if (text.length > maxSize) {\n over = true;\n // A body still arriving a second after its cap is a\n // stream, or one the page is not reading: its event is\n // masked then (emit), not held to its end.\n setTimeout(finished, 1_000);\n once(truncate(text, maxSize));\n text = \"\";\n }\n }\n queue.push({ chunk, textEnd: text.length });\n }\n }\n hand();\n pump();\n } catch (err) {\n // A chunk that is not bytes (a page-built body under the SDK)\n // fails the body as the platform's own read of it would: the\n // page's read rejects, the network is let go. Never a page read\n // left waiting.\n fail(err);\n void reader.cancel(err).catch(() => {});\n }\n },\n (reason: unknown) => {\n reading = false;\n if (stopped) return;\n fail(reason);\n },\n );\n };\n\n /** The body failed: what had arrived is recorded cut, and the page's stream is errored at once. */\n const fail = (reason: unknown): void => {\n stopped = true;\n finished();\n // The body never finished: what had arrived is recorded, cut and\n // marked, as a pagehide or settle() cut records it. Firefox and\n // WebKit abort a document's fetches when it navigates, BEFORE\n // pagehide (MEASURED), so this is where a page that leaves mid-body\n // is cut there. (Past the cap the recording is already reported.)\n once(cutText(text));\n queue.length = 0;\n try {\n controller?.error(reason);\n } catch {\n // Already closed or errored.\n }\n const resolve = waiting;\n waiting = null;\n resolve?.();\n };\n\n const source = {\n start(c: PageController) {\n controller = c;\n },\n pull() {\n return new Promise<void>((resolve) => {\n waiting = resolve;\n hand();\n pump();\n });\n },\n cancel(reason: unknown) {\n stopped = true;\n finished();\n // What the page read, as it read it: never a marker. (Past the\n // cap the recording is already reported, and this does nothing.)\n once(text.slice(0, pageText));\n queue.length = 0;\n return reader.cancel(reason);\n },\n };\n // A BYTE stream, as the network's body is (Fetch spec), so a page's\n // `getReader({ mode: \"byob\" })` works as it does without the SDK; a\n // platform without byte streams gets a default one.\n let pageStream: ReadableStream<Uint8Array>;\n try {\n pageStream = new Stream(\n {\n ...source,\n type: BYTE_SOURCE,\n } as unknown as UnderlyingDefaultSource<Uint8Array>,\n { highWaterMark: 0 },\n );\n } catch {\n pageStream = new Stream(\n source as unknown as UnderlyingDefaultSource<Uint8Array>,\n { highWaterMark: 0 },\n );\n }\n\n let page: Response;\n try {\n page = new PageResponse(pageStream, {\n status: network.status,\n statusText: network.statusText,\n headers: network.headers,\n });\n } catch {\n return null;\n }\n // Taken only once the page's Response is built, so a body the platform\n // will not rebuild is left to the page unlocked. Throws for a body\n // already locked or read: the caller records that as unreadable and the\n // page gets the network's Response as it came. (The closures above use\n // it only once the page reads, after this line.)\n const reader = body.getReader();\n dress(page, network);\n pump();\n return {\n page,\n cut: () => {\n if (!over) once(cutText(text));\n // The recording is final once cut (pause(), pagehide, settle()'s\n // bound): what waits for the relay to be over -- the body's copy to\n // the worker, its redaction here -- need not wait for a stream that\n // may never end.\n finished();\n },\n done,\n };\n}\n\n/**\n * The URL the RECORDING carries: the WHATWG serialization of what the\n * app passed, resolved against the document.\n *\n * `spec/canonical-key.v1.json` computes the key over the serialized\n * absolute URL at both ends. Replay keys Playwright's `request.url()`,\n * which is that form; the recorder has to supply the same form or the\n * stored key and the live key disagree on exactly the inputs a browser\n * rewrites before sending -- a default port (`:443` is gone on the\n * wire), a protocol-relative `//host` (the browser fills in the page's\n * scheme), non-ASCII (percent-encoded), `..` (resolved). `fetch` was\n * already covered because `new Request(input).url` IS this\n * serialization; `XMLHttpRequest.open` recorded the raw string, so an\n * app that opened `/api/jobs/42` recorded a key nothing at replay could\n * match. Both paths go through here now.\n *\n * `document.baseURI` is the base a browser resolves against, `<base\n * href>` included. Outside a document (a worker) `location.href` is the\n * base. The raw string is returned only when neither exists AND the\n * value is already absolute -- the one case where there is nothing to\n * resolve against and nothing to resolve.\n */\nexport function recordedUrl(raw: string): string {\n const base =\n typeof document !== \"undefined\" && document.baseURI\n ? document.baseURI\n : typeof location !== \"undefined\"\n ? location.href\n : undefined;\n return new URL(raw, base).href;\n}\n\n/* ------------------------------------------------------------------ */\n/* NetworkInterceptor */\n/* ------------------------------------------------------------------ */\n\nexport class NetworkInterceptor {\n private callback: NetworkEventCallback | null = null;\n private privacyEngine: PrivacyEngine;\n private maxBodySize: number;\n /** Absolute URLs never observed — the SDK's own ingest endpoint. */\n private ignored: Set<string>;\n private active = false;\n /**\n * Exchanges answered while recording whose bodies are still being read\n * for the recording, and events reported and still waiting for their\n * task (see emit). The page has its Response already (see\n * relayResponse); what is pending is only the event. stop() lets them\n * report, and settle() bounds the wait, so an exchange answered before\n * stop() is still recorded -- as it was when the page's fetch() waited\n * for the read.\n */\n private inflight = new Set<Promise<unknown>>();\n /** An answered exchange's synchronous report, until it has reported. */\n private unloadCuts = new Set<() => void>();\n /**\n * Bodies reported and not yet recorded: each is redacted off the main\n * thread (body-jobs.ts, see emit), and recorded now, in the order they\n * were reported, when the page leaves or the capture stops waiting\n * (cutInflight).\n */\n private bodies = new BodyJobs();\n /** Takes an event's place in the recording when it is reported (see start()). */\n private place?: () => number;\n /**\n * Whether an exchange is recorded at all, asked at the exchange's OWN\n * moments -- when its request leaves, and again when a fetch is\n * answered or an XHR finishes -- never when its event is emitted. A fetch's event follows\n * its body, which the page reads AFTER its fetch() resolved: asked at\n * emit, `pause(); await fetch(card); resume()` recorded the card\n * exchange (the resume() came before the body was read), and `await\n * fetch(x); pause()` lost x. Every event the callback gets has been\n * admitted.\n */\n private admit: (() => boolean) | null = null;\n /** Which start() an exchange belongs to: one from before a stop() never reports into a later start(). */\n private run = 0;\n\n // Store originals so we can restore them on stop().\n private originalFetch: typeof globalThis.fetch | null = null;\n private originalXhrOpen: typeof XMLHttpRequest.prototype.open | null = null;\n private originalXhrSend: typeof XMLHttpRequest.prototype.send | null = null;\n private originalXhrSetHeader:\n typeof XMLHttpRequest.prototype.setRequestHeader | null = null;\n\n constructor(\n privacyConfig: Partial<PrivacyConfig> = {},\n maxBodySize = 524_288,\n ignoreUrls: string[] = [],\n /** The capture's privacyMode: `strict` records no body and no query value. */\n privacyMode: CaptureConfig[\"privacyMode\"] = \"balanced\",\n ) {\n this.privacyEngine = new PrivacyEngine(privacyConfig, privacyMode);\n this.maxBodySize = maxBodySize;\n this.ignored = new Set(ignoreUrls.map(absolute));\n }\n\n /** True for a request the interceptor must pass through untouched. */\n private ignores(url: string): boolean {\n return this.ignored.size > 0 && this.ignored.has(absolute(url));\n }\n\n /* -------------------------------------------------------------- */\n /* Lifecycle */\n /* -------------------------------------------------------------- */\n\n /**\n * `place`, when given, is asked for an exchange's place in the\n * recording at the moment it is reported -- where it was recorded\n * before its masking moved to a task of its own (see emit) -- and the\n * answer is handed to `callback` beside the event.\n */\n start(\n callback: NetworkEventCallback,\n admit?: () => boolean,\n place?: () => number,\n ): void {\n if (this.active) return;\n this.active = true;\n this.run++;\n this.callback = callback;\n this.admit = admit ?? null;\n this.place = place;\n this.termWarned = false;\n // The worker, starting in an idle period from the capture's start, when\n // it records bodies to redact, and the body code if KeployCapture has\n // not asked for it already (body-jobs.ts, askForCode).\n if (!this.privacyEngine.getConfig().maskNetworkBodies) prepareSoon(true);\n this.patchFetch();\n this.patchXHR();\n }\n\n /**\n * Ask for the body code now (body-jobs.ts, askForCode), for a capture\n * that will redact bodies with it: none for one that masks them whole.\n */\n askForCode(): void {\n if (!this.privacyEngine.getConfig().maskNetworkBodies) askForCode();\n }\n\n stop(): void {\n if (!this.active) return;\n this.active = false;\n // No new exchange is recorded from here. One already answered is\n // still reading its body for the recording; it reports when that\n // read ends, until settle() says otherwise.\n if (this.inflight.size === 0) this.callback = null;\n this.restoreFetch();\n this.restoreXHR();\n }\n\n /**\n * Wait at most `timeoutMs` for the exchanges answered before stop() to\n * report, then report nothing more. An endless stream never ends; the\n * bound is what ends the wait. The page's own streams are not touched:\n * they go on flowing through the SDK's relay, unrecorded.\n */\n settle(timeoutMs: number): Promise<void> {\n const done = Promise.allSettled([...this.inflight]);\n let timer: ReturnType<typeof setTimeout> | undefined;\n const bound = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, timeoutMs);\n });\n return Promise.race([done, bound]).then(() => {\n clearTimeout(timer);\n if (this.active) return;\n // What is still open at the bound (an endless stream) is recorded as\n // pagehide records it, cut where the SDK had it, then nothing more.\n this.cutInflight();\n this.callback = null;\n });\n }\n\n /**\n * Report, now and synchronously, every answered exchange still reading\n * its body: what the SDK has read of it, cut and marked. Called at\n * pagehide, right before the transport's last flush. The page gets its\n * Response at the headers, so a page that leaves as soon as it has one\n * (a login form that navigates on `res.ok`) can leave while the body\n * is still arriving; the exchange was recorded when fetch() waited for\n * the body, and must still be.\n */\n cutInflight(): void {\n this.cutBodies();\n this.bodies.now(true);\n }\n\n /**\n * Report every answered exchange still reading its body, cut where the\n * SDK had it (see cutInflight): at pause(), whose exchanges are then\n * recorded as their bodies come back from the worker -- an exchange\n * answered before the pause is admitted.\n */\n cutBodies(): void {\n for (const cut of [...this.unloadCuts]) cut();\n }\n\n /**\n * Record now, on this thread and in the order they were reported, the\n * bodies still being redacted (see emit) that fit the main thread's\n * budget: when the tab is hidden, before the drain that may be its\n * last, when the browser is back online, before the upload that ends\n * an outage, and at stop(). The rest are left to the worker; pagehide and\n * settle()'s bound record them all (cutInflight()).\n */\n reportDue(): void {\n this.bodies.now(false);\n }\n\n /** True while an exchange answered while recording is still reading its body for the recording. */\n hasInflight(): boolean {\n return this.inflight.size > 0;\n }\n\n /** True when an exchange is recorded: asked when its request leaves and again when it ends. */\n private admits(): boolean {\n if (!this.active) return false;\n try {\n const admitted = this.admit ? this.admit() : true;\n // The body code and the worker, if the capture's start has not loaded\n // them yet: from the first exchange\n // recorded with bodies to redact (body-jobs.ts).\n if (admitted && !this.privacyEngine.getConfig().maskNetworkBodies) {\n prepareSoon();\n }\n return admitted;\n } catch {\n return false;\n }\n }\n\n /** Report `event` for an exchange of start() number `run`, stamped `at` (see NetworkEventCallback); `after` is when its relay is over (see emit). */\n private emitFor(\n run: number,\n event: NetworkEvent,\n at?: number,\n after?: Promise<void>,\n mark?: number,\n ): void {\n if (run === this.run) this.emit(event, at, after, mark);\n }\n\n /** Track a pending recording until it has reported. */\n private track(recording: Promise<unknown>): void {\n this.inflight.add(recording);\n void recording.finally(() => {\n this.inflight.delete(recording);\n if (!this.active && this.inflight.size === 0) this.callback = null;\n });\n }\n\n /**\n * The Response the page gets for `response`, and, through `report`, its\n * body as recorded. See relayResponse. Bodies the SDK does not relay\n * are recorded as they always were.\n */\n private recordResponse(\n response: Response,\n report: (body: string | null) => void,\n ): { page: Response; cut: (() => void) | null; done?: Promise<void> } {\n const contentLength = Number(response.headers.get(\"content-length\") ?? 0);\n if (contentLength > this.maxBodySize) {\n // Never downloaded for the recording: the page's Response is the\n // network's, untouched.\n report(`[Response body too large: ${contentLength} bytes]`);\n return { page: response, cut: null };\n }\n if (response.body === null) {\n report(\"\");\n return { page: response, cut: null };\n }\n let relayed: ReturnType<typeof relayResponse> = null;\n if (response.body !== undefined) {\n try {\n relayed = relayResponse(response, this.maxBodySize, report);\n } catch {\n // A body already read or locked: nothing to record from, as before.\n report(null);\n return { page: response, cut: null };\n }\n }\n if (relayed) return relayed;\n // No body stream at all (a fetch polyfill's Response: whatwg-fetch,\n // which pretender and Mirage JS put under the page, has text() and no\n // `.body`), or one the platform would not rebuild: read a clone the\n // way every body used to be read, BESIDE the page's Response.\n try {\n response\n .clone()\n .text()\n .then(\n (text) => report(truncate(text, this.maxBodySize)),\n () => report(null),\n );\n } catch {\n report(null);\n }\n return { page: response, cut: null };\n }\n\n /* -------------------------------------------------------------- */\n /* Fetch patching */\n /* -------------------------------------------------------------- */\n\n private patchFetch(): void {\n if (typeof globalThis.fetch !== \"function\") return;\n\n const originalFetch = globalThis.fetch;\n this.originalFetch = originalFetch;\n\n // An arrow function: `this` is the interceptor, lexically, and fetch\n // does not depend on its own `this`. Not async: everything the SDK\n // does before the page's request leaves is synchronous, and a failure\n // of the SDK's own is never the page's.\n const patchedFetch = (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // Switched off: the page's own fetch, untouched. restoreFetch() puts\n // the global back, but a caller that took this function while the\n // recorder was on still calls it.\n if (!this.active) return originalFetch.call(globalThis, input, init);\n // Asked when the request leaves AND when it is answered: an exchange\n // that began inside a pause() is not recorded however late its\n // answer comes (`pause(); fetch(pay, card); resume()` with the\n // answer after the resume recorded the card), nor one answered\n // inside it. Asked, like the ignore check, BEFORE the copy below is\n // made: a copy of a streamed Request body that is never read holds\n // the whole upload.\n if (!this.admits()) return originalFetch.call(globalThis, input, init);\n let target: string;\n try {\n target = isRequest(input)\n ? input.url\n : input instanceof URL\n ? input.href\n : String(input);\n } catch {\n return originalFetch.call(globalThis, input, init);\n }\n if (this.ignores(target)) {\n // The captured local, not `this.originalFetch`: restoreFetch() nulls\n // the field, and anything still holding the patched fetch -- an APM\n // shim, a fetch adapter, rrweb -- would then throw a TypeError into\n // the page for an IGNORED url, which is the one path that is meant\n // to be indistinguishable from not being patched at all.\n return originalFetch.call(globalThis, input, init);\n }\n /*\n * THE PAGE'S REQUEST IS NEVER THE ONE INSPECTED. `new Request(input,\n * init)` TAKES the body of a Request given as `input`, so the page's\n * own fetch then threw \"Cannot construct a Request with a Request\n * object that has already been used\" -- every POST from ky and from\n * axios's fetch adapter, which both call fetch(request), failed with\n * the SDK installed. A copy is inspected instead; one that cannot be\n * copied (its body already read) goes to the page's fetch untouched,\n * which rejects it exactly as it would without the SDK. A body in\n * `init` replaces the Request's, which is then never read: such a\n * Request is used as it is, even one whose own body is spent\n * (review r2 -- copying it threw, and the exchange went unrecorded).\n * Any other request the SDK cannot copy goes through untouched too:\n * failing to record it must never be why it fails.\n */\n let inspected: RequestInfo | URL = input;\n if (isRequest(input) && init?.body == null) {\n try {\n inspected = input.clone();\n } catch {\n return originalFetch.call(globalThis, input, init);\n }\n }\n let request: Request;\n try {\n request = new Request(inspected, init);\n } catch {\n return originalFetch.call(globalThis, input, init);\n }\n const run = this.run;\n const startTime = performance.now();\n\n const method = request.method;\n // Already serialized by the Request constructor; passed through\n // recordedUrl so both interception paths have ONE definition of\n // what a recorded URL is.\n const url = recordedUrl(request.url);\n const requestHeaders = headersToRecord(request.headers);\n // Bodies masked whole are decided, not read (maskedSent).\n const masked = this.privacyEngine.getConfig().maskNetworkBodies;\n\n // THE PAGE'S REQUEST LEAVES NOW, before anything the SDK awaits: it\n // used to wait for the SDK's own read of the request body.\n const sent = originalFetch.call(globalThis, input, init);\n\n // Prefer init.body; fall back to the copy's body, for a body passed\n // in a Request without an init one: a Request's own body, read from\n // the copy UNCUT -- the term is computed over it whole, and only the\n // recorded body is cut.\n const requestText =\n init?.body == null &&\n (request.body ||\n // No `body` on a Request at all (Firefox): the copy is read\n // all the same, from memory (see readRequestBody).\n (isRequest(input) &&\n request.body === undefined &&\n !/^(?:GET|HEAD)$/.test(method)))\n ? readRequestBody(request, this.maxBodySize, masked)\n : null;\n const requestBody: Promise<string | null> =\n init?.body != null\n ? masked\n ? Promise.resolve(maskedSent(init.body, false))\n : serializeBody(init.body, this.maxBodySize)\n : requestText\n ? requestText.then(\n (text) =>\n text == null ? null : truncate(text, this.maxBodySize),\n // A multipart body that does not parse: the fail-closed note.\n () => \"[Unreadable body]\",\n )\n : Promise.resolve(null);\n // canonical-key.v2's term over the body as the app handed it over,\n // before redaction, masking or the cut: a body given in init at\n // once; a Request's from the SDK's read of its copy, uncut up to\n // the term's own bound (body:* past it, or when the copy cannot be\n // read). Computed beside the exchange, never in front of it.\n const term: string | Promise<string | undefined> | undefined =\n init?.body != null\n ? this.termFor(init.body, method)\n : requestText\n ? requestText.then(\n (text) =>\n text === null ? \"body:*\" : this.termFor(text, method),\n // Its text is unknown (a multipart body that does not parse).\n () => \"body:*\",\n )\n : this.termFor(null, method);\n return Promise.resolve(sent).then(\n (response) => {\n // stop() ends recording for every exchange not yet ANSWERED: one\n // whose Response arrives after it is traffic after the recorder\n // was turned off. One answered before it is recorded even if its\n // body is still being read.\n if (run !== this.run || !this.admits()) return response;\n try {\n let relayed!: ReturnType<NetworkInterceptor[\"recordResponse\"]>;\n // NO BODY TO READ: a HEAD's, a 204's, a 205's or a 304's is\n // empty by definition, recorded as such, and the page gets the\n // network's Response untouched, in every mode. Read through the\n // relay, Chromium (which gives these a body stream) ended one\n // the page never read as finished, where without the SDK it ends\n // aborted (a Next.js HEAD prefetch on Keploy's blog,\n // sdk-request-outcome.spec.ts).\n const empty =\n method === \"HEAD\" || [204, 205, 304].includes(response.status);\n // The exchange is stamped when it was answered, not when its\n // body has been read: a stream's body may end minutes later, or\n // be cut at pagehide, pause() or stop(), and two exchanges the\n // page made one after the other may finish their bodies the\n // other way round. The recording orders its events by this\n // clock (api-server, the flow engine), and reads timestamp less\n // duration as when the exchange was asked. Reported ONCE, when\n // its request body, its term and its response body are all\n // known, or when the page leaves first (reportWhenKnown); its\n // masking waits for a task after the page's (emit).\n this.reportWhenKnown(\n run,\n Date.now(),\n {\n method,\n url,\n requestHeaders,\n requestBody: null,\n responseHeaders: headersToRecord(response.headers),\n responseBody: null,\n statusCode: response.status,\n duration: performance.now() - startTime,\n type: \"fetch\",\n },\n requestBody,\n term,\n (report) => {\n if (empty) {\n report(\"\");\n return (relayed = { page: response, cut: null });\n }\n // A body masked whole is decided, never read: the page's\n // Response is the network's own, untouched.\n if (masked) {\n report(maskedResponse(response));\n return (relayed = { page: response, cut: null });\n }\n return (relayed = this.recordResponse(response, report));\n },\n );\n return relayed.page;\n } catch {\n // Recording runs beside the page's exchange and never decides\n // it: an answer the SDK could not read is the page's as it came.\n return response;\n }\n },\n (err: unknown) => {\n if (run !== this.run || !this.admits()) throw err;\n // Network error - still emit an event, stamped when it failed:\n // its request body may be read after that.\n this.reportWhenKnown(\n run,\n Date.now(),\n {\n method,\n url,\n requestHeaders,\n requestBody: null,\n responseHeaders: {},\n responseBody: null,\n statusCode: 0,\n duration: performance.now() - startTime,\n type: \"fetch\",\n },\n requestBody,\n term,\n );\n throw err;\n },\n );\n };\n globalThis.fetch = patchedFetch;\n }\n\n private restoreFetch(): void {\n if (this.originalFetch) {\n globalThis.fetch = this.originalFetch;\n this.originalFetch = null;\n }\n }\n\n /* -------------------------------------------------------------- */\n /* XMLHttpRequest patching */\n /* -------------------------------------------------------------- */\n\n private patchXHR(): void {\n if (typeof XMLHttpRequest === \"undefined\") return;\n\n /*\n * The originals are read off the prototype UNBOUND on purpose: they\n * are invoked with the request as `this` (`.call(this, ...)`) and\n * put back on the prototype by restoreXHR(). There is no bound form\n * of \"the method this prototype had before\"; the rule below flags\n * exactly that read.\n */\n // oxlint-disable-next-line typescript/unbound-method -- captured to call with an explicit receiver and to restore\n const originalOpen = XMLHttpRequest.prototype.open;\n // oxlint-disable-next-line typescript/unbound-method -- captured to call with an explicit receiver and to restore\n const originalSend = XMLHttpRequest.prototype.send;\n this.originalXhrOpen = originalOpen;\n this.originalXhrSend = originalSend;\n\n // What the patched methods need from the interceptor, captured here\n // rather than through a `self` alias. maxBodySize is fixed at\n // construction; `active` is read live.\n const maxBodySize = this.maxBodySize;\n const admits = (): boolean => this.admits();\n const currentRun = (): number => this.run;\n const termFor = (body: unknown, method: string) =>\n this.termFor(body, method);\n const reportWhenKnown: NetworkInterceptor[\"reportWhenKnown\"] = (...a) =>\n this.reportWhenKnown(...a);\n const ignores = (u: string): boolean => this.ignores(u);\n const masks = (): boolean =>\n this.privacyEngine.getConfig().maskNetworkBodies;\n\n // We store per-request metadata on the XHR instance via a WeakMap.\n const meta = new WeakMap<\n XMLHttpRequest,\n {\n method: string;\n url: string;\n requestHeaders: Record<string, string>;\n startTime: number;\n }\n >();\n\n // Also intercept setRequestHeader to capture request headers.\n // oxlint-disable-next-line typescript/unbound-method -- captured to call with an explicit receiver and to restore\n const origSetHeader = XMLHttpRequest.prototype.setRequestHeader;\n this.originalXhrSetHeader = origSetHeader;\n\n XMLHttpRequest.prototype.setRequestHeader = function (\n name: string,\n value: string,\n ) {\n const m = meta.get(this);\n if (m) {\n m.requestHeaders[name] = value;\n }\n return origSetHeader.call(this, name, value);\n };\n\n /*\n * The trailing arguments are forwarded EXACTLY as given, arity\n * included: `open(m, u)` is asynchronous and `open(m, u, undefined)`\n * is not (ToBoolean(undefined) is false), so normalising them to the\n * five-argument overload would turn a page's async request into a\n * synchronous one.\n */\n const forwardOpen = originalOpen as (\n this: XMLHttpRequest,\n ...args: unknown[]\n ) => void;\n XMLHttpRequest.prototype.open = function (\n method: string,\n url: string | URL,\n ...rest: unknown[]\n ) {\n const href = typeof url === \"string\" ? url : url.toString();\n // The browser's own open() FIRST: it is what refuses an unparseable URL,\n // and a request that never opened must not be recorded as though it had.\n // forwardOpen is the captured local, not a lookup through `self`, so an\n // app that replaces XMLHttpRequest.prototype.open after us still reaches\n // the real one.\n const result = forwardOpen.call(this, method, url, ...rest);\n // No meta for an ignored URL: send() and loadend then see nothing.\n if (!ignores(href)) {\n meta.set(this, {\n method,\n // RESOLVED, not the raw string the app typed. See recordedUrl.\n url: recordedUrl(href),\n requestHeaders: {},\n startTime: 0,\n });\n }\n return result;\n };\n\n XMLHttpRequest.prototype.send = function (\n body?: Document | XMLHttpRequestBodyInit | null,\n ) {\n const m = meta.get(this);\n if (m) {\n m.startTime = performance.now();\n }\n const run = currentRun();\n // Asked when the request leaves and again when it finishes, as fetch.\n const admitted = admits();\n // ANSWERED AT ITS HEADERS, as a fetch is (reportWhenKnown): one the\n // page was still reading as a leave began is not one of the leave\n // (body-jobs.ts). Listened for until then only: one listener a send(),\n // removed at its headers (a request re-opened before them drops it at\n // the next one's), never one a LOADING tick runs for the download.\n let mark: number | undefined;\n const answered = (): void => {\n if (this.readyState < 2) return;\n mark = leaveMark();\n this.removeEventListener(\"readystatechange\", answered);\n };\n if (m && admitted) this.addEventListener(\"readystatechange\", answered);\n // Bodies masked whole are decided, not read (maskedSent).\n const masked = masks();\n\n const onFinish = () => {\n if (!m || !admitted || !admits()) return;\n\n const duration = performance.now() - m.startTime;\n\n // Parse response headers.\n const rawHeaders = this.getAllResponseHeaders();\n const responseHeaders: Record<string, string> = {};\n if (rawHeaders) {\n for (const line of rawHeaders.trim().split(/[\\r\\n]+/)) {\n const idx = line.indexOf(\": \");\n if (idx > 0) {\n responseHeaders[line.slice(0, idx)] = line.slice(idx + 2);\n }\n }\n }\n\n let responseBody: string | null = null;\n if (masked) {\n responseBody = maskedXhrResponse(this);\n } else {\n try {\n if (typeof this.responseText === \"string\") {\n responseBody = truncate(this.responseText, maxBodySize);\n }\n } catch {\n // responseText may throw if responseType is not \"\" or \"text\".\n responseBody = `[${this.responseType} response]`;\n }\n }\n\n // A FormData here used to be assembled and recorded WHOLE: the\n // one shape the cap never reached. See serializeXhrBody().\n const requestBody = masked\n ? maskedSent(body, true)\n : serializeXhrBody(body, maxBodySize);\n\n // canonical-key.v2's term over the body as sent, computed at\n // loadend: after the request has gone out, including a\n // synchronous XHR's, whose loadend fires inside send(). Stamped\n // now, though a hashed term is ready a moment later.\n reportWhenKnown(\n run,\n Date.now(),\n {\n method: m.method,\n url: m.url,\n requestHeaders: m.requestHeaders,\n requestBody,\n responseHeaders,\n responseBody,\n statusCode: this.status,\n duration,\n type: \"xhr\",\n },\n null,\n termFor(body, m.method),\n undefined,\n mark,\n );\n };\n\n this.addEventListener(\"loadend\", onFinish, { once: true });\n\n return originalSend.call(this, body);\n };\n }\n\n private restoreXHR(): void {\n if (typeof XMLHttpRequest === \"undefined\") return;\n if (this.originalXhrOpen) {\n XMLHttpRequest.prototype.open = this.originalXhrOpen;\n this.originalXhrOpen = null;\n }\n if (this.originalXhrSend) {\n XMLHttpRequest.prototype.send = this.originalXhrSend;\n this.originalXhrSend = null;\n }\n if (this.originalXhrSetHeader) {\n XMLHttpRequest.prototype.setRequestHeader = this.originalXhrSetHeader;\n this.originalXhrSetHeader = null;\n }\n }\n\n /* -------------------------------------------------------------- */\n /* Internal */\n /* -------------------------------------------------------------- */\n\n /**\n * Report an exchange whose request body (`body`, when not yet read),\n * term or response body (`response`, a fetch's) may still be settling:\n * once all are known, or -- cut first, at pagehide, pause() or settle()'s\n * bound after stop() -- at once, with the fail-closed note for a request\n * body not yet read, body:* (unknown) for a term not yet known, and the\n * response body as the SDK has it, cut (its relay's cut). So an exchange\n * is never lost waiting for its term (its chunk loading, its hash\n * running), and is reported once.\n *\n * `response` is handed the report of the response body and returns its\n * cut, and when the page's body is relayed, when the relay is over\n * (`done`): what the main thread does for the event waits for that too\n * (emit) -- its redaction where there is no worker -- so it never runs\n * while the page reads the rest of a body past the cap (but for the copy\n * in a browser with no idle periods, body-jobs.ts redact()). It is\n * called once the cut is in place, so a body known at once (none, or one\n * too large to read) reports into it.\n */\n private reportWhenKnown(\n run: number,\n at: number,\n event: NetworkEvent,\n body: Promise<string | null> | null,\n term: string | Promise<string | undefined> | undefined,\n response?: (report: (body: string | null) => void) => {\n cut: (() => void) | null;\n done?: Promise<void>;\n },\n // Answered now (a fetch's headers), or at an XHR's: a body the page is\n // still reading as a leave begins is cut where it left (body-jobs.ts).\n mark = leaveMark(),\n ): void {\n let bodyNow = body ? null : { value: event.requestBody };\n let termNow = typeof term === \"object\" ? null : { value: term };\n let responseNow = response ? null : { value: event.responseBody };\n // Assigned below, after the closures that read it: as a const it would\n // be in its dead zone if `response` ever reported synchronously.\n // oxlint-disable-next-line eslint/prefer-const -- see above\n let relay: ReturnType<NonNullable<typeof response>> | undefined;\n let reported = false;\n let recorded: () => void = () => {};\n const emit = (\n b: { value: string | null },\n t: { value: string | undefined },\n r: { value: string | null },\n ): void => {\n if (reported) return;\n reported = true;\n this.unloadCuts.delete(cut);\n recorded();\n this.emitFor(\n run,\n {\n ...event,\n requestBody: b.value,\n responseBody: r.value,\n ...(t.value === undefined ? {} : { requestTerm: t.value }),\n },\n at,\n relay?.done,\n mark,\n );\n };\n const settle = (): void => {\n if (bodyNow && termNow && responseNow)\n emit(bodyNow, termNow, responseNow);\n };\n const cut = (): void => {\n relay?.cut?.();\n emit(\n bodyNow ?? { value: \"[Unreadable body]\" },\n termNow ?? { value: \"body:*\" },\n responseNow ?? { value: null },\n );\n };\n if (bodyNow && termNow && responseNow) return settle();\n this.unloadCuts.add(cut);\n this.track(new Promise<void>((resolve) => (recorded = resolve)));\n void body?.then((value) => {\n bodyNow = { value };\n settle();\n });\n if (typeof term === \"object\")\n void term.then((value) => {\n termNow = { value };\n settle();\n });\n relay = response?.((value) => {\n responseNow = { value };\n settle();\n });\n }\n\n /** Whether this capture has said KUI_E_REQUEST_TERM_FAILED yet. */\n private termWarned = false;\n\n /**\n * canonical-key.v2's term for a request body, FAIL-SAFE: the SDK runs\n * inside the customer's page, so a failure of its own instrumentation\n * -- a lexer, a parser or a page's SubtleCrypto that throws, at once\n * or later -- must never reach the page's fetch or XHR. Any throw\n * becomes NO term (the event is recorded with no requestTerm, as an\n * SDK older than canonical-key.v2 records it); a term chunk that did\n * not load (a CSP, offline, a 404) makes the term unknown, body:*, for\n * this request and, the failed load being kept, for every later one of\n * the page. Either is said once per capture, typed, on the console --\n * the channel the SDK's other non-terminal warnings use.\n */\n private termFor(\n body: unknown,\n method: string,\n ): string | Promise<string | undefined> | undefined {\n try {\n const known = termBeforeLoad(body);\n if (known !== null) return known;\n const subtle = globalThis.crypto?.subtle;\n return unlessHeld(loadTermCode(), termLoaded)\n .then(\n // Held by the page's leave: unknown, and nothing said.\n (code) => (code ? code.recordTermFor(body, subtle) : \"body:*\"),\n // The chunk did not load: the term is unknown, as where the page\n // cannot hash.\n (err: unknown) => (this.termFailed(method, err), \"body:*\"),\n )\n .catch((err: unknown) => this.termFailed(method, err));\n } catch (err) {\n return this.termFailed(method, err);\n }\n }\n\n private termFailed(method: string, err: unknown): undefined {\n if (!this.termWarned) {\n this.termWarned = true;\n try {\n // What threw, or why the chunk did not load, as recorder.ts\n // names a failed rrweb load: `<name>: <message>` for an Error.\n console.warn(termWarningLine(method, describeValue(err)));\n } catch {\n // A console that throws is not the page's problem either.\n }\n }\n return undefined;\n }\n\n /**\n * THE PAGE HAS ITS RESPONSE FIRST; IT IS RECORDED AFTER, AND ITS BODIES\n * ARE REDACTED OFF THE PAGE'S THREAD. The relay reports a body when the\n * network's ends -- before the page's stream is handed its end -- and\n * the masking, the scrub and the event's serialisation all used to run\n * there, synchronously: the page's `await res.json()` waited for them.\n * MEASURED (MEASURE.md, uic-sdk-perf): 50 parallel 64 KB JSON fetches\n * took 32 -> 382 ms in Chromium, and WebKit's time to headers went\n * 39 -> 322 ms. So the report only takes the exchange's place in the\n * recording (`place`, the order it was recorded in before) and hands\n * its bodies to body-jobs.ts, which redacts them in a Web Worker (or,\n * where the page has none, on this thread in a task of its own, under\n * a budget); the headers, the URL and the event's serialisation run\n * when the bodies come back. Its task -- the copy to the worker (where\n * the browser has idle periods; Safari copies at once), or its\n * redaction where there is no worker -- waits for the relay to be over\n * too (`after`):\n * one past the cap is reported at the cap, while the page is still\n * reading the rest.\n *\n * Nothing recorded is lost or changed: the event is the same, stamped\n * when it was answered (`at`), and in the same place. It is tracked\n * until it is recorded; settle()'s bound and pagehide (cutInflight())\n * record at once what the worker still holds, and a hidden tab and\n * stop() what fits the main thread's budget (reportDue()).\n */\n private emit(\n raw: NetworkEvent,\n at?: number,\n after?: Promise<void>,\n mark?: number,\n ): void {\n const callback = this.callback;\n if (!callback) return;\n const placed = this.place?.();\n let recorded!: () => void;\n this.track(new Promise<void>((resolve) => (recorded = resolve)));\n let job;\n try {\n job = this.privacyEngine.bodyJob(raw);\n } catch {\n return recorded();\n }\n this.bodies.redact(\n job,\n (bodies) => {\n recorded();\n if (!bodies) return;\n try {\n callback(this.privacyEngine.maskNetworkData(raw, bodies), at, placed);\n } catch {\n // Never let SDK errors propagate into application code.\n }\n },\n after,\n mark,\n );\n }\n}\n\n/** Exposed for tests: the cut and the XHR body shape, without an XHR. */\nexport const __internals = {\n truncate,\n serializeXhrBody,\n /** Load the term code with `load` from now on (the page's import() when none), forgetting any load so far. */\n termLoader(load?: () => Promise<TermCode>): void {\n termCode = undefined;\n termLoaded = false;\n // Through ownChunk, as the page's own: the leave gate holds it too.\n importTermCode = load ? () => ownChunk(load) : pageImport;\n },\n};\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - Batched transport layer */\n/* ------------------------------------------------------------------ */\n\nimport type { SessionEvent, SessionMetadata, TransportPayload } from \"./types\";\nimport {\n IngestRejection,\n codeForStatus,\n parseServerError,\n noticeLine,\n serverReason,\n warningLine,\n} from \"./errors\";\nimport type {\n AnyCaptureError,\n CaptureWarningEvidence,\n ServerAnsweredCode,\n} from \"./errors\";\nimport type { CaptureIdentity } from \"./identity\";\nimport { version as manifestVersion } from \"../package.json\";\n\n/* ------------------------------------------------------------------ */\n/* Constants */\n/* ------------------------------------------------------------------ */\n\nconst SDK_NAME = \"@keploy/capture-sdk\";\n/*\n * THE VERSION ON THE WIRE IS THE MANIFEST'S, read at build time, and the\n * manifest's is the git tag's: the committed package.json carries the\n * placeholder 0.0.0-tag and the release lane writes the tag's version in\n * before `pnpm publish` runs the build (tools/check-release-version.mjs,\n * RELEASING.md). A hand-typed constant here was a second copy of the\n * version, which is how the two drift.\n */\nconst SDK_VERSION: string = manifestVersion;\nconst MAX_RETRY_ATTEMPTS = 3;\nconst BASE_RETRY_DELAY_MS = 1_000;\n/*\n * THE WAIT BETWEEN FLIGHTS WHILE UPLOADS FAIL. Once a flight has spent its\n * attempts, the next one is not started by the timer, by a batch filling\n * or by an event over the keepalive quota until this has passed: 2 s,\n * doubling per flight that fails, to 60 s, each stretched by up to half\n * again at random so pages that lost the ingest together do not come\n * back to it together. Nothing is waited ON -- the next trigger after it\n * finds the way open -- so the page never blocks on it. A flight sent\n * while uploads fail makes ONE attempt, so a dead endpoint gets at most\n * one scheduled POST a minute once the wait has reached its cap. (A page whose only\n * traffic is DOM events can run its queue empty, which ends the outage\n * without an upload: see flush().) MEASURED before it,\n * on MEASURE.md's page with the ingest resetting every connection: 747\n * POSTs in 300 s, each new flight three attempts at once, and every event\n * over 64 KiB starting one.\n */\nconst OUTAGE_FIRST_MS = 2_000;\nconst OUTAGE_MAX_MS = 60_000;\n/*\n * THE SDK'S SHARE OF THE KEEPALIVE QUOTA, IN BYTES: half of it.\n *\n * The Fetch standard caps the SUM of in-flight keepalive request bodies\n * per document at 64 KiB, and navigator.sendBeacon is specified as a\n * keepalive fetch, so both share it. MEASURED in Chromium 145.0.7632.6:\n * a 65,536-byte body is accepted and a 65,537-byte body is refused —\n * sendBeacon returns false, fetch(keepalive:true) rejects with \"Failed\n * to fetch\" — while the same POST without keepalive carries 200,000\n * bytes. A refused request loses ALL of its events, so every keepalive\n * request here is sized against this number.\n *\n * THE QUOTA IS THE PAGE'S TOO, so the SDK takes half and the page keeps\n * the rest whatever the SDK has on the wire. MEASURED (sdk-keepalive-room\n * .spec.ts, the pinned Playwright image's engines), a 63 KB upload held on the wire\n * when the SDK took the whole quota: the page's own 2 KB beacon was\n * refused in Chromium and WebKit, its 2 KB keepalive fetch too in\n * WebKit (\"Load failed\") -- a lead form or an analytics beacon lost to\n * the capture. All three engines refuse past 65,536 bytes in flight\n * (Firefox counts keepalive fetch, not sendBeacon). An upload over this\n * share still goes, without keepalive.\n */\nconst KEEPALIVE_QUOTA_BYTES = 32_768;\n\n/* ------------------------------------------------------------------ */\n/* Helpers */\n/* ------------------------------------------------------------------ */\n\n/**\n * AN OWNER'S CALLBACK, RUN SO THAT ITS THROW IS NEVER THE TRANSPORT'S.\n * Called inside sendWithRetry's attempt, a throw from onDelivered,\n * onFailing or the rejection path was read as a network error, and the\n * batch the server had just accepted (or refused for good) was posted\n * again; called in run()'s catch, it left the failed flight out of the\n * retry queue. The throw still reaches the page, as an uncaught error in\n * a task of its own, where an error tracker sees it.\n */\nfunction tell(say: () => void): void {\n try {\n say();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n}\n\nfunction utf8Length(text: string): number {\n return new TextEncoder().encode(text).length;\n}\n\n/**\n * A batch run() has taken out of the queue and not yet acknowledged.\n *\n * It exists so the page-unload flush can see it. Between the splice and\n * the fetch there is real time — compressPayload is asynchronous, and a\n * failed attempt sleeps 0.5–1 s then 1–2 s before the next — and in\n * those windows the events are in neither the queue nor a request. See\n * reclaimInFlight().\n */\ninterface InFlightBatch {\n events: SessionEvent[];\n /**\n * THE IDEMPOTENCY KEY, BOUND TO THESE EXACT EVENTS.\n *\n * The server stores a batch under a document id derived from this,\n * so a POST whose response was lost and is sent again with the same\n * id and byte-identical events is a success that stores nothing --\n * and the same id with DIFFERENT events is a 409 the SDK treats as\n * terminal. Both halves of that contract are met by one rule: the\n * id and the JSON are minted together when the flight is formed, and\n * a flight is re-sent WHOLE or not at all. It is never re-spliced\n * into the event queue once it has been dispatched (see\n * `dispatched` and the retry queue in run()).\n *\n * Without it every POST got a server-minted id, so a batch re-sent\n * after a lost response landed twice. MEASURED against a real\n * MongoDB through the server's own ingest service, one batch posted\n * twice: with a batchId 1 stored row; without, 2 -- and a DOUBLED\n * recording passes every integrity refusal the server has, because\n * all three detect a recording that is SHORT, so the generated test\n * clicked twice and waited for a response the app never sends.\n */\n batchId: string;\n /** The request body, serialised ONCE so every attempt is byte-identical. */\n json: string;\n /** True once a fetch() for these events has ever been dispatched. */\n dispatched: boolean;\n /** True only while a fetch() for these events is actually pending. */\n onWire: boolean;\n /** Set when the unload flush took the events back; stops every further attempt. */\n abandoned: boolean;\n /** `json`'s UTF-8 bytes, as formFlight() measured them; what MAX_QUEUE_BYTES counts. */\n bytes: number;\n /**\n * Sent early, because the queue was past what the unload request\n * carries: a plain fetch, never keepalive, so the page's pagehide\n * request keeps the SDK's whole share. (An event over the share alone\n * is a rush, not this: it rides keepalive when it fits, to survive the\n * navigation.)\n */\n early?: boolean;\n /**\n * The body as it goes on the wire, gzipped ONCE for every attempt and\n * every re-send of this flight: gzipping it again each time, in an\n * outage, was the same work for the same bytes per POST.\n */\n wire?: Promise<WireBody>;\n /** `wire` once it has resolved: what the unload flush re-sends, as it was posted (flushOnUnload). */\n sent?: WireBody;\n}\n\n/** A request body plus its size on the wire, which the keepalive gate needs. */\ninterface WireBody {\n body: BodyInit;\n bytes: number;\n encoding: string | null;\n}\n\n/** Exported for its test; not part of the package surface (index.ts does not re-export it). */\nexport async function compressPayload(data: string): Promise<WireBody> {\n // Use the Compression Streams API when available (modern browsers).\n if (\n typeof CompressionStream !== \"undefined\" &&\n typeof Response !== \"undefined\"\n ) {\n try {\n /*\n * PIPED, NOT WRITTEN-THEN-READ.\n *\n * This used to take a writer, `await writer.write(bytes)`, `await\n * writer.close()`, and only THEN take a reader. A TransformStream's\n * writable side holds back until its readable side is consumed, so\n * with nobody reading yet, the close never resolved — and neither\n * did the flush, which held `flushing` for the life of the page.\n * MEASURED in Chromium 145.0.7632.6 with the built transport: one\n * event ({mock:true}, an 87-byte JSON payload), flush() had not\n * resolved after 5 s and no ingest request left the browser. Not\n * one batch of any session has ever shipped from a browser with\n * CompressionStream. Node's stream buffers happened to absorb small\n * payloads, which is why every unit test was green.\n */\n const compressed = new Response(data).body!.pipeThrough(\n new CompressionStream(\"gzip\"),\n );\n const buf = await new Response(compressed).arrayBuffer();\n /*\n * THE SMALLER BODY GOES ON THE WIRE. The byte cut in formFlight()\n * bounds the DECODED body at the server's cap, and the same cap\n * applies to the wire, so it relies on gzip never being larger\n * than the JSON. For the SDK's payloads that holds in practice --\n * they are JSON text, whose UTF-8 has well under 8 bits of\n * entropy per byte, MEASURED: 96 KiB of random printable ASCII\n * gzips to 82%, base64 of random bytes to 75%, and the smallest\n * possible payload (one empty event, 273 bytes) to 207 -- but it\n * is not true of gzip in general (a 1-byte input gzips to 21),\n * and the cut should not rest on an argument about entropy.\n * Sending the identity body whenever gzip did not shrink it makes\n * it true by construction.\n */\n const plain = utf8Length(data);\n if (buf.byteLength < plain) {\n return { body: buf, bytes: buf.byteLength, encoding: \"gzip\" };\n }\n return { body: data, bytes: plain, encoding: null };\n } catch {\n // Fall through to uncompressed.\n }\n }\n return { body: data, bytes: utf8Length(data), encoding: null };\n}\n\n/* ------------------------------------------------------------------ */\n/* Transport */\n/* ------------------------------------------------------------------ */\n\n/**\n * The most events the ingest route accepts in one batch:\n * sdkwire.MaxEventsPerBatch in api-server. A batch over it is refused\n * with a 400 naming `events`, so the transport never builds one.\n */\nexport const MAX_EVENTS_PER_BATCH = 5000;\n\n/**\n * The most bytes the ingest route accepts in one body, DECODED:\n * uiIngestMaxBodyBytes in api-server (10 MiB; the same cap applies to\n * the wire, and compressPayload sends whichever of gzip and identity\n * is smaller, so the wire is never larger than the JSON). A body over\n * it is a terminal 413\n * `decoded request body exceeds N bytes`, so a flight is formed\n * against this as well as the count -- MEASURED before the byte cut:\n * batchSize 5000 of 2 KB network events made one 10.3 MiB POST, and\n * the DEFAULT batchSize 50 of 220 KB responses (inside maxBodySize)\n * made 10.5 MiB, each ending the capture with a remedy that blamed a\n * version mismatch. An event that alone exceeds it is dropped at\n * enqueue: the server can never take it.\n */\nexport const MAX_BATCH_BYTES = 10 * 1024 * 1024;\n\n/**\n * THE MOST BYTES THE TRANSPORT HOLDS UNSENT: the event queue and the\n * flights waiting to be re-sent, together, as their JSON. The count cap\n * (maxQueueSize) alone let 5,000 events of up to MAX_BATCH_BYTES each\n * pile up while the ingest was down -- MEASURED (MEASURE.md \"Outage\"):\n * the 22.5k-node page's heap went 29 -> 211 MB in 90 s once its\n * multi-MB snapshots queued behind a dead endpoint. Past this, the\n * oldest go first, whole: a waiting flight as one (its batchId is bound\n * to its events), then queued events.\n *\n * WHY 16 MiB. It must hold one event of MAX_BATCH_BYTES, the largest the\n * server takes and enqueue() admits -- a big page's FullSnapshot -- or a\n * HEALTHY page would evict its own snapshot on arrival. Above that floor\n * it is memory against how much of an outage is kept: the 6 MiB left\n * behind one such flight is a minute of the busiest stream MEASURE.md\n * recorded (a 64 KB response every second plus mutations and small\n * fetches: about 100 KB/s of JSON) and far longer for a page of ordinary\n * events, which hit the 5,000-event cap first.\n */\nexport const MAX_QUEUE_BYTES = 16 * 1024 * 1024;\n\nexport interface TransportConfig {\n endpoint: string;\n apiKey: string;\n /** Events per POST; clamped to MAX_EVENTS_PER_BATCH. */\n batchSize: number;\n batchInterval: number;\n maxQueueSize: number;\n /**\n * Called once when capture stops for good, AFTER the capture has\n * ended and the singleton is released, so a handler that calls\n * KeployCapture.init() again gets a fresh instance rather than the\n * dead one. Optional, and the console error happens regardless: an\n * integrator who does not supply one must still find out. The\n * argument is a CaptureError: `code` is the contract's KUI_E_* for\n * what happened, `serverMessage` is the server's own sentence,\n * `remedy` is what to do about it, and `message` is the prose a human\n * read before. A program should branch on `code`.\n */\n onError?: (err: AnyCaptureError) => void;\n\n /**\n * Called synchronously at pagehide, before the unload flush cuts the\n * last batch, so the owner can hand over what it still holds -- the\n * network exchanges still reading their bodies, which would otherwise\n * be enqueued after the page had gone. Not at beforeunload: a page\n * whose user cancels the leave prompt stays, and its exchanges finish\n * normally.\n */\n beforeUnloadFlush?: () => void;\n\n /**\n * Called synchronously when the tab is hidden, before the drain that\n * may be the page's last chance to send (a mobile browser can discard a\n * hidden page with no pagehide), so the owner can queue what it has\n * recorded and not yet handed over: the exchanges whose bodies are still\n * being redacted, as far as they fit the main thread's budget\n * (NetworkInterceptor.reportDue()). Nothing is cut: the page is still\n * there, and the rest is recorded when the worker answers.\n */\n beforeHiddenFlush?: () => void;\n\n /**\n * Called synchronously when the browser is back online, before the\n * flush that ends an outage, so the owner can queue what it recorded\n * offline and has not yet handed over: the exchanges whose bodies are\n * still being redacted, as far as they fit the main thread's budget\n * and its body code had loaded before the outage\n * (NetworkInterceptor.reportDue()): such an exchange made offline is in\n * the upload that ends the outage; the rest follow it, recorded the\n * same, when the code and the worker load and answer.\n */\n beforeOnlineFlush?: () => void;\n\n /**\n * Called once when a terminal rejection has ended this transport, so\n * the owner can end the CAPTURE.\n *\n * Distinct from {@link onError}, which is the integrator's. This one\n * is the orchestrator's: stopping the transport leaves rrweb\n * recording, fetch and XHR patched, the session timer armed and the\n * singleton set, so without it a revoked key produced a page that\n * went on paying for a capture that could never post again — and a\n * later init() handed back the dead instance.\n */\n onCaptureEnd?: () => void;\n\n /**\n * The owner's answer to \"does this terminal rejection end only the\n * SESSION?\". When it says yes, the transport stops and calls\n * {@link onSessionEnd} instead: no console error, no onError, no\n * onCaptureEnd -- the capture goes on in a new session. Absent, every\n * terminal rejection ends the capture, as it always has.\n */\n endsSessionOnly?: (\n code: ServerAnsweredCode,\n reason: string | null,\n ) => boolean;\n /** Called once when {@link endsSessionOnly} said yes, after the transport has stopped. */\n onSessionEnd?: () => void;\n\n /**\n * Called with the events this transport drops without sending them:\n * refused at enqueue (unserialisable, or over the body cap alone) or\n * dropped to hold the queue at maxQueueSize. A dropped DOM event is a\n * hole in the recording -- every rrweb event after it names nodes by\n * the last FullSnapshot and the mutations since -- so the owner tells\n * the recorder, which holds rrweb's incrementals until a FullSnapshot\n * is sent again. Unsaid, clicks after a snapshot too big to send were\n * posted against no baseline and the flow engine resolved them to\n * `body` (found in review #23). `rebaselined` says a FullSnapshot\n * queued after the dropped DOM events still stands: it is the baseline\n * of everything after it, so there is no hole to hold over -- read as\n * one, a snapshot retaken into a full queue evicted older events, and\n * each eviction asked for another snapshot.\n */\n onDropped?: (events: SessionEvent[], rebaselined: boolean) => void;\n\n /**\n * Called with the events of a batch the server accepted. The owner's\n * recorder starts the retake's backoff over when a FullSnapshot is among\n * them: started over as one was emitted, before this transport refused\n * it, the backoff stayed at 5 s and a page too big to send was\n * re-serialised every 5 s for the session (found in review #24).\n */\n onDelivered?: (events: SessionEvent[]) => void;\n\n /**\n * Called with true when uploads are failing -- a flight has spent its\n * attempts, or an event was dropped while the browser said it was\n * offline -- and with false when the outage ends: an upload accepted\n * again, or a flush, online, that finds nothing left to probe with\n * (see flush()). The owner's\n * recorder takes no snapshot in between: re-serialising the page into a\n * queue nothing drains is how an outage froze it (MEASURED on a 22.5k-node\n * page: 19 long tasks over 200 ms, up to 373 ms, in the 90 s after the cap), and one snapshot\n * when uploads come back is the baseline for every hole the outage made.\n */\n onFailing?: (failing: boolean) => void;\n}\n\nexport class Transport {\n private config: TransportConfig;\n private queue: SessionEvent[] = [];\n /**\n * Flights that failed to send and must go out again AS THEY WERE.\n * Drained ahead of the event queue by run(). Never merged back into\n * `queue`: re-splicing a dispatched flight's events with newer ones\n * would put already-stored events under a new batchId, which is the\n * duplication the id exists to prevent -- and re-using the id over a\n * different event set is the 409 the server answers instead.\n */\n private retryQueue: InFlightBatch[] = [];\n /** Only used by the no-randomUUID fallback of mintBatchId(). */\n private batchCounter = 0;\n private flushTimer: ReturnType<typeof setInterval> | null = null;\n /** The flush in progress, or null. One at a time: batches stay ordered. */\n private current: Promise<void> | null = null;\n private sessionId: string | null = null;\n private metadata: SessionMetadata | null = null;\n /*\n * The browser half of the offline backend join, or null when this\n * capture cannot be joined. Sent on EVERY batch rather than once at\n * session start: a batch is the only thing the server is guaranteed to\n * receive, and an identity that arrives only with the first one is\n * lost whenever that batch is the one that fails.\n */\n private captureIdentity: CaptureIdentity | null = null;\n /**\n * Whether the browser says it is online, ASKED EACH TIME. It was a flag\n * the `online` and `offline` events fed, read once more at start() and\n * at release() -- and a page's own listener, registered first, can stop\n * either event before it reaches this transport. After a blip whose\n * `online` was stopped the flag said offline for good: nothing was sent\n * on the transport's own schedule until the tab was hidden or left\n * (found in review #29 on one path, a capture resumed from such a\n * listener, and on two more refuting review #30); and with `offline`\n * stopped it sent into a network the browser called down.\n * navigator.onLine is what the two events report, so it is what is\n * read. The `online` event is when to send at once; the timed flush\n * finds the network back when no event said so.\n */\n private get online(): boolean {\n return typeof navigator === \"undefined\" || navigator.onLine !== false;\n }\n private started = false;\n /** The stamp the next queued event gets; see enqueue(). */\n private nextSeq = 1;\n /** Set by a drain request that arrived while a flush was running. */\n private drainPending = false;\n /** Set by hold(): nothing is sent until release(). */\n private holding = false;\n /**\n * Full batches enqueue() asked for while a flight was out, which the run\n * under way owes: one batch each, sent as its flight settles (run()).\n */\n private asked = 0;\n /**\n * A DRAIN IS OWED: an event over the keepalive quota was queued while\n * the browser said it was offline. The next thing that sends -- the\n * `online` handler, or a timed flush that finds the browser online --\n * then drains instead of taking one batch. Cleared once the queue has\n * run empty. (A drain that failed is owed by the outage it starts or\n * continues: the upload that ends it drains; see run()'s catch.)\n */\n private rushDeferred = false;\n /** Ends the wait of a sender that is between two attempts; see backoff(). */\n private wakeSender: (() => void) | null = null;\n /*\n * Bytes of keepalive request bodies currently on the wire, so the\n * unload flush can size itself against what is LEFT of the quota\n * rather than the whole of it.\n */\n private inflightKeepaliveBytes = 0;\n /**\n * Bytes of a request carrying no events: the fixed cost every request\n * pays, so an event's own size can be measured against the quota.\n */\n private envelopeBytes = 0;\n /** Set by the first event JSON.stringify refused; see reportUnserialisable(). */\n private reportedUnserialisable = false;\n private reportedOversized = false;\n private reportedScrubOversized = false;\n private reportedNavigationUnwrapped = false;\n /**\n * Each queued event's JSON and its bytes, written and measured once at\n * enqueue (the keepalive rush needs the number there anyway): the bytes\n * read wherever a cut is sized (the timed flight, the unload flush, the\n * byte cap), the JSON joined into its flight's body (body()) and never\n * written again. Let go once a flight carries it: the flight keeps its\n * body and its bytes.\n */\n private readonly jsonOf = new WeakMap<SessionEvent, [string, number]>();\n /** The batch run() is working on, so the unload flush can take it back. */\n private inFlight: InFlightBatch | null = null;\n /**\n * At least the bytes held unsent (MAX_QUEUE_BYTES): set to the exact\n * sum by fit(), raised by everything that adds to the queue or the retry\n * queue, and never lowered by what leaves them, so it can only be over.\n * fit() counts again only when it is over the cap.\n */\n private held = 0;\n /**\n * The JSON bytes of what `queue` holds, kept exactly at every change of\n * it (each event's size is measured once, at enqueue): what the unload\n * flush would have to carry. O(1) an event; never a walk of the queue.\n */\n private queued = 0;\n /**\n * The next flight is the counter's: the queue went past the share, and\n * no drain was asked. It is capped at the share (formFlight).\n */\n private counted = false;\n /** Flights that spent their attempts since one was last accepted; 0 when uploads work. */\n private failures = 0;\n /** performance.now() before which no flight starts on the timer's or an enqueue's say; see OUTAGE_FIRST_MS. */\n private notBefore = 0;\n\n constructor(config: TransportConfig) {\n /*\n * batchSize IS CLAMPED TO THE SERVER'S CAP. The ingest route refuses\n * a batch of more than MAX_EVENTS_PER_BATCH events with a 400 whose\n * `issues` say \"a batch may carry at most 5000 events, got N\" -- and\n * an integrator who set `batchSize: 6000` on a busy page got that\n * 400 as KUI_E_INGEST_REJECTED with a remedy blaming a version\n * mismatch. A value above the cap can never be honoured, so the SDK\n * takes the largest batch the server allows rather than post one it\n * knows will be refused; the option's docstring and the README say\n * so. With this, a 400 naming `events` can only mean the server's\n * cap is lower than this SDK's, which IS a version mismatch.\n */\n this.config = {\n ...config,\n batchSize: Math.min(config.batchSize, MAX_EVENTS_PER_BATCH),\n };\n }\n\n /* -------------------------------------------------------------- */\n /* Lifecycle */\n /* -------------------------------------------------------------- */\n\n private fail(\n code: ServerAnsweredCode,\n status: number,\n detail: string | null,\n ): void {\n /*\n * Report a condition that ends the capture, and end it.\n *\n * NOT a throw: this runs inside a flush that nobody awaits, so a throw\n * becomes an unhandled rejection and is exactly as invisible as the\n * bare `return` it replaces. An integrator gets the callback; everyone\n * else gets a console error, which is the floor.\n */\n /*\n * THE QUEUE IS CLEARED BEFORE stop(), and the order is the point:\n * stop() ends with a drain of the queue, which would post the very\n * batch that was just rejected to the very server that rejected it.\n */\n // And the flights waiting to be re-sent: stop()'s drain would\n // otherwise post the very kind of batch that was just rejected.\n this.discard();\n /*\n * TYPED FOR THE PROGRAM, PROSE FOR THE HUMAN. The code is the one\n * codeForStatus answered at the call site -- the same predicate that\n * decided this response was terminal -- so there is no second\n * mapping here to disagree with it and no fallback to hide a caller\n * bug behind. The server's sentence (the `error` field of its JSON\n * body, not the JSON around it) and its `issues[]` -- which fields\n * it refused, the only diagnosis a 400 carries -- ride as evidence,\n * and the prose names them too.\n */\n const err = new IngestRejection({\n code,\n status,\n server: parseServerError(detail),\n endpoint: this.config.endpoint,\n sessionId: this.sessionId ?? null,\n });\n\n // A rejection that ends only this session (see endsSessionOnly) is\n // not an error to anyone: the owner starts the next session.\n if (this.config.endsSessionOnly?.(code, serverReason(detail))) {\n void this.stop();\n try {\n this.config.onSessionEnd?.();\n } catch {\n // As onCaptureEnd below: nothing may resurface inside a flush.\n }\n return;\n }\n\n tell(() => console.error(err.message));\n void this.stop();\n\n /*\n * AND THE CAPTURE ENDS, not just this transport.\n *\n * stop() here left rrweb recording, fetch and XMLHttpRequest\n * patched, the maxSessionDuration timer armed and the singleton\n * set. Every later event was still serialised and masked, then\n * dropped at enqueue(); and a later KeployCapture.init() — after a\n * login that minted a working key — returned the dead instance and\n * recorded nothing for the life of the page, with no second error\n * to say why. LAST, after stop(), so the owner's teardown finds\n * this transport already stopped rather than re-entering it.\n */\n try {\n this.config.onCaptureEnd?.();\n } catch {\n // The owner's teardown must not resurface inside a flush nobody\n // awaits; the console error above has already been written.\n }\n\n /*\n * onError LAST OF ALL, after the singleton is released. It used to\n * come first, and the remedy for a full session -- stop, then\n * init() for a new one -- was a trap when followed from inside the\n * handler: MEASURED, KeployCapture.getInstance() was still the dead\n * instance there and init() returned it, then onCaptureEnd nulled\n * the singleton behind the handler's back -- no new session, no\n * second error. Now a handler that re-inits gets a fresh capture,\n * which is the whole recovery path after a key is rotated.\n */\n try {\n this.config.onError?.(err);\n } catch {\n // An integrator's handler must not be able to suppress the log.\n }\n }\n\n start(\n sessionId: string,\n metadata: SessionMetadata,\n captureIdentity: CaptureIdentity | null = null,\n ): void {\n if (this.started) return;\n this.started = true;\n this.sessionId = sessionId;\n this.metadata = metadata;\n this.captureIdentity = captureIdentity;\n // Sized with a real id: every id this transport mints has the\n // same length, so the envelope cost is a constant.\n this.envelopeBytes = utf8Length(\n JSON.stringify(this.payload([], this.mintBatchId())),\n );\n\n // The timed flush is also where a network that came back unannounced\n // is found (see `online`): it then does what the `online` handler\n // would have done, a drain for the event that could not wait.\n this.flushTimer = setInterval(() => {\n if (this.paced) return;\n void this.flush(this.rushDeferred && this.online);\n }, this.config.batchInterval);\n\n // The browser's state is read wherever it is acted on (`online`): a\n // page started offline (a PWA opened without a network) sent every\n // batch into a failing fetch and its retries instead of holding them\n // until the network was back.\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"online\", this.handleOnline);\n /*\n * pagehide AS WELL AS beforeunload. MEASURED in Chromium\n * 145.0.7632.6 (Playwright 1.58.2, 3 runs each, every run\n * identical): navigating away fires beforeunload, then pagehide; a\n * close that does not run beforeunload handlers — Playwright's\n * page.close() default, runBeforeUnload:false — fires pagehide and\n * never beforeunload; page.close({runBeforeUnload:true}) fires\n * both. Whether a user's own tab close runs beforeunload handlers\n * is the browser's decision; pagehide fired on every unload\n * measured, so the listener on it does not depend on that\n * decision. The old listener was beforeunload alone. Both are\n * kept; the second to fire finds the queue already drained.\n */\n window.addEventListener(\"pagehide\", this.handleUnload);\n window.addEventListener(\"beforeunload\", this.handleUnload);\n document.addEventListener(\"visibilitychange\", this.handleVisibility);\n }\n }\n\n /**\n * HELD: nothing is sent until release(). The capture holds its transport\n * while rrweb's import waits for the network; if that import then\n * fails, the capture is refused, and what was queued meanwhile -- the\n * page's offline calls -- must not reach the server as a session with\n * no DOM. stop() while held sends nothing and drops what was held.\n */\n hold(): void {\n this.holding = true;\n }\n\n /**\n * Sends ALL that was held, batch after batch, and from now on as it\n * comes. All of it, whatever asked: one batch left the rest for the\n * timer, and the FullSnapshot of a page started offline sat behind the\n * page's offline calls -- with them, more than a leaving document's one\n * request can carry -- so a visitor who left within seconds of\n * reconnecting was recorded with no DOM (found in review #28, MEASURED\n * in Chromium). A first fix kept only a drain something had asked for\n * while held, which a snapshot under the keepalive quota never does.\n *\n * What comes AFTER is sent as the browser's state allows, read each\n * time (`online`). A release says rrweb's import was answered, which\n * for a transport started offline is most often the network being back\n * -- and the `online` event that would say so need not reach this\n * transport: the page resumed its capture from a listener of its own\n * that stops the event. Believing the browser offline until an event\n * said otherwise, the transport sent what it had held and nothing after\n * it until the page was left (found in review #29, MEASURED in\n * Chromium). Read, not assumed: a service worker that took control\n * after start() answers the import with the network still down, and\n * what comes after waits for the network there as it did.\n */\n release(): void {\n this.holding = false;\n void this.flush(true);\n }\n\n /** Drops what is queued and what waits to be re-sent, unsent. */\n discard(): void {\n this.queue = [];\n this.queued = 0;\n this.retryQueue = [];\n }\n\n /**\n * Stop accepting events and send what is queued.\n *\n * Resolves when the final flush has settled — a caller that needs to\n * know the tail arrived (a test, an integrator about to navigate)\n * can await it; nothing requires it.\n */\n stop(): Promise<void> {\n if (!this.started) return this.current ?? Promise.resolve();\n this.started = false;\n if (this.holding) this.discard();\n\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n\n /*\n * Final flush through the OBSERVABLE path: the document is alive\n * when stop() is called by the integrator or by the session ending,\n * so there is a response to read, retries to make and an onError to\n * reach. The fire-and-forget path is reserved for page teardown,\n * where there is nothing to read it with.\n */\n const drained = this.flush(true);\n\n if (typeof window !== \"undefined\") {\n window.removeEventListener(\"online\", this.handleOnline);\n /*\n * THE UNLOAD LISTENERS STAY UNTIL THE QUEUE IS EMPTY. The drain\n * goes batch by batch through fetch, and awaiting stop() is\n * optional, so an integrator who calls it on logout and sets\n * location.href in the same tick has every batch but the first\n * still queued when pagehide fires. Removing the listeners here,\n * synchronously, left those batches with no last-chance flush.\n * The unload flush during a drain sends only what run() has not\n * spliced yet, so nothing goes twice.\n *\n * EMPTIED, NOT SETTLED. A drain also settles by failing: three\n * attempts at a 503 or a dropped connection, the batch re-queued,\n * and run() returns. Removing the listeners then left those\n * events with no timer, no listener and nothing that would ever\n * send them — a navigation ten seconds later had no last-chance\n * keepalive send, the very loss this block exists to close. With\n * events still queued, the three listeners stay: a hidden tab\n * drains again through the observable path, and the unload flush\n * carries what fits — the two last chances a document has. The\n * online listener goes as before: after stop() nothing schedules\n * a send. disarmWhenDrained() is the one decision, and every path\n * that empties the queue after stop() takes it (see there).\n */\n void drained.finally(() => this.disarmWhenDrained());\n }\n return drained;\n }\n\n private disarmWhenDrained(): void {\n /*\n * Removes the unload and hidden-tab listeners once there is nothing\n * left for them to send: after stop(), the first time the queue is\n * empty. Called wherever the queue can become empty — the drain\n * stop() started, a later drain (a hidden tab, or fail() on a\n * terminal rejection), the unload flush itself — because a listener\n * kept past that point is a leak for the life of the document: a\n * drain that failed on logout kept them, and the hidden-tab drain\n * that later emptied the queue removed nothing, so the Transport was\n * retained by pagehide, beforeunload and visibilitychange for as\n * long as the document lived. Idempotent; a no-op while started or\n * while events remain.\n */\n if (this.started || this.pendingCount() > 0) return;\n if (typeof window === \"undefined\") return;\n window.removeEventListener(\"pagehide\", this.handleUnload);\n window.removeEventListener(\"beforeunload\", this.handleUnload);\n document.removeEventListener(\"visibilitychange\", this.handleVisibility);\n }\n\n /* -------------------------------------------------------------- */\n /* Enqueue */\n /* -------------------------------------------------------------- */\n\n enqueue(event: SessionEvent): void {\n // `started` is what stops a failed capture accepting more: fail()\n // calls stop(), which clears it. A separate `stopped` flag was added\n // alongside and was redundant — two names for one state, with the\n // second one unreachable.\n if (!this.started) return;\n\n /*\n * STAMPED WITH ITS PLACE IN THE SESSION, HERE, before anything\n * measures or sends it. The server orders a session by this: two\n * requests for one session are on the wire at once by design (the\n * unload flush goes out beside the batch that was being gzipped\n * when it fired), and the later-queued one can arrive first. The\n * stamp is taken as the event is QUEUED, not as it is sent, so a\n * batch that failed, was re-queued and went again keeps its place\n * ahead of the events queued while it was failing. A fetch's event\n * comes with its stamp, taken when it was reported (place()): its\n * masking and this enqueue wait for a task after the page's. It is on the\n * event before the size below is taken because it is bytes on the\n * wire: `,\"seq\":12345` counts against the keepalive quota like\n * everything else.\n */\n event.seq ??= this.nextSeq++;\n\n /*\n * MEASURED BEFORE IT IS QUEUED, AND THE MEASUREMENT CAN FAIL.\n *\n * JSON.stringify throws for a value that references itself\n * (\"Converting circular structure to JSON\") and for a BigInt\n * anywhere inside it (\"Do not know how to serialize a BigInt\").\n * recorder.emitEvent is public and takes `data: unknown`, and this\n * is the end of the emit chain, so that throw does not stay in the\n * SDK: it comes out of rrweb's emit callback, or out of the\n * integrator's own call, in the middle of their page.\n *\n * The push used to come first, so the event also STAYED — and\n * sendWithRetry's stringify of the whole payload sits outside its\n * try, which meant the same value then rejected run(): the batch\n * dropped without being re-queued, and the rejection surfaced from\n * a `void this.flush()` nobody awaits. One bad event poisoned the\n * queue and every enqueue after it threw into the page.\n *\n * Measuring first makes the refusal complete: nothing is queued,\n * nothing is thrown, the session goes on. The seq is spent, so the\n * server sees a gap — which is what it already sees for any batch\n * still in flight, and it sorts by seq rather than requiring a run.\n */\n let bytes: number;\n try {\n const json = JSON.stringify(event);\n const own = utf8Length(json);\n this.jsonOf.set(event, [json, own]);\n bytes = this.envelopeBytes + own;\n } catch (err) {\n this.reportUnserialisable(event, err);\n this.dropped([event]);\n return;\n }\n\n /*\n * AN EVENT THE SERVER CAN NEVER TAKE IS NOT QUEUED. Alone in a body\n * it is already over the decoded cap, so no flight could carry it,\n * and at the head of the queue it would hold everything behind it\n * forever (formFlight() cuts at the first event that does not\n * fit). Dropped and said once, like an unserialisable event: not\n * terminal, the capture goes on without it.\n */\n if (bytes > MAX_BATCH_BYTES) {\n this.reportOversized(event, bytes);\n this.dropped([event]);\n return;\n }\n\n this.queue.push(event);\n this.held += bytes;\n this.queued += this.eventBytes(event);\n\n // Drop oldest events if we exceed the cap.\n const evicted: SessionEvent[] = [];\n while (this.queue.length > this.config.maxQueueSize) {\n const e = this.queue.shift()!;\n this.queued -= this.eventBytes(e);\n evicted.push(e);\n }\n if (evicted.length > 0) this.dropped(evicted);\n this.fit();\n\n /*\n * AN EVENT THE UNLOAD FLUSH CAN NEVER CARRY DOES NOT WAIT FOR THE\n * TIMER. flushOnUnload cuts at the first event that does not fit\n * the keepalive quota, so one over the quota on its own — an rrweb\n * FullSnapshot of a big page, a network event with a large body —\n * holds back everything behind it, and a document that is leaving\n * has no other way to send. A session that ended by\n * navigation before its first timed flush, with that snapshot at\n * the head of the queue, shipped nothing at all: every bounce from\n * a big page was lost entirely. So such an event is sent the moment\n * it is queued, through the observable path, as a drain: a drain is\n * picked up by a flush already running, where a plain flush()\n * request would be absorbed by it and the event would wait for the\n * timer after all. Not while the browser says it is offline —\n * nothing can be sent then, the timed flush honours that flag too,\n * and the online handler sends the moment it clears. It DRAINS\n * then, because it is told to: a plain flush() there is one batch,\n * and an oversized event queued offline behind batchSize events\n * is not in it — it waited for the timer after all, and a\n * navigation in that window lost it and everything behind it.\n *\n * The measurement is one JSON.stringify per event. MEASURED in\n * Node 24.21: 2.1 µs for a 228-byte rrweb mutation event, 27 µs for\n * 11.6 KB, 0.61 ms for a 236 KB snapshot.\n */\n // While uploads fail, nothing here starts a flight before the wait\n // between flights is over (OUTAGE_FIRST_MS): an event over the\n // keepalive share started one each, three attempts at once, into a dead endpoint.\n if (this.paced) return;\n if (bytes > KEEPALIVE_QUOTA_BYTES) {\n if (this.online) void this.flush(true);\n else this.rushDeferred = true;\n } else if (this.queue.length >= this.config.batchSize) {\n // A full batch is a batch, whatever its bytes: never the counter's.\n // With a flight out, flush() hands back the run under way, so the\n // ask is that run's to make good (run()).\n if (this.current !== null) this.asked++;\n void this.flush();\n } else if (\n // THE QUEUE PAST WHAT THE UNLOAD REQUEST CARRIES GOES NOW: a visitor\n // who left with more queued lost the newest of it -- the click that\n // navigated away (review). A plain fetch (Flight.early), and run()\n // goes on only while the queue is still past it: one upload at a\n // time, ending once it is back under (review). Counters only:\n // nothing walks the queue, and offline nothing is started (the\n // online handler sends).\n this.online &&\n this.pastShare()\n ) {\n this.counted = true;\n void this.flush();\n }\n }\n\n /**\n * A place in the session, taken now for an event queued later: a\n * fetch's, reported when its body ends and recorded in a task after\n * the page's (NetworkInterceptor.emit). Its seq is the one it would\n * have been stamped with, recorded there, so the server orders the\n * session as it did.\n */\n place(): number {\n return this.nextSeq++;\n }\n\n /** Uploads are failing and the wait before the next flight is not over. */\n private get paced(): boolean {\n return performance.now() < this.notBefore;\n }\n\n /**\n * Holds what is unsent at MAX_QUEUE_BYTES, dropping the oldest first:\n * waiting flights whole, then queued events. fit() never drops the\n * newest -- enqueue() admits none over MAX_BATCH_BYTES, which is under\n * the cap -- though dropped() may, as it takes any incremental read\n * against a DOM event that went. What goes is said (dropped()), so the recorder knows\n * of the hole a DOM event leaves.\n */\n private fit(): void {\n if (this.held <= MAX_QUEUE_BYTES) return;\n let n = 0;\n for (const f of this.retryQueue) n += f.bytes;\n for (const e of this.queue) n += this.eventBytes(e);\n const out: SessionEvent[] = [];\n while (n > MAX_QUEUE_BYTES) {\n const f = this.retryQueue.shift();\n if (f) {\n n -= f.bytes;\n out.push(...f.events);\n } else {\n const e = this.queue.shift()!;\n n -= this.eventBytes(e);\n this.queued -= this.eventBytes(e);\n out.push(e);\n }\n }\n this.held = n;\n if (out.length > 0) this.dropped(out);\n }\n\n /**\n * Said to the owner (TransportConfig.onDropped): events dropped unsent.\n * A dropped DOM event takes with it the rrweb incrementals still queued\n * behind it up to the next FullSnapshot: each is read against what the\n * dropped event held, and posted, a click on a button the dropped\n * snapshot held was resolved to `body` (found in review #23). A\n * FullSnapshot is never dropped ahead of its incrementals.\n */\n private dropped(events: SessionEvent[]): void {\n /*\n * OFFLINE IS AN OUTAGE TOO. Nothing is sent while the browser says it\n * is offline, so a hole made then is held, like one made while uploads\n * fail, and the recorder's one snapshot waits for the outage to\n * end. MEASURED on MEASURE.md's 22.5k-node page offline for 300 s:\n * the eviction re-snapshot was a long task\n * of 195-337 ms (main 81f32f0960, 2 runs). Said here, at the\n * drop, so the recorder hears it before lost() asks for a snapshot.\n */\n if (!this.online && this.failures === 0) {\n this.failures = 1;\n tell(() => this.config.onFailing?.(true));\n }\n let from = Infinity;\n for (const e of events)\n if (e.type === \"dom\") from = Math.min(from, e.seq ?? -Infinity);\n let baseline = false;\n if (from !== Infinity) {\n // Only what was queued AFTER it: a trim drops the newest events,\n // and the older ones it leaves were read against a baseline that\n // was sent.\n const kept: SessionEvent[] = [];\n for (const e of this.queue) {\n const after = (e.seq ?? -Infinity) > from;\n const rrwebType =\n e.type === \"dom\"\n ? (e.data as { type?: unknown } | null)?.type\n : undefined;\n if (after && rrwebType === 2) baseline = true;\n if (after && !baseline && rrwebType === 3) {\n events.push(e);\n this.queued -= this.eventBytes(e);\n } else kept.push(e);\n }\n this.queue = kept;\n }\n tell(() => this.config.onDropped?.(events, baseline));\n }\n\n private reportUnserialisable(event: SessionEvent, err: unknown): void {\n /*\n * Say that an event was dropped because it could not be serialised —\n * ONCE per transport, and the line says so.\n *\n * Not a throw: the caller is rrweb's emit callback or the\n * integrator's own code, and the SDK has no business ending their\n * turn. Not `onError` either: that one is reserved for a terminal\n * condition that ENDS the capture, and this one does not — the\n * session goes on without this event.\n *\n * Once, because a custom event emitted from a render or a timer would\n * otherwise write a console line every few milliseconds for the life\n * of the page: the SDK degrading the page it is there to record. The\n * first line carries the event's id and the reason, which is what a\n * developer needs to find the emitter; the rest would only repeat it.\n */\n if (this.reportedUnserialisable) return;\n this.reportedUnserialisable = true;\n const reason = err instanceof Error ? err.message : String(err);\n // eslint-disable-next-line no-console -- the one console write the SDK\n // makes, and only once per session: an event that cannot be serialised\n // is dropped silently otherwise, and `onError` is deliberately NOT\n // called for it, so the page would lose data with nothing said. The\n // line names KUI_E_EVENT_UNSERIALISABLE so a log scanner can resolve it.\n // console.warn, as every warning: a page whose tests or error tracker\n // fail on console.error must not fail on an event the SDK dropped.\n // The reason rides in the evidence JSON only, escaped: repeated in the\n // prose it would put V8's three-line cycle message, or an \"evidence=\"\n // of its own, there. See warningLine.\n console.warn(\n warningLine(\n {\n code: \"KUI_E_EVENT_UNSERIALISABLE\",\n eventId: event.id,\n eventType: event.type,\n reason,\n },\n `it cannot be serialised to JSON.`,\n ),\n );\n }\n\n private reportOversized(event: SessionEvent, bytes: number): void {\n /*\n * Say that an event was dropped because, alone in a body, it is over\n * the server's decoded cap -- ONCE per transport, like\n * reportUnserialisable and for the same reasons: not a throw into the\n * emitter's turn, not `onError` (the capture goes on), and not a line\n * per event.\n */\n if (this.reportedOversized) return;\n this.reportedOversized = true;\n this.warnOversized(\n {\n code: \"KUI_E_EVENT_OVERSIZED\",\n eventId: event.id,\n eventType: event.type,\n bytes,\n cap: MAX_BATCH_BYTES,\n },\n `${bytes} bytes in a body, over the ingest server's ` +\n `${MAX_BATCH_BYTES}-byte cap, so no batch could carry it.`,\n );\n }\n\n /**\n * Say that the recorder dropped an event because scrubbing the page\n * URL's credentials out of it passed the server's decoded cap (privacy.ts\n * ScrubOverCap) -- ONCE per transport, like reportOversized. The event\n * never reached the queue, so it has no id; `atLeast` is a lower bound of\n * the scrubbed event's size: what the scrub had written when it stopped,\n * less what a later replacement could still take off it.\n */\n reportScrubOversized(\n eventType: SessionEvent[\"type\"],\n atLeast: number,\n cap: number,\n ): void {\n if (this.reportedScrubOversized) return;\n this.reportedScrubOversized = true;\n this.warnOversized(\n { code: \"KUI_E_EVENT_OVERSIZED_SCRUBBING\", eventType, atLeast, cap },\n `scrubbing the page URL's credentials out of it was certain to write at least ` +\n `${atLeast} characters, over the ingest server's ${cap}-byte cap, ` +\n `so no batch could carry it.`,\n );\n }\n\n /**\n * Say that the page made a History or Navigation API method the SDK wraps\n * impossible to replace and put back, so the recorder wrapped none\n * (recorder.ts wrapHistory) -- ONCE per transport, like\n * reportScrubOversized. Nothing is dropped: route changes are still\n * recorded, with less detail (recorder.ts, ALL OR NOTHING).\n */\n reportNavigationUnwrapped(method: string): void {\n if (this.reportedNavigationUnwrapped) return;\n this.reportedNavigationUnwrapped = true;\n this.warn(\n noticeLine(\n { code: \"KUI_E_NAVIGATION_UNWRAPPED\", method },\n \"the page made a History or Navigation API method impossible to replace and put back, \" +\n \"so the SDK wrapped none of them. The capture continues: route changes are still \" +\n \"recorded, with less detail, and none says that the page's script asked for it.\",\n ),\n );\n }\n\n /** The console line for an event too large to send: once per code, as each caller decides. */\n private warnOversized(evidence: CaptureWarningEvidence, why: string): void {\n this.warn(warningLine(evidence, why));\n }\n\n /** One console line; each caller says its code once per capture. */\n private warn(line: string): void {\n // eslint-disable-next-line no-console -- once per session; see reportUnserialisable.\n console.warn(line);\n }\n\n /** The request body for `events`, with everything a batch carries. */\n private payload(events: SessionEvent[], batchId: string): TransportPayload {\n return {\n sessionId: this.sessionId!,\n batchId,\n events,\n metadata: this.metadata,\n sdk: { name: SDK_NAME, version: SDK_VERSION },\n captureIdentity: this.captureIdentity,\n };\n }\n\n /* -------------------------------------------------------------- */\n /* Flush */\n /* -------------------------------------------------------------- */\n\n /**\n * Send queued events.\n *\n * `drain` sends EVERYTHING queued — batch after batch, each one sized\n * like a timed batch, so the server's body limit is the same one a\n * timed batch faces — and if a flush is already running it is picked\n * up by that flush when its current batch finishes. A drain that\n * silently returned because a batch happened to be in flight would\n * leave a hidden tab holding events it may never get another chance\n * to send. A drain also ignores the `offline` flag: it is the last\n * attempt, the browser's offline signal is advisory, and a fetch that\n * fails retries and re-queues anyway. The promise resolves when the\n * running flush, drain included, has settled.\n */\n flush(drain = false): Promise<void> {\n // Held, nothing is sent and nothing is remembered: release() drains\n // whatever was asked for meanwhile.\n if (this.holding) return Promise.resolve();\n if (drain) this.drainPending = true;\n if (this.current) return this.current;\n if (this.pendingCount() === 0 || (!this.online && !this.drainPending)) {\n this.drainPending = false;\n /*\n * NOTHING LEFT TO PROBE WITH, AND ONLINE. The cap took the flight that\n * waited and dropped() the incrementals read against it: on a page\n * that makes only DOM events nothing is pending, nothing would ever\n * be sent, and the outage -- and the recorder's hold -- would never\n * end (found in review). So it ends at the first flush the wait lets\n * through, and the recorder's one snapshot is the next flight and the\n * probe. Not while offline: there the snapshot would only be queued,\n * and dropped again.\n */\n if (this.failures > 0 && this.pendingCount() === 0 && this.online) {\n this.failures = this.notBefore = 0;\n tell(() => this.config.onFailing?.(false));\n }\n return Promise.resolve();\n }\n this.current = this.run();\n return this.current;\n }\n\n private async run(): Promise<void> {\n let full = false;\n try {\n do {\n /*\n * A FLIGHT THAT FAILED GOES OUT AGAIN AS IT WAS, before anything\n * newer: same batchId, same bytes. Only when none is waiting is\n * a new one formed from the queue.\n */\n const flight = this.reviveNext() ?? this.formFlight();\n if (flight === null) return;\n /*\n * VISIBLE TO THE UNLOAD FLUSH while it is out of the queue. See\n * reclaimInFlight(): pagehide before the fetch is dispatched\n * takes these events back rather than shipping the tail over a\n * hole.\n */\n this.inFlight = flight;\n try {\n await this.sendWithRetry(flight);\n } catch {\n // Re-queue the FLIGHT that failed to send (at the front).\n // Whole, never as loose events: see batchId. The unload flush\n // cannot have taken it meanwhile: sendWithRetry throws only as\n // its last attempt ends, in the same turn -- no wait follows\n // that attempt -- and the loop of a flight the flush took\n // returns instead of throwing. (A guard stood here for the\n // wait that used to follow the last attempt: a pagehide inside\n // it sent the batch, and the throw after it queued the batch\n // again.)\n /*\n * UPLOADS ARE FAILING: the next flight waits (OUTAGE_FIRST_MS),\n * and is said to fail BEFORE the flight is queued again, so a\n * DOM event that trim drops now finds the recorder already\n * holding its snapshot for the recovery.\n */\n this.notBefore =\n performance.now() +\n Math.min(OUTAGE_FIRST_MS * 2 ** this.failures, OUTAGE_MAX_MS) *\n (1 + Math.random() / 2);\n if (this.failures++ === 0) tell(() => this.config.onFailing?.(true));\n this.held += flight.bytes;\n this.retryQueue.unshift(flight);\n this.trimToCapacity();\n // A DRAIN THAT FAILED IS STILL OWED, and is made: this failure\n // starts or continues an outage, and the upload that ends it sends all that\n // is queued (sendWithRetry), never a batch per timed flush --\n // a visitor who left meanwhile took the rest with them (found\n // in review #29, MEASURED in Chromium: 50 of 95 calls and no\n // snapshot, 6 times of 6).\n return;\n } finally {\n if (this.inFlight === flight) this.inFlight = null;\n }\n // Past the share with no drain asked: the counter's run goes on.\n this.counted = !this.drainPending && this.online && this.pastShare();\n /*\n * A FULL BATCH QUEUED WHILE A FLIGHT WAS OUT GOES AS IT SETTLES.\n * Its enqueue() asked for a flush, and the flush was this run's\n * (flush() hands back the run under way), so with the run ended\n * here it waited for the timer: at batchSize 1 an exchange\n * recorded while the one before it was posted reached the server\n * batchInterval later, and a tab killed meanwhile lost it. One\n * batch per ask, as with no flight out: a backlog the timer finds\n * (offline, an outage, held) still drains a batch a flush.\n */\n full =\n this.asked > 0 &&\n !this.holding &&\n this.online &&\n this.queue.length >= this.config.batchSize;\n if (full) this.asked--;\n } while (\n (this.drainPending || this.counted || full) &&\n this.pendingCount() > 0\n );\n } finally {\n // Inside the async function, so there is no microtask gap between\n // the loop ending and this: a drain requested in that gap used to\n // be cleared here without ever running.\n this.drainPending = false;\n /*\n * THE COUNTER'S ASK ENDS WITH THE RUN. An enqueue past the share\n * while a flight was out asked for the counter's run; a success\n * reads the queue again above, but a failed upload returned with\n * the ask still set, and capped at the share the one flight the\n * next timed or asked flush formed once no failed flight waited.\n * The next enqueue past the share asks again.\n */\n this.counted = false;\n // So do the asks for full batches: one the run could not make good\n // (offline, held, a failed upload) is the next flush's backlog.\n this.asked = 0;\n if (this.pendingCount() === 0) this.rushDeferred = false;\n this.current = null;\n // After stop(), the drain that empties the queue is the one that\n // releases the unload listeners — this one, when stop()'s own\n // drain failed and a later one (a hidden tab) succeeded.\n this.disarmWhenDrained();\n }\n }\n\n /* -------------------------------------------------------------- */\n /* Network send */\n /* -------------------------------------------------------------- */\n\n /**\n * The wait before the next attempt, ENDED BY `online`: the network\n * being back is what the wait was for, and a sender that slept on\n * sent nothing for up to 2 s more while the page's visitor was\n * leaving (found in review #29). One sender runs at a time, so one\n * wait is pending at most.\n */\n private backoff(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const done = (): void => {\n clearTimeout(timer);\n if (this.wakeSender === done) this.wakeSender = null;\n resolve();\n };\n const timer = setTimeout(done, ms);\n this.wakeSender = done;\n });\n }\n\n private async sendWithRetry(flight: InFlightBatch): Promise<void> {\n // Serialised when the flight was formed, never here: a retry, a\n // re-queue and a re-send after a lost response all put the same\n // bytes under the same batchId, which is what makes the server's\n // \"already stored\" answer possible.\n const json = flight.json;\n // Gzipped once per flight (InFlightBatch.wire), not once per attempt.\n const wire = (flight.wire ??= compressPayload(json));\n\n for (let attempt = 0; attempt < MAX_RETRY_ATTEMPTS; attempt++) {\n // The unload flush took these events while this was sleeping or\n // compressing. They are sent or re-queued by now; sending them\n // again would duplicate them in the server's seq-sorted file.\n if (flight.abandoned) return;\n /*\n * THE TRY IS THE NETWORK'S ALONE: the wire body, the fetch and the\n * read of its body. What is done with the answer -- the owner told\n * of a delivery, of the outage's end, of a rejection -- is outside\n * it: in it, a throw from any of those was read as a network error\n * and the batch went out again (the server's \"already stored\" for\n * an accepted one, a second POST of a rejected one).\n */\n let response: Response | undefined;\n let detail: string | null = null;\n try {\n const { body, bytes, encoding } = (flight.sent = await wire);\n if (flight.abandoned) return;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"X-API-Key\": this.config.apiKey,\n };\n if (encoding) {\n headers[\"Content-Encoding\"] = encoding;\n }\n\n /*\n * KEEPALIVE ONLY WHEN THE BROWSER WILL ACCEPT IT. keepalive lets\n * a request outlive a tab closed mid-flight, but a keepalive body\n * over the quota is refused before it leaves the browser — so an\n * rrweb full snapshot of a large page never shipped: refused,\n * retried three times, re-queued at the head, and eventually\n * shifted out as the queue filled. See KEEPALIVE_QUOTA_BYTES.\n */\n // Less what is in flight: an unload request of a document restored\n // from the back/forward cache may still be on the wire (review).\n const keepalive =\n !flight.early &&\n bytes <= KEEPALIVE_QUOTA_BYTES - this.inflightKeepaliveBytes;\n\n if (keepalive) this.inflightKeepaliveBytes += bytes;\n /*\n * THE COUNTER FALLS WITH THE BROWSER'S, WHICH IS WHEN THE BODY\n * HAS BEEN READ.\n *\n * inflightKeepaliveBytes is this SDK's copy of a counter the\n * browser also keeps: the SDK sizes the next keepalive request\n * against its copy (see flushOnUnload) and the browser refuses\n * that request against its own, so a copy that falls early is\n * a copy that says there is room the browser does not have.\n *\n * It used to fall in the finally below, on the headers.\n * MEASURED in Chromium 145.0.7632.6 (Playwright, a page posting\n * two 40 KiB keepalive bodies back to back to a second port,\n * 200 with a 4 KB JSON ack, 5 pairs = 10 requests per scenario,\n * the matrix re-run in a different order for the same result):\n *\n * - response never read: 1/10 delivered\n * - `await response.body.cancel()`: 5/10 — the second of\n * every pair refused\n * - `await response.arrayBuffer()`: 10/10\n * - `await response.text()`: 10/10\n *\n * The bytes are the browser's until the body has been READ TO\n * COMPLETION; cancelling the stream frees nothing. And two\n * near-quota requests back to back are the ordinary case, not a\n * corner: an event near the quota is posted the moment it is\n * queued (see enqueue). So the body is read here, before the\n * counter falls — and the text it returns is the diagnostic the\n * 4xx branch below needs anyway, read once rather than twice.\n *\n * A body the endpoint starts and never finishes now stalls this\n * attempt, where the old code returned on the headers. It costs\n * the same capture either way: the browser holds that request's\n * bytes against the quota for exactly as long, so every\n * keepalive batch behind it would be refused instead. The\n * events in the stalled batch are not lost either — the server\n * answered 200 for them, which is why `flight.onWire` stays set\n * across the read rather than letting the unload flush post\n * them again.\n */\n /*\n * ON THE WIRE, AND STILL ON IT WHILE THE BODY IS BEING READ.\n * The unload flush leaves these events alone for as long as\n * this is set: a keepalive request that has been dispatched\n * outlives the document, one without keepalive may still\n * arrive, and by the time the headers are in the server HAS\n * the batch — reclaiming it across the read below would post\n * the same events a second time into a file the server appends\n * to by seq. Cleared in the same finally as the counter, which\n * also runs on the throw path, so the backoff after a failed\n * attempt is reclaimable again.\n */\n flight.onWire = true;\n flight.dispatched = true;\n try {\n response = await fetch(this.config.endpoint, {\n method: \"POST\",\n headers,\n body,\n keepalive,\n });\n try {\n detail = await response.text();\n } catch {\n // A body that could not be read is still a body the browser\n // has finished with; there is just nothing to say about it.\n detail = null;\n }\n } finally {\n flight.onWire = false;\n if (keepalive) this.inflightKeepaliveBytes -= bytes;\n }\n } catch {\n // Network error - retry.\n }\n\n if (response) {\n if (response.ok) {\n if (this.failures > 0) {\n /*\n * BACK. The wait between flights is over, what piled up goes\n * now rather than a batch per timer -- left at the cap, the\n * queue would go on dropping -- and the recorder takes its\n * one snapshot for the outage's holes.\n */\n this.failures = this.notBefore = 0;\n this.drainPending = true;\n tell(() => this.config.onFailing?.(false));\n }\n tell(() => this.config.onDelivered?.(flight.events));\n return;\n }\n\n /*\n * A TERMINAL 4xx IS REPORTED AND STOPS THE CAPTURE.\n *\n * This was a bare `return`: no throw, no callback, no log. So a\n * server rejecting every batch — a revoked API key, a 409 from\n * two runs claiming one session id — produced a capture with\n * ZERO events and no indication anywhere that anything was\n * wrong. Empty-result-as-success, in the SDK, for a condition\n * the server had diagnosed precisely.\n *\n * The 409 case made it routine rather than rare: it is the\n * documented outcome of a supported feature\n * (`sessionIdGenerator` returning a fixed value), so the silent\n * path became the normal one.\n *\n * Retrying is still wrong — the server's answer will not change —\n * so this stops posting instead of looping into a permanent\n * rejection, and says why.\n */\n const { status } = response;\n const code = codeForStatus(status);\n if (code !== null) {\n tell(() => this.fail(code, status, detail));\n return;\n }\n // 5xx or 429 - fall through to retry.\n }\n\n // No wait after the LAST attempt: there is nothing to wait for,\n // and for those 2 to 4 s the batch was in neither the queue nor a\n // request (found in review #29).\n // One attempt while uploads fail: the wait between flights is the\n // back-off then, and three a flight was three POSTs per trigger.\n if (this.failures > 0) break;\n if (attempt === MAX_RETRY_ATTEMPTS - 1) break;\n // Exponential backoff with jitter.\n const delay =\n BASE_RETRY_DELAY_MS *\n Math.pow(2, attempt) *\n (0.5 + Math.random() * 0.5);\n await this.backoff(delay);\n }\n\n // All retries exhausted - throw so the caller can re-queue.\n throw new Error(\"Transport: all retry attempts failed\");\n }\n\n /* -------------------------------------------------------------- */\n /* Page-unload flush */\n /* -------------------------------------------------------------- */\n\n /**\n * The last flush, issued while the document is being torn down.\n *\n * THIS WAS navigator.sendBeacon, AND EVERY SESSION LOST ITS TAIL.\n * sendBeacon cannot set headers, so the batch arrived at the ingest\n * endpoint with no X-API-Key and was refused with 401 — after the\n * events had been spliced out of the queue, and with no response for\n * anything here to read. MEASURED in Chromium 145.0.7632.6 with a\n * cross-origin endpoint, 5 runs per scenario: the beacon's\n * application/json Blob also forces a CORS preflight the beacon does\n * not survive, 0/5 delivered on navigate-away and 0/5 on tab close.\n *\n * fetch with keepalive:true is what sendBeacon is specified as, plus\n * headers: same measurement, 5/5 and 5/5, key attached. The request\n * is dispatched SYNCHRONOUSLY inside the unload handler — no\n * compression, because CompressionStream is async and an await here\n * lands after the document is gone.\n *\n * THE PAYLOAD IS CUT AT THE KEEPALIVE QUOTA, oldest events first. A\n * keepalive request over the quota is refused by the browser before\n * it leaves, and one refused request loses everything; one cut at the\n * quota ships the prefix that fits. The quota is on the SUM of\n * in-flight keepalive bodies, so a timed batch still on the wire is\n * subtracted.\n *\n * THE CUT IS AT THE FIRST EVENT THAT DOES NOT FIT, in order — not\n * skip-and-continue. An event over the quota on its own (a network\n * event with a large body; an rrweb FullSnapshot of a big page) holds\n * back everything queued behind it, small or not. Not for order's\n * sake — every event carries its `seq` and the server sorts by it, so\n * a document that survives its pagehide (a back/forward-cache entry)\n * and later ships the held-back event from its timer is stored in\n * order regardless. For the node map: the flow engine's extractor.ts\n * rebuilds the DOM from the FullSnapshot and the mutations after it,\n * and every incremental event behind a snapshot names its nodes by\n * that snapshot's ids. Shipped without it, they are resolved against\n * a DOM that does not hold their nodes, and selectorFromNode answers\n * `body` for a node it cannot find — a click on `body` in the generated test, silently,\n * where the session ending at the snapshot would have been the\n * truth. So what does not fit holds back what depends on it.\n *\n * Events that do not fit stay in the queue: there is no way to send\n * them from a dying page, and no way to report it — this is the one\n * flush that is fire-and-forget, and only because the document is\n * leaving. Which is why an event that can never fit is not left to\n * wait here: enqueue() sends it as soon as it is queued.\n */\n private reclaimInFlight(): void {\n /*\n * Take back the batch run() is holding, if no request for it has been\n * dispatched yet.\n *\n * THE GAP THIS CLOSES. run() splices a batch out of the queue and\n * hands it to sendWithRetry, and a request does not leave the browser\n * straight away: compressPayload is asynchronous, and after a failed\n * attempt sendWithRetry sleeps 0.5–1 s, then 1–2 s, before the next\n * one. Through all of that the events are in neither the queue nor a\n * request, and the unload flush could not see them. pagehide in that\n * window shipped the events queued AFTER them with keepalive and\n * never dispatched these, because an await does not resume in a\n * document that is gone — so the server's seq-sorted file got the\n * tail with a hole in the body. A hole is worse than a short\n * recording: the events after it name node ids the missing batch\n * introduced, and the flow engine resolves them against a map that\n * does not hold them.\n *\n * ONLY WHILE NOTHING IS ON THE WIRE. A dispatched keepalive request\n * outlives the document by design, and one without keepalive may\n * still arrive; re-sending those events would duplicate them in a\n * file the server appends to by seq. That request in flight when the\n * document dies is the residual limit, and it is the same one every\n * in-flight request has.\n *\n * `abandoned` stops every further attempt, so a document that\n * SURVIVES its pagehide (a back/forward-cache entry, a cancelled\n * navigation) does not send the batch a second time when the backoff\n * resumes: its loop returns, and so throws nothing for run() to\n * queue again.\n */\n const flight = this.inFlight;\n if (!flight || flight.onWire || flight.abandoned) return;\n flight.abandoned = true;\n this.inFlight = null;\n this.held += flight.bytes;\n if (flight.dispatched) {\n /*\n * IT HAS BEEN ON THE WIRE, so the server may hold it under this\n * batchId already. It goes back as a flight, to be re-sent whole\n * under the same id, never as loose events the unload flush would\n * re-batch under a new one.\n */\n this.retryQueue.unshift(flight);\n this.trimToCapacity();\n return;\n }\n // Never dispatched: the server has never seen these events under\n // any id, so they are ordinary queued events again. At the FRONT:\n // they were spliced off the head, so their seq numbers are below\n // everything still queued, except an exchange's event queued since\n // with the lower seq it was reported at, which the unload cut sorts\n // back in.\n this.queue.unshift(...flight.events);\n this.uncount(flight.events, -1);\n this.trimToCapacity();\n }\n\n private reviveNext(): InFlightBatch | null {\n /*\n * The next waiting flight as a FRESH ATTEMPT CONTEXT, or null.\n *\n * `abandoned` does one job: it stops the sendWithRetry loop that was\n * running when the unload flush took the flight. That loop still\n * holds the OLD object, so it must keep seeing `abandoned === true`\n * -- but the re-send must not, or it returns from sendWithRetry\n * before its first attempt and run() counts the flight as delivered.\n * MEASURED: a flight over the keepalive quota, reclaimed at pagehide\n * during its backoff on a document that survived (a download click,\n * a cancelled navigation, a bfcache restore), was shifted by the next\n * flush and dropped -- queueSize 2 -> 0, zero requests, where the\n * pre-batchId transport delivered both events. So the flags are\n * per attempt and the id and bytes are per flight.\n */\n const waiting = this.retryQueue.shift();\n if (!waiting) return null;\n return {\n events: waiting.events,\n batchId: waiting.batchId,\n json: waiting.json,\n bytes: waiting.bytes,\n wire: waiting.wire,\n dispatched: waiting.dispatched,\n onWire: false,\n abandoned: false,\n // Sent early, it is re-sent early: never keepalive (review).\n early: waiting.early,\n };\n }\n\n private formFlight(): InFlightBatch | null {\n /*\n * A new flight from the head of the queue, or null when it is empty.\n * The id and the bytes are minted together, once.\n *\n * CUT BY BYTES AS WELL AS BY COUNT, the way the unload flush cuts\n * against the keepalive quota: at the first event that would take the\n * decoded body over MAX_BATCH_BYTES, everything behind it holding for\n * the next flight. Under MAX_BATCH_BYTES the first event always fits\n * -- enqueue() refused anything that alone would not; under the\n * counter's cap it may not (an unload request still on the wire after\n * a back/forward-cache restore), and the guard below sends it alone.\n * A flight is never empty while the queue is not.\n */\n if (this.queue.length === 0) return null;\n const pastShare = this.pastShare();\n // THE COUNTER'S FLIGHT FITS THE PAGEHIDE REQUEST: Firefox aborts a\n // plain upload on the wire as the navigation starts, before pagehide,\n // and it is re-sent there first, whole, with its batchId; one over the\n // share held back the whole pagehide request (MEASURED in Firefox,\n // logs/diagff2.log). Drains are not capped, nor are timed and asked\n // flushes: the counter's ask ends with its run (run()). Its bytes are\n // counted below either way.\n const cap =\n this.counted && !this.drainPending && pastShare\n ? KEEPALIVE_QUOTA_BYTES - this.inflightKeepaliveBytes\n : MAX_BATCH_BYTES;\n this.counted = false;\n let biggest = 0;\n let bytes = this.envelopeBytes;\n let count = 0;\n const most = Math.min(this.config.batchSize, this.queue.length);\n while (count < most) {\n const cost = this.eventBytes(this.queue[count]!) + (count === 0 ? 0 : 1);\n if (bytes + cost > cap) break;\n if (cost > biggest) biggest = cost;\n bytes += cost;\n count++;\n }\n // Never an empty flight while the queue is not: count is 0 only when\n // the counter's cap is under the head event, which then goes alone.\n // Were none sent, run()'s drain would post empty batches forever\n // with the head stuck; one over-cap POST and its 413 is the\n // visible failure, so the guard takes that side. ITS BYTES ARE THE\n // FLIGHT'S: a failed flight is held by `bytes` (fit()), and left out,\n // an outage held more than MAX_QUEUE_BYTES (MEASURED: sdk-outage's\n // e2e, 16,808,376 B held, CI pipeline 331).\n if (count === 0) {\n biggest = this.eventBytes(this.queue[0]!);\n bytes += biggest;\n }\n const batch = this.queue.splice(0, Math.max(count, 1));\n this.uncount(batch);\n const batchId = this.mintBatchId();\n const json = this.body(batch, batchId);\n for (const e of batch) this.jsonOf.delete(e);\n return {\n events: batch,\n batchId,\n json,\n dispatched: false,\n onWire: false,\n abandoned: false,\n bytes,\n // A rush is an event enqueue() measured over the share with its envelope.\n early: pastShare && this.envelopeBytes + biggest <= KEEPALIVE_QUOTA_BYTES,\n };\n }\n\n /**\n * The POST body for `events`: JSON.stringify(this.payload(events,\n * batchId)), the same text, with each event's JSON as enqueue() wrote\n * it, joined. The envelope is written with no events; its\n * `\"events\":[]` is the first, since only the session and batch ids,\n * strings, come before it, and no string's JSON holds a bare `\"`. An\n * event with no JSON kept (one a flight carried, taken back at\n * pagehide) is written now.\n */\n private body(events: SessionEvent[], batchId: string): string {\n return JSON.stringify(this.payload([], batchId)).replace(\n '\"events\":[]',\n () =>\n `\"events\":[${events.map((e) => this.jsonOf.get(e)?.[0] ?? JSON.stringify(e)).join()}]`,\n );\n }\n\n /** The event's JSON bytes: what enqueue() measured, or measured now for one a flight carried and pagehide took back. */\n private eventBytes(event: SessionEvent): number {\n return this.jsonOf.get(event)?.[1] ?? utf8Length(JSON.stringify(event));\n }\n\n private mintBatchId(): string {\n /*\n * The SDK's idempotency key for one POST: 36 characters of a UUID,\n * which is within the server's session-id shape (letters, digits,\n * dot, dash, underscore). Falls back to time plus a counter and a\n * random suffix where crypto.randomUUID is not available; only\n * uniqueness within one session matters, since the server scopes the\n * id to the session.\n */\n const c = typeof crypto !== \"undefined\" ? crypto : undefined;\n if (c && typeof c.randomUUID === \"function\") return c.randomUUID();\n /*\n * CONSTANT LENGTH, because envelopeBytes is measured once at start()\n * with one of these and every unload cut is sized against it. The\n * fallback is the ORDINARY path on any non-loopback http:// origin\n * (an insecure context has no crypto.randomUUID), and a counter\n * written as bare hex grows a digit at 16, 256 and 4096 flights --\n * MEASURED: an unload batch sized with the 22-character envelope was\n * posted at 65,537 bytes with the 23-character id, one over the\n * quota this file measures Chromium refusing. Padded, the id is 30\n * characters: Date.now() in hex is 11 digits today and 12 from the\n * year 2527, both inside the 12 it is padded to, until the year\n * 10,889.\n */\n this.batchCounter += 1;\n const rand = Math.floor(Math.random() * 0xffffffff)\n .toString(16)\n .padStart(8, \"0\");\n return (\n `${Date.now().toString(16).padStart(12, \"0\")}-` +\n `${(this.batchCounter % 0x100000000).toString(16).padStart(8, \"0\")}-` +\n rand\n );\n }\n\n /** Takes `events` off the queued bytes (`sign` -1: puts them back). */\n private uncount(events: SessionEvent[], sign = 1): void {\n for (const e of events) this.queued -= sign * this.eventBytes(e);\n }\n\n /** The queue is past what the unload request can carry: O(1), from the counters. */\n private pastShare(): boolean {\n return (\n this.envelopeBytes + this.queued + this.queue.length >\n KEEPALIVE_QUOTA_BYTES - this.inflightKeepaliveBytes\n );\n }\n\n /** Events waiting to be sent, retry flights included. */\n private pendingCount(): number {\n let n = this.queue.length;\n for (const f of this.retryQueue) n += f.events.length;\n return n;\n }\n\n private trimToCapacity(): void {\n /*\n * On a re-queue, hold the total at maxQueueSize by dropping the NEWEST\n * queued events, as the old unshift-then-pop did. enqueue() trims the\n * queue alone (oldest first) and does not see waiting flights, so\n * between re-queues the total can stand one batch over maxQueueSize\n * -- the same bound the old code had, where one batch sat off the\n * queue in flight. A retry flight is never trimmed: dropping events\n * from it would change the set its batchId is bound to, and the\n * server answers that with a 409. (fit(), below, drops one only whole,\n * past MAX_QUEUE_BYTES.)\n */\n let retry = 0;\n for (const f of this.retryQueue) retry += f.events.length;\n const trimmed: SessionEvent[] = [];\n while (\n this.queue.length > 0 &&\n retry + this.queue.length > this.config.maxQueueSize\n ) {\n const e = this.queue.pop()!;\n this.queued -= this.eventBytes(e);\n trimmed.push(e);\n }\n if (trimmed.length > 0) this.dropped(trimmed.reverse());\n this.fit();\n }\n\n private flushOnUnload(beforeUnload = false): void {\n if (this.holding) return;\n this.reclaimInFlight();\n // In the session's order (seq), which the queue's is not always: a\n // fetch's event is queued after the events of the page's continuation\n // with the seq it was reported at (place()), and a flight taken back\n // goes to the front. Cut in queue order, the quota left behind the\n // exchange main had sent ahead of them.\n this.queue.sort((a, b) => a.seq! - b.seq!);\n if (typeof fetch !== \"function\") return;\n\n /*\n * RETRY FLIGHTS FIRST, EACH AS ITSELF. A flight in the retry queue\n * may already be stored under its batchId, so it must go out with\n * that id and those bytes -- it cannot be folded into the envelope\n * below, which carries a fresh id. Each is one keepalive request\n * against the same quota; one that does not fit holds everything\n * behind it, as the loop's own comment says.\n */\n while (this.retryQueue.length > 0) {\n const flight = this.retryQueue[0];\n /*\n * AS IT WAS POSTED: gzipped, when it was. Sent as its JSON, a failed\n * flight over the share held back the whole pagehide request though\n * its body on the wire fit it: a full batch or a timed flush is not\n * capped at the share, and its JSON is several times its gzip. Same\n * batchId, same events: the server stores it once either way.\n */\n const wire = flight.sent;\n const size = wire ? wire.bytes : utf8Length(flight.json);\n /*\n * THE CUT IS AT THE FIRST THING THAT DOES NOT FIT, and everything\n * behind it holds -- the rule the event loop below has always\n * followed, applied to flights. A `break` here fell through to the\n * queue and shipped the tail over a hole: a failed [1,2] over the\n * quota stayed, event 3 went out under a fresh id, and a 5xx-failed\n * flight is by definition NOT on the server. A hole is worse than a\n * short recording.\n */\n if (size > KEEPALIVE_QUOTA_BYTES - this.inflightKeepaliveBytes) return;\n this.retryQueue.shift();\n flight.dispatched = true;\n this.postKeepalive(wire ? wire.body : flight.json, size, wire?.encoding);\n }\n\n if (this.queue.length === 0) return;\n\n // AT beforeunload, ROOM FOR THE EARLY UPLOAD ON THE WIRE: Firefox aborts\n // it next, and pagehide re-sends it first, whole; this request, still\n // counted then, left it no room and the pagehide request sent nothing\n // (MEASURED in Firefox, logs/r6diag.log).\n const budget =\n KEEPALIVE_QUOTA_BYTES -\n this.inflightKeepaliveBytes -\n (beforeUnload && this.inFlight?.early && this.inFlight.onWire\n ? (this.inFlight.sent?.bytes ?? this.inFlight.bytes)\n : 0);\n const batchId = this.mintBatchId();\n // Bytes of the envelope with an empty events array; each event then\n // costs its own JSON plus a separating comma.\n let bytes = this.envelopeBytes;\n let count = 0;\n for (const event of this.queue) {\n const cost = this.eventBytes(event) + (count === 0 ? 0 : 1);\n if (bytes + cost > budget) break;\n bytes += cost;\n count++;\n }\n if (count === 0) return;\n\n const sent = this.queue.splice(0, count);\n this.uncount(sent);\n const json = this.body(sent, batchId);\n this.postKeepalive(json, utf8Length(json));\n }\n\n /** One fire-and-forget keepalive POST, accounted against the quota. */\n private postKeepalive(\n body: BodyInit,\n size: number,\n encoding?: string | null,\n ): void {\n try {\n this.inflightKeepaliveBytes += size;\n fetch(this.config.endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-API-Key\": this.config.apiKey,\n ...(encoding ? { \"Content-Encoding\": encoding } : {}),\n },\n body,\n keepalive: true,\n })\n /*\n * READ, THOUGH THERE IS NOTHING TO READ IT FOR. The response\n * says nothing anyone here can act on — the document is\n * leaving. Reading it is what frees the BROWSER's share of the\n * keepalive quota (MEASURED in Chromium 145.0.7632.6; see\n * sendWithRetry, where the same measurement is written out),\n * and this counter must not fall before the browser's does. A\n * document that survives its pagehide — a back/forward-cache\n * entry, a cancelled navigation — flushes again later, and a\n * quota this flush is still holding is one the next flush is\n * refused against.\n */\n .then((response) => response.arrayBuffer())\n .catch(() => {\n // Nothing left to report it to.\n })\n .finally(() => {\n this.inflightKeepaliveBytes -= size;\n });\n } catch {\n this.inflightKeepaliveBytes -= size;\n }\n }\n\n /* -------------------------------------------------------------- */\n /* Event handlers */\n /* -------------------------------------------------------------- */\n\n private handleOnline = (): void => {\n try {\n this.config.beforeOnlineFlush?.();\n } catch {\n // The owner's handover must never cost the flush below.\n }\n // A sender between two attempts tries again now (backoff()).\n this.wakeSender?.();\n // A drain when one is owed (rushDeferred); a reconnect otherwise\n // sends one batch, as the timer would -- unless it ends an outage,\n // whose accepted upload drains all that is queued.\n void this.flush(this.rushDeferred);\n };\n\n private handleUnload = (event: Event): void => {\n if (event.type === \"pagehide\") {\n try {\n this.config.beforeUnloadFlush?.();\n } catch {\n // The owner's handover must never cost the flush below.\n }\n }\n this.flushOnUnload(event.type === \"beforeunload\");\n // A document that survives its pagehide (a back/forward-cache\n // entry) keeps its listeners; with the queue now empty after\n // stop(), there is nothing left for them to do.\n this.disarmWhenDrained();\n };\n\n private handleVisibility = (): void => {\n if (document.visibilityState === \"hidden\") {\n /*\n * The page is hidden, not gone: this is the last reliable moment\n * to send on many mobile paths, but there is still a document to\n * read the response with. So it drains through the observable\n * path — a 401 reaches onError, a 503 keeps the events for the\n * next attempt — rather than the fire-and-forget unload flush,\n * which cannot tell anyone anything.\n */\n this.config.beforeHiddenFlush?.();\n void this.flush(true);\n }\n };\n\n /* -------------------------------------------------------------- */\n /* Accessors */\n /* -------------------------------------------------------------- */\n\n /**\n * Events waiting their turn: the queue, and flights waiting to be\n * re-sent. NOT a batch already taken off the queue and being compressed\n * or on the wire, so 0 does not mean everything was sent -- await\n * stop() for that.\n */\n get queueSize(): number {\n return this.pendingCount();\n }\n}\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - Core recorder (wraps rrweb) */\n/* ------------------------------------------------------------------ */\n\nimport { staying, unlessHeld } from \"./leave\";\nimport { moduleOf, ownChunk } from \"./module-of\";\nimport type { CaptureConfig, SessionEvent, SessionMetadata } from \"./types\";\nimport {\n DomRecorderRefusal,\n PrivacyRouteRefusal,\n SessionIdRefusal,\n StrictAttributesRefusal,\n describeReceived,\n describeValue,\n} from \"./errors\";\nimport {\n pageSecrets,\n recordedPageUrl,\n scrubSecrets,\n secretPattern,\n type PageSecret,\n type SecretMatcher,\n declareRoutes,\n parseRoute,\n routesGeneration,\n ScrubOverCap,\n StyleTexts,\n scrubAddedTextRuns,\n scrubDomAttributes,\n scrubDomCss,\n scrubDomText,\n scrubDomTree,\n scrubPageUrl,\n keepStrict,\n} from \"./privacy\";\nimport { isValidSessionId } from \"./session-id\";\nimport { MAX_BATCH_BYTES } from \"./transport\";\n\n/* ------------------------------------------------------------------ */\n/* Helpers */\n/* ------------------------------------------------------------------ */\n\nfunction uuid(): string {\n if (typeof crypto !== \"undefined\" && crypto.randomUUID) {\n return crypto.randomUUID();\n }\n // Fallback for older environments.\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n return (c === \"x\" ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\nfunction gatherMetadata(scrub: (url: string) => string): SessionMetadata {\n const w = typeof window !== \"undefined\" ? window : undefined;\n // The URL and the referrer are recorded by the page URL's rule: after a\n // load away from `/reset?token=…`, document.referrer is that URL whole\n // (found in review); and of every credential the page has carried, as\n // its events are (secretsOf): a session that starts after the address\n // bar hid a token still names the page it is on.\n const href = w?.location?.href ?? \"\";\n const secrets = href === \"\" ? null : secretsOf(href);\n return {\n // The page URL's rule, then this capture's own scrub of it (see\n // scrubUrl): strict mode's query values, a token-shaped value, a PII\n // pattern, a JWT path segment.\n url: scrubSecrets(scrub(href), secrets),\n userAgent: typeof navigator !== \"undefined\" ? navigator.userAgent : \"\",\n viewport: {\n width: w?.innerWidth ?? 0,\n height: w?.innerHeight ?? 0,\n },\n referrer:\n typeof document !== \"undefined\" && document.referrer\n ? scrubSecrets(scrub(document.referrer), secrets)\n : \"\",\n language: typeof navigator !== \"undefined\" ? navigator.language : \"\",\n devicePixelRatio: w?.devicePixelRatio ?? 1,\n timestamp: Date.now(),\n };\n}\n\n/**\n * rrweb's `record`, as this file uses it.\n *\n * `takeFullSnapshot` is a property rrweb hangs on the function (the\n * `export declare namespace record` block in rrweb.d.ts). Optional\n * here because it is read off a dynamically imported module: a future\n * rrweb without it must degrade, not throw.\n */\ntype RRWebRecord = ((...args: unknown[]) => (() => void) | undefined) & {\n takeFullSnapshot?: (isCheckout?: boolean) => void;\n /** The ids record() numbers nodes by, and the node each is. */\n mirror?: { getNode: (id: number) => Node | null };\n};\n\n/**\n * rrweb's record(), imported ONCE per document -- or why it could not\n * be. Dynamic, so the SDK loads under SSR / Node without crashing;\n * memoised, so every start() on every recorder in the page awaits the\n * one chunk. A failed import (no bundler to resolve the bare specifier,\n * a chunk blocked or lost) is not memoised: the next start() asks again.\n */\ntype RRWebImport = { record: RRWebRecord } | RRWebFailure;\n/** Why the recorder could not load: rrweb's import, or (`strict`) strict's allow-list. */\ntype RRWebFailure = { failed: string; strict?: true };\nlet rrwebImport: Promise<RRWebImport> | null = null;\n/** Whether rrweb's import has succeeded in this document. */\nlet rrwebLoaded = false;\n\n/**\n * Whether a service worker controls the page -- the one thing that can\n * answer rrweb's import with no network. CONTROLS, not merely exists:\n * every secure page has `navigator.serviceWorker`, and only a worker in\n * control serves the page's fetches. And asked behind a guard: in a frame\n * sandboxed without `allow-same-origin`, Chromium and WebKit throw a\n * SecurityError from the read of `navigator.serviceWorker` itself, and\n * read bare, a capture started offline there rejected init() with the\n * browser's own error -- no onError, nothing recorded after (found in\n * review #29, MEASURED in Chromium 153). A frame that may not ask has no\n * worker to answer.\n */\nfunction workerInControl(): boolean {\n try {\n return Boolean(navigator.serviceWorker?.controller);\n } catch {\n return false;\n }\n}\n\n/**\n * rrweb's import, through the leave gate (leave.ts) as every lazy load the\n * SDK makes: never started while the page is leaving, and, cancelled by\n * the leave, asked for once more when the page has stayed -- at start(),\n * at the DOM gate's opening and at the `online` retry alike.\n */\nfunction loadRRWeb(): Promise<RRWebImport> {\n if (!rrwebImport) {\n rrwebImport = staying(() => import(\"rrweb\")).then(\n (rrweb) => (\n (rrwebLoaded = true),\n { record: moduleOf(rrweb).record as unknown as RRWebRecord }\n ),\n (err: unknown) => {\n rrwebImport = null;\n return { failed: describeValue(err) };\n },\n );\n }\n return rrwebImport;\n}\n\n/*\n * STRICT'S ATTRIBUTE ALLOW-LIST IS A CHUNK OF ITS OWN (strict-attributes.ts),\n * loaded under strict alone, IN PARALLEL with rrweb's import, and\n * installed in privacy.ts before record() can take a snapshot:\n * loadRecorder() answers once both are in, so no strict recording ever\n * starts without it. Imported by the package's own name, or, on a page\n * that maps no such name, by its built file beside dist/index.mjs\n * (ownChunk), as the term chunk is (network.ts). A failed load is not\n * memoised, as rrweb's is not, and ends the capture with\n * KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE before anything is recorded: strict\n * records nothing rather than attributes it cannot read.\n */\nlet strictImport: Promise<string | null> | null = null;\n/** Whether strict's allow-list has been installed in this document. */\nlet strictLoaded = false;\nfunction loadStrict(): Promise<string | null> {\n return (strictImport ??= ownChunk(\n () => import(\"@keploy/capture-sdk/strict-attributes\"),\n // oxlint-disable-next-line no-undef -- a constant of the build (scripts/build-main.mjs), declared in build-flags.d.ts: true in dist/index.mjs alone\n __BESIDE__ ? () => import(\"./strict-attributes.mjs\" as string) : undefined,\n )\n .then((code) => {\n // A module of another shape (an import map pinning another version)\n // is a failed load, not a list that keeps nothing (review round 8).\n if (typeof code.kept != \"function\")\n throw new TypeError(\"strict-attributes has no kept()\");\n keepStrict(code.kept);\n strictLoaded = true;\n return null;\n })\n .catch((err: unknown) => ((strictImport = null), describeValue(err))));\n}\n\n/** rrweb's record(), and under `strict` strict's allow-list too: answered once both are in, or why either is not. */\nfunction loadRecorder(strict: boolean): Promise<RRWebImport> {\n return strict\n ? Promise.all([loadRRWeb(), loadStrict()]).then(([loaded, failed]) =>\n failed === null || \"failed\" in loaded\n ? loaded\n : { failed, strict: true },\n )\n : loadRRWeb();\n}\n\n/*\n * ONE REACTION WAITS ON A HELD IMPORT, whatever recorder, session, tab show\n * or resume() asks again (startRRWeb): the recorders that wait on rrweb's\n * import while the page's leave holds it, by mode (1 strict, 0 not), are\n * told as it lands, and each leaves the set at its stop(). Kept per\n * recorder, a reaction was kept per continuous session (each a recorder of\n * its own), holding that stopped recorder and its capture for the life of\n * a page whose leave never ends (a 204, a download).\n */\nconst landers = [\n new Set<KeployCaptureRecorder>(),\n new Set<KeployCaptureRecorder>(),\n];\n/** The reactions waiting on a held import, by mode: one at most. */\nconst reactions = [0, 0];\n/** Exposed for tests: reactions on rrweb's held import, and the recorders they tell. */\nexport const __landing = {\n reactions: (): number => reactions[0] + reactions[1],\n landers: (): number => landers[0].size + landers[1].size,\n};\n\n/** The refusal for a recorder that could not load. */\nconst refusal = (f: RRWebFailure) =>\n f.strict\n ? new StrictAttributesRefusal({ reason: f.failed })\n : new DomRecorderRefusal({ reason: f.failed });\n\n/** rrweb's EventType.Meta: `{href, width, height}`, the page a recording is on. */\nconst RRWEB_META = 4;\n\n/**\n * The first wait before a FullSnapshot is retaken after one was dropped,\n * and the most it doubles to (see rebaseline()): long enough that a page\n * too big to send is not re-serialised in a loop, short enough that a page\n * that shrank is recorded again within a minute.\n */\nconst RETAKE_FIRST_MS = 5_000;\nconst RETAKE_MAX_MS = 60_000;\n\n/**\n * How often a capture that waits for the network to import rrweb reads\n * the browser's state for itself (see retryWhenOnline()): one property\n * read a second, for as long as the wait lasts and no longer.\n */\nconst ONLINE_POLL_MS = 1_000;\n\n/** The viewport as rrweb's own Meta event measures it (getWindowWidth/Height). */\nfunction viewport(): { width: number; height: number } {\n const el = document.documentElement as HTMLElement | null;\n return {\n width:\n window.innerWidth || el?.clientWidth || document.body?.clientWidth || 0,\n height:\n window.innerHeight ||\n el?.clientHeight ||\n document.body?.clientHeight ||\n 0,\n };\n}\n\n/** `href` without its query strings -- the page's own and its route fragment's. */\nfunction withoutQuery(href: string): string {\n return href\n .split(\"#\")\n .map((part) => {\n const q = part.indexOf(\"?\");\n return q === -1 ? part : part.slice(0, q);\n })\n .join(\"#\");\n}\n\n/*\n * A PAGE URL'S CREDENTIALS ARE KEPT FOR THE DOCUMENT'S LIFE, not for as\n * long as the address bar shows them: an auth library or a reset page\n * reads the token and hides it with replaceState, and the page still\n * holds it -- in its DOM, in its next request, in a later capture's\n * snapshot (found in review). The URL the document was LOADED with is\n * read too, for an app that hid the token before init() ran, and every URL\n * the History API moves to, whether or not the recording is open then.\n *\n * The newest forms are kept, at most MAX_DOCUMENT_SECRETS of them and\n * MAX_SECRET_CHARS in all: a page that signs every URL it visits would\n * otherwise grow the set, and the matcher every event is tested with --\n * compiling one over 256 forms of 8 KB took 2.3 s (MEASURED in review).\n * The matcher is rebuilt whenever the set CHANGES, not when its size does:\n * at the cap, a new form in and an old one out kept the size, and the new\n * credential went out in the clear (found in review).\n */\nconst MAX_DOCUMENT_SECRETS = 256;\nconst MAX_SECRET_CHARS = 64 * 1024;\nconst documentSecrets = new Map<string, PageSecret>();\nlet secretsFor = \"\";\nlet secretsGeneration = -1;\nlet secretsMatch: SecretMatcher | null = null;\n\n/** A secret's identity: its rule and its text (a segment has no `/`). */\nfunction secretKey(s: PageSecret): string {\n return s.kind === 2 ? `2${s.before}/${s.value}` : `${s.kind}${s.value}`;\n}\n\nfunction remember(forms: readonly PageSecret[]): boolean {\n let changed = false;\n // Re-seen forms move to the newest end, so the cap evicts the oldest;\n // only a form not held before changes what is matched. SHORTEST FIRST,\n // so a value's whole form is the newest of its forms: evicted first, it\n // left a 4000-character token recorded past its first `/` (found in\n // review). And the forms of the URL the page is on now are never\n // evicted, whatever the cap.\n for (let i = forms.length - 1; i >= 0; i--) {\n const key = secretKey(forms[i]!);\n if (!documentSecrets.delete(key)) changed = true;\n documentSecrets.set(key, forms[i]!);\n }\n const current = new Set(forms.map(secretKey));\n let chars = 0;\n for (const key of documentSecrets.keys()) chars += key.length;\n for (const oldest of documentSecrets.keys()) {\n if (\n current.has(oldest) ||\n (documentSecrets.size <= MAX_DOCUMENT_SECRETS &&\n chars <= MAX_SECRET_CHARS)\n )\n break;\n documentSecrets.delete(oldest);\n chars -= oldest.length;\n changed = true;\n }\n return changed;\n}\n\n/*\n * The URLs the document has been on, newest last, at most MAX_VISITED of\n * them and MAX_VISITED_CHARS in all: routes declared later read each again.\n * Read only when declared, a later capture's routes never reached a URL an\n * earlier capture had already moved past, and its value went out in the\n * page's DOM (found in review).\n */\nconst MAX_VISITED = 64;\nconst MAX_VISITED_CHARS = 512 * 1024;\nconst visitedUrls = new Set<string>();\n\nfunction visited(href: string): void {\n visitedUrls.delete(href);\n visitedUrls.add(href);\n let chars = 0;\n for (const url of visitedUrls) chars += url.length;\n for (const oldest of visitedUrls) {\n if (\n oldest === href ||\n (visitedUrls.size <= MAX_VISITED && chars <= MAX_VISITED_CHARS)\n )\n break;\n visitedUrls.delete(oldest);\n chars -= oldest.length;\n }\n}\n\nfunction secretsOf(href: string): SecretMatcher | null {\n // Keyed on the declared routes too: a capture declaring routes on a page\n // another had read already was matched with the old set, and what its\n // routes name went out in its events (found in review). New routes read\n // the URL the page was loaded with again, and every URL it has been on.\n const generation = routesGeneration();\n if (href !== secretsFor || generation !== secretsGeneration) {\n let changed = false;\n if (secretsFor === \"\" || generation !== secretsGeneration) {\n const loaded = globalThis.performance?.getEntriesByType?.(\"navigation\");\n if (loaded?.[0]) changed = remember(pageSecrets(loaded[0].name));\n for (const url of visitedUrls)\n if (remember(pageSecrets(url))) changed = true;\n }\n secretsFor = href;\n secretsGeneration = generation;\n visited(href);\n if (remember(pageSecrets(href)) || changed)\n secretsMatch = secretPattern([...documentSecrets.values()]);\n }\n return secretsMatch;\n}\n\n/*\n * THE HISTORY API IS WRAPPED ONCE PER DOCUMENT, not once per recorder.\n * A router can wrap `history.pushState` too -- Next.js's app router does,\n * after the SDK when init() runs from an effect -- and a recorder that\n * put back the function it found would remove the router's wrapper with\n * it. So the wrapper is installed on first use, every recorder only\n * subscribes to it, and it is removed only when nobody is subscribed AND\n * every property is still the SDK's and one it can put back (untouched);\n * otherwise it stays, passing calls straight through, and the next\n * subscriber reuses it.\n */\nconst navigationListeners = new Set<\n (\n cause: NavigationCause,\n userInitiated?: boolean,\n initiator?: NavigationInitiator,\n ) => void\n>();\nlet historyWrap: {\n navigation: EventTarget | null;\n methods: WrappedMethod[];\n refused: string | null;\n} | null = null;\n\n/**\n * What moved the page to a new URL: the `cause` of the route Meta event the\n * recorder writes (rrweb's own Meta, on a load or a returning tab, has none).\n * \"push\" and \"replace\": a navigation that added or replaced a history entry\n * -- history.pushState or replaceState (a replace that changes the URL is a\n * redirect), or, where the Navigation API reports it, one the page made\n * another way. \"traverse\": a move through the session history -- the\n * browser's Back or Forward, or the page's own history.back() or go().\n * \"hash\": a fragment navigation the History API did not make -- a link to\n * `#/orders`, `location.hash = ...` -- told only where the browser has the\n * Navigation API; without it such a navigation reads as \"traverse\".\n */\nexport type NavigationCause = \"push\" | \"replace\" | \"traverse\" | \"hash\";\n\n/**\n * Who asked for a traversal, where the SDK saw it asked: \"script\" when the\n * page's own script called history.back(), forward() or go(), or the\n * Navigation API's navigation.back(), forward() or traverseTo(), for it. The\n * route Meta carries it as `initiator`; it is absent when that is not\n * known, never guessed.\n */\nexport type NavigationInitiator = \"script\";\n\n/**\n * A method the SDK put its wrapper in place of: the object it is on\n * (history, or the Navigation API's navigation), its name, the own\n * property it had (undefined when the method was its prototype's), and the\n * own property the SDK put there.\n */\ntype WrappedMethod = [\n target: object,\n name: string,\n had: PropertyDescriptor | undefined,\n put: PropertyDescriptor,\n];\n\n/*\n * WHERE THE BROWSER HAS THE NAVIGATION API, ITS currententrychange SAYS WHAT\n * MOVED THE PAGE, AND IT IS HEARD FIRST. It fires as a same-document\n * navigation commits: inside pushState and replaceState, for a fragment\n * navigation, for a traversal BEFORE popstate -- so before a router's own\n * popstate listener can re-stamp the entry or redirect -- and for a\n * navigation the History API wrappers never see (one an app intercepts with\n * navigation.navigate(), which fires no popstate either; a pushState the page\n * saved before the SDK wrapped it). Its navigationType says traverse, push or\n * replace. A push or replace made inside the SDK's own wrapper is that call\n * (historyCall); one that changes only the fragment otherwise is a fragment\n * navigation (\"hash\"); any other is the push or replace it says. Where there\n * is no Navigation API (Chromium has it), the wrappers and the popstate and\n * hashchange events decide, and a fragment navigation, which fires popstate\n * before hashchange as Back between two fragments does, reads as \"traverse\".\n * The SDK's listeners are CAPTURE listeners, which the DOM standard runs\n * at the target before every non-capture listener, whenever it was added\n * (Firefox, WebKit and jsdom do), so the SDK hears of a move before a\n * router's own listener can re-stamp the entry or redirect. Chromium runs\n * the listeners at the window in the order they were added (MEASURED), so\n * there a router's popstate listener added before init() runs first --\n * which matters only without the Navigation API, and every Chromium that\n * ships has it.\n */\nlet historyCall: \"push\" | \"replace\" | null = null;\n\n/*\n * WHO STARTED A MOVE: the Navigation API's navigate event, which fires\n * before a navigation commits, says `userInitiated` -- by the standard,\n * true when the visitor started it (the browser's Back and Forward, a click\n * on a link, a form) and false when the page's script did (an in-app Back\n * button calling history.back(), a pushState). An extractor needs it: a\n * traversal the page's own button made is that click's doing. It is\n * recorded as the engine says it, never corrected: MEASURED, WebKit says\n * true for a pushState or history.back() made inside a click handler,\n * where Chromium and Firefox say false (see sdk-navigation.spec.ts).\n * `announced` is what the last navigate event said, for the URL it named;\n * the entry change for that URL takes it (userInitiatedHere), and nothing\n * else does. Where the browser has no Navigation API, or the move was found\n * late (noticeUnheardMove), the route Meta carries no `userInitiated`.\n */\nlet announced: { href: string; userInitiated: boolean } | null = null;\n\n/*\n * WHO ASKED FOR A TRAVERSAL. userInitiated cannot tell a page's own\n * history.back() from the browser's Back in every engine (WebKit says true\n * for one made in a click handler), so the SDK notes the call itself:\n * history.back(), forward() and go() are wrapped with pushState and\n * replaceState, and so are the Navigation API's navigation.back(), forward()\n * and traverseTo(). Where the browser has the Navigation API, a call notes\n * the entry it names in navigation.entries() by its key; the browser\n * traverses a task later, and a navigate event to a noted entry is credited\n * to the page's script (`credited`, by that entry's key) until the entry\n * change for that entry records `initiator: \"script\"` (initiatorHere).\n *\n * CALLS THAT OVERLAP, MEASURED in Playwright 1.63's builds. Chromium and\n * Firefox move once per call, each counted on from the entry the call\n * before it named, Chromium firing each navigate event once the move\n * before it has committed, Firefox firing the navigate event of every move\n * before the first move commits. A call counted on to the entry the page\n * is on moves nothing in Chromium, and changes entry to it with no\n * navigate event in Firefox, and the next call counts on from it (back(),\n * forward(), back() from an entry with one after it: one move back in\n * Chromium, two in Firefox). Chromium drops a\n * call that names no entry from the page's entry (forward() from the last\n * one) and counts the next on from the call before it; Firefox counts it\n * on too. WebKit keeps the LAST call alone, counted from the page's entry,\n * and moves once, or not at all when that call names no entry. So a history\n * call notes the entry it names counting on from the calls still pending\n * (`aims`, in call order, `base` the entry the next counts on from: what\n * Chromium visits), unless that is the page's entry, and the one it names\n * from the page's entry (`lastAim`: what WebKit visits); a call that names\n * no entry from the page's entry notes neither, and spends WebKit's: the\n * notes of the calls before it stay, as Chromium and Firefox still make\n * their moves.\n *\n * A navigate event to `lastAim` is the script's. One to the entry at the\n * head of the queue is the script's when it says userInitiated false, as\n * Chromium and Firefox say of every move a page's call makes; the spec has\n * the browser's own Back and Forward buttons say true (Playwright's\n * page.goBack() says true in Chromium, false in Firefox and WebKit,\n * measured). Where the engine counts as the queue does, each of its moves\n * goes to the head. The event spends the head, and the rest stays queued\n * only when it said false: WebKit's one move says true when the calls were\n * made during a user gesture (a click handler, measured), and the entries\n * the calls it dropped named go with it. An entry change to the head's\n * entry spends it too (Chromium's one move for two calls that name it).\n * Firefox fires two navigate events to one entry before either entry\n * change (back(), back(), forward() from an entry with one after it), so\n * `credited` counts them, and each entry change spends one. A replace\n * keeps the notes, as a key names the same entry after one (a router\n * re-stamping its entry from popstate does). A push drops the entries\n * after the current one alone; MEASURED for a pushState in the task of the\n * calls, Chromium and WebKit still make the pending calls' moves to the\n * entries before it, as the calls named them, and count a call made after\n * the push from the pushed entry, where Firefox drops the pending calls.\n * So a push keeps the notes for the entries before the current one, and\n * the next call counts from the pushed entry; the last call's note stays\n * only for such an entry and only when the push says userInitiated true,\n * WebKit's during a gesture, whose move says true and no queued note can\n * take it. Any other navigate event but a replace's spends them all.\n * A call made while another wrapped call runs (a navigation.back()\n * polyfill calling history.back()) notes nothing: its move is the outer\n * call's.\n * navigation.back() and forward() name the entry before or after the\n * current one when they are called (how they count with history calls\n * still pending was not measured), and traverseTo() the entry with its\n * key, read only when it is a string (anything else would run the page's\n * toString a second time).\n *\n * Never guessed: nothing is noted without the Navigation API, nor for a\n * call whose argument the SDK does not read -- a delta given as an object\n * (reading its valueOf would run the page's code a second time; a string\n * converts as the browser converts it, go(\"-1\")), a traverseTo() key that\n * is no string -- and a call that\n * throws spends every note, since what will move is no longer known. A\n * router calling a back() it kept from before init() passes no wrapper.\n *\n * The limits, MEASURED. A note no traversal's navigate event spends stays\n * for the next one; past a push, a queued one stays while its entry is\n * before the current one. A call's notes stay when no such event follows\n * it: for a call\n * the browser applies to another frame's history (an iframe that navigated\n * since, or the parent's when the page is a frame), and one it drops; and\n * a traversal the browser makes to the entry a call named, before the\n * call's own move, takes them. Each then reads as the script's. The next\n * history call also counts on from such a call's entry, as from a pending\n * one's, so after an in-app Back that moved a frame, a second one's move\n * is the script's but leaves the entry before it queued: a later traversal\n * there that says userInitiated false reads as the script's.\n * And queued entries stay when WebKit drops the calls that named them and\n * no move of its says userInitiated true: its one move for calls made with\n * no user gesture says false, as Chromium's first of several does, and\n * nothing tells the two apart when it is made; and calls whose last names\n * no entry from the page's entry move nothing at all. A later traversal to\n * such an entry that says false (Playwright's page.goBack() in WebKit)\n * reads as the script's (MEASURED, sdk-navigation.spec.ts). And the queue\n * counts as Chromium does where the engines differ: after a call that\n * names no entry from the page's entry, Firefox counts on where Chromium\n * does not, so a move of Firefox's the queue did not count, and an earlier\n * move of the same calls to the same entry, read as the browser's (back(),\n * forward(), back() or back(), back(), forward() from the last entry).\n * Nothing tells Firefox's drop of the calls pending at a push in their task\n * from Chromium's move to come when the push is made (a push a task later,\n * Firefox moves too), so their notes stay at the head of the queue until\n * its next traversal. That spends them, and the notes of any calls queued\n * behind them, unless it goes straight to such an entry and says\n * userInitiated false; a single Back, to the entry before the pushed one,\n * never does. So after back() then a push in Firefox, of two back() calls\n * the first move is the script's and the second reads as the browser's.\n * Firefox fires a navigate event before a push a popstate listener makes\n * for it, and the push spends that credit. A fragment push in the calls'\n * task (location.hash, navigation.navigate(\"#x\")) moves Firefox one back\n * from the pushed entry, which the calls did not name: that move reads as\n * the browser's. WebKit also drops the pending calls at an intercepted\n * navigation.navigate(), and their notes stay. And WebKit's move\n * for overlapping calls with no gesture, past the head of the queue, loses\n * its note at a push, which says false then: go(-1), go(-2), a push reads\n * as the browser's.\n */\nlet aims: string[] = [];\n/** The entry the next history call counts on from while `aims` is not empty. */\nlet base: string | null = null;\nlet lastAim: string | null = null;\n/** How many navigate events credited each entry, not yet spent by its entry change. */\nconst credited = new Map<string, number>();\n/** Whether a wrapped traversal call is running, and no navigate event came since it noted. */\nlet inCall = false;\n\nfunction onNavigate(event: Event): void {\n const e = event as Event & {\n userInitiated?: unknown;\n navigationType?: unknown;\n destination?: { url?: unknown; key?: unknown };\n };\n const href = e.destination?.url;\n announced =\n typeof href === \"string\" && typeof e.userInitiated === \"boolean\"\n ? { href, userInitiated: e.userInitiated }\n : null;\n // The calls' notes are this navigate event's to spend (see above); a\n // replace's is not.\n const key = e.destination?.key;\n if (e.navigationType === \"replace\") return;\n if (e.navigationType === \"traverse\" && typeof key === \"string\") {\n const queued = aims[0] === key && e.userInitiated === false;\n if (queued || key === lastAim)\n credited.set(key, (credited.get(key) ?? 0) + 1);\n else credited.delete(key);\n aims = queued ? aims.slice(1) : [];\n lastAim = null;\n } else {\n // A push drops the entries after the current one alone: the notes for\n // the entries before it stay (see above), and the next call counts from\n // the pushed entry.\n let kept: string[] = [];\n if (e.navigationType === \"push\")\n try {\n const api = event.currentTarget as Navigation;\n kept = api\n .entries()\n .slice(0, api.currentEntry!.index)\n .map((x) => x.key);\n } catch {\n // A polyfill's entries() keeps no note.\n }\n aims = aims.filter((k) => kept.includes(k));\n base = null;\n // WebKit's move alone needs it: during a gesture, when the push says true\n // and that move does too, so no queued note could take it.\n if (e.userInitiated !== true || !kept.includes(lastAim!)) lastAim = null;\n credited.clear();\n }\n inCall = false;\n}\n\n/**\n * The key of the page's entry `delta` from the entry keyed `from` (null:\n * the current one), where the Navigation API names one.\n */\nfunction entryKeyAt(\n navigation: EventTarget | null,\n delta: unknown,\n from: string | null,\n): string | null {\n // A primitive converts as the browser converts it (go(\"-1\")), running none\n // of the page's code; an object's valueOf would run it a second time.\n if (typeof delta === \"object\" || typeof delta === \"function\") return null;\n const api = navigation as Navigation | null;\n try {\n const steps = Number(delta) | 0; // as the browser reads a long (a Symbol throws)\n const entries = api?.entries() ?? [];\n const index =\n from === null\n ? Number(api?.currentEntry?.index)\n : entries.findIndex((e) => e.key === from);\n return index < 0 ? null : (entries[index + steps]?.key ?? null);\n } catch {\n // A polyfill or a page's own entries() must not break the page's Back.\n return null;\n }\n}\n\n/** What a traversal call names: counting on from the pending calls, and from the current entry. */\ninterface Aim {\n next: string | null;\n now: string | null;\n}\n\n/** A traversal method's wrapper: it notes the entries `aim(args)` names, then calls the method. */\nfunction traversing(\n original: (...args: never[]) => unknown,\n aim: (args: unknown[]) => Aim,\n): (this: unknown, ...args: unknown[]) => unknown {\n return function (this: unknown, ...args: unknown[]): unknown {\n if (inCall) return Reflect.apply(original, this, args);\n // Before the call, so a traversal made during it (a polyfill's, a\n // page's own back()) finds the note.\n const { next, now } = aim(args);\n lastAim = now;\n // Chromium drops a call that names no entry from the page's entry, and\n // one counted on to the page's entry moves nothing (see above).\n if (now !== null && next !== null) {\n base = next;\n if (next !== entryKeyAt(historyWrap?.navigation ?? null, 0, null))\n aims.push(next);\n }\n inCall = true;\n try {\n return Reflect.apply(original, this, args);\n } catch (error) {\n aims = [];\n lastAim = null;\n throw error;\n } finally {\n inCall = false;\n }\n };\n}\n\n/** \"script\" when a navigate event credited the entry the page is now on to its script; one credit each time. */\nfunction initiatorHere(\n navigation: EventTarget | null,\n): NavigationInitiator | undefined {\n const key = (navigation as Navigation | null)?.currentEntry?.key;\n if (typeof key !== \"string\") return undefined;\n while (aims[0] === key) aims.shift();\n const n = credited.get(key) ?? 0;\n if (n > 1) credited.set(key, n - 1);\n else credited.delete(key);\n return n ? \"script\" : undefined;\n}\n\n/** What the navigate event for the URL the page is on said of who started it; once. */\nfunction userInitiatedHere(): boolean | undefined {\n const said = announced;\n announced = null;\n return said !== null && said.href === location.href\n ? said.userInitiated\n : undefined;\n}\n\n/** Whether two URLs differ in their fragment alone. */\nfunction fragmentOnly(from: string, to: string): boolean {\n return from !== to && from.split(\"#\")[0] === to.split(\"#\")[0];\n}\n\nfunction onEntryChange(event: Event): void {\n const e = event as Event & {\n navigationType?: unknown;\n from?: { url?: unknown };\n };\n const type = e.navigationType;\n const initiated = userInitiatedHere();\n // A push's or replace's entry change finds no note: its navigate event\n // spent them, or a replace keeps the key a traversal's credit was spent on.\n const initiator = initiatorHere(historyWrap?.navigation ?? null);\n if (type === \"traverse\") notifyNavigation(\"traverse\", initiated, initiator);\n else if (type === \"push\" || type === \"replace\") {\n const from = typeof e.from?.url === \"string\" ? e.from.url : \"\";\n notifyNavigation(\n historyCall ?? (fragmentOnly(from, location.href) ? \"hash\" : type),\n initiated,\n );\n }\n}\n\n/**\n * What moved the page when the SDK hears of the move only from a later\n * History API call that left the URL as it was. Inside a popstate or\n * hashchange dispatch, a traversal did (a listener heard before the SDK's\n * re-stamped the entry); anywhere else, a pushState the page saved before\n * the SDK wrapped history did (SvelteKit keeps its own).\n */\nfunction earlierMove(): NavigationCause {\n const type = (Reflect.get(window, \"event\") as Event | undefined)?.type;\n return type === \"popstate\" || type === \"hashchange\" ? \"traverse\" : \"push\";\n}\n\nfunction notifyNavigation(\n cause: NavigationCause,\n userInitiated?: boolean,\n initiator?: NavigationInitiator,\n): void {\n // Before any recorder's gate: a token pushed while paused or hidden, or\n // by a query-only push, and hidden again before the next event, is the\n // page's all the same (found in review).\n secretsOf(location.href);\n for (const listener of navigationListeners) {\n try {\n listener(cause, userInitiated, initiator);\n } catch {\n // The page's navigation has already happened; a recording that\n // could not note it must not turn that into an exception in the\n // router that called pushState.\n }\n }\n}\n\nfunction wrapHistory(): void {\n if (historyWrap) return;\n const h = window.history;\n // oxlint-disable-next-line typescript/unbound-method -- captured to call with an explicit receiver and to restore\n const push = h.pushState;\n // oxlint-disable-next-line typescript/unbound-method -- captured to call with an explicit receiver and to restore\n const replace = h.replaceState;\n // Called AFTER the original, which is what changes location; a call the\n // browser refuses (a cross-origin URL throws) is not a navigation. With the\n // Navigation API the move is recorded during the call (onEntryChange, told\n // it is this call by historyCall). Without it, a call that leaves the URL\n // as it was did not move the page: if the page has moved, earlierMove()\n // says what did.\n const wrappedPush = function (\n this: History,\n ...args: Parameters<History[\"pushState\"]>\n ): void {\n const before = location.href;\n const outer = historyCall;\n historyCall = \"push\";\n try {\n push.apply(this, args);\n } finally {\n historyCall = outer;\n }\n notifyNavigation(location.href === before ? earlierMove() : \"push\");\n };\n const wrappedReplace = function (\n this: History,\n ...args: Parameters<History[\"replaceState\"]>\n ): void {\n const before = location.href;\n const outer = historyCall;\n historyCall = \"replace\";\n try {\n replace.apply(this, args);\n } finally {\n historyCall = outer;\n }\n notifyNavigation(location.href === before ? earlierMove() : \"replace\");\n };\n const navigation =\n (Reflect.get(window, \"navigation\") as EventTarget | undefined) ?? null;\n navigation?.addEventListener(\"currententrychange\", onEntryChange, {\n capture: true,\n });\n navigation?.addEventListener(\"navigate\", onNavigate, { capture: true });\n // A history call's delta counts from the entry current at the call, and\n // on from the pending calls'; a Navigation API call names one entry.\n const by =\n (delta: (args: unknown[]) => unknown) =>\n (args: unknown[]): Aim => {\n const d = delta(args);\n return {\n next: entryKeyAt(navigation, d, aims.length ? base : null),\n now: entryKeyAt(navigation, d, null),\n };\n };\n const to =\n (key: (args: unknown[]) => string | null) =>\n (args: unknown[]): Aim => {\n const k = key(args);\n return { next: k, now: k };\n };\n // Each method a page's script traverses with, and the entry a call names.\n const traversals: Array<[object | null, string, (args: unknown[]) => Aim]> = [\n [h, \"back\", by(() => -1)],\n [h, \"forward\", by(() => 1)],\n [h, \"go\", by((args) => args[0])],\n [navigation, \"back\", to(() => entryKeyAt(navigation, -1, null))],\n [navigation, \"forward\", to(() => entryKeyAt(navigation, 1, null))],\n [\n navigation,\n \"traverseTo\",\n to((args) =>\n typeof args[0] === \"string\" ? entryKeyAt(navigation, 0, args[0]) : null,\n ),\n ],\n ];\n const wanted: Array<[object, string, unknown]> = [\n [h, \"pushState\", wrappedPush],\n [h, \"replaceState\", wrappedReplace],\n ];\n for (const [target, name, aim] of traversals) {\n // Read to call with an explicit receiver and to restore; a method the\n // browser does not have is not made up.\n const original: unknown = target && Reflect.get(target, name);\n if (typeof original === \"function\")\n wanted.push([target!, name, traversing(original as () => unknown, aim)]);\n }\n const refused = wanted.find(([target, name]) => !replaceable(target, name));\n historyWrap = {\n navigation,\n methods: refused\n ? []\n : wanted.map(([target, name, value]) => install(target, name, value)),\n refused: refused\n ? `${refused[0] === h ? \"history\" : \"navigation\"}.${refused[1]}`\n : null,\n };\n}\n\n/*\n * ALL OR NOTHING. A page can make a method impossible to replace and put\n * back -- a frozen history.back, a navigation object that takes no new\n * property. Every method is checked before any is wrapped, and none is\n * wrapped when one cannot be, so what a recording carries means one thing\n * on every page: every call to a method the SDK wraps is heard, with its\n * own cause and, for a traversal, who asked for it, or none is and the\n * capture says so once\n * (KUI_E_NAVIGATION_UNWRAPPED, reported by the recorder from `refused`).\n * Wrapping only some would leave an absent `initiator` meaning \"the\n * browser's\" for one method and \"unseen\" for another. Route changes are\n * then recorded from the page's navigation events -- the Navigation API's,\n * popstate and hashchange -- and from a move found at the next recorded\n * event (noticeUnheardMove), with less detail: where the browser has the\n * API a pushState to a fragment reads as a hash; where it has none, a\n * pushState or replaceState is found only at the next recorded event, as\n * a push, two before it read as one, and a credential pushed and hidden\n * again before it is never collected. A method is replaced by defining an\n * own property and put back by defining the one it had, or by deleting the\n * SDK's when it had none.\n */\n\n/** Whether `name` on `target` can be replaced by an own property and put back exactly. */\nfunction replaceable(target: object, name: string): boolean {\n const had = Object.getOwnPropertyDescriptor(target, name);\n return had === undefined\n ? Object.isExtensible(target)\n : had.configurable === true || had.writable === true;\n}\n\n/** Put `value` in place of `name` on `target`, keeping what it had to put back. */\nfunction install(target: object, name: string, value: unknown): WrappedMethod {\n const had = Object.getOwnPropertyDescriptor(target, name);\n Object.defineProperty(\n target,\n name,\n had?.configurable === false\n ? { value } // writable but fixed: only its value may change\n : {\n value,\n writable: true,\n enumerable: had?.enumerable ?? true,\n configurable: true,\n },\n );\n return [target, name, had, Object.getOwnPropertyDescriptor(target, name)!];\n}\n\n/**\n * Whether the property is still the SDK's wrapper and still one restore()\n * can put back: its own (a router has not wrapped it since), as\n * configurable as install() left it, and, when that is not configurable,\n * still writable (the page has not fixed it since).\n */\nfunction untouched([target, name, , put]: WrappedMethod): boolean {\n const now = Object.getOwnPropertyDescriptor(target, name);\n return (\n now !== undefined &&\n now.value === put.value &&\n now.configurable === put.configurable &&\n (now.configurable === true || now.writable === true)\n );\n}\n\n/** Put back what was there: an own property the page had set, or none. */\nfunction restore([target, name, had]: WrappedMethod): void {\n if (had) Object.defineProperty(target, name, had);\n else Reflect.deleteProperty(target, name);\n}\n\nfunction unwrapHistory(): void {\n if (!historyWrap || navigationListeners.size > 0) return;\n if (!historyWrap.methods.every(untouched)) {\n return; // something wrapped ours since; see above\n }\n // Assigning the native function back would leave an own property the\n // page never had (found in review); restore() deletes the SDK's instead.\n for (const method of historyWrap.methods) restore(method);\n historyWrap.navigation?.removeEventListener(\n \"currententrychange\",\n onEntryChange,\n { capture: true },\n );\n historyWrap.navigation?.removeEventListener(\"navigate\", onNavigate, {\n capture: true,\n });\n announced = null;\n // A note no navigate event took while nobody listened is no capture's.\n aims = [];\n lastAim = null;\n credited.clear();\n historyWrap = null;\n}\n\n/**\n * Keep collecting the page's URL credentials while no recorder is open --\n * between a continuous capture's sessions -- and return the release. A\n * visitor going back to `/reset/<token>` in that gap started no session,\n * the token was never collected, and the next session's snapshot carried\n * it once the page had hidden it (found in review).\n */\nexport function collectPageSecrets(): () => void {\n return onNavigation(() => {});\n}\n\n/** Subscribe to the page's same-document navigations; returns the unsubscribe. */\nfunction onNavigation(\n listener: (\n cause: NavigationCause,\n userInitiated?: boolean,\n initiator?: NavigationInitiator,\n ) => void,\n): () => void {\n if (typeof window === \"undefined\" || !window.history) return () => {};\n navigationListeners.add(listener);\n wrapHistory();\n // The visitor moving through history reaches URLs the page did not push:\n // their credentials are the page's too, collected before any gate.\n // Without the Navigation API both events are a traverse: a fragment\n // navigation fires popstate before hashchange, as Back between two\n // fragments does, so neither event can tell them apart.\n const traverse = () => {\n secretsOf(location.href);\n listener(\"traverse\");\n };\n window.addEventListener(\"popstate\", traverse, { capture: true });\n window.addEventListener(\"hashchange\", traverse, { capture: true });\n return () => {\n navigationListeners.delete(listener);\n window.removeEventListener(\"popstate\", traverse, { capture: true });\n window.removeEventListener(\"hashchange\", traverse, { capture: true });\n unwrapHistory();\n };\n}\n\n/* ------------------------------------------------------------------ */\n/* KeployCaptureRecorder */\n/* ------------------------------------------------------------------ */\n\nexport type RecorderState = \"idle\" | \"recording\" | \"paused\" | \"stopped\";\n\n/**\n * Callback invoked every time a new {@link SessionEvent} is produced\n * by the recorder.\n */\nexport type OnEventCallback = (event: SessionEvent) => void;\n\n/**\n * Called when the recorder ends the session ON ITS OWN — today, when\n * `maxSessionDuration` elapses. Not called for an explicit stop(): the\n * caller of stop() already knows. Once it returns (or throws), the\n * recorder stops itself, unless the callback began stopping it with\n * stopDom(): then the callback's owner finishes with stop(), as\n * KeployCapture does once the exchanges answered inside the session have\n * recorded.\n */\nexport type OnSessionEndCallback = () => void;\n\n/**\n * Called when an event is dropped because scrubbing it passed the ingest\n * server's body cap (privacy.ts ScrubOverCap): its type, how many\n * characters the scrubbed event was certain to reach, and the cap.\n */\nexport type OnScrubOversizedCallback = (\n eventType: SessionEvent[\"type\"],\n atLeast: number,\n cap: number,\n) => void;\n\nexport class KeployCaptureRecorder {\n /*\n * TWO GATES, AND WHAT EACH ONE HOLDS.\n *\n * `phase` is the lifecycle; the two flags are the two independent\n * reasons an active session is not emitting everything. They are\n * independent on purpose: a visibilitychange used to call resume()\n * unconditionally, so a tab coming back into view silently undid a\n * pause the integrator had asked for with KeployCapture.pause(). Now\n * a hidden tab and a manual pause each shut their own gate, and only\n * their own transition reopens it.\n *\n * THE TWO GATES HOLD DIFFERENT EVENTS, and collapsing them into one\n * was a regression of its own:\n *\n * sessionOpen — phase \"active\" and not userPaused. This gate holds\n * EVERY event. That is what pause() promises and what a session\n * that has ended means.\n *\n * getState() === \"recording\" — sessionOpen and not hidden. The DOM\n * gate. It decides where rrweb may start (record() emits its Meta\n * and FullSnapshot synchronously, so starting into a shut gate\n * loses both for good) and whether rrweb's events are emitted.\n *\n * A hidden tab therefore pauses DOM emission and NOT the network\n * exchanges the page makes. Gating those on `hidden` too meant a user\n * who clicked Submit and switched tab had the click recorded with no\n * mock for its request, and a page init()'d in a background tab\n * recorded none of its load-time API calls — in both cases the\n * request had already been issued and the page was still doing the\n * work. The DOM is the part that genuinely is not happening while\n * nobody is looking, and the mutations that are get their baseline\n * back from the full snapshot taken when the gate reopens (see\n * openDomGate()).\n *\n * \"stopping\" is the window between stopDom() and stop(): the session\n * is ending, so neither gate is open and nothing of the DOM starts or is\n * recorded, but an exchange already admitted still reports into it\n * (emitEvent's `admitted`) while KeployCapture.stop() settles.\n */\n private phase: \"idle\" | \"active\" | \"stopping\" | \"stopped\" = \"idle\";\n private userPaused = false;\n private hidden = false;\n private droppedWhileShut = false;\n\n /**\n * A DOM event was dropped while the gate was OPEN -- its scrub failed or\n * passed the body cap -- so the recording has no baseline rrweb's later\n * events can be read against: each names its nodes by the ids of the\n * last FullSnapshot and the mutations after it. Until a FullSnapshot is\n * sent again, rrweb's incremental events are held back: posted, a click\n * on a button the dropped snapshot held was resolved by the flow engine\n * to `body`, and a generated test clicked the page body (found in\n * review #22). Not cleared by retaking one at once: a snapshot dropped\n * for its size would be dropped again. The next opening of the gate\n * takes it: a hold is a hole to openDomGate() whatever the gate itself\n * dropped, so nothing that sets this sets droppedWhileShut beside it.\n * Set beside it, that flag outlived the snapshot that ended the hold\n * wherever the drop was said from INSIDE takeFullSnapshot -- the Meta\n * rrweb emits first evicting an event from a full queue, or failing its\n * scrub -- since the snapshot behind it clears the hold alone: the next\n * reopening of the gate serialised the whole page again for nothing\n * (measured refuting review #30, real rrweb and transport: two\n * takeFullSnapshot calls where one is owed).\n */\n private baselineLost = false;\n /** The pending retake of a FullSnapshot after a dropped DOM event; see rebaseline(). */\n private retakeTimer: ReturnType<typeof setTimeout> | null = null;\n /** The pending retake is the one taken AT ONCE, after a dropped incremental; see rebaseline(). */\n private retakeAtOnce = false;\n /** How long the next retake after a dropped SNAPSHOT waits; see rebaseline(). */\n private retakeDelay = RETAKE_FIRST_MS;\n /** Uploads are failing (TransportConfig.onFailing): no snapshot is taken; see failing(). */\n private outage = false;\n\n /**\n * UPLOADS FAIL, SO NOTHING IS RE-SERIALISED UNTIL ONE IS ACCEPTED AGAIN.\n * Each DOM event the transport drops in an outage is a hole, and each\n * hole asked for a FullSnapshot -- at once after an incremental -- into\n * a queue nothing drains, where the snapshot evicted more DOM events\n * and asked for the next. MEASURED (MEASURE.md \"Outage\", 22.5k nodes,\n * ingest down): in the 90 s after the cap, 19 long tasks over 200 ms\n * (up to 373 ms) and the heap 29 -> 211 MB. Now a hole in an outage only starts the hold (baselineLost:\n * rrweb's incrementals are not queued), a retake already pending is\n * cancelled, and the ONE snapshot is taken when the outage ends -- an upload accepted, or\n * on a page that makes only DOM events, a queue run empty, which comes\n * again only once the cap has refilled: it\n * is queued after everything the outage left, so the server, sorting by\n * seq, has it before every incremental that follows.\n */\n failing(on: boolean): void {\n this.outage = on;\n if (this.retakeTimer !== null) clearTimeout(this.retakeTimer);\n this.retakeTimer = null;\n if (!on && this.baselineLost) this.rebaseline(false);\n }\n /**\n * Events the transport dropped unsent (TransportConfig.onDropped). A\n * DOM event among them is a hole exactly as one the recorder drops: no\n * baseline until a FullSnapshot is sent, so rrweb's incrementals are\n * held, and one is retaken (rebaseline()). Unless a snapshot queued\n * after it still stands (`rebaselined`): that is the baseline already. Unsaid, clicks\n * after a snapshot too big to send were posted and resolved to `body`\n * (found in review #23).\n */\n lost(events: readonly SessionEvent[], rebaselined: boolean): void {\n if (rebaselined || !events.some((e) => e.type === \"dom\")) return;\n this.baselineLost = true;\n this.rebaseline(\n events.some(\n (e) =>\n e.type === \"dom\" && (e.data as { type?: unknown } | null)?.type === 2,\n ),\n );\n }\n\n /**\n * A dropped DOM event left the recording with no baseline: take one when\n * it could fit, rather than only at the next opening of the gate -- a\n * visitor who never switched tab had every later click held for the rest\n * of the session (found in review #23). After an incremental, at once: a\n * snapshot of the page may well fit where the event did not reach the\n * server (a full queue). After a SNAPSHOT, on a backoff -- RETAKE_FIRST_MS,\n * doubling to RETAKE_MAX_MS -- because the page must shrink before one\n * fits and each attempt serialises the whole document. Only while the\n * gate is open: a shut gate's reopening takes its own (droppedWhileShut).\n * The delay starts over once a snapshot is sent.\n *\n * ONE RETAKE IS PENDING AT A TIME, and a dropped SNAPSHOT puts its\n * backoff in the place of one pending at once. rrweb emits a Meta and\n * then the snapshot: with the transport's queue full, the retake's own\n * Meta evicted a DOM event, which asked for a retake at once from inside\n * takeFullSnapshot; the snapshot behind it was then refused by the\n * scrub, found that retake pending and left it -- so the page was\n * serialised again on the next turn, and the next: 3,212 times in 4 s\n * where the backoff allows none (found refuting review #30). A backoff\n * already pending is left as it is: put off again by every drop, it\n * would never fire.\n */\n private rebaseline(snapshotDropped: boolean): void {\n // In an outage the hold waits for the upload that ends it; see failing().\n if (this.outage) return;\n if (this.retakeTimer !== null) {\n if (!snapshotDropped || !this.retakeAtOnce) return;\n clearTimeout(this.retakeTimer);\n }\n this.retakeAtOnce = !snapshotDropped;\n const delay = snapshotDropped ? this.retakeDelay : 0;\n if (snapshotDropped)\n this.retakeDelay = Math.min(this.retakeDelay * 2, RETAKE_MAX_MS);\n this.retakeTimer = setTimeout(() => {\n this.retakeTimer = null;\n if (!this.baselineLost || this.getState() !== \"recording\") return;\n const takeFullSnapshot = this.rrwebRecord?.takeFullSnapshot;\n if (!takeFullSnapshot) return;\n // This snapshot is the baseline for a hole the GATE recorded too --\n // one its own reopening could not close, rrweb's takeFullSnapshot\n // having thrown there -- so that is spent here: left set, the next\n // reopening re-serialised the page for nothing.\n this.droppedWhileShut = false;\n try {\n takeFullSnapshot.call(this.rrwebRecord);\n } catch {\n // As in openDomGate(): the hole stays, and the next opening of\n // the gate tries again.\n this.droppedWhileShut = true;\n }\n }, delay);\n }\n\n /**\n * Events the transport delivered (TransportConfig.onDelivered). A\n * FullSnapshot among them is the baseline on the server: the retake's\n * backoff starts over.\n */\n delivered(events: readonly SessionEvent[]): void {\n if (\n events.some(\n (e) =>\n e.type === \"dom\" && (e.data as { type?: unknown } | null)?.type === 2,\n )\n )\n this.retakeDelay = RETAKE_FIRST_MS;\n }\n\n /** Which of rrweb's text nodes are a <style>'s, so their text is scrubbed as CSS (StyleTexts). */\n private readonly styles = new StyleTexts({\n note: (id) => {\n const node = this.rrwebRecord?.mirror?.getNode(id);\n if (node) this.styleNodes.set(id, node);\n },\n present: (id) => this.inPage(id),\n forget: (id) => {\n this.styleNodes.delete(id);\n },\n });\n /** The node of each id the styles' observer follows, kept from when it started (NodePresence). */\n private readonly styleNodes = new Map<number, Node>();\n private sessionId: string | null = null;\n private metadata: SessionMetadata | null = null;\n private config: CaptureConfig;\n private onEvent: OnEventCallback | null = null;\n private onSessionEnd: OnSessionEndCallback | null = null;\n private onScrubOversized: OnScrubOversizedCallback | null = null;\n /** Told how rrweb's import went once the network is back -- null when it landed; see startRRWeb(). */\n private onRRWeb:\n | ((err: DomRecorderRefusal | StrictAttributesRefusal | null) => void)\n | null = null;\n /** Whether rrweb's import, held by the page's leave, is still to land; see startRRWeb(). */\n private landing = false;\n /** The `online` listener that retries rrweb's import; see startRRWeb(). */\n private onlineRetry: (() => void) | null = null;\n /** The timer that reads the browser's state while onlineRetry waits; see retryWhenOnline(). */\n private onlinePoll: ReturnType<typeof setInterval> | null = null;\n private rrwebStopFn: (() => void) | null = null;\n /** rrweb's record(), once its import has landed. Held for takeFullSnapshot. */\n private rrwebRecord: RRWebRecord | null = null;\n /** Set the moment rrweb's start is requested, so it is requested once. */\n private rrwebRequested = false;\n /**\n * Counts start() calls. Both awaits below — start()'s on startRRWeb()\n * and startRRWeb()'s on the import — resume into whatever session is\n * current by then, and compare this against the value they captured\n * before yielding: a continuation of a superseded session does\n * nothing. See startRRWeb().\n */\n private generation = 0;\n private sessionTimer: ReturnType<typeof setTimeout> | null = null;\n private visibilityHandler: (() => void) | null = null;\n private stopNavigation: (() => void) | null = null;\n private lastHref = \"\";\n /** location.href as the recorder last read it; see noticeUnheardMove(). */\n private seenHref = \"\";\n\n constructor(config: CaptureConfig) {\n /* DROPPEDWHILESHUT (the field).\n * A dom event has been dropped since the DOM gate last shut — i.e.\n * the recording has a hole that only a new baseline can close.\n *\n * Set in emitEvent, which is the single place a dom event is\n * dropped, and cleared by the baseline that closes it. Without it\n * openDomGate() re-serialised the document on EVERY transition: a\n * visitor who alt-tabs thirty times on a page that mutates nothing\n * while hidden paid thirty FullSnapshots of a document that had not\n * changed. A snapshot of a real page is large — transport.ts's own\n * measurement is 236 KB for one — and any event over\n * KEEPALIVE_QUOTA_BYTES (32 KiB, the SDK's share) is sent the moment it is queued as\n * a full drain, so each one is also an upload of its own.\n */\n this.config = config;\n }\n\n /* -------------------------------------------------------------- */\n /* Lifecycle */\n /* -------------------------------------------------------------- */\n\n /**\n * Start recording. Resolves to the session id, or \"\" when sampleRate\n * left this visitor out. `onSessionEnd` is called when the session ends\n * on its own, and the recorder then stops itself unless the callback\n * called stopDom() (see OnSessionEndCallback); `startPaused` opens it paused, as pause() would;\n * `onScrubOversized` when an event is dropped because scrubbing it passed\n * the ingest server's body cap; `onNavigationUnwrapped` when the page made\n * a History or Navigation API method the SDK wraps impossible to replace,\n * with that method's name (wrapHistory).\n */\n async start(\n onEvent: OnEventCallback,\n onSessionEnd: OnSessionEndCallback | null = null,\n startPaused = false,\n onScrubOversized: OnScrubOversizedCallback | null = null,\n onRRWeb:\n | ((err: DomRecorderRefusal | StrictAttributesRefusal | null) => void)\n | null = null,\n onNavigationUnwrapped: ((method: string) => void) | null = null,\n ): Promise<string> {\n if (this.phase === \"active\") return this.sessionId!;\n // A session stopDom() left stopping is finished before the next one\n // starts: started over it, its navigation subscription would be\n // overwritten without being let go, and its online retry kept, so the\n // next session started offline would arm none of its own.\n if (this.phase === \"stopping\") this.stop();\n\n /*\n * THE DECLARED PRIVACY ROUTES ARE CHECKED FIRST, before anything\n * reads the page's URL: a route the SDK cannot match protects nothing,\n * and recording on would send what it was declared to keep. Before\n * sampling too: checked after it, a bad route was refused only on the\n * loads sampled in, so a rate of 0.01 hid it from 99 of 100 test runs\n * (found in review).\n */\n const routes = {\n secretRoutes: [] as string[][],\n keepRoutes: [] as string[][],\n };\n for (const option of [\"secretRoutes\", \"keepRoutes\"] as const) {\n const list: unknown = this.config.privacy?.[option] ?? [];\n // A list, or it is refused whole: read as one, a string was each of\n // its characters and an object threw out of init() (found in review).\n if (!Array.isArray(list)) {\n this.phase = \"stopped\";\n throw new PrivacyRouteRefusal({\n option,\n received: describeReceived({ returned: list }),\n });\n }\n for (const route of list) {\n const parsed = parseRoute(route, option === \"keepRoutes\");\n if (parsed === null) {\n this.phase = \"stopped\";\n throw new PrivacyRouteRefusal({\n option,\n received: describeReceived({ returned: route }),\n });\n }\n routes[option].push(parsed);\n }\n }\n declareRoutes(routes.secretRoutes, routes.keepRoutes);\n\n // Sampling: decide whether this session should be recorded.\n const sampleRate = this.config.sampleRate ?? 1;\n if (Math.random() > sampleRate) {\n this.phase = \"stopped\";\n return \"\";\n }\n\n this.onEvent = onEvent;\n this.onSessionEnd = onSessionEnd;\n this.onScrubOversized = onScrubOversized;\n this.onRRWeb = onRRWeb;\n /*\n * THE ONE INTEGRATOR-SUPPLIED VALUE ON THE WIRE IS CHECKED HERE,\n * before rrweb starts and before a byte is sent. The server refuses\n * an id outside its rule with a 400 whose only diagnosis is\n * `issues: [{path: \"sessionId\"}]`, and that used to reach onError\n * five seconds later as KUI_E_INGEST_REJECTED with a remedy blaming\n * a version mismatch -- for a `user:42/session 1` the option's own\n * docstring invites. The SDK's own UUIDs always pass; only the\n * override can fail, so it is the only thing checked -- and it is\n * integrator code, so it can THROW as well as return the wrong\n * thing, and a throw here used to leave the singleton set for the\n * life of the page (init() rejected with the raw error, onError\n * never ran, and a corrected init() got the dead instance back).\n * Both go the same way: the SessionIdRefusal reaches\n * KeployCapture.start(), which ends the capture and hands onError\n * the error, the path a server rejection takes.\n */\n\n let produced: unknown;\n try {\n produced = this.config.sessionIdGenerator\n ? this.config.sessionIdGenerator()\n : uuid();\n } catch (threw) {\n this.phase = \"stopped\";\n throw new SessionIdRefusal({\n sessionId: null,\n received: describeReceived({ threw }),\n });\n }\n if (!isValidSessionId(produced)) {\n this.phase = \"stopped\";\n throw new SessionIdRefusal({\n sessionId: typeof produced === \"string\" ? produced : null,\n received: describeReceived({ returned: produced }),\n });\n }\n this.sessionId = produced;\n this.metadata = gatherMetadata(this.scrubUrl);\n\n /*\n * THE GATE OPENS BEFORE rrweb STARTS. record() emits the Meta event\n * and the FullSnapshot synchronously, inside the call, whenever the\n * document is already interactive or complete — and the flow engine\n * builds its node map from that snapshot. With the state set after\n * the await, the gate was still \"idle\" for both and every session\n * began without the one event that makes its selectors resolvable.\n *\n * THE HIDDEN FLAG IS READ FROM THE DOCUMENT, not assumed false. A\n * page opened in a background tab (ctrl+click, a prerender) is\n * hidden before init() runs, and a flag that tracked only\n * transitions recorded and posted from such a tab until its first\n * visibilitychange — then saw nothing to change when the user\n * finally focused it.\n */\n this.phase = \"active\";\n // Paused from the first event when the integrator's pause() covered\n // the moment this session started (a continuous capture's next\n // session): rrweb then starts at resume(), not before.\n this.userPaused = startPaused;\n // A hole from a session that has ended is not a hole in this one:\n // start() takes its own baseline below.\n this.droppedWhileShut = false;\n this.hidden =\n typeof document !== \"undefined\" && document.visibilityState === \"hidden\";\n this.rrwebRequested = false;\n const generation = ++this.generation;\n\n // A hidden tab closes the gate; visible reopens ITS reason only —\n // and starts rrweb if it has been waiting for the gate to open.\n if (typeof document !== \"undefined\") {\n this.visibilityHandler = () => {\n this.hidden = document.visibilityState === \"hidden\";\n if (this.getState() === \"recording\") this.openDomGate();\n };\n document.addEventListener(\"visibilitychange\", this.visibilityHandler);\n }\n\n // A single-page app changes page without a load, and rrweb records a\n // page (its Meta event) only on a load. See navigated(). lastHref is\n // the page URL, as recorded (recordedPageUrl), that the recording last\n // put in a Meta event -- rrweb's or this recorder's: a History API call\n // that leaves its path unchanged is not a navigation. stopNavigation\n // unsubscribes this session from the page's same-document navigations.\n this.seenHref = typeof location !== \"undefined\" ? location.href : \"\";\n this.lastHref =\n typeof location !== \"undefined\" ? this.scrubUrl(location.href) : \"\";\n this.stopNavigation = onNavigation((cause, userInitiated, initiator) =>\n this.navigated(cause, userInitiated, initiator),\n );\n\n /*\n * rrweb WAITS FOR AN OPEN GATE, and startRRWeb() is where that is\n * decided — after its import, not here. Started into a shut gate,\n * record() would emit its Meta and FullSnapshot into it, and the\n * session would consist of incremental events with no snapshot to\n * resolve them against. A check here alone covered the tab that\n * was hidden at init() and missed the one that went hidden while\n * the import was in flight; a check of `hidden` alone covered the\n * tab and missed the manual pause() that shuts the same gate.\n */\n const unavailable = await this.startRRWeb();\n\n /*\n * STOPPED WHILE THE IMPORT WAS PENDING: there is no session to\n * return and nothing to end later. This used to arm the timer and\n * hand back the id anyway, so onSessionEnd fired for a session that\n * never ran — and the caller started a transport and patched fetch\n * for a capture it had already released. The empty string is what\n * the caller already reads as \"no session\" (see the sampling\n * branch above).\n *\n * SUPERSEDED WHILE THE IMPORT WAS PENDING — stop() and then start()\n * again inside the window — is the same answer: the session that\n * is active now is the later call's, and this one has nothing to\n * return. `phase` alone read \"active\" and handed back the other\n * session's id.\n */\n if (generation !== this.generation || this.phase !== \"active\") return \"\";\n\n // No rrweb in a browser, or no allow-list under strict: refuse, as a\n // bad session id is refused, before the caller starts a transport. See\n // DomRecorderRefusal and StrictAttributesRefusal.\n if (unavailable !== null && typeof window !== \"undefined\") {\n this.stop();\n throw refusal(unavailable);\n }\n\n // The session ends after maxSessionDuration — the whole session,\n // which is why the owner is told: the recorder used to stop only\n // itself here, and network events kept flowing through emitEvent\n // (ungated at the time) for as long as the page lived.\n // The owner first, while the session still takes what it hands over:\n // KeployCapture's stop() records the network exchanges reported and\n // waiting for their own task (NetworkInterceptor.emit) before this one.\n // AN OWNER THAT BEGAN ENDING THE SESSION FINISHES IT: KeployCapture's\n // stop() moves this recorder to \"stopping\" (stopDom) and stops it once\n // the exchanges answered inside the session have recorded (settle()).\n // Stopping here as well, right after, shut that window at once, and\n // every exchange still waiting for its body's redaction -- the body\n // chunk loading, the worker -- was dropped: MEASURED with\n // maxSessionDuration 0, a request made and answered inside the session\n // was never posted (session-gate.test.ts). A recorder still \"active\"\n // once the callback has returned or thrown -- none was given, it only\n // logs (KeployCaptureRecorder is exported and used on its own), or it\n // threw before stopDom() -- stops itself: the session ends at the\n // deadline whatever the callback does (recorder-session-end.test.ts).\n const maxDuration = this.config.maxSessionDuration ?? 600_000;\n this.sessionTimer = setTimeout(() => {\n try {\n this.onSessionEnd?.();\n } finally {\n if (this.phase === \"active\") this.stop();\n }\n }, maxDuration);\n\n // A method the SDK could not wrap (wrapHistory), said once the capture\n // runs: a refused or superseded start says nothing of it.\n if (historyWrap?.refused) onNavigationUnwrapped?.(historyWrap.refused);\n return this.sessionId;\n }\n\n /**\n * Stop DOM recording now, and leave the session open for what is\n * already in flight (the network exchanges stop() settles): the phase\n * moves to \"stopping\", which every gate reads as ended -- rrweb is\n * not started, an import still in flight resumes into nothing, a\n * hidden tab shown starts nothing, a retake due takes no snapshot, a\n * same-document navigation is not recorded -- while an exchange\n * already admitted still reports. Review round 3 measured the\n * alternative: a tab hidden at init() and shown during stop()'s\n * settle started rrweb and posted a FullSnapshot after stop(). rrweb\n * is stopped here too. The visibility handler, which the phase now\n * keeps from starting anything, and the navigation subscription stay\n * until stop(): the URLs the page moves to are still read for their\n * credentials, which the exchanges recorded in the window are\n * scrubbed of. And maxSessionDuration is disarmed: the session is\n * ending, and a timer that ended it inside the window dropped the\n * very exchanges the window is for. stop() must follow\n * (KeployCapture.stop() calls it once the settle ends); start()\n * finishes a stopping session first.\n */\n stopDom(): void {\n if (this.phase === \"active\") this.phase = \"stopping\";\n if (this.rrwebStopFn) {\n this.rrwebStopFn();\n this.rrwebStopFn = null;\n }\n if (this.sessionTimer) {\n clearTimeout(this.sessionTimer);\n this.sessionTimer = null;\n }\n }\n\n stop(): void {\n if (this.phase !== \"active\" && this.phase !== \"stopping\") return;\n\n if (this.onlineRetry !== null) {\n window.removeEventListener(\"online\", this.onlineRetry);\n this.onlineRetry = null;\n this.stopOnlinePoll();\n }\n this.landing = false;\n for (const waiting of landers) waiting.delete(this);\n\n this.stopDom();\n this.rrwebRecord = null;\n\n if (this.retakeTimer) {\n clearTimeout(this.retakeTimer);\n this.retakeTimer = null;\n }\n\n if (this.visibilityHandler && typeof document !== \"undefined\") {\n document.removeEventListener(\"visibilitychange\", this.visibilityHandler);\n this.visibilityHandler = null;\n }\n\n this.stopNavigation?.();\n this.stopNavigation = null;\n\n this.phase = \"stopped\";\n }\n\n /** A same-document navigation, recorded as rrweb records a load: a Meta event. */\n private navigated(\n cause: NavigationCause,\n userInitiated?: boolean,\n initiator?: NavigationInitiator,\n ): void {\n // The page changed URL without a load: record it the way rrweb records\n // a load, as a Meta event `{href, width, height}`, plus what moved it\n // (`cause`, NavigationCause): a step the visitor took can move the page,\n // and Back pressed right after one is not that step's doing.\n //\n // rrweb emits Meta only with a full snapshot -- on load, and when a\n // hidden tab comes back -- so before this every step of a single-page\n // app was attributed to the page the visit LANDED on (MEASURED on a real\n // session: steps on /cart and /checkout recorded on \"/\", the flow named\n // \"Fill on /\"). A Meta event, and not a custom one, because \"a Meta\n // href that differs from the current URL is a navigation\" is already the\n // flow engine's rule (spec/flow-engine rules.actions) in both its\n // implementations, so the server that is deployed today reads it.\n //\n // A History API call that keeps the path -- a router syncing query\n // state, a framework stamping history.state, a search box pushing `?q=`\n // per keystroke, which would otherwise split one search into a flow per\n // character (found in review) -- is not a page change: no Meta event.\n // One that changes the path is recorded, a redirect included. rrweb's\n // own Meta, written with a full snapshot (a load, a returning tab),\n // carries the URL as it is, query included: every extraction version\n // reads a URL that differs as a navigation, and a flow starting there\n // opens that exact URL, which is where its replay has to start. Through\n // the gate like every DOM event: a navigation while the tab is hidden\n // or paused is dropped, and the full snapshot that reopens the gate\n // carries the page the visitor is on by then.\n if (this.phase !== \"active\") return;\n this.seenHref = location.href;\n const href = this.scrubUrl(location.href);\n if (withoutQuery(href) === withoutQuery(this.lastHref)) return;\n this.lastHref = href;\n this.emitEvent(\"dom\", {\n type: RRWEB_META,\n data: {\n href,\n ...viewport(),\n cause,\n // Only what the Navigation API said; never guessed.\n ...(userInitiated === undefined ? {} : { userInitiated }),\n // Only a traversal the SDK saw the page's script ask for.\n ...(initiator === undefined ? {} : { initiator }),\n },\n timestamp: Date.now(),\n });\n }\n\n /** rrweb's events on their way to emitEvent, a Meta event's href recorded as the page URL. */\n private recordedRRWebEvent(event: unknown): unknown {\n // rrweb's own events, on their way to emitEvent. A Meta event's href is\n // `location.href` verbatim; it is recorded by the rule the SDK's own\n // navigation Meta uses (recordedPageUrl), so a credential in the page's\n // URL is not, and so the two kinds compare equal for the same page.\n if (typeof event !== \"object\" || event === null) return event;\n const e = event as { type?: unknown; data?: Record<string, unknown> };\n const href = e.data?.[\"href\"];\n if (e.type !== RRWEB_META || typeof href !== \"string\") return event;\n // The URL the page is on, as it is: rewriting it to the page reached\n // before a change of the query made the recording state a URL the\n // visitor was not on, and a test generated from it opened the wrong\n // page (found in review).\n this.lastHref = this.scrubUrl(href);\n return { ...e, data: { ...e.data, href: this.lastHref } };\n }\n\n /** Whether pause() closed the gate; a hidden tab does not count. */\n isUserPaused(): boolean {\n return this.userPaused;\n }\n\n /** Close the gate until resume(). A visibility change cannot reopen it. */\n pause(): void {\n if (this.phase !== \"active\") return;\n // rrweb has no native pause — emitEvent drops everything instead.\n this.userPaused = true;\n }\n\n /**\n * Reopen the manual pause. A hidden tab still keeps the gate shut.\n *\n * And start rrweb if it has been waiting for this — the same way the\n * visibilitychange that shows the tab does. A pause() before rrweb's\n * import landed (init() and pause() in one tick behind a consent\n * gate) meant the import resolved into a shut gate; the decision\n * there read `hidden` alone, so record() went ahead, Meta and\n * FullSnapshot were dropped, and with nothing here to start it\n * again, the session stayed snapshotless for good.\n */\n resume(): void {\n if (this.phase !== \"active\") return;\n this.userPaused = false;\n if (this.getState() === \"recording\") this.openDomGate();\n }\n\n private openDomGate(): void {\n /*\n * The DOM gate has just reopened: give the recording a baseline.\n *\n * rrweb HAS NO PAUSE, so while the gate was shut it went on observing\n * and emitEvent dropped what it emitted. Every incremental event\n * rrweb produces names its nodes by the ids of the last FullSnapshot\n * — an `add` introduces an id and the `attributes`, `texts` and\n * `removes` after it refer to it — so the events from here on refer\n * to nodes the recording never showed. The flow engine resolves those\n * ids against the DOM it rebuilds from the snapshot and the mutations\n * after it (flow-engine/src/extractor.ts, spec/flow-engine.v2), and a\n * DROPPED mutation is one it never sees, so selectorFromNode answers\n * `body` for the id it introduced: a click on a button added while the\n * tab was hidden becomes a click on `body` in the generated test, and\n * it passes. Nothing anywhere said the recording had a hole.\n *\n * So a reopened gate re-serialises the document and re-numbers\n * rrweb's mirror. Two ways in, and exactly one of them fires:\n *\n * - rrweb has not started (hidden or paused since init, where\n * starting it would have emitted Meta and FullSnapshot into the\n * shut gate). Start it now; the snapshot record() takes inside\n * that call IS the baseline.\n * - rrweb is running. takeFullSnapshot(), which also throws before\n * record() has run — inside a visibilitychange handler that would\n * be an exception in the integrator's document.\n */\n if (!this.rrwebStopFn) {\n // The snapshot record() takes inside that call IS the baseline,\n // so it closes whatever hole was recorded before rrweb ran —\n // otherwise the flag outlives it and the next quiet transition\n // takes a second, pointless FullSnapshot.\n this.droppedWhileShut = false;\n // Its import can fail here too -- a page started offline whose own\n // `online` handler resumes the capture before the SDK's retry runs\n // -- and the failure refuses the capture as anywhere else: ignored,\n // the hold was released and the page's calls went out with no\n // refusal (found in review #27).\n const generation = this.generation;\n void this.startRRWeb().then((failed) => {\n if (failed !== null) this.refuseLate(generation, failed);\n else this.landedBeforeTheRetry(generation);\n });\n return;\n }\n /*\n * NOTHING WAS DROPPED, SO THERE IS NOTHING TO RE-BASELINE. rrweb\n * renumbers its mirror in the same callbacks that emit, so a gate\n * that dropped no dom event leaves the last FullSnapshot still\n * describing the mirror every later event is numbered against —\n * the hole this method exists for does not exist. Re-serialising\n * anyway is what made a tab flap cost a full document each time.\n */\n // A hold no retake ended is a hole too: a retake refused, then a timer\n // that fired with the gate shut, left the session held for good with\n // nothing here to end it (found in review #24).\n if (!this.droppedWhileShut && !this.baselineLost) return;\n /*\n * AN rrweb THAT CANNOT SNAPSHOT DEGRADES, AND KEEPS THE HOLE.\n * takeFullSnapshot is optional on RRWebRecord because it is read\n * off a dynamically imported module (see the type). An absent\n * method used to be indistinguishable from a snapshot taken —\n * `?.()` then `= false` — so the flag was spent on a call that\n * never happened and no later transition retried it. Nothing is\n * owed to a hole that was closed; this one was not.\n */\n const takeFullSnapshot = this.rrwebRecord?.takeFullSnapshot;\n if (!takeFullSnapshot) return;\n // In an outage the hole is held, and the snapshot taken when uploads\n // come back (failing()): taken here, a tab flap re-serialised the page\n // into a queue nothing drains.\n if (this.outage) {\n this.baselineLost = true;\n return;\n }\n // Spent on this call. A snapshot dropped inside it -- over the cap,\n // refused by the transport -- is a hole of its own, which lost() or\n // the scrub records as the hold it starts (baselineLost) and the next\n // opening reads: recorded in this flag, and wiped by a clear that came\n // after the call, it was forgotten (found in review #24). One that\n // threw puts it back.\n this.droppedWhileShut = false;\n try {\n takeFullSnapshot.call(this.rrwebRecord);\n } catch {\n this.droppedWhileShut = true;\n // A baseline that could not be taken leaves the recording as it\n // was; it must not take the page's visibilitychange handler with\n // it. There is nothing here that could report it either — this\n // runs in an event handler nobody awaits.\n }\n }\n\n /**\n * The id of the session that is LIVE, or null when none is.\n *\n * Null once the session has ended, including when the\n * maxSessionDuration timer ended it — this used to keep answering\n * with the id of a session its own timer had stopped, so an\n * integrator tagging their logs with it went on tagging them with a\n * session that had finished ten minutes earlier. A pause does not\n * end a session, so this keeps answering through one.\n */\n getSessionId(): string | null {\n return this.phase === \"active\" ? this.sessionId : null;\n }\n\n /**\n * The SESSION gate: a live session the integrator has not paused.\n *\n * Deliberately not derived from getState(), which is the narrower DOM\n * gate and answers \"paused\" for a hidden tab.\n */\n private get sessionOpen(): boolean {\n return this.phase === \"active\" && !this.userPaused;\n }\n\n /**\n * The DOM gate, as a public state.\n *\n * \"recording\" means rrweb may run and its events are emitted; a\n * hidden tab reads \"paused\" here while the session itself is still\n * open and still recording the exchanges the page makes. This is the\n * meaning the state has always had — every caller of it decides\n * something about rrweb — and it is the only one it can have while\n * one enum stands for two independent gates.\n */\n getState(): RecorderState {\n if (this.phase === \"idle\") return \"idle\";\n if (this.phase === \"stopped\" || this.phase === \"stopping\") return \"stopped\";\n return this.userPaused || this.hidden ? \"paused\" : \"recording\";\n }\n\n getMetadata(): SessionMetadata | null {\n return this.metadata;\n }\n\n /* -------------------------------------------------------------- */\n /* rrweb integration */\n /* -------------------------------------------------------------- */\n\n /** Starts rrweb when the gate allows; answers why rrweb (or strict's allow-list) could not be imported, else null. */\n private async startRRWeb(): Promise<RRWebFailure | null> {\n // Once. The import below is async, so a visibility flap inside that\n // window would otherwise reach record() twice.\n if (this.rrwebRequested) return null;\n this.rrwebRequested = true;\n const generation = this.generation;\n\n /*\n * OFFLINE, rrweb IS NOT ASKED FOR until the network is back. Its import\n * is a chunk fetch in an app that code-splits, and Chromium keeps a\n * failed module import for the life of the page: asked offline, it\n * failed, and asked again at `online` it failed at once with no\n * request -- the capture refused for good (found in reviews #25 and\n * #26, MEASURED in Chromium). Still failing online, the capture is\n * refused as at start (onRRWeb). Already loaded, it is used.\n *\n * UNLESS A SERVICE WORKER CONTROLS THE PAGE: it may answer the import\n * with no network, and a page that starts offline at all is most often\n * one a worker served. Deferred there too, an offline-first app\n * recorded nothing its visitor did offline, where the release before\n * recorded all of it (found in review #28, MEASURED in Chromium). So a\n * controlled page asks at once; a worker without rrweb's chunk fails\n * the import, and that capture is refused at start as it always was.\n */\n if (\n !this.loaded() &&\n typeof window !== \"undefined\" &&\n navigator.onLine === false &&\n !workerInControl()\n ) {\n this.rrwebRequested = false;\n this.retryWhenOnline(generation);\n return null;\n }\n /*\n * HELD BY THE PAGE'S LEAVE (leave.ts), start() WAITS NO LONGER: a leave\n * that cancelled the import, as WebKit and Firefox do, holds it until\n * the page has stayed, and a page that stays with no proof of it (a\n * prompt the user cancelled in Firefox or WebKit, a 204) gives none.\n * Awaited, init() never settled there. So the capture is set up without\n * rrweb, its transport held as for an import that waits for the network\n * (awaitingRRWeb), and rrweb starts when its import lands: recorded\n * then, or refused then as at start. No proof ever: no DOM events, and\n * nothing said. A session started WHILE the page leaves (a continuous\n * capture's next, from the visitor's input) finds the import held\n * already, and waits on it no more either: kept waiting, its start()\n * never settled, and index.ts held every event of it until then.\n *\n * ONE REACTION WAITS ON THE HELD IMPORT (landers): under a leave that\n * never ends, one kept per tab show, resume() or session grew without\n * bound, and asked again, under strict each made a Promise.all on the\n * held loads. So while one waits, no load is asked for at all.\n */\n const strict = +(this.config.privacyMode === \"strict\");\n if (reactions[strict]) return (landers[strict].add(this), this.land());\n const loading = loadRecorder(strict > 0);\n const loaded = await unlessHeld(loading, this.loaded());\n if (!loaded) {\n // A recorder stopped while it waited (stop() keeps its generation)\n // joins nothing: kept, it was reachable until the import lands, and\n // under a leave that never ends that is never.\n if (generation === this.generation && this.phase === \"active\") {\n landers[strict].add(this);\n this.land();\n if (!reactions[strict])\n KeployCaptureRecorder.whenLanded(strict, loading);\n }\n return null;\n }\n /*\n * A LATER start() OWNS THE RECORDER NOW. stop() and start() again\n * inside the import window reset the once-only flag and requested\n * rrweb a second time; this import then resolved into the new\n * session's open gate, passed the check below, and called record()\n * beside the new session's own call: two recordings, two Meta and\n * FullSnapshot pairs in one session, and rrwebStopFn overwritten so\n * the first recording's stop function was dropped and it emitted\n * for the life of the document. The flag is the new session's now,\n * so it is left alone -- by an import that FAILED as by one that\n * landed, which is why this is asked first: freed below for a\n * session refused and restarted inside its own refusal, the new\n * session's flag was gone while its import was on its way, a pause\n * and resume inside it asked again, and the page was recorded twice\n * (found in review #29). The answer is nobody's: every caller reads\n * the generation itself before it acts on one.\n */\n if (generation !== this.generation) return null;\n // No DOM recording: start() refuses the capture in a browser, and\n // under SSR there is no page to record.\n // Failed: the request is free again, so the next asks rather than\n // being told by the guard above that rrweb is on its way.\n if (\"failed\" in loaded) {\n this.rrwebRequested = false;\n return loaded;\n }\n const rrwebRecord = loaded.record;\n /*\n * THE GATE IS SHUT NOW. The import is a network fetch in a consumer\n * app, and a stop(), a tab switch or a consent gate's pause() fits\n * inside it. Stopped: a recording started now would have no stop()\n * left to end it. Hidden, or paused: record() emits Meta and\n * FullSnapshot synchronously, so starting into a shut gate drops\n * both, and once dropped they are never taken again. The decision\n * is THE GATE ITSELF, the one emitEvent reads — it read `hidden`\n * alone, so a pause() in that window started rrweb into a gate\n * shut by userPaused. The request is released so that the\n * transition which reopens the gate (the visibilitychange that\n * shows the tab, or resume()) starts rrweb — with the flag left\n * set, that handler returned at the guard above and the session\n * stayed snapshotless for good.\n */\n if (this.getState() !== \"recording\") {\n this.rrwebRequested = false;\n return null;\n }\n\n this.rrwebRecord = rrwebRecord;\n this.rrwebStopFn = rrwebRecord(this.rrwebOptions()) ?? null;\n return null;\n }\n\n /**\n * Asks for rrweb again when the browser is back online, for this session\n * only.\n *\n * THE BROWSER'S STATE IS READ WHILE THIS WAITS, AS WELL AS HEARD. The\n * `online` event is on window, and a page's own listener, registered\n * first, can stop it before it reaches this one\n * (stopImmediatePropagation). Waiting for the event alone, such a page's\n * capture sat for good once started offline: rrweb never asked for, its\n * transport held, nothing sent and nothing said until the visitor\n * switched tab (found refuting review #30, with the real stack). So a\n * timer asks navigator.onLine, which is what the event reports, and\n * whichever comes first runs the retry, once, and ends the other. (The\n * timer asks before it runs the retry only so that a look at a browser\n * still offline changes nothing: the retry would find the same, and\n * start this wait over.)\n */\n private retryWhenOnline(generation: number): void {\n if (this.onlineRetry !== null) return;\n const retry = (): void => {\n window.removeEventListener(\"online\", retry);\n this.stopOnlinePoll();\n this.onlineRetry = null;\n if (generation !== this.generation || this.phase !== \"active\") return;\n // Offline again by now: wait for the next `online`, not import into a\n // network the browser says is down.\n if (navigator.onLine === false) {\n this.retryWhenOnline(generation);\n return;\n }\n // Decided on the import's own answer: startRRWeb()'s null also means\n // \"already requested\", and read as rrweb landed, an import someone\n // else started and lost released the hold (found in review #27).\n void loadRecorder(this.config.privacyMode === \"strict\").then((loaded) =>\n this.loadedLate(generation, loaded),\n );\n };\n this.onlineRetry = retry;\n window.addEventListener(\"online\", retry, { once: true });\n this.onlinePoll = setInterval(() => {\n if (navigator.onLine !== false) retry();\n }, ONLINE_POLL_MS);\n }\n\n /**\n * The ONE reaction on rrweb's held import (by mode): each recorder still\n * landing as it lands is told. Static, so it holds none of them: a\n * recorder stopped meanwhile has left the set.\n */\n private static whenLanded(\n strict: number,\n loading: Promise<RRWebImport>,\n ): void {\n reactions[strict]++;\n void loading.then((late) => {\n reactions[strict]--;\n const told = [...landers[strict]];\n landers[strict].clear();\n for (const r of told) if (r.landing) r.loadedLate(r.generation, late);\n });\n }\n\n /** rrweb lands later, its owner told then (awaitingRRWeb): the request is free again. */\n private land(): null {\n this.rrwebRequested = false;\n this.landing = true;\n return null;\n }\n\n /** How the import went after start() (back online, or a leave's hold ended): refused, or recorded now or when the DOM gate next opens, its owner told. */\n private loadedLate(generation: number, loaded: RRWebImport): void {\n // Stopped meanwhile: nothing left to refuse (review #26).\n if (generation !== this.generation || this.phase !== \"active\") return;\n this.landing = false;\n if (\"failed\" in loaded) {\n this.refuseLate(generation, loaded);\n return;\n }\n void this.startRRWeb();\n this.onRRWeb?.(null);\n }\n\n /** Ends the timer retryWhenOnline() started, if it is still running. */\n private stopOnlinePoll(): void {\n if (this.onlinePoll === null) return;\n clearInterval(this.onlinePoll);\n this.onlinePoll = null;\n }\n\n /**\n * rrweb could not be imported after start(): the capture is refused as it\n * is at start, once, unless it has ended or been superseded meanwhile.\n */\n private refuseLate(generation: number, failure: RRWebFailure): void {\n if (generation !== this.generation || this.phase !== \"active\") return;\n this.stop();\n this.onRRWeb?.(refusal(failure));\n }\n\n /**\n * rrweb landed while the retry at `online` was still waiting -- the page\n * resumed the capture, or showed its tab, once the browser was online,\n * and the DOM gate imported rrweb itself. The capture's owner is told as\n * the retry would have told it, and the retry is dropped: left waiting,\n * the capture was live and recording and its transport stayed held until\n * an `online` event came to ask again (found in review #28).\n */\n private landedBeforeTheRetry(generation: number): void {\n if (generation !== this.generation || this.phase !== \"active\") return;\n if (!this.loaded() || this.onlineRetry === null) return;\n window.removeEventListener(\"online\", this.onlineRetry);\n this.onlineRetry = null;\n this.stopOnlinePoll();\n this.onRRWeb?.(null);\n }\n\n /** Whether what the recorder loads -- rrweb, and under strict its allow-list -- has loaded in this document. */\n private loaded(): boolean {\n return (\n rrwebLoaded && (strictLoaded || this.config.privacyMode !== \"strict\")\n );\n }\n\n /** Whether rrweb's import waits for the network, or for a leave's hold to end: onRRWeb says how it went. */\n awaitingRRWeb(): boolean {\n return this.onlineRetry !== null || this.landing;\n }\n\n private rrwebOptions(): Record<string, unknown> {\n /*\n * Everything the SDK's privacy configuration means to rrweb.\n *\n * NO `maskAllInputs`. MEASURED in rrweb 2.0.0-alpha.20's record()\n * (rrweb.js:13778-13795): `maskAllInputs: true` DISCARDS the\n * maskInputOptions object it was handed and substitutes a fixed map\n * of 16 input types, and neither `hidden` nor `file` is among them —\n * so the SDK's own map was dead in balanced and strict, and a CSRF\n * token, a session id or an internal record id in `<input\n * type=\"hidden\">` was serialised in the clear in every mode.\n * Leaving `maskAllInputs` unset makes rrweb use the map below\n * verbatim (the `_maskInputOptions !== void 0` branch of the same\n * expression), which is the only way to name a type rrweb's fixed\n * map omits.\n *\n * The map is the ONLY statement of what each mode masks. Three\n * things are held to it and none of them keeps a second copy:\n * dom-masking.test.ts drives one case per entry through real rrweb\n * and asserts the serialised `value`, readme.test.ts holds the npm\n * page's privacy table to it, and readme.test.ts also requires every\n * input type the HTML spec has to be either in it or named in the\n * page's carve-out. Before that, thirteen of its rows were untested:\n * MEASURED, flipping `email`, `select`, `month`, `tel` and `number`\n * to `false` left the whole SDK suite green.\n */\n const privacyMode = this.config.privacyMode ?? \"balanced\";\n const privacy = this.config.privacy ?? {};\n\n /*\n * ONE CONTROL, TWO SPELLINGS, MERGED. `maskSelectors` exists on\n * CaptureConfig and again on PrivacyConfig; both were dead, and\n * making one of them win as they were revived would be the same\n * silent no-op in a subtler form — an integrator who sets the other\n * still gets nothing and still has no way to tell.\n */\n const maskSelectors = [\n ...(this.config.maskSelectors ?? []),\n ...(privacy.maskSelectors ?? []),\n ];\n const unmaskSelectors = [\n ...(this.config.unmaskSelectors ?? []),\n ...(privacy.unmaskSelectors ?? []),\n ];\n\n /*\n * Every typed value, or only a password. rrweb's fixed map for\n * `maskAllInputs: true` is reproduced here verbatim — the effective\n * behaviour of balanced and strict is unchanged for those 16 — plus\n * `hidden` and `file`.\n *\n * `file` is the FILENAME the person picked: rrweb reads `n.value`,\n * and a file input's value is `C:\\fakepath\\<name>` once a file is\n * chosen. MEASURED through the FullSnapshot before it was added\n * here: `C:\\fakepath\\Resume_John_Smith.pdf` was serialised\n * verbatim under `strict`. It follows the mode like a typed value,\n * because it IS one — the person chose it.\n *\n * NOT HERE, and measured in dom-masking.test.ts: `radio`,\n * `checkbox`, `submit` and `button`, whose value rrweb-snapshot\n * serialises before masking is consulted (rrweb-snapshot.js:987),\n * so an entry for them would do nothing; and `reset` and `image`,\n * which DO reach this map and are left out on purpose, their value\n * being a button caption or author-set metadata rather than\n * anything the person using the page entered.\n *\n * `password` and `hidden` are true in EVERY mode, `off` included.\n * `off` is about what the USER typed; a password is never wanted in\n * a recording and a hidden field is machinery the user never sees,\n * so neither is what `off` is asking for. The README says this in\n * as many words, and readme.test.ts holds it to this object.\n */\n const typed = privacyMode !== \"off\";\n const maskInputOptions: Record<string, boolean> = {\n color: typed,\n date: typed,\n \"datetime-local\": typed,\n email: typed,\n file: typed,\n month: typed,\n number: typed,\n range: typed,\n search: typed,\n tel: typed,\n text: typed,\n time: typed,\n url: typed,\n week: typed,\n textarea: typed,\n select: typed,\n password: true,\n hidden: true,\n };\n\n /*\n * WHERE UNMASKING HAPPENS. rrweb 2.0.0-alpha.20's recordOptions has\n * no `unmaskTextSelector` (rrweb.d.ts:221-252). It does call\n * `maskTextFn(text, element)` for every text node it has decided to\n * mask, with that node's parent element — so the exception is\n * expressible there, and only there. Undefined when nothing is\n * unmasked, so rrweb keeps its own masking and this adds no call\n * per text node.\n *\n * `closest`, not `matches`, because that is what rrweb itself uses\n * to decide masking (rrweb-snapshot.js:754-760 with\n * checkAncestors) — an unmask that only covered the immediate\n * parent would leave a selector on a container unmasking nothing\n * while its mask counterpart covered everything under it.\n *\n * TEXT ONLY. An input's value is decided by privacyMode and by\n * nothing a selector can reach, so \"every typed value is masked\n * under balanced\" holds whatever else is configured.\n */\n /*\n * TEXT TYPED INTO AN EDITOR IS TYPED TEXT. rrweb's input masking\n * reaches input, textarea and select only, so what a person typed\n * into a contenteditable -- TipTap, Quill, Lexical, ProseMirror, a\n * plain one -- was recorded in clear under balanced, emails and card\n * numbers included. It is masked as an input's value is: under\n * balanced and strict, whatever unmaskSelectors says, and not under\n * off.\n */\n const editable = '[contenteditable]:not([contenteditable=\"false\"])';\n const editors = typed ? [editable] : [];\n const textMask = [...maskSelectors, ...editors].join(\",\");\n const unmask = unmaskSelectors.join(\",\");\n const maskTextFn = unmask\n ? (text: string, element: HTMLElement | null): string => {\n try {\n if (typed && element?.closest(editable)) {\n return text.replace(/[\\S]/g, \"*\");\n }\n if (element?.closest(unmask)) return text;\n } catch {\n // An invalid selector must not take the snapshot with it.\n }\n // rrweb's own default for a masked text node\n // (rrweb-snapshot.js:921), so an unmask that matches nothing\n // changes nothing.\n return text.replace(/[\\S]/g, \"*\");\n }\n : undefined;\n\n // emit is gated inside emitEvent, like every other emitter.\n return {\n emit: (event: unknown) =>\n this.emitEvent(\"dom\", event, (e) => this.recordedRRWebEvent(e)),\n maskTextSelector: privacyMode === \"strict\" ? \"*\" : textMask || undefined,\n ...(maskTextFn ? { maskTextFn } : {}),\n blockSelector: privacy.blockSelectors?.join(\",\") || undefined,\n maskInputOptions,\n // Each Input event carries `userTriggered`, which rrweb sets from the\n // event's isTrusted: true for the visitor's own input, false for a\n // value the page's script writes (`input.value = \"\"` after a submit)\n // and for any other change no trusted event made (the other radios\n // of a group, a date picker's write). Without it a recording cannot\n // tell a script's write from typing, so an extractor reading it\n // would turn the app's clear into a step the visitor never took.\n userTriggeredOnInput: true,\n };\n }\n\n /**\n * rrweb's node `id` is still in the page: the node kept for it when the\n * styles' observer started following it (rrweb's mirror forgets the id\n * of a node moved out of a frame into the page; NodePresence), else the\n * one rrweb's mirror has, connected, and -- in a frame -- in a frame\n * that is itself still in the page, up to the top. A removed shadow\n * host's insides stay in the mirror and a removed frame's nodes stay\n * connected to that frame's document, so the mirror alone could not\n * say. Asked by the styles' observer after a mutation that removes\n * nodes; with no rrweb, nothing is pruned.\n */\n private inPage(id: number): boolean {\n const mirror = this.rrwebRecord?.mirror;\n if (mirror === undefined) return true;\n const node = this.styleNodes.get(id) ?? mirror.getNode(id);\n if (!node || !node.isConnected) return false;\n for (let doc = node.ownerDocument; doc !== null && doc !== document;) {\n const frame = doc.defaultView?.frameElement ?? null;\n if (frame === null || !frame.isConnected) return false;\n doc = frame.ownerDocument;\n }\n return true;\n }\n\n /* -------------------------------------------------------------- */\n /* Event emission */\n /* -------------------------------------------------------------- */\n\n /**\n * A MOVE NO LISTENER HEARD, found when the next event is recorded. A\n * router that calls a pushState it saved before the SDK wrapped history\n * moves the page past the wrapper; where the browser has the Navigation\n * API its entry change still reports the move, and where it has none the\n * move is found here, before the event that follows it is recorded, so\n * that event and every one after it belong to the new page. Recorded\n * while popstate itself is being dispatched (by a listener of the page's\n * own that ran before the SDK's) it was the traversal; anywhere else it is\n * read as a push -- a replace cannot be told apart from one any more, and\n * nor can a traversal whose popstate listener caused another event first\n * (earlierMove reads the innermost event).\n * No timer looks\n * for it: one string comparison per event, and the page URL is read\n * again only when it has changed. rrweb's own Meta (the snapshot that\n * reopens a shut gate) names the page itself: a move made while the\n * gate was shut is that snapshot's, as a heard one is, and no step's.\n */\n private noticeUnheardMove(event: unknown): void {\n if (typeof location === \"undefined\" || location.href === this.seenHref)\n return;\n if ((event as { type?: unknown } | null)?.type === RRWEB_META) {\n this.seenHref = location.href;\n return;\n }\n this.navigated(earlierMove());\n }\n\n /**\n * A page URL as this capture records it: the page URL's rule\n * (recordedPageUrl), then scrubPageUrl over what that keeps -- every\n * query value under strict, and otherwise a value shaped like a token\n * or holding a PII pattern, a JWT path segment and a URL nested in a\n * value; never a value that rule kept by its own judgement of names and\n * ids. Used for the session's URL and referrer and for every Meta\n * event's href, rrweb's and this recorder's.\n */\n private scrubUrl = (url: string): string =>\n scrubPageUrl(\n recordedPageUrl(url),\n (this.config.privacyMode ?? \"balanced\") === \"strict\",\n );\n\n /**\n * The URLs in an rrweb event's DOM, scrubbed: every URL-valued\n * attribute in a full snapshot (type 2), and in a mutation (type 3,\n * source 0) every added subtree's, every changed attribute and every\n * changed text's CSS; the CSS of a rule, a replaced sheet, a declaration\n * or an adopted sheet a script put through the CSSOM (sources 8, 13,\n * 15). See scrubDomAttributes and scrubDomCss. A Meta event's href is the page URL, scrubbed by\n * scrubUrl in recordedRRWebEvent. It runs before the credential scrub\n * (scrubSecrets), knowing the page URL's credentials by value\n * (`matcher`), on rrweb's own objects, in place: copying a 50,000-node\n * tree to change three attributes would cost more than the scrub. A\n * throw is emitEvent's to handle, as the credential scrub's is: the\n * event is not sent.\n */\n private scrubDomUrls(data: unknown, matcher: SecretMatcher | null): unknown {\n const ev = data as {\n type?: unknown;\n data?: {\n node?: unknown;\n source?: unknown;\n adds?: unknown;\n attributes?: unknown;\n texts?: unknown;\n replace?: unknown;\n replaceSync?: unknown;\n set?: unknown;\n styles?: unknown;\n fontSource?: unknown;\n text?: unknown;\n };\n } | null;\n if (ev === null || typeof ev !== \"object\") return data;\n const d = ev.data;\n if (d === null || typeof d !== \"object\") return data;\n const strict = (this.config.privacyMode ?? \"balanced\") === \"strict\";\n const known =\n matcher === null ? [] : [...matcher.plain, ...matcher.bounded];\n if (ev.type === 2) scrubDomTree(d.node, strict, known);\n if (ev.type === 3 && d.source === 0) {\n if (Array.isArray(d.adds)) {\n scrubAddedTextRuns(d.adds);\n for (const add of d.adds as Array<{ node?: unknown } | null>) {\n if (add !== null && typeof add === \"object\") {\n scrubDomTree(add.node, strict, known);\n }\n }\n }\n if (Array.isArray(d.attributes)) {\n for (const change of d.attributes as Array<{\n id?: number;\n attributes?: unknown;\n } | null>) {\n const attrs = change?.attributes;\n if (attrs !== null && typeof attrs === \"object\") {\n // The changed element, from rrweb's mirror: strict keeps an\n // SVG's geometry, and a custom element's own names are text.\n const el = (\n strict\n ? this.rrwebRecord?.mirror?.getNode(change!.id ?? -1)\n : null\n ) as Element | null | undefined;\n scrubDomAttributes(\n attrs as Record<string, unknown>,\n strict,\n known,\n el?.localName ?? \"\",\n el?.namespaceURI === \"http://www.w3.org/2000/svg\",\n );\n }\n }\n }\n // A `<style>`'s text changed: its CSS. Which text nodes are a\n // style's, StyleTexts knows from the events before this one; the\n // text of any other node is the page's text, read for tokens.\n if (Array.isArray(d.texts)) {\n const styleTexts = this.styles.recordsIn(ev);\n for (const text of d.texts as Array<{ value?: unknown } | null>) {\n if (typeof text?.value !== \"string\") continue;\n text.value = styleTexts.has(text)\n ? scrubDomCss(text.value, strict, known)\n : scrubDomText(text.value);\n }\n }\n }\n // CSS a script put through the CSSOM: rrweb's StyleSheetRule (8),\n // StyleDeclaration (13) and AdoptedStyleSheet (15) events.\n if (ev.type === 3 && (d.source === 8 || d.source === 15)) {\n const rules = [\n ...(Array.isArray(d.adds) ? d.adds : []),\n ...(Array.isArray(d.styles)\n ? (d.styles as Array<{ rules?: unknown } | null>).flatMap((sheet) =>\n Array.isArray(sheet?.rules) ? sheet.rules : [],\n )\n : []),\n ] as Array<{ rule?: unknown } | null>;\n for (const rule of rules) {\n if (rule !== null && typeof rule?.rule === \"string\") {\n rule.rule = scrubDomCss(rule.rule, strict, known);\n }\n }\n if (typeof d.replace === \"string\")\n d.replace = scrubDomCss(d.replace, strict, known);\n if (typeof d.replaceSync === \"string\")\n d.replaceSync = scrubDomCss(d.replaceSync, strict, known);\n }\n // A value typed into a field, as rrweb records it (masked but under\n // `off`): its tokens -- a key pasted into a form. Under strict, masked\n // whatever the field: rrweb records a checkbox's or a radio's value\n // in clear.\n if (ev.type === 3 && d.source === 5 && typeof d.text === \"string\") {\n d.text = strict ? d.text.replace(/\\S/g, \"*\") : scrubDomText(d.text);\n }\n // A font a script loaded through the FontFace API: rrweb's Font event\n // (9), its source a `url(...)` (or, from a buffer, its bytes).\n if (ev.type === 3 && d.source === 9 && typeof d.fontSource === \"string\") {\n d.fontSource = scrubDomCss(d.fontSource, strict, known);\n }\n if (ev.type === 3 && d.source === 13) {\n const set = d.set as { value?: unknown } | null | undefined;\n if (set !== null && typeof set?.value === \"string\") {\n set.value = scrubDomCss(set.value, strict, known);\n }\n }\n return data;\n }\n\n /**\n * True while an event decided now would pass the session gate: what the\n * network interceptor asks at an exchange's own moment (see\n * NetworkInterceptor's `admit`).\n */\n acceptsNetwork(): boolean {\n return this.sessionOpen;\n }\n\n /**\n * Emit an event to the registered callback. This is also called\n * externally by the main KeployCapture orchestrator for network\n * events.\n *\n * THE GATES ARE HERE, so every emitter faces the same two. They used\n * to sit only in rrweb's emit callback, which meant \"paused\" and\n * \"stopped\" applied to DOM events and to nothing else. `prepare`\n * rewrites `data` only once the gates let the event through: rewriting\n * one that is then dropped is work for nothing.\n *\n * `admitted`: the caller asked {@link acceptsNetwork} at the event's own\n * moment and the gate was open, so a pause() since then does not drop\n * it -- the exchange happened before the pause. The session must still\n * be live. `at`: the event's timestamp when it is not now -- a fetch's,\n * stamped when it was answered (see NetworkEventCallback). `seq`: its\n * place in the session when one was taken for it before (see\n * Transport.place), else the transport stamps it as it is queued.\n */\n emitEvent(\n type: SessionEvent[\"type\"],\n data: unknown,\n prepare?: (data: unknown) => unknown,\n admitted = false,\n at?: number,\n seq?: number,\n ): void {\n /*\n * A DROPPED DOM EVENT IS A HOLE, and this is where the recorder drops\n * one — by either gate, since pause() drops rrweb's events exactly\n * as a hidden tab does, or because its scrub failed. The transport\n * drops them too (over the cap alone, a full queue), and says so\n * through lost(). openDomGate() takes its baseline if and only if a\n * hole is recorded, so every drop must record one: a drop that is not\n * recorded is a hole nothing closes. A SHUT gate's drop is recorded\n * here (droppedWhileShut); an open gate's -- a scrub that failed, the\n * transport's -- as the hold it starts (baselineLost), which the\n * opening reads beside it.\n *\n * `phase === \"active\"` and not the wider sessionOpen, because a\n * stopped session has no baseline to take and start() clears this\n * anyway.\n */\n if (\n type === \"dom\" &&\n this.phase === \"active\" &&\n this.getState() !== \"recording\"\n ) {\n this.droppedWhileShut = true;\n }\n if (\n admitted\n ? this.phase !== \"active\" && this.phase !== \"stopping\"\n : !this.sessionOpen\n )\n return;\n // The DOM gate is the narrower one: a hidden tab holds rrweb's\n // events and nothing else. See the note on `phase` above.\n if (type === \"dom\" && this.hidden) return;\n if (!this.onEvent || !this.sessionId) return;\n this.noticeUnheardMove(type === \"dom\" ? data : null);\n\n const prepared = prepare ? prepare(data) : data;\n const rrwebType =\n type === \"dom\" && prepared !== null && typeof prepared === \"object\"\n ? (prepared as { type?: unknown }).type\n : undefined;\n // rrweb's IncrementalSnapshot is 3: what is held while no baseline is.\n if (this.baselineLost && rrwebType === 3) return;\n // Every credential value the page's URL carries leaves the browser in\n // no event of any kind: rrweb copies the page URL into absolute links\n // and CSS url()s, and the page's own requests and DOM can carry it too\n // (see pageSecrets and secretsOf). Only events through the gates are\n // read. Before that, the URLs in a DOM event are scrubbed by their\n // structure (scrubDomUrls), on what the page holds and knowing those\n // credentials by value -- never by marker text -- so each is replaced\n // once; a throw there is the same failure as one here.\n let scrubbed: unknown = prepared;\n if (typeof location !== \"undefined\") {\n try {\n if (type === \"dom\")\n scrubbed = this.scrubDomUrls(prepared, secretsOf(location.href));\n scrubbed = scrubSecrets(\n scrubbed,\n secretsOf(location.href),\n type,\n this.styles,\n MAX_BATCH_BYTES,\n );\n } catch (err) {\n // FAIL CLOSED: an event the scrub could not read is not sent with\n // whatever it carries. A dropped DOM event is a hole, so the next\n // opening of the gate re-baselines (baselineLost). One whose\n // scrub passed the body cap could never have been sent, and is\n // said (KUI_E_EVENT_OVERSIZED_SCRUBBING).\n if (type === \"dom\") {\n this.baselineLost = true;\n this.rebaseline(rrwebType === 2);\n }\n if (err instanceof ScrubOverCap)\n this.onScrubOversized?.(type, err.atLeast, err.cap);\n return;\n }\n }\n // rrweb's FullSnapshot is 2: sent, it is the baseline again. The\n // retake's backoff starts over only once one is DELIVERED (delivered()):\n // started over here, before the transport refused it, it stayed at 5 s\n // for the session (found in review #24).\n if (rrwebType === 2) {\n this.baselineLost = false;\n // The retake a pending timer was waiting to take: left pending, a\n // later dropped incremental found it and waited out its backoff -- up\n // to 60 s of held clicks -- instead of being retaken at once (found in\n // review #25).\n if (this.retakeTimer !== null) {\n clearTimeout(this.retakeTimer);\n this.retakeTimer = null;\n }\n }\n const event: SessionEvent = {\n id: uuid(),\n sessionId: this.sessionId,\n timestamp: at ?? Date.now(),\n type,\n data: scrubbed,\n seq,\n };\n\n this.onEvent(event);\n }\n}\n","/* ------------------------------------------------------------------ */\n/* Capture identity — the browser half of the offline join */\n/* ------------------------------------------------------------------ */\n/*\n * A browser capture and a keploy backend recording are joined OFFLINE, by\n * content hashes. Nothing correlates them at request time — see the long\n * rationale on models.UIJoinAnnotation in the keploy repo, which comes\n * down to two facts: models.FlakyHeaders already auto-noises every header\n * a correlation id would live in, and stamping a custom header on a\n * customer's production traffic trips CORS preflight on every\n * cross-origin call.\n *\n * So the two halves must agree on WHICH RUN they belong to without ever\n * exchanging anything during the run. That is this module: the smallest\n * set of facts content hashing cannot supply.\n *\n * captureId which capture session — the SDK's own sessionId\n * sessionNonce which RUN of that session\n * t0WallMs when the browser half started\n * appOrigins the origins the app under test was served from\n *\n * WHY A NONCE WHEN THE SESSION ID IS ALREADY A UUID. Because it is not\n * always a UUID. `CaptureConfig.sessionIdGenerator` lets an integrator\n * supply their own id, and the obvious implementation — a stable id per\n * scenario, so a run can be looked up by name — makes two runs of the\n * same script indistinguishable. Both then match one browser capture, and\n * the joiner returns edges for the wrong run with no way to tell. The\n * nonce is minted HERE and is deliberately not configurable, so the one\n * field that separates two runs cannot be made constant by a caller who\n * had a different goal in mind.\n */\n\n/** The browser half of the join, as the server side needs it. */\nexport interface CaptureIdentity {\n /** The capture session. Equal to the SDK's sessionId. */\n captureId: string;\n /** Distinguishes this RUN from another run of the same session id. */\n sessionNonce: string;\n /** Unix epoch ms at which the browser half started. */\n t0WallMs: number;\n /**\n * Origins the app under test was served from.\n *\n * MAY BE EMPTY, and an empty array is a real answer: the document had\n * no usable origin (a sandboxed iframe, a data: or file: URL). The\n * capture is still identified — see build() — it just cannot be joined\n * to backend traffic by origin. A consumer asking \"is this joinable?\"\n * asks about this array.\n */\n appOrigins: string[];\n}\n\n/**\n * Why no identity is available, when none is.\n *\n * Returned rather than thrown, and rather than substituting a weaker\n * value: a capture with no identity is still a perfectly good capture,\n * it just cannot be joined. Degrading the capture because the join is\n * unavailable would be the wrong trade.\n */\nexport type IdentityRefusal = \"no-csprng\";\n\n/**\n * Mint a session nonce.\n *\n * CSPRNG ONLY, with no Math.random fallback. The fallback would not be a\n * weaker nonce, it would be a nonce that reads as proof of same-run while\n * two concurrent runs can collide — and the resulting join is wrong in a\n * way that still returns pairs, so nothing downstream can notice. When\n * there is no CSPRNG the answer is that this capture is not joinable.\n */\nexport function mintSessionNonce(): string | null {\n const c = typeof crypto !== \"undefined\" ? crypto : undefined;\n if (!c || typeof c.getRandomValues !== \"function\") return null;\n const bytes = new Uint8Array(16);\n c.getRandomValues(bytes);\n let out = \"\";\n for (const b of bytes) out += b.toString(16).padStart(2, \"0\");\n return out;\n}\n\n/**\n * The origin of the document being captured.\n *\n * `location.origin` is absent on a few older engines and is the string\n * \"null\" for an opaque origin (a sandboxed iframe, a data: or file: URL).\n * An opaque origin cannot identify an app, so it is refused rather than\n * recorded — an appOrigins of [\"null\"] would make every exchange look\n * FOREIGN_ORIGIN, which is a silent empty join rather than a reported\n * one.\n */\nexport function currentOrigin(): string | null {\n if (typeof window === \"undefined\" || !window.location) return null;\n const origin = window.location.origin;\n if (typeof origin !== \"string\" || origin === \"\" || origin === \"null\") {\n return null;\n }\n return origin;\n}\n\n/**\n * The identity for one capture, fixed at the moment it starts.\n *\n * FIXED, NOT ACCUMULATED. An earlier version collected origins as the\n * capture proceeded, on the reasoning that a single-page app can move\n * between them. That is true and it was still wrong here, for two\n * reasons that only became visible once the wire protocol existed:\n *\n * - The transport takes a SNAPSHOT at start and sends that same value\n * on every batch, so an origin observed later was never transmitted.\n * - The server takes the first identity it sees and refuses to let a\n * later batch replace it, because the nonce is what distinguishes\n * this run from another run of the same session id.\n *\n * So the accumulation was unreachable from production — nothing outside\n * the constructor ever called it — while three tests pinned its\n * dedup-and-copy behaviour, which is a test suite describing a feature\n * the product does not have.\n *\n * The consequence is a real and stated limitation: a capture that\n * navigates across origins records only the one it started on. Widening\n * that needs the server to accept an origin set that grows without the\n * rest of the identity changing, which is a protocol decision, not a\n * line of glue.\n */\nexport class CaptureIdentityBuilder {\n private readonly captureId: string;\n private readonly nonce: string | null;\n private readonly t0WallMs: number;\n private readonly origins: string[];\n\n constructor(captureId: string, now: number = Date.now()) {\n this.captureId = captureId;\n this.nonce = mintSessionNonce();\n this.t0WallMs = now;\n const origin = currentOrigin();\n this.origins = origin === null ? [] : [origin];\n }\n\n /**\n * The identity, or the reason there is none.\n *\n * FAILS CLOSED on every incomplete case, matching Validate() on the Go\n * side: an identity missing the nonce or the origins is not a weaker\n * identity, it is one that would make the joiner confident about a\n * pairing it cannot actually establish.\n */\n /*\n * IDENTITY AND JOINABILITY ARE DIFFERENT THINGS.\n *\n * This used to refuse the whole identity when no usable document origin\n * existed — a sandboxed iframe, a data: or file: URL — so those captures\n * sent `captureIdentity: null`. The server then had no token to tell one\n * run from another, and two runs sharing a session id merged their\n * events into one file at 200 OK. The guard that was supposed to stop\n * that could only fire when BOTH runs identified themselves, so the\n * degraded case — where the data is least trustworthy — was the one that\n * slipped through.\n *\n * The origin is what makes a capture JOINABLE to backend traffic. The\n * nonce is what makes it IDENTIFIABLE, and mintSessionNonce succeeds in\n * every browser that can run rrweb. So the identity is always sent when\n * a CSPRNG exists, `appOrigins` may be empty, and \"can this be joined?\"\n * is a question about that array rather than about the identity's\n * existence.\n */\n build(): { identity: CaptureIdentity } | { refusal: IdentityRefusal } {\n if (this.nonce === null) return { refusal: \"no-csprng\" };\n return {\n identity: {\n captureId: this.captureId,\n sessionNonce: this.nonce,\n t0WallMs: this.t0WallMs,\n // A copy, so a caller cannot mutate the builder's array through\n // an identity it was handed.\n appOrigins: [...this.origins],\n },\n };\n }\n}\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - Main entry point */\n/* ------------------------------------------------------------------ */\n\nexport type {\n CaptureConfig,\n SessionEvent,\n SessionEventType,\n NetworkEvent,\n NetworkRequestType,\n SessionMetadata,\n CaptureSession,\n PrivacyConfig,\n PiiPattern,\n TransportPayload,\n EventCallback,\n NetworkEventCallback,\n} from \"./types\";\n\nexport { PrivacyEngine, defaultPrivacyConfig } from \"./privacy\";\nexport { NetworkInterceptor } from \"./network\";\nexport { Transport } from \"./transport\";\nexport {\n CaptureDeclined,\n CaptureError,\n DomRecorderRefusal,\n IngestRejection,\n PrivacyConflict,\n PrivacyRouteRefusal,\n SessionIdRefusal,\n StrictAttributesRefusal,\n SDK_ERRORS,\n SDK_WARNINGS,\n codeForStatus,\n describeValue,\n parseServerError,\n} from \"./errors\";\nexport type {\n AnyCaptureError,\n CaptureDeclinedEvidence,\n CaptureErrorCode,\n CaptureWarningCode,\n CaptureWarningEvidence,\n CaptureEvidence,\n CaptureRemedy,\n DomRecorderEvidence,\n PrivacyRouteEvidence,\n IngestEvidence,\n ServerAnsweredCode,\n ServerError,\n PrivacyConflictEvidence,\n PrivacySignal,\n ServerIssue,\n SessionIdEvidence,\n} from \"./errors\";\nexport {\n SESSION_ID_MAX_LENGTH,\n SESSION_ID_PATTERN,\n SESSION_ID_RULE,\n isValidSessionId,\n} from \"./session-id\";\nexport type { TransportConfig } from \"./transport\";\nexport { KeployCaptureRecorder } from \"./recorder\";\nexport type {\n RecorderState,\n OnEventCallback,\n OnSessionEndCallback,\n} from \"./recorder\";\nexport {\n CaptureIdentityBuilder,\n mintSessionNonce,\n currentOrigin,\n} from \"./identity\";\nexport type { CaptureIdentity, IdentityRefusal } from \"./identity\";\n\nimport type { CaptureConfig, SessionEvent, NetworkEvent } from \"./types\";\nimport { KeployCaptureRecorder, collectPageSecrets } from \"./recorder\";\nimport { releaseWorker } from \"./body-jobs\";\nimport { watchLeave } from \"./leave\";\nimport { NetworkInterceptor } from \"./network\";\nimport { Transport, type TransportConfig } from \"./transport\";\nimport {\n CaptureDeclined,\n DomRecorderRefusal,\n PrivacyConflict,\n PrivacyRouteRefusal,\n SessionIdRefusal,\n StrictAttributesRefusal,\n type AnyCaptureError,\n type PrivacySignal,\n} from \"./errors\";\nimport {\n CaptureIdentityBuilder,\n type CaptureIdentity,\n type IdentityRefusal,\n} from \"./identity\";\n\n/* ------------------------------------------------------------------ */\n/* KeployCapture — the single public API */\n/* ------------------------------------------------------------------ */\n\n/** The longest stop() waits for the final flush of a session that ended earlier. */\nconst ENDED_FLUSH_WAIT_MS = 10_000;\n\n/** A decline's console line has been written on this page: see decline(). */\nlet declineLogged = false;\n\n/**\n * The privacy signal the browser sends, or null: Global Privacy Control\n * first (it is the one with legal force in several jurisdictions), then\n * Do Not Track. Read defensively: a missing navigator, or a property\n * that throws, is no signal.\n */\nfunction privacySignal(): PrivacySignal | null {\n try {\n if (typeof navigator === \"undefined\") return null;\n const nav = navigator as Navigator & {\n globalPrivacyControl?: unknown;\n msDoNotTrack?: unknown;\n };\n if (nav.globalPrivacyControl === true) return \"globalPrivacyControl\";\n // Do Not Track as browsers have spelled it: \"1\"; \"yes\" (Firefox before\n // 32); on `window` (Safari, IE 11); `msDoNotTrack` (IE 10).\n if (nav.doNotTrack === \"1\" || nav.doNotTrack === \"yes\") return \"doNotTrack\";\n if (\n typeof window !== \"undefined\" &&\n (window as Window & { doNotTrack?: unknown }).doNotTrack === \"1\"\n )\n return \"doNotTrack\";\n if (nav.msDoNotTrack === \"1\") return \"doNotTrack\";\n } catch {\n // An unreadable navigator says nothing.\n }\n return null;\n}\n\nexport class KeployCapture {\n private static instance: KeployCapture | null = null;\n\n private recorder: KeployCaptureRecorder;\n private network: NetworkInterceptor;\n private transport: Transport;\n private config: CaptureConfig;\n private started = false;\n private identity: CaptureIdentityBuilder | null = null;\n\n private constructor(config: CaptureConfig) {\n this.config = config;\n\n this.recorder = new KeployCaptureRecorder(config);\n\n // The ingest endpoint is excluded from interception: the transport\n // posts through the global fetch the interceptor patches, and every\n // batch became a network event that was queued, posted, captured\n // again... MEASURED: one application request, 13 ingest POSTs in\n // 1.2 s at a 100 ms batch interval, each carrying the previous one.\n this.network = new NetworkInterceptor(\n config.privacy ?? {},\n config.maxBodySize ?? 524_288,\n [config.endpoint],\n config.privacyMode,\n );\n\n // endsSessionOnly: in a continuous capture of session ids the SDK\n // mints, a refusal the server says ends only THIS session -- it has\n // completed it (it idled past the server's window: a laptop asleep), or\n // the session is at its size limit -- is followed by a new session at\n // the visitor's next interaction (endSession). Decided on the server's\n // `reason`, never on the status: its 409 also means a batchId reused\n // with different events, an SDK defect that must surface (found in\n // review), and a server without the field stays terminal. A terminal\n // rejection ends the CAPTURE (onCaptureEnd), through the same path the\n // recorder's onSessionEnd takes -- see endCapture() -- except a refusal\n // that ends only this session (onSessionEnd).\n const transportConfig: TransportConfig = {\n endpoint: config.endpoint,\n apiKey: config.apiKey,\n batchSize: config.batchSize ?? 50,\n batchInterval: config.batchInterval ?? 5_000,\n maxQueueSize: config.maxQueueSize ?? 5_000,\n ...(config.onError !== undefined ? { onError: config.onError } : {}),\n onCaptureEnd: () => this.endCapture(),\n endsSessionOnly: (code, reason) =>\n config.continuous === true &&\n config.sessionIdGenerator === undefined &&\n ((code === \"KUI_E_SESSION_CONFLICT\" &&\n reason === \"session_completed\") ||\n (code === \"KUI_E_INGEST_REJECTED\" && reason === \"session_full\")),\n onSessionEnd: () => this.endSession(),\n // A DOM event the transport dropped is a hole the recorder must\n // hold rrweb's incrementals over (recorder.lost).\n onDropped: (events, rebaselined) =>\n this.recorder.lost(events, rebaselined),\n // A snapshot delivered starts the retake's backoff over.\n onDelivered: (events) => this.recorder.delivered(events),\n // Uploads failing, or a drop offline: no snapshot until the outage ends (recorder.failing).\n onFailing: (on) => this.recorder.failing(on),\n // The exchanges still reading a body go into the last batch, cut\n // where the page left. See NetworkInterceptor.cutInflight().\n beforeUnloadFlush: () => this.network.cutInflight(),\n // The bodies still being redacted that fit the main thread's budget\n // go into the drain a hidden tab makes; the rest stay with the\n // worker. See NetworkInterceptor.reportDue().\n beforeHiddenFlush: () => this.network.reportDue(),\n // And, as far as they fit the main thread's budget and the body code\n // loaded before the outage, into the upload that ends it (the rest\n // follow when the code and the worker load and answer).\n beforeOnlineFlush: () => this.network.reportDue(),\n };\n this.transport = new Transport(transportConfig);\n }\n\n /* -------------------------------------------------------------- */\n /* Static API */\n /* -------------------------------------------------------------- */\n\n /**\n * Initialise and start capturing. This is the **only** call users need.\n *\n * ```ts\n * import { KeployCapture } from '@keploy/capture-sdk';\n * KeployCapture.init({ endpoint: '…', apiKey: '…' });\n * ```\n */\n static async init(config: CaptureConfig): Promise<KeployCapture> {\n if (KeployCapture.instance) {\n return KeployCapture.instance;\n }\n // An explicit init() supersedes a continuous capture's wait for its\n // next session -- one capture per page -- and keeps a pause that wait\n // carried: a component that remounts and calls init() on a paused\n // payment page must not start recording it (found in review). Only\n // resume() and stop() end a pause.\n const paused = KeployCapture.nextSessionPaused;\n KeployCapture.cancelNextSession();\n KeployCapture.nextSessionPaused = false;\n return KeployCapture.begin(config, paused);\n }\n\n private static async begin(\n config: CaptureConfig,\n paused: boolean,\n byInput = false,\n ): Promise<KeployCapture> {\n const capture = new KeployCapture(config);\n KeployCapture.instance = capture;\n try {\n await capture.start(paused, byInput);\n } catch (err) {\n /*\n * A THROW OUT OF start() MUST NOT LEAVE THE SINGLETON SET. The\n * instance is registered before start() so a concurrent init()\n * gets the same capture, and until this catch existed anything\n * start() threw -- rrweb failing to import, say -- rejected\n * init() with the singleton still pointing at a capture that\n * never started: a later, corrected init() returned it, recorded\n * nothing and said nothing. MEASURED with a throwing\n * sessionIdGenerator before the recorder caught that case itself.\n * The error still propagates; what changes is that the next\n * init() starts fresh.\n */\n if (KeployCapture.instance === capture) KeployCapture.instance = null;\n throw err;\n }\n return capture;\n }\n\n /**\n * Stop all recording and flush remaining events.\n *\n * Resolves once the final flush has settled; awaiting it is optional.\n */\n static stop(): Promise<void> {\n KeployCapture.cancelNextSession();\n KeployCapture.nextSessionPaused = false;\n const instance = KeployCapture.instance;\n KeployCapture.instance = null;\n // And the final flush of a capture that ended on its own -- a session\n // timer, a terminal refusal -- which nothing awaited: \"resolves once the\n // final flush has settled\" held only for the live capture, so a stop()\n // after a continuous session ended could resolve with that session's\n // batch still in flight (MEASURED: a late flush landed in the next test\n // of capture-continuous.test.ts under load). Every such flush, and for\n // at most ENDED_FLUSH_WAIT_MS: the transport sets no deadline on a\n // request, and an earlier session's stalled one must not hang this\n // stop() for good (found in review).\n const ended = Promise.all(KeployCapture.ending);\n const bounded = new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, ENDED_FLUSH_WAIT_MS);\n void ended.then(() => {\n clearTimeout(timer);\n resolve();\n });\n });\n // The leave a next session kept watched (stop() below) is watched no\n // more once that wait is over, nothing being live: a stalled final\n // flush, which has no deadline, does not keep it. Nor the worker kept\n // for that session's leave (body-jobs.ts).\n if (!instance)\n void bounded.then(() => {\n if (!KeployCapture.instance && !KeployCapture.restartPending) {\n watchLeave(false);\n releaseWorker();\n }\n });\n return Promise.all([instance ? instance.stop() : undefined, bounded]).then(\n () => undefined,\n );\n }\n\n /**\n * Pause recording: nothing more is recorded until {@link resume}. No\n * DOM event, and no network exchange that starts or is answered while\n * paused; an exchange still reading its body is recorded at once with\n * what had arrived, cut and marked, and nothing of it after, resume()\n * included. The tab going hidden and visible in between does not end\n * the pause.\n */\n static pause(): void {\n KeployCapture.instance?.pause();\n // Between a continuous capture's sessions there is no instance; the\n // pause is kept for the next one (see endSession). With no session\n // waiting either, there is nothing to pause, as before.\n if (KeployCapture.instance === null && KeployCapture.restartPending) {\n KeployCapture.nextSessionPaused = true;\n }\n }\n\n /** Resume recording after {@link pause}. A hidden tab stays paused until it is visible. */\n static resume(): void {\n KeployCapture.instance?.resume();\n KeployCapture.nextSessionPaused = false;\n }\n\n /** Current session ID (empty string if not recording). */\n static getSessionId(): string {\n return KeployCapture.instance?.recorder.getSessionId() ?? \"\";\n }\n\n /** Get the singleton instance (null if not initialised). */\n static getInstance(): KeployCapture | null {\n return KeployCapture.instance;\n }\n\n /**\n * The browser half of the offline backend join, exactly as it was\n * SENT — or the reason there isn't one, or null before a capture has\n * started.\n *\n * Rebuilding here is safe because the builder is IMMUTABLE: everything\n * it holds is assigned once in its constructor, so this returns the\n * same value start() handed the transport. An earlier version of the\n * builder accumulated origins, which would have made these two diverge\n * — and this method's docstring also claimed it could be consulted\n * \"BEFORE the run\", which was never true, since nothing is minted\n * until start().\n *\n * Three distinguishable answers, deliberately: `null` is \"no capture\n * has started\", `{refusal}` is \"this capture cannot be joined and here\n * is why\", `{identity}` is the value the server received.\n */\n static getCaptureIdentity():\n { identity: CaptureIdentity } | { refusal: IdentityRefusal } | null {\n const builder = KeployCapture.instance?.identity;\n return builder ? builder.build() : null;\n }\n\n /* -------------------------------------------------------------- */\n /* Instance methods */\n /* -------------------------------------------------------------- */\n\n private async start(paused: boolean, byInput = false): Promise<void> {\n if (this.started) return;\n this.started = true;\n\n // Strict records no body; an explicit maskNetworkBodies: false asks for\n // them. Refused rather than resolved either way (KUI_E_PRIVACY_CONFLICT),\n // and checked first: the conflict is in the site's code, the same for\n // every visitor, so a privacy signal from this one must not hide it\n // from an integrator testing in a browser that sends GPC.\n if (\n this.config.privacyMode === \"strict\" &&\n this.config.privacy?.maskNetworkBodies === false\n ) {\n this.refuse(new PrivacyConflict());\n return;\n }\n\n // The person using the page said no: nothing is recorded, patched or\n // sent, and the capture never starts. Checked before the recorder\n // imports rrweb or reads the page. See honorPrivacySignals.\n const signal =\n this.config.honorPrivacySignals !== false ? privacySignal() : null;\n if (signal !== null) {\n this.decline(new CaptureDeclined(signal));\n return;\n }\n\n /*\n * HELD UNTIL THE TRANSPORT HAS STARTED. rrweb emits the Meta event\n * and the FullSnapshot synchronously inside recorder.start(), and\n * the transport cannot start before that call returns — it needs\n * the session id and metadata the recorder mints. enqueue() on a\n * transport that has not started drops the event, so every session\n * used to begin without the snapshot its selectors resolve against.\n */\n let held: SessionEvent[] | null = [];\n const handleEvent = (event: SessionEvent): void => {\n if (held) held.push(event);\n else this.transport.enqueue(event);\n };\n\n // Start rrweb recording. The recorder ends the session itself at\n // maxSessionDuration, and that has to end the capture: network\n // interception and the transport's timer used to outlive it.\n let sessionId: string;\n try {\n // A session that ends on its own is followed by the next in a\n // continuous capture -- of ids the SDK mints. A sessionIdGenerator's\n // id is the integrator's, often stable for the visit, and the next\n // session would claim it a second time: the server refuses that run\n // (409 capture_identity_conflict) and an onError lands at the\n // visitor's first click (found in review). So with one, the capture\n // ends here as it always did.\n // THE PAGE'S LEAVE IS WATCHED FROM HERE (leave.ts), before rrweb's\n // import, which goes through the same gate: a capture starting is the\n // page's script alive and starting one, so a leave the page did not\n // make is over -- unless the visitor's input started it (a\n // continuous capture's next session, endSession): the old page gets\n // clicks and keys while a real navigation loads, so that start\n // attaches the watch and proves nothing. Unwatched again below if\n // this capture does not go live, and at the last capture's stop.\n watchLeave(true, !byInput);\n const opening = this.recorder.start(\n handleEvent,\n () =>\n this.config.continuous === true &&\n this.config.sessionIdGenerator === undefined\n ? this.endSession()\n : this.endCapture(),\n paused,\n (type, atLeast, cap) =>\n this.transport.reportScrubOversized(type, atLeast, cap),\n // rrweb's import once the network is back: landed, the transport\n // sends what it held; still failing, refused as at start, and\n // what was held is dropped by the transport's stop().\n (err) => {\n if (err === null) this.transport.release();\n else this.refuse(err);\n },\n (method) => this.transport.reportNavigationUnwrapped(method),\n );\n // THE BODY CODE AS SOON AS THE CAPTURE STARTS (body-jobs.ts,\n // askForCode): asked for here, in init()'s own task beside rrweb's\n // import, once the recorder has opened the session -- sampled in, its\n // id valid. Never waited for: the page's network is recorded from the\n // start, and a body the page leaves on before it arrives is recorded\n // as not captured, never in the clear.\n if (\n this.config.networkCapture !== false &&\n this.recorder.getSessionId() !== null\n )\n this.network.askForCode();\n sessionId = await opening;\n } catch (err) {\n if (!(\n err instanceof SessionIdRefusal ||\n err instanceof DomRecorderRefusal ||\n err instanceof StrictAttributesRefusal ||\n err instanceof PrivacyRouteRefusal\n )) {\n throw err;\n }\n this.refuse(err);\n return;\n }\n if (!sessionId) {\n // Sampled out — or stop() was called while recorder.start() was\n // awaiting rrweb's import, in which case this capture has already\n // been released and must not start a transport or patch fetch:\n // its later teardown would restore fetch underneath whatever\n // capture is live by then.\n this.started = false;\n if ((KeployCapture.instance ?? this) === this) watchLeave(false);\n return;\n }\n\n const metadata = this.recorder.getMetadata()!;\n\n // THE CAPTURE ID IS THE SESSION ID. The annotation, the SDK and the\n // joiner previously used three names for two ideas; this is the one\n // place that says they are the same thing.\n this.identity = new CaptureIdentityBuilder(sessionId);\n const built = this.identity.build();\n\n // Start transport. A capture with no identity is still a capture —\n // it just cannot be joined to a backend recording, so the field is\n // null rather than the capture being refused.\n // HELD while rrweb's import waits for the network: if it then fails,\n // the capture is refused, and the page's offline calls must not have\n // gone out as a session with no DOM. MEASURED: the transport's own\n // `online` handler sent them before the import had failed (round 27).\n if (this.recorder.awaitingRRWeb()) this.transport.hold();\n this.transport.start(\n sessionId,\n metadata,\n \"identity\" in built ? built.identity : null,\n );\n const first = held;\n held = null;\n for (const event of first) this.transport.enqueue(event);\n\n // Start network interception (unless disabled).\n if (this.config.networkCapture !== false) {\n // Admitted when the exchange's request leaves and when it is\n // answered, so the pause gate applies to the exchange and not to when\n // its body happened to be read.\n this.network.start(\n (netEvent: NetworkEvent, at?: number, seq?: number) => {\n this.recorder.emitEvent(\n \"network\",\n netEvent,\n undefined,\n true,\n at,\n seq,\n );\n },\n () => this.recorder.acceptsNetwork(),\n // The exchange's place, taken when it is reported: its masking\n // and serialisation wait for a task after the page's.\n () => this.transport.place(),\n );\n }\n }\n\n private stop(): Promise<void> {\n // Nothing new is recorded from here: no DOM, no new exchange. An\n // exchange already on the wire is still reading its body for the\n // recording (the page got its Response at the headers), so it gets\n // up to a second to report before the session closes -- an exchange\n // that finished before stop() used to be recorded, and still is.\n //\n // A stop() during a pending init() is safe whenever the recorder\n // closes: stopDom() moves the recorder to its stopping phase, which\n // every DOM gate reads as ended, so the start() still awaiting its\n // rrweb import resumes into nothing. The close used to be synchronous\n // when nothing was in flight, for that case alone; the stopping phase\n // makes it unnecessary, and settle() with nothing in flight resolves\n // at once.\n // What the interceptor reported and has not yet recorded is recorded\n // now, before the session closes, as far as it fits the main thread's\n // budget (NetworkInterceptor.reportDue()): left to settle(), an exchange\n // whose task does not run (a page that never goes idle) holds the last\n // flush until the bound. The rest comes back from the worker within\n // settle()'s bound, or is recorded cut at it.\n this.network.reportDue();\n this.recorder.stopDom();\n this.network.stop();\n this.started = false;\n return this.network.settle(1_000).then(() => {\n // Every body of this capture is recorded: its worker can go, and,\n // with no capture live, the body chunk's wait for the network. The\n // leave stays watched while a next session waits for the visitor's\n // input (endSession): a leave begun between sessions is then seen,\n // and a load it holds is not asked for at the input that starts one.\n // A worker running as the page leaves is kept for that next session\n // (body-jobs.ts): it could not start again until the leave ends.\n const last = KeployCapture.instance === null;\n const wanted = (): boolean =>\n KeployCapture.instance !== null || KeployCapture.restartPending;\n releaseWorker(last, wanted);\n if (last && !KeployCapture.restartPending) watchLeave(false);\n this.recorder.stop();\n return this.transport.stop();\n });\n }\n\n /**\n * The capture was declined by a privacy signal: the capture ended,\n * then onError -- on EVERY declined init(), so each handler learns its\n * capture did not start (a silent init() looks like success) -- and\n * the console line ONCE PER PAGE, since the signal does not change and\n * a page that re-inits (React StrictMode's double effect, a re-init per\n * route) would otherwise repeat it. Logged as information: nothing\n * failed.\n */\n private decline(declined: CaptureDeclined): void {\n if (!declineLogged) console.info(declined.message);\n declineLogged = true;\n this.endCapture();\n try {\n this.config.onError?.(declined);\n } catch {\n // An integrator's handler must not be able to stop the capture ending.\n }\n }\n\n private refuse(err: AnyCaptureError): void {\n /*\n * The capture refused to start: the configured sessionIdGenerator\n * did not produce a session id -- a string outside the server's\n * rule, a non-string, or a throw (KUI_E_SESSION_ID_INVALID); a\n * declared privacy route is no route (KUI_E_PRIVACY_ROUTE_INVALID);\n * two privacy options contradict each other (KUI_E_PRIVACY_CONFLICT); or,\n * in a browser, rrweb could not be imported\n * (KUI_E_DOM_RECORDER_UNAVAILABLE), or under strict its attribute\n * allow-list (KUI_E_STRICT_ATTRIBUTES_UNAVAILABLE). Nothing\n * has been sent and nothing is patched, but the singleton is set, so\n * this takes the path a server rejection takes and in the same order\n * -- the console line, the capture ended and the singleton released,\n * THEN onError -- so a handler that fixes the generator and calls\n * init() again gets a fresh capture, not this dead one.\n */\n console.error(err.message);\n this.endCapture();\n try {\n this.config.onError?.(err);\n } catch {\n // An integrator's handler must not be able to suppress the log.\n }\n }\n\n private endCapture(): void {\n /*\n * A subsystem ended this capture on its own. ONE path, two callers:\n *\n * - the recorder, when `maxSessionDuration` elapses;\n * - the transport, when the server answers a batch with a terminal\n * 4xx — a revoked key, a key for another app, or a second run\n * claiming a live session id. That one used to stop the transport\n * alone, so rrweb kept recording, fetch and XHR stayed patched and\n * the session timer stayed armed for a capture that could never\n * post another byte.\n *\n * The singleton is released either way, so a later init() starts a\n * NEW session rather than handing back a finished or dead one — which\n * is the whole recovery path after a key is rotated.\n */\n // Kept for stop() to wait on until it settles; its failure is this\n // flush's own.\n const flush: Promise<unknown> = this.stop()\n .catch(() => undefined)\n .finally(() => KeployCapture.ending.delete(flush));\n KeployCapture.ending.add(flush);\n if (KeployCapture.instance === this) KeployCapture.instance = null;\n }\n\n /** Cancels a continuous capture's wait for the visitor's next interaction. */\n private static cancelNextSession: () => void = () => {};\n\n private static nextSessionPaused = false;\n private static ending = new Set<Promise<unknown>>();\n private static restartPending = false;\n\n private endSession(): void {\n /*\n * A continuous capture's session has ended (see CaptureConfig.continuous):\n * end it like a capture, then start the next session at the visitor's\n * next click, tap or key press.\n *\n * At an interaction, not at once: a tab left open records nothing until\n * someone uses it, where an immediate restart would post a full DOM\n * snapshot every maxSessionDuration for a page nobody is looking at.\n * Captured on `document` before the page's own handlers, so the new\n * session is recording before the click it was started by is dispatched:\n * init() reaches rrweb's record() through promises already settled.\n * `sampleRate: 1` because this visitor was already sampled in -- a\n * re-roll per session would drop the rest of a visit at random.\n */\n // Only the LIVE capture schedules a next session. stop() releases the\n // singleton before its final flush, and a 409 on that flush lands\n // here: restarting then turned the integrator's stop() into \"until the\n // next click\" (found in review).\n const live = KeployCapture.instance === this;\n // The integrator's pause() carries over: a session ending on its timer\n // must not undo a consent or payment-page pause (found in review).\n const paused = this.recorder.isUserPaused();\n this.endCapture();\n if (!live || typeof document === \"undefined\") return;\n KeployCapture.cancelNextSession();\n KeployCapture.nextSessionPaused = paused;\n const next: CaptureConfig = { ...this.config, sampleRate: 1 };\n const start = (): void => {\n const startPaused = KeployCapture.nextSessionPaused;\n KeployCapture.cancelNextSession();\n KeployCapture.nextSessionPaused = false;\n if (KeployCapture.instance !== null) return;\n KeployCapture.begin(next, startPaused, true).catch((err: unknown) => {\n // Not the page's unhandled rejection: say what failed, here. A\n // warning: the page goes on, and only a capture's end is an error.\n console.warn(\n \"[keploy] the capture's next session could not start:\",\n err,\n );\n });\n };\n const options = { capture: true, passive: true } as const;\n document.addEventListener(\"pointerdown\", start, options);\n document.addEventListener(\"keydown\", start, options);\n // The page's URL credentials are still the page's while no session is\n // open: a back-navigation to a reset link starts none.\n const stopCollecting = collectPageSecrets();\n KeployCapture.restartPending = true;\n KeployCapture.cancelNextSession = () => {\n stopCollecting();\n document.removeEventListener(\"pointerdown\", start, options);\n document.removeEventListener(\"keydown\", start, options);\n KeployCapture.restartPending = false;\n KeployCapture.cancelNextSession = () => {};\n };\n }\n\n /*\n * pause()/resume() shut and open the recorder's gate, which every\n * emitter honours; the network interceptor stays installed for the\n * life of the capture rather than being unpatched and re-patched\n * around each pause. A pause means nothing more is recorded, so an\n * exchange still reading its body is cut at pause() as a page that\n * leaves cuts it (NetworkInterceptor.cutInflight()): what had arrived,\n * marked, and nothing after. Its event is emitted after the gate shut\n * -- the exchange is admitted, it happened before the pause -- and an\n * exchange is reported once, so resume() never reattaches to it.\n */\n private pause(): void {\n this.recorder.pause();\n this.network.cutBodies();\n }\n\n private resume(): void {\n this.recorder.resume();\n }\n}\n"]}
|