@buoy-gg/network 7.0.73 → 7.0.75

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.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.canSynthesizeResponse=canSynthesizeResponse;exports.sleep=void 0;exports.synthesizeFetchError=synthesizeFetchError;exports.synthesizeResponse=synthesizeResponse;const sleep=e=>e>0?new Promise(s=>setTimeout(s,e)):Promise.resolve();exports.sleep=sleep;function canSynthesizeResponse(){return typeof Response==="function"}function synthesizeResponse(e,s){const t=new Response(s.body,{status:s.status,statusText:s.statusText,headers:s.headers});try{Object.defineProperty(t,"url",{value:e,configurable:true})}catch{}return t}function synthesizeFetchError(e){return new TypeError(e.failKind==="timeout"?"Network request timed out":"Network request failed")}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NULL_BODY_STATUSES=void 0;exports.canSynthesizeResponse=canSynthesizeResponse;exports.sleep=void 0;exports.synthesizeFetchError=synthesizeFetchError;exports.synthesizeResponse=synthesizeResponse;const NULL_BODY_STATUSES=exports.NULL_BODY_STATUSES=[204,205,304];const sleep=s=>s>0?new Promise(e=>setTimeout(e,s)):Promise.resolve();exports.sleep=sleep;function canSynthesizeResponse(){return typeof Response==="function"}function synthesizeResponse(s,e){const r=NULL_BODY_STATUSES.includes(e.status)?null:e.body;const t=new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers});try{Object.defineProperty(t,"url",{value:s,configurable:true})}catch{}return t}function synthesizeFetchError(s){return new TypeError(s.failKind==="timeout"?"Network request timed out":"Network request failed")}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.OVERRIDES_INACTIVE_REASON=void 0;exports.inspectEngine=inspectEngine;exports.overrideForRequest=overrideForRequest;exports.overridesCanApply=overridesCanApply;exports.setOverrideHooks=setOverrideHooks;var _sharedUi=require("@buoy-gg/shared-ui");var _resolveOverride=require("./resolveOverride");let hooks=null;function setOverrideHooks(e){hooks=e}function overridesCanApply(){return(0,_sharedUi.hasAccountAccess)()&&!(typeof __DEV__!=="undefined"&&!__DEV__)}const OVERRIDES_INACTIVE_REASON=exports.OVERRIDES_INACTIVE_REASON="Response overrides never apply in a release build \u2014 the rule is saved but will not affect any request.";function inspectEngine(e,n){return{hooksInstalled:hooks!==null,devFlag:typeof __DEV__==="undefined"?"undefined":__DEV__,ruleCount:hooks?hooks.getRules().length:0,matches:hooks?(0,_resolveOverride.findMatchingRule)(e,n,hooks.getRules())!==null:false}}function overrideForRequest(e,n,s){if(!hooks)return null;if(!overridesCanApply())return null;const t=hooks.getRules();if(t.length===0)return null;const r=(0,_resolveOverride.findMatchingRule)(e,n,t,s);if(!r)return null;const u=(0,_resolveOverride.shouldApply)(r);hooks.recordMatch(r.id);if(!u)return null;hooks.recordHit(r.id);return(0,_resolveOverride.toOutcome)(r)}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.OVERRIDES_INACTIVE_REASON=void 0;exports.accountCheckFor=accountCheckFor;exports.inspectEngine=inspectEngine;exports.overrideForRequest=overrideForRequest;exports.overridesCanApply=overridesCanApply;exports.setOverrideHooks=setOverrideHooks;var _sharedUi=require("@buoy-gg/shared-ui");var _resolveOverride=require("./resolveOverride");var _realNow=require("../utils/realNow");let hooks=null;function setOverrideHooks(r){hooks=r}function overridesCanApply(){return(0,_sharedUi.hasAccountAccess)()&&!(typeof __DEV__!=="undefined"&&!__DEV__)}const OVERRIDES_INACTIVE_REASON=exports.OVERRIDES_INACTIVE_REASON="Response overrides never apply in a release build \u2014 the rule is saved but will not affect any request.";function inspectEngine(r,t){return{hooksInstalled:hooks!==null,devFlag:typeof __DEV__==="undefined"?"undefined":__DEV__,ruleCount:hooks?hooks.getRules().length:0,matches:hooks?(0,_resolveOverride.findMatchingRule)(r,t,hooks.getRules())!==null:false}}const ACCOUNT_WAIT_MS=3e3;function accountCheckFor(r,t,s,i){if(!hooks||(0,_sharedUi.hasAccountAccess)())return null;if(typeof __DEV__!=="undefined"&&!__DEV__)return null;if((0,_sharedUi.getAccountAccess)().status!=="initializing")return null;if(!(0,_resolveOverride.findMatchingRule)(r,t,hooks.getRules(),s,i))return null;return new Promise(n=>{let e=()=>{};const u=()=>{(0,_realNow.realClearTimeout)(o);e();n()};const o=(0,_realNow.realSetTimeout)(u,ACCOUNT_WAIT_MS);e=(0,_sharedUi.subscribeAccountAccess)(()=>{if((0,_sharedUi.getAccountAccess)().status!=="initializing")u()})})}function overrideForRequest(r,t,s,i){if(!hooks)return null;if(!overridesCanApply())return null;const n=hooks.getRules();if(n.length===0)return null;const e=(0,_resolveOverride.findMatchingRule)(r,t,n,s,i);if(!e)return null;const u=(0,_resolveOverride.shouldApply)(e);hooks.recordMatch(e.id);if(!u)return null;hooks.recordHit(e.id);return(0,_resolveOverride.toOutcome)(e)}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.compilePattern=compilePattern;exports.escapeRegex=escapeRegex;exports.ruleMatches=ruleMatches;const SPECIAL_CHARACTERS="[]{}()\\.^$+|-,?";function escapeRegex(e){let r="";for(let s=0;s<e.length;s++){const t=e.charAt(s);if(SPECIAL_CHARACTERS.indexOf(t)!==-1){r+="\\"}r+=t}return r.split("*").join(".*")}const compiled=new Map;function compilePattern(e){const r=compiled.get(e);if(r)return r;const s=e.startsWith("/")?`[a-zA-Z][a-zA-Z0-9+.-]*://[^/]*${escapeRegex(e)}`:escapeRegex(e);const t=new RegExp(`^${s}$`);if(compiled.size>200)compiled.clear();compiled.set(e,t);return t}function hasHeader(e,r){if(!e)return false;const s=r.toLowerCase();for(const t of Object.keys(e)){if(t.toLowerCase()===s&&e[t]!==void 0&&e[t]!=="")return true}return false}function ruleMatches(e,r,s,t){if(e.methods&&e.methods.length>0){if(!e.methods.includes(s.toUpperCase()))return false}if(e.requireHeader&&!hasHeader(t,e.requireHeader))return false;try{return compilePattern(e.urlPattern).test(r)}catch{return false}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.compilePattern=compilePattern;exports.escapeRegex=escapeRegex;exports.ruleMatches=ruleMatches;const SPECIAL_CHARACTERS="[]{}()\\.^$+|-,?";function escapeRegex(e){let r="";for(let s=0;s<e.length;s++){const t=e.charAt(s);if(SPECIAL_CHARACTERS.indexOf(t)!==-1){r+="\\"}r+=t}return r.split("*").join(".*")}const compiled=new Map;function compilePattern(e){const r=compiled.get(e);if(r)return r;const s=e.startsWith("/")?`[a-zA-Z][a-zA-Z0-9+.-]*://[^/]*${escapeRegex(e)}`:escapeRegex(e);const t=new RegExp(`^${s}$`);if(compiled.size>200)compiled.clear();compiled.set(e,t);return t}function hasHeader(e,r){if(!e)return false;const s=r.toLowerCase();for(const t of Object.keys(e)){if(t.toLowerCase()===s&&e[t]!==void 0&&e[t]!=="")return true}return false}function ruleMatches(e,r,s,t,n){if(e.methods&&e.methods.length>0){if(!e.methods.includes(s.toUpperCase()))return false}if(e.requireHeader&&!hasHeader(t,e.requireHeader))return false;if(e.bodyIncludes&&(typeof n!=="string"||!n.includes(e.bodyIncludes)))return false;try{return compilePattern(e.urlPattern).test(r)}catch{return false}}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.overrideRulesStore=void 0;var _sharedUi=require("@buoy-gg/shared-ui");var _networkListener=require("../utils/networkListener");var _engine=require("./engine");var _resolveOverride=require("./resolveOverride");var _types=require("./types");var _realNow=require("../utils/realNow");const REMOTE_ECHO_GRACE_MS=800;const MAX_UNTOUCHED_LAUNCHES=3;const EMPTY_RULES=Object.freeze([]);const HIT_EMIT_COALESCE_MS=250;const VALID_KINDS=["respond","fail","delay"];function parseRules(n){if(!Array.isArray(n))return[];const t=[];for(const i of n){if(!i||typeof i!=="object")continue;const e=i;if(typeof e.id!=="string"||typeof e.urlPattern!=="string"){continue}if(!e.urlPattern)continue;const s=VALID_KINDS.includes(e.kind)?e.kind:"respond";t.push({id:e.id,enabled:e.enabled!==false,name:typeof e.name==="string"?e.name:void 0,urlPattern:e.urlPattern,methods:Array.isArray(e.methods)?e.methods.filter(r=>typeof r==="string"):void 0,requireHeader:typeof e.requireHeader==="string"&&e.requireHeader?e.requireHeader:void 0,kind:s,status:typeof e.status==="number"?Math.min(_types.STATUS_MAX,Math.max(_types.STATUS_MIN,e.status)):void 0,statusText:typeof e.statusText==="string"?e.statusText:void 0,headers:e.headers&&typeof e.headers==="object"?e.headers:void 0,body:typeof e.body==="string"?e.body:void 0,failKind:e.failKind==="timeout"?"timeout":void 0,delayMs:typeof e.delayMs==="number"?e.delayMs:void 0,times:typeof e.times==="number"?e.times:null,alternate:e.alternate===true,hits:0,seen:0,createdAt:typeof e.createdAt==="number"?e.createdAt:0})}return t.slice(0,_types.MAX_RULES)}class OverrideRulesStore{rules=[];enabled=true;listeners=new Set;loaded=false;loadPromise=null;dirty=false;idCounter=0;state={enabled:true,rules:[],autoPaused:false};launchStreak=0;autoPaused=false;keepAlive=null;hitEmitTimer=null;engineDisabled=false;remote=null;remoteEchoUntil=0;enableRemoteMode(t){this.remote=t;this.disableEngine()}disableRemoteMode(){this.remote=null}replaceRules(t,i=false){if(!this.remote)return;if(!i&&(0,_realNow.realNow)()<this.remoteEchoUntil)return;this.enabled=t.enabled;this.rules=t.rules;this.rebuild();this.emit()}markLocalEdit(){if(this.remote)this.remoteEchoUntil=(0,_realNow.realNow)()+REMOTE_ECHO_GRACE_MS}disableEngine(){this.engineDisabled=true;if(this.keepAlive){this.keepAlive();this.keepAlive=null;if((0,_networkListener.getNetworkListenerCount)()===0)(0,_networkListener.stopNetworkListener)()}}getState(){return this.state}getRules(){if(this.engineDisabled||!this.enabled)return EMPTY_RULES;return this.rules}async fetchRuleBody(t){const i=this.rules.find(e=>e.id===t);if(!i)return null;if(!i.bodyOmitted)return i.body??null;if(!this.remote?.getRuleBody)return null;try{return await this.remote.getRuleBody(t)}catch{return null}}activeCount(){if(!this.enabled)return 0;return this.rules.filter(t=>t.enabled&&!(0,_resolveOverride.isSpent)(t)).length}subscribe(t){this.listeners.add(t);void this.ensureLoaded();return()=>{this.listeners.delete(t)}}setEnabled(t){if(this.enabled===t)return;this.remote?.setEnabled(t);this.markLocalEdit();this.markTouched();this.enabled=t;this.commit(this.rules)}addRule(t){if(this.rules.length>=_types.MAX_RULES)return null;const i={...t,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,hits:0,seen:0,createdAt:Date.now()};this.commit([i,...this.rules]);return i}upsertRule(t){this.remote?.upsertRule(t);this.markLocalEdit();this.markTouched();const{id:i,...e}=t;if(i&&this.rules.some(s=>s.id===i)){this.updateRule(i,e);return this.rules.find(s=>s.id===i)??null}return this.addRule(e)}updateRule(t,i){const e=this.rules.findIndex(r=>r.id===t);if(e===-1)return;const s=[...this.rules];s[e]={...s[e],...i,hits:0,seen:0};this.commit(s)}setRuleEnabled(t,i){const e=this.rules.findIndex(r=>r.id===t);if(e===-1||this.rules[e].enabled===i)return;this.remote?.setRuleEnabled(t,i);this.markLocalEdit();this.markTouched();const s=[...this.rules];s[e]={...s[e],enabled:i,hits:i?0:s[e].hits,seen:i?0:s[e].seen};this.commit(s)}removeRule(t){const i=this.rules.filter(e=>e.id!==t);if(i.length===this.rules.length)return;this.remote?.removeRule(t);this.markLocalEdit();this.markTouched();this.commit(i)}clearRules(){if(this.rules.length===0)return;this.remote?.clearRules();this.markLocalEdit();this.markTouched();this.commit([])}recordMatch(t){const i=this.rules.findIndex(s=>s.id===t);if(i===-1)return;const e=[...this.rules];e[i]={...e[i],seen:e[i].seen+1};this.rules=e;this.rebuild()}recordHit(t){const i=this.rules.findIndex(u=>u.id===t);if(i===-1)return;const e=this.rules[i];const s=e.hits+1;const r=typeof e.times==="number"&&s>=e.times;const l=[...this.rules];l[i]={...e,hits:s,enabled:r?false:e.enabled};if(r){this.commit(l);return}this.rules=l;this.rebuild();this.scheduleHitEmit()}ensureLoaded(){if(this.remote)return Promise.resolve();if(this.loaded)return Promise.resolve();if(this.loadPromise)return this.loadPromise;this.loadPromise=(async()=>{try{const t=await _sharedUi.persistentStorage.getItem(_sharedUi.devToolsStorageKeys.network.overrides());if(t&&!this.dirty){const i=JSON.parse(t);this.enabled=i?.enabled!==false;this.rules=parseRules(i?.rules);this.launchStreak=typeof i?.launchStreak==="number"?i.launchStreak:0;this.applyLaunchGuard();this.rebuild()}}catch{}finally{this.loaded=true;this.syncKeepAlive();this.emit()}})();return this.loadPromise}applyLaunchGuard(){if(!this.enabled||this.activeCount()===0){this.launchStreak=0;return}this.launchStreak+=1;if(this.launchStreak>=MAX_UNTOUCHED_LAUNCHES){this.enabled=false;this.autoPaused=true;this.launchStreak=0}this.persist()}syncKeepAlive(){const t=!this.engineDisabled&&this.activeCount()>0;if(t&&!this.keepAlive){(0,_networkListener.startNetworkListener)();this.keepAlive=(0,_networkListener.addNetworkListener)(()=>{});return}if(!t&&this.keepAlive){this.keepAlive();this.keepAlive=null;if((0,_networkListener.getNetworkListenerCount)()===0)(0,_networkListener.stopNetworkListener)()}}scheduleHitEmit(){if(this.hitEmitTimer!==null)return;this.hitEmitTimer=setTimeout(()=>{this.hitEmitTimer=null;this.emit()},HIT_EMIT_COALESCE_MS)}commit(t){this.dirty=true;this.rules=t.slice(0,_types.MAX_RULES);this.rebuild();this.syncKeepAlive();this.emit();this.persist()}rebuild(){this.state={enabled:this.enabled,rules:this.rules,autoPaused:this.autoPaused}}markTouched(){this.launchStreak=0;this.autoPaused=false}noteHealthyLaunch(){if(this.launchStreak===0&&!this.autoPaused)return;this.markTouched();this.persist();this.rebuild();this.emit()}persist(){if(this.remote)return;_sharedUi.persistentStorage.setItem(_sharedUi.devToolsStorageKeys.network.overrides(),JSON.stringify({enabled:this.enabled,rules:this.rules,launchStreak:this.launchStreak})).catch(()=>{})}emit(){this.listeners.forEach(t=>t())}}const overrideRulesStore=exports.overrideRulesStore=new OverrideRulesStore;(0,_engine.setOverrideHooks)({getRules:()=>overrideRulesStore.getRules(),recordHit:n=>overrideRulesStore.recordHit(n),recordMatch:n=>overrideRulesStore.recordMatch(n)});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.overrideRulesStore=void 0;var _sharedUi=require("@buoy-gg/shared-ui");var _networkListener=require("../utils/networkListener");var _engine=require("./engine");var _resolveOverride=require("./resolveOverride");var _types=require("./types");var _realNow=require("../utils/realNow");const REMOTE_ECHO_GRACE_MS=800;const MAX_UNTOUCHED_LAUNCHES=3;function countedThisTab(){const r=`${_sharedUi.devToolsStorageKeys.network.overrides()}_launch`;try{const t=globalThis.sessionStorage;if(!t)return false;if(t.getItem(r))return true;t.setItem(r,"1")}catch{}return false}const EMPTY_RULES=Object.freeze([]);const HIT_EMIT_COALESCE_MS=250;const VALID_KINDS=["respond","fail","delay"];function parseRules(r){if(!Array.isArray(r))return[];const t=[];for(const i of r){if(!i||typeof i!=="object")continue;const e=i;if(typeof e.id!=="string"||typeof e.urlPattern!=="string"){continue}if(!e.urlPattern)continue;const s=VALID_KINDS.includes(e.kind)?e.kind:"respond";t.push({id:e.id,enabled:e.enabled!==false,name:typeof e.name==="string"?e.name:void 0,urlPattern:e.urlPattern,methods:Array.isArray(e.methods)?e.methods.filter(n=>typeof n==="string"):void 0,requireHeader:typeof e.requireHeader==="string"&&e.requireHeader?e.requireHeader:void 0,bodyIncludes:typeof e.bodyIncludes==="string"&&e.bodyIncludes?e.bodyIncludes:void 0,kind:s,status:typeof e.status==="number"?Math.min(_types.STATUS_MAX,Math.max(_types.STATUS_MIN,e.status)):void 0,statusText:typeof e.statusText==="string"?e.statusText:void 0,headers:e.headers&&typeof e.headers==="object"?e.headers:void 0,body:typeof e.body==="string"?e.body:void 0,failKind:e.failKind==="timeout"?"timeout":void 0,delayMs:typeof e.delayMs==="number"?e.delayMs:void 0,times:typeof e.times==="number"?e.times:null,alternate:e.alternate===true,hits:0,seen:0,createdAt:typeof e.createdAt==="number"?e.createdAt:0})}return t.slice(0,_types.MAX_RULES)}class OverrideRulesStore{rules=[];enabled=true;listeners=new Set;loaded=false;loadPromise=null;dirty=false;idCounter=0;state={enabled:true,rules:[],autoPaused:false};launchStreak=0;autoPaused=false;keepAlive=null;hitEmitTimer=null;engineDisabled=false;remote=null;remoteEchoUntil=0;enableRemoteMode(t){this.remote=t;this.disableEngine()}disableRemoteMode(){this.remote=null}replaceRules(t,i=false){if(!this.remote)return;if(!i&&(0,_realNow.realNow)()<this.remoteEchoUntil)return;this.enabled=t.enabled;this.rules=t.rules;this.rebuild();this.emit()}markLocalEdit(){if(this.remote)this.remoteEchoUntil=(0,_realNow.realNow)()+REMOTE_ECHO_GRACE_MS}disableEngine(){this.engineDisabled=true;if(this.keepAlive){this.keepAlive();this.keepAlive=null;if((0,_networkListener.getNetworkListenerCount)()===0)(0,_networkListener.stopNetworkListener)()}}getState(){return this.state}getRules(){if(this.engineDisabled||!this.enabled)return EMPTY_RULES;return this.rules}async fetchRuleBody(t){const i=this.rules.find(e=>e.id===t);if(!i)return null;if(!i.bodyOmitted)return i.body??null;if(!this.remote?.getRuleBody)return null;try{return await this.remote.getRuleBody(t)}catch{return null}}activeCount(){if(!this.enabled)return 0;return this.rules.filter(t=>t.enabled&&!(0,_resolveOverride.isSpent)(t)).length}subscribe(t){this.listeners.add(t);void this.ensureLoaded();return()=>{this.listeners.delete(t)}}setEnabled(t){if(this.enabled===t)return;this.remote?.setEnabled(t);this.markLocalEdit();this.markTouched();this.enabled=t;this.commit(this.rules)}addRule(t){if(this.rules.length>=_types.MAX_RULES)return null;const i={...t,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,hits:0,seen:0,createdAt:Date.now()};this.commit([i,...this.rules]);return i}upsertRule(t){this.remote?.upsertRule(t);this.markLocalEdit();this.markTouched();const{id:i,...e}=t;if(i&&this.rules.some(s=>s.id===i)){this.updateRule(i,e);return this.rules.find(s=>s.id===i)??null}return this.addRule(e)}replaceAllRules(t,i){if(this.remote)return null;this.markTouched();const e=t.map(s=>s&&typeof s==="object"&&typeof s.id==="string"?s:{...s,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,createdAt:Date.now()});this.enabled=i;this.commit(parseRules(e));return this.rules.slice()}updateRule(t,i){const e=this.rules.findIndex(n=>n.id===t);if(e===-1)return;const s=[...this.rules];s[e]={...s[e],...i,hits:0,seen:0};this.commit(s)}setRuleEnabled(t,i){const e=this.rules.findIndex(n=>n.id===t);if(e===-1||this.rules[e].enabled===i)return;this.remote?.setRuleEnabled(t,i);this.markLocalEdit();this.markTouched();const s=[...this.rules];s[e]={...s[e],enabled:i,hits:i?0:s[e].hits,seen:i?0:s[e].seen};this.commit(s)}removeRule(t){const i=this.rules.filter(e=>e.id!==t);if(i.length===this.rules.length)return;this.remote?.removeRule(t);this.markLocalEdit();this.markTouched();this.commit(i)}clearRules(){if(this.rules.length===0)return;this.remote?.clearRules();this.markLocalEdit();this.markTouched();this.commit([])}recordMatch(t){const i=this.rules.findIndex(s=>s.id===t);if(i===-1)return;const e=[...this.rules];e[i]={...e[i],seen:e[i].seen+1};this.rules=e;this.rebuild()}recordHit(t){const i=this.rules.findIndex(l=>l.id===t);if(i===-1)return;const e=this.rules[i];const s=e.hits+1;const n=typeof e.times==="number"&&s>=e.times;const u=[...this.rules];u[i]={...e,hits:s,enabled:n?false:e.enabled};if(n){this.commit(u);return}this.rules=u;this.rebuild();this.scheduleHitEmit()}ensureLoaded(){if(this.remote)return Promise.resolve();if(this.loaded)return Promise.resolve();if(this.loadPromise)return this.loadPromise;this.loadPromise=(async()=>{let t=null;try{t=await _sharedUi.persistentStorage.getItem(_sharedUi.devToolsStorageKeys.network.overrides())}catch{}this.hydrate(t)})();return this.loadPromise}loadNow(){if(this.remote||this.loaded||this.loadPromise)return;let t;try{t=globalThis.localStorage?.getItem(_sharedUi.devToolsStorageKeys.network.overrides())??null}catch{return}if(t===null)return;this.hydrate(t)}hydrate(t){try{if(t&&!this.dirty){const i=JSON.parse(t);this.enabled=i?.enabled!==false;this.rules=parseRules(i?.rules);this.launchStreak=typeof i?.launchStreak==="number"?i.launchStreak:0;this.autoPaused=i?.autoPaused===true&&!this.enabled;this.applyLaunchGuard();this.rebuild()}}catch{}finally{this.loaded=true;this.syncKeepAlive();this.emit()}}applyLaunchGuard(){if(!this.enabled||this.activeCount()===0){this.launchStreak=0;return}if(countedThisTab())return;this.launchStreak+=1;if(this.launchStreak>=MAX_UNTOUCHED_LAUNCHES){this.enabled=false;this.autoPaused=true;this.launchStreak=0}this.persist()}syncKeepAlive(){const t=!this.engineDisabled&&this.activeCount()>0;if(t&&!this.keepAlive){(0,_networkListener.startNetworkListener)();this.keepAlive=(0,_networkListener.addNetworkListener)(()=>{});return}if(!t&&this.keepAlive){this.keepAlive();this.keepAlive=null;if((0,_networkListener.getNetworkListenerCount)()===0)(0,_networkListener.stopNetworkListener)()}}scheduleHitEmit(){if(this.hitEmitTimer!==null)return;this.hitEmitTimer=setTimeout(()=>{this.hitEmitTimer=null;this.emit()},HIT_EMIT_COALESCE_MS)}commit(t){this.dirty=true;this.rules=t.slice(0,_types.MAX_RULES);this.rebuild();this.syncKeepAlive();this.emit();this.persist()}rebuild(){this.state={enabled:this.enabled,rules:this.rules,autoPaused:this.autoPaused}}markTouched(){this.launchStreak=0;this.autoPaused=false}noteHealthyLaunch(){if(this.launchStreak===0&&!this.autoPaused)return;this.markTouched();this.persist();this.rebuild();this.emit()}persist(){if(this.remote)return;_sharedUi.persistentStorage.setItem(_sharedUi.devToolsStorageKeys.network.overrides(),JSON.stringify({enabled:this.enabled,rules:this.rules,launchStreak:this.launchStreak,autoPaused:this.autoPaused})).catch(()=>{})}emit(){this.listeners.forEach(t=>t())}}const overrideRulesStore=exports.overrideRulesStore=new OverrideRulesStore;(0,_engine.setOverrideHooks)({getRules:()=>overrideRulesStore.getRules(),recordHit:r=>overrideRulesStore.recordHit(r),recordMatch:r=>overrideRulesStore.recordMatch(r)});if(typeof window!=="undefined"&&typeof document!=="undefined"&&!(typeof navigator!=="undefined"&&navigator.product==="ReactNative")){overrideRulesStore.loadNow()}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.findMatchingRule=findMatchingRule;exports.isSpent=isSpent;exports.resolveOverride=resolveOverride;exports.shouldApply=shouldApply;exports.toOutcome=toOutcome;var _matchRule=require("./matchRule");var _types=require("./types");const NEVER_OVERRIDE=[/(^|\.)keygen\.sh/i,/^https?:\/\/(www\.)?buoy\.gg\/api\/license(\/|$)/i];function isProtectedUrl(t){return NEVER_OVERRIDE.some(e=>e.test(t))}function inferContentType(t){const e=t.trim();if(e==="")return"text/plain; charset=utf-8";if(e.startsWith("{")||e.startsWith("[")){try{JSON.parse(e);return"application/json"}catch{}}return"text/plain; charset=utf-8"}function hasHeader(t,e){const n=e.toLowerCase();return Object.keys(t).some(r=>r.toLowerCase()===n)}function toOutcome(t){const e=Math.max(0,t.delayMs??0);if(t.kind==="delay"){return{kind:"delay",rule:t,delayMs:e}}if(t.kind==="fail"){return{kind:"fail",rule:t,delayMs:e,failKind:t.failKind??"network"}}const n=t.body??"";const r={...t.headers??{}};if(!hasHeader(r,"content-type")){r["content-type"]=inferContentType(n)}return{kind:"respond",rule:t,delayMs:e,status:Math.min(_types.STATUS_MAX,Math.max(_types.STATUS_MIN,t.status??200)),statusText:t.statusText??"",headers:r,body:n}}function isSpent(t){return typeof t.times==="number"&&t.hits>=t.times}function shouldApply(t){if(!t.alternate)return true;return t.seen%2===1}function findMatchingRule(t,e,n,r){if(n.length===0)return null;if(e.toUpperCase()==="OPTIONS")return null;if(isProtectedUrl(t))return null;for(const i of n){if(!i.enabled)continue;if(isSpent(i))continue;if(!(0,_matchRule.ruleMatches)(i,t,e,r))continue;return i}return null}function resolveOverride(t,e,n,r){const i=findMatchingRule(t,e,n,r);if(!i||!shouldApply(i))return null;return toOutcome(i)}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.findMatchingRule=findMatchingRule;exports.isSpent=isSpent;exports.resolveOverride=resolveOverride;exports.shouldApply=shouldApply;exports.toOutcome=toOutcome;var _applyToFetch=require("./applyToFetch");var _matchRule=require("./matchRule");var _types=require("./types");const NEVER_OVERRIDE=[/(^|\.)keygen\.sh/i,/^https?:\/\/(www\.)?buoy\.gg\/api\/license(\/|$)/i];function isProtectedUrl(t){return NEVER_OVERRIDE.some(e=>e.test(t))}function inferContentType(t){const e=t.trim();if(e==="")return"text/plain; charset=utf-8";if(e.startsWith("{")||e.startsWith("[")){try{JSON.parse(e);return"application/json"}catch{}}return"text/plain; charset=utf-8"}function hasHeader(t,e){const n=e.toLowerCase();return Object.keys(t).some(r=>r.toLowerCase()===n)}function toOutcome(t){const e=Math.max(0,t.delayMs??0);if(t.kind==="delay"){return{kind:"delay",rule:t,delayMs:e}}if(t.kind==="fail"){return{kind:"fail",rule:t,delayMs:e,failKind:t.failKind??"network"}}const n=Math.min(_types.STATUS_MAX,Math.max(_types.STATUS_MIN,t.status??200));const r=_applyToFetch.NULL_BODY_STATUSES.includes(n)?"":t.body??"";const s={...t.headers??{}};if(!hasHeader(s,"content-type")){s["content-type"]=inferContentType(r)}return{kind:"respond",rule:t,delayMs:e,status:n,statusText:t.statusText??"",headers:s,body:r}}function isSpent(t){return typeof t.times==="number"&&t.hits>=t.times}function shouldApply(t){if(!t.alternate)return true;return t.seen%2===1}function findMatchingRule(t,e,n,r,s){if(n.length===0)return null;if(e.toUpperCase()==="OPTIONS")return null;if(isProtectedUrl(t))return null;for(const i of n){if(!i.enabled)continue;if(isSpent(i))continue;if(!(0,_matchRule.ruleMatches)(i,t,e,r,s))continue;return i}return null}function resolveOverride(t,e,n,r,s){const i=findMatchingRule(t,e,n,r,s);if(!i||!shouldApply(i))return null;return toOutcome(i)}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.networkSyncAdapter=exports.SNAPSHOT_HEADER_VALUE_LIMIT=exports.SNAPSHOT_EVENTS_BUDGET=exports.SNAPSHOT_BODY_INLINE_LIMIT=void 0;var _store=require("../conditions/store");var _networkEventStore=require("../utils/networkEventStore");var _networkSavedStore=require("../utils/networkSavedStore");var _overrideRulesStore=require("../overrides/overrideRulesStore");var _presets=require("../overrides/presets");var _engine=require("../overrides/engine");var _networkListener=require("../utils/networkListener");var _sharedUi=require("@buoy-gg/shared-ui");const SNAPSHOT_BODY_INLINE_LIMIT=exports.SNAPSHOT_BODY_INLINE_LIMIT=16*1024;const SNAPSHOT_EVENTS_BUDGET=exports.SNAPSHOT_EVENTS_BUDGET=1.25*1024*1024;function shouldStripBody(e,t){if(e===void 0)return false;if((t??0)>SNAPSHOT_BODY_INLINE_LIMIT)return true;return(0,_sharedUi.isOverWireBudget)(e,SNAPSHOT_BODY_INLINE_LIMIT)}const wireCache=new WeakMap;const strippedCache=new WeakMap;function toWireEvent(e){const t=wireCache.get(e);if(t)return t;let r;try{r=buildWireEvent(e)}catch{r=buildMetadataOnly(e)}wireCache.set(e,r);return r}function buildMetadataOnly(e){const t={...e,requestData:void 0,responseData:void 0,graphqlVariables:void 0,requestBodyOmitted:e.requestData!==void 0?true:void 0,responseBodyOmitted:e.responseData!==void 0?true:void 0};let r=1024;try{r=(0,_sharedUi.approxJsonSize)(t,SNAPSHOT_EVENTS_BUDGET).bytes}catch{}return{event:t,bytes:r}}function buildWireEvent(e){const t=shouldStripBody(e.requestData,e.requestSize);const r=shouldStripBody(e.responseData,e.responseSize);const n=toWireGraphqlVariables(e.graphqlVariables);const o=toWireHeaders(e.requestHeaders);const s=toWireHeaders(e.responseHeaders);const d=t||r||n!==e.graphqlVariables||o!==e.requestHeaders||s!==e.responseHeaders;let i=e;if(d){i={...e};if(t){i.requestData=void 0;i.requestBodyOmitted=true}if(r){i.responseData=void 0;i.responseBodyOmitted=true}if(n!==e.graphqlVariables){i.graphqlVariables=n}if(o!==e.requestHeaders){i.requestHeaders=o;i.headersOmitted=true}if(s!==e.responseHeaders){i.responseHeaders=s;i.headersOmitted=true}}return{event:i,bytes:(0,_sharedUi.approxJsonSize)(i,SNAPSHOT_EVENTS_BUDGET).bytes}}function toStrippedEvent(e){const t=strippedCache.get(e);if(t)return t;const{event:r}=toWireEvent(e);const n={...r};if(n.requestData!==void 0){n.requestData=void 0;n.requestBodyOmitted=true}if(n.responseData!==void 0){n.responseData=void 0;n.responseBodyOmitted=true}if(n.graphqlVariables!==void 0){n.graphqlVariables=toWireGraphqlVariables(n.graphqlVariables,true)}const o={event:n,bytes:(0,_sharedUi.approxJsonSize)(n,SNAPSHOT_EVENTS_BUDGET).bytes};strippedCache.set(e,o);return o}function fitEventsToBudget(e){const t=new Array(e.length);let r=0;for(let n=0;n<e.length;n++){const o=toWireEvent(e[n]);if(r+o.bytes<=SNAPSHOT_EVENTS_BUDGET){t[n]=o.event;r+=o.bytes}else{const s=toStrippedEvent(e[n]);t[n]=s.event;r+=s.bytes}}return t}function toWireGraphqlVariables(e,t=false){if(!e)return e;if(!t&&!shouldStripBody(e,void 0))return e;const r={};for(const[n,o]of Object.entries(e)){if(typeof o==="string"&&o.length<=64)r[n]=o;else if(typeof o==="number"||typeof o==="boolean"){r[n]=o}}return Object.keys(r).length>0?r:void 0}const SNAPSHOT_HEADER_VALUE_LIMIT=exports.SNAPSHOT_HEADER_VALUE_LIMIT=64;function toWireHeaders(e){if(!e)return e;let t=false;const r={};for(const[n,o]of Object.entries(e)){if(typeof o!=="string")continue;if(o.length<=SNAPSHOT_HEADER_VALUE_LIMIT){r[n]=o}else{r[n]=`${o.slice(0,SNAPSHOT_HEADER_VALUE_LIMIT)}\u2026 [${o.length-SNAPSHOT_HEADER_VALUE_LIMIT} more]`;t=true}}return t?r:e}const stripLargeRuleBodies=e=>{let t=false;const r=e.rules.map(n=>{if(!n.body||n.body.length<=SNAPSHOT_BODY_INLINE_LIMIT){return n}t=true;return{...n,body:void 0,bodyOmitted:true}});return t?{...e,rules:r}:e};const resolveEvent=e=>_networkEventStore.networkEventStore.getEventById(e)??_networkSavedStore.networkSavedStore.getEventById(e);const readId=e=>e&&typeof e==="object"?e.id:void 0;const readBool=(e,t)=>!!(e&&typeof e==="object"&&e[t]);const inactiveStamp=()=>(0,_engine.overridesCanApply)()?{}:{active:false,inactiveReason:_engine.OVERRIDES_INACTIVE_REASON};const VALID_KINDS=["respond","fail","delay"];function readRuleDraft(e,t){if(!e||typeof e!=="object")return null;const r=e.rule??e;if(!r||typeof r!=="object")return null;const n=r;const o=typeof n.urlPattern==="string"&&n.urlPattern.trim()?n.urlPattern.trim():t?.urlPattern??"";if(!o)return null;const s=VALID_KINDS.includes(n.kind)?n.kind:t?.kind??"respond";return{id:typeof n.id==="string"?n.id:void 0,enabled:n.enabled!==false,name:typeof n.name==="string"?n.name:t?.name,urlPattern:o,methods:Array.isArray(n.methods)?n.methods.filter(d=>typeof d==="string").map(d=>d.toUpperCase()):t?.methods,requireHeader:typeof n.requireHeader==="string"&&n.requireHeader.trim()?n.requireHeader.trim():void 0,kind:s,status:typeof n.status==="number"?n.status:t?.status,statusText:typeof n.statusText==="string"?n.statusText:t?.statusText,headers:n.headers&&typeof n.headers==="object"?n.headers:t?.headers,body:patchedBody(n,t),failKind:n.failKind==="timeout"?"timeout":void 0,delayMs:typeof n.delayMs==="number"?n.delayMs:void 0,times:typeof n.times==="number"?n.times:null,alternate:n.alternate===true}}const isPlainObject=e=>!!e&&typeof e==="object"&&!Array.isArray(e);function deepMerge(e,t,r="",n={shrunk:[],breaks:[]}){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>0&&t.length<e.length){n.shrunk.push({path:r||"(root)",have:e.length,sent:t.length})}return t}if(!isPlainObject(e)||!isPlainObject(t))return t;const o={...e};for(const[s,d]of Object.entries(t)){const i=r?`${r}.${s}`:s;if(s in e){const u=(0,_sharedUi.shapeKind)(e[s]);const l=(0,_sharedUi.shapeKind)(d);if((u==="array"||u==="object")&&u!==l){n.breaks.push({path:i,from:u,to:l})}o[s]=deepMerge(e[s],d,i,n)}else{o[s]=d}}return o}function patchViolations(e,t){if(e.body!=null||!isPlainObject(e.bodyPatch)||typeof t!=="string")return[];try{return(0,_sharedUi.typedEditViolations)(JSON.parse(t),e.bodyPatch,{noun:"response body"})}catch{return[]}}function patchedBody(e,t){if(typeof e.body==="string")return e.body;if(e.body!=null)return JSON.stringify(e.body,null,2);const r=t?.body??(typeof e.id==="string"?_overrideRulesStore.overrideRulesStore.getState().rules.find(n=>n.id===e.id)?.body:void 0);if(isPlainObject(e.bodyPatch)&&typeof r==="string"){try{return JSON.stringify(deepMerge(JSON.parse(r),e.bodyPatch),null,2)}catch{return r}}return r}function existingRule(e){if(!e||typeof e!=="object")return null;const t=e.rule??e;if(!t||typeof t!=="object")return null;const r=t.id;if(typeof r!=="string")return null;const n=_overrideRulesStore.overrideRulesStore.getState().rules.find(o=>o.id===r);return n?{...n}:null}function preservedBody(e){if(!e||typeof e!=="object")return null;const t=e.rule??e;if(!t||typeof t!=="object")return null;const r=t;if(r.bodyOmitted!==true||typeof r.id!=="string")return null;const n=_overrideRulesStore.overrideRulesStore.getState().rules.find(o=>o.id===r.id);return n?{body:n.body}:null}function baseFromRequest(e){if(!e||typeof e!=="object")return null;const t=e.fromRequestId;if(typeof t!=="string"||!t)return null;const r=resolveEvent(t);return r?(0,_presets.draftFromEvent)(r):null}const networkSyncAdapter=exports.networkSyncAdapter={dispose:()=>{_overrideRulesStore.overrideRulesStore.setEnabled(false)},version:6,getSnapshot:()=>{_networkEventStore.networkEventStore.ensureInterception();return{conditions:{version:1,runtimeId:_store.networkConditionsRuntimeId,profile:(0,_store.getNetworkCondition)(),available:(0,_store.conditionsCanApply)()},events:fitEventsToBudget(_networkEventStore.networkEventStore.getEvents()),overrides:stripLargeRuleBodies(_overrideRulesStore.overrideRulesStore.getState()),saved:_networkSavedStore.networkSavedStore.getRecords().map(e=>({...e,event:toWireEvent(e.event).event}))}},subscribe:e=>{const t=_networkEventStore.networkEventStore.subscribeToEvents(e);const r=(0,_store.subscribeNetworkConditions)(e);const n=_networkSavedStore.networkSavedStore.subscribe(e);const o=_overrideRulesStore.overrideRulesStore.subscribe(e);return()=>{r();t();n();o()}},actions:{getNetworkConditions:()=>({runtimeId:_store.networkConditionsRuntimeId,profile:(0,_store.getNetworkCondition)(),available:(0,_store.conditionsCanApply)()}),setNetworkConditions:e=>{const t=e&&typeof e==="object"?e.profile:void 0;return{runtimeId:_store.networkConditionsRuntimeId,profile:(0,_store.setNetworkCondition)(t),available:(0,_store.conditionsCanApply)()}},clearEvents:()=>{_networkEventStore.networkEventStore.clearEvents()},getEventBody:e=>{const t=readId(e);if(!t)return null;const r=resolveEvent(t);if(!r)return null;return{url:r.url??null,method:r.method??null,status:r.status??null,override:r.override??null,requestData:r.requestData??null,responseData:r.responseData??null,requestHeaders:r.requestHeaders??null,responseHeaders:r.responseHeaders??null}},setPinned:e=>{const t=readId(e);if(!t)return null;const r=resolveEvent(t);if(!r)return null;const n=readBool(e,"pinned");const o=(0,_networkSavedStore.flagsForEventId)(_networkSavedStore.networkSavedStore.getState(),t).pinned;if(o===n)return{ok:true};return _networkSavedStore.networkSavedStore.togglePin(r)},setSaved:e=>{const t=readId(e);if(!t)return null;const r=resolveEvent(t);if(!r)return null;const n=readBool(e,"saved");const o=(0,_networkSavedStore.flagsForEventId)(_networkSavedStore.networkSavedStore.getState(),t).saved;if(o===n)return{ok:true};return _networkSavedStore.networkSavedStore.toggleSave(r)},removeSavedRecord:e=>{const t=e&&typeof e==="object"?e.key:void 0;if(!t)return null;_networkSavedStore.networkSavedStore.remove(t);return{ok:true}},clearSavedRequests:()=>{_networkSavedStore.networkSavedStore.clearSaved();return{ok:true}},clearPinnedRequests:()=>{_networkSavedStore.networkSavedStore.clearPinned();return{ok:true}},setOverridesEnabled:e=>{_overrideRulesStore.overrideRulesStore.setEnabled(readBool(e,"enabled"));return{ok:true,enabled:_overrideRulesStore.overrideRulesStore.getState().enabled,...inactiveStamp()}},upsertOverrideRule:e=>{const t=baseFromRequest(e)??preservedBody(e)??existingRule(e);const r=e?.rule??e;if(r&&typeof r.bodyPath==="string"&&r.body==null){const s=t?.body??(typeof r.id==="string"?_overrideRulesStore.overrideRulesStore.getState().rules.find(u=>u.id===r.id)?.body:void 0);if(typeof s!=="string"){return{ok:false,error:"bodyPath needs something to patch: send fromRequestId (the captured request whose real response it addresses) or the id of an existing rule."}}if(r.bodyValue===void 0){return{ok:false,error:`Refused: sent \`bodyPath\` without \`bodyValue\`. Say what to set "${r.bodyPath}" to.`}}let d;try{d=JSON.parse(s)}catch{return{ok:false,error:"The captured response body is not JSON, so it cannot be addressed by path. Send a whole `body` instead."}}const i=(0,_sharedUi.patchFromPath)(d,r.bodyPath,r.bodyValue);if(!i.ok)return{ok:false,error:`Refused: ${i.error}`};r.bodyPatch=i.patch;delete r.bodyPath;delete r.bodyValue}if(r&&isPlainObject(r.bodyPatch)&&r.body==null){const s=t?.body??(typeof r.id==="string"?_overrideRulesStore.overrideRulesStore.getState().rules.find(d=>d.id===r.id)?.body:void 0);if(typeof s!=="string"){return{ok:false,error:"bodyPatch needs something to patch: send fromRequestId (the captured request whose real response the patch is merged into) or the id of an existing rule."}}if(r.force!==true){let d;try{const u=(0,_sharedUi.expandKeyedArrays)(JSON.parse(s),r.bodyPatch);d=u.error;if(u.notes.length)r.bodyPatch=u.patch}catch{}if(d){return{ok:false,error:`Refused: ${d}`}}const i=patchViolations(r,s);if(i.length>0){return{ok:false,error:(0,_sharedUi.refusalText)(i,"response body",(0,_sharedUi.suggestedPatch)(r.bodyPatch,i)),violations:i}}}}const n=readRuleDraft(e,t);if(!n){const s=e?.fromRequestId;return{ok:false,error:s?`No captured request \`${s}\` \u2014 it may have been cleared. Send a urlPattern instead.`:"A rule needs a non-empty urlPattern."}}const o=_overrideRulesStore.overrideRulesStore.upsertRule(n);if(!o)return{ok:false,error:"Override rule limit reached."};if(o.enabled)_overrideRulesStore.overrideRulesStore.setEnabled(true);return{ok:true,rule:{id:o.id,urlPattern:o.urlPattern,enabled:o.enabled,kind:o.kind,status:o.status,times:o.times,bodySize:o.body?o.body.length:0},...o.times===void 0||o.times===null?{lingers:`This rule has no \`times\` budget, so it overrides EVERY matching request until it is disabled or deleted (id \`${o.id}\`). If you meant only the next one, set times:1.`}:{},...inactiveStamp()}},setOverrideRuleEnabled:e=>{const t=readId(e);if(!t)return{ok:false,error:"Missing rule id."};_overrideRulesStore.overrideRulesStore.setRuleEnabled(t,readBool(e,"enabled"));return{ok:true,...inactiveStamp()}},deleteOverrideRule:e=>{const t=readId(e);if(!t)return{ok:false,error:"Missing rule id."};_overrideRulesStore.overrideRulesStore.removeRule(t);return{ok:true}},clearOverrideRules:()=>{_overrideRulesStore.overrideRulesStore.clearRules();return{ok:true}},listOverrideRules:async()=>{await _overrideRulesStore.overrideRulesStore.ensureLoaded();return _overrideRulesStore.overrideRulesStore.getState()},getOverrideRuleBody:e=>{const t=readId(e);if(!t)return null;const r=_overrideRulesStore.overrideRulesStore.getState().rules.find(n=>n.id===t);if(!r)return null;return{body:r.body??null}},getCaptureStatus:()=>{const e=_networkEventStore.networkEventStore.getSubscriberCounts().total;let t=null;let r=null;try{t=(0,_networkListener.isNetworkListening)();r=(0,_networkListener.getNetworkListenerCount)()}catch{}let n=null;try{n=(0,_networkListener.isNetworkInterceptionLive)()}catch{}return{capturing:e>0,subscribers:e,interceptorInstalled:t,interceptorLive:n,listenerCount:r,eventCount:_networkEventStore.networkEventStore.getEvents().length}},debugOverrides:e=>{const t=(e&&typeof e==="object"?e.url:void 0)??"https://example.com/";return{interceptorInstalled:(0,_networkListener.isNetworkListening)(),listenerCount:(0,_networkListener.getNetworkListenerCount)(),engine:(0,_engine.inspectEngine)(t,"GET"),store:{enabled:_overrideRulesStore.overrideRulesStore.getState().enabled,ruleCount:_overrideRulesStore.overrideRulesStore.getState().rules.length,rulesVisibleToEngine:_overrideRulesStore.overrideRulesStore.getRules().length}}}}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.networkSyncAdapter=exports.SNAPSHOT_HEADER_VALUE_LIMIT=exports.SNAPSHOT_EVENTS_BUDGET=exports.SNAPSHOT_BODY_INLINE_LIMIT=void 0;var _store=require("../conditions/store");var _networkEventStore=require("../utils/networkEventStore");var _networkSavedStore=require("../utils/networkSavedStore");var _overrideRulesStore=require("../overrides/overrideRulesStore");var _presets=require("../overrides/presets");var _engine=require("../overrides/engine");var _networkListener=require("../utils/networkListener");var _types=require("../overrides/types");var _sharedUi=require("@buoy-gg/shared-ui");const SNAPSHOT_BODY_INLINE_LIMIT=exports.SNAPSHOT_BODY_INLINE_LIMIT=16*1024;const SNAPSHOT_EVENTS_BUDGET=exports.SNAPSHOT_EVENTS_BUDGET=1.25*1024*1024;function shouldStripBody(e,t){if(e===void 0)return false;if((t??0)>SNAPSHOT_BODY_INLINE_LIMIT)return true;return(0,_sharedUi.isOverWireBudget)(e,SNAPSHOT_BODY_INLINE_LIMIT)}const wireCache=new WeakMap;const strippedCache=new WeakMap;function toWireEvent(e){const t=wireCache.get(e);if(t)return t;let n;try{n=buildWireEvent(e)}catch{n=buildMetadataOnly(e)}wireCache.set(e,n);return n}function buildMetadataOnly(e){const t={...e,requestData:void 0,responseData:void 0,graphqlVariables:void 0,requestBodyOmitted:e.requestData!==void 0?true:void 0,responseBodyOmitted:e.responseData!==void 0?true:void 0};let n=1024;try{n=(0,_sharedUi.approxJsonSize)(t,SNAPSHOT_EVENTS_BUDGET).bytes}catch{}return{event:t,bytes:n}}function buildWireEvent(e){const t=shouldStripBody(e.requestData,e.requestSize);const n=shouldStripBody(e.responseData,e.responseSize);const r=toWireGraphqlVariables(e.graphqlVariables);const o=toWireHeaders(e.requestHeaders);const s=toWireHeaders(e.responseHeaders);const d=t||n||r!==e.graphqlVariables||o!==e.requestHeaders||s!==e.responseHeaders;let i=e;if(d){i={...e};if(t){i.requestData=void 0;i.requestBodyOmitted=true}if(n){i.responseData=void 0;i.responseBodyOmitted=true}if(r!==e.graphqlVariables){i.graphqlVariables=r}if(o!==e.requestHeaders){i.requestHeaders=o;i.headersOmitted=true}if(s!==e.responseHeaders){i.responseHeaders=s;i.headersOmitted=true}}return{event:i,bytes:(0,_sharedUi.approxJsonSize)(i,SNAPSHOT_EVENTS_BUDGET).bytes}}function toStrippedEvent(e){const t=strippedCache.get(e);if(t)return t;const{event:n}=toWireEvent(e);const r={...n};if(r.requestData!==void 0){r.requestData=void 0;r.requestBodyOmitted=true}if(r.responseData!==void 0){r.responseData=void 0;r.responseBodyOmitted=true}if(r.graphqlVariables!==void 0){r.graphqlVariables=toWireGraphqlVariables(r.graphqlVariables,true)}const o={event:r,bytes:(0,_sharedUi.approxJsonSize)(r,SNAPSHOT_EVENTS_BUDGET).bytes};strippedCache.set(e,o);return o}function fitEventsToBudget(e){const t=new Array(e.length);let n=0;for(let r=0;r<e.length;r++){const o=toWireEvent(e[r]);if(n+o.bytes<=SNAPSHOT_EVENTS_BUDGET){t[r]=o.event;n+=o.bytes}else{const s=toStrippedEvent(e[r]);t[r]=s.event;n+=s.bytes}}return t}function toWireGraphqlVariables(e,t=false){if(!e)return e;if(!t&&!shouldStripBody(e,void 0))return e;const n={};for(const[r,o]of Object.entries(e)){if(typeof o==="string"&&o.length<=64)n[r]=o;else if(typeof o==="number"||typeof o==="boolean"){n[r]=o}}return Object.keys(n).length>0?n:void 0}const SNAPSHOT_HEADER_VALUE_LIMIT=exports.SNAPSHOT_HEADER_VALUE_LIMIT=64;function toWireHeaders(e){if(!e)return e;let t=false;const n={};for(const[r,o]of Object.entries(e)){if(typeof o!=="string")continue;if(o.length<=SNAPSHOT_HEADER_VALUE_LIMIT){n[r]=o}else{n[r]=`${o.slice(0,SNAPSHOT_HEADER_VALUE_LIMIT)}\u2026 [${o.length-SNAPSHOT_HEADER_VALUE_LIMIT} more]`;t=true}}return t?n:e}const stripLargeRuleBodies=e=>{let t=false;const n=e.rules.map(r=>{if(!r.body||r.body.length<=SNAPSHOT_BODY_INLINE_LIMIT){return r}t=true;return{...r,body:void 0,bodyOmitted:true}});return t?{...e,rules:n}:e};const resolveEvent=e=>_networkEventStore.networkEventStore.getEventById(e)??_networkSavedStore.networkSavedStore.getEventById(e);const readId=e=>e&&typeof e==="object"?e.id:void 0;const readBool=(e,t)=>!!(e&&typeof e==="object"&&e[t]);const inactiveStamp=()=>(0,_engine.overridesCanApply)()?{}:{active:false,inactiveReason:_engine.OVERRIDES_INACTIVE_REASON};const VALID_KINDS=["respond","fail","delay"];function readRuleDraft(e,t){if(!e||typeof e!=="object")return null;const n=e.rule??e;if(!n||typeof n!=="object")return null;const r=n;const o=typeof r.urlPattern==="string"&&r.urlPattern.trim()?r.urlPattern.trim():t?.urlPattern??"";if(!o)return null;const s=VALID_KINDS.includes(r.kind)?r.kind:t?.kind??"respond";return{id:typeof r.id==="string"?r.id:void 0,enabled:r.enabled!==false,name:typeof r.name==="string"?r.name:t?.name,urlPattern:o,methods:Array.isArray(r.methods)?r.methods.filter(d=>typeof d==="string").map(d=>d.toUpperCase()):t?.methods,requireHeader:typeof r.requireHeader==="string"&&r.requireHeader.trim()?r.requireHeader.trim():void 0,bodyIncludes:typeof r.bodyIncludes==="string"&&r.bodyIncludes?r.bodyIncludes.slice(0,4096):t?.bodyIncludes,kind:s,status:typeof r.status==="number"?r.status:t?.status,statusText:typeof r.statusText==="string"?r.statusText:t?.statusText,headers:r.headers&&typeof r.headers==="object"?r.headers:t?.headers,body:patchedBody(r,t),failKind:r.failKind==="timeout"?"timeout":void 0,delayMs:typeof r.delayMs==="number"?r.delayMs:void 0,times:typeof r.times==="number"?r.times:null,alternate:r.alternate===true}}const isPlainObject=e=>!!e&&typeof e==="object"&&!Array.isArray(e);function deepMerge(e,t,n="",r={shrunk:[],breaks:[]}){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>0&&t.length<e.length){r.shrunk.push({path:n||"(root)",have:e.length,sent:t.length})}return t}if(!isPlainObject(e)||!isPlainObject(t))return t;const o={...e};for(const[s,d]of Object.entries(t)){const i=n?`${n}.${s}`:s;if(s in e){const u=(0,_sharedUi.shapeKind)(e[s]);const l=(0,_sharedUi.shapeKind)(d);if((u==="array"||u==="object")&&u!==l){r.breaks.push({path:i,from:u,to:l})}o[s]=deepMerge(e[s],d,i,r)}else{o[s]=d}}return o}function patchViolations(e,t){if(e.body!=null||!isPlainObject(e.bodyPatch)||typeof t!=="string")return[];try{return(0,_sharedUi.typedEditViolations)(JSON.parse(t),e.bodyPatch,{noun:"response body"})}catch{return[]}}function patchedBody(e,t){if(typeof e.body==="string")return e.body;if(e.body!=null)return JSON.stringify(e.body,null,2);const n=t?.body??(isPlainObject(e.bodyPatch)&&typeof e.id==="string"?_overrideRulesStore.overrideRulesStore.getState().rules.find(r=>r.id===e.id)?.body:void 0);if(isPlainObject(e.bodyPatch)&&typeof n==="string"){try{return JSON.stringify(deepMerge(JSON.parse(n),e.bodyPatch),null,2)}catch{return n}}return n}function existingRule(e){if(!e||typeof e!=="object")return null;const t=e.rule??e;if(!t||typeof t!=="object")return null;const n=t.id;if(typeof n!=="string")return null;const r=_overrideRulesStore.overrideRulesStore.getState().rules.find(o=>o.id===n);return r?{...r}:null}function preservedBody(e){if(!e||typeof e!=="object")return null;const t=e.rule??e;if(!t||typeof t!=="object")return null;const n=t;if(n.bodyOmitted!==true||typeof n.id!=="string")return null;const r=_overrideRulesStore.overrideRulesStore.getState().rules.find(o=>o.id===n.id);return r?{body:r.body}:null}function baseFromRequest(e){if(!e||typeof e!=="object")return null;const t=e.fromRequestId;if(typeof t!=="string"||!t)return null;const n=resolveEvent(t);return n?(0,_presets.draftFromEvent)(n):null}const networkSyncAdapter=exports.networkSyncAdapter={dispose:()=>{_overrideRulesStore.overrideRulesStore.setEnabled(false)},version:6,getSnapshot:()=>{_networkEventStore.networkEventStore.ensureInterception();return{conditions:{version:1,runtimeId:_store.networkConditionsRuntimeId,profile:(0,_store.getNetworkCondition)(),available:(0,_store.conditionsCanApply)()},events:fitEventsToBudget(_networkEventStore.networkEventStore.getEvents()),overrides:stripLargeRuleBodies(_overrideRulesStore.overrideRulesStore.getState()),saved:_networkSavedStore.networkSavedStore.getRecords().map(e=>({...e,event:toWireEvent(e.event).event}))}},subscribe:e=>{const t=_networkEventStore.networkEventStore.subscribeToEvents(e);const n=(0,_store.subscribeNetworkConditions)(e);const r=_networkSavedStore.networkSavedStore.subscribe(e);const o=_overrideRulesStore.overrideRulesStore.subscribe(e);return()=>{n();t();r();o()}},actions:{getNetworkConditions:()=>({runtimeId:_store.networkConditionsRuntimeId,profile:(0,_store.getNetworkCondition)(),available:(0,_store.conditionsCanApply)()}),setNetworkConditions:e=>{const t=e&&typeof e==="object"?e.profile:void 0;return{runtimeId:_store.networkConditionsRuntimeId,profile:(0,_store.setNetworkCondition)(t),available:(0,_store.conditionsCanApply)()}},clearEvents:()=>{_networkEventStore.networkEventStore.clearEvents()},getEventBody:e=>{const t=readId(e);if(!t)return null;const n=resolveEvent(t);if(!n)return null;return{url:n.url??null,method:n.method??null,status:n.status??null,override:n.override??null,requestData:n.requestData??null,responseData:n.responseData??null,requestHeaders:n.requestHeaders??null,responseHeaders:n.responseHeaders??null}},setPinned:e=>{const t=readId(e);if(!t)return null;const n=resolveEvent(t);if(!n)return null;const r=readBool(e,"pinned");const o=(0,_networkSavedStore.flagsForEventId)(_networkSavedStore.networkSavedStore.getState(),t).pinned;if(o===r)return{ok:true};return _networkSavedStore.networkSavedStore.togglePin(n)},setSaved:e=>{const t=readId(e);if(!t)return null;const n=resolveEvent(t);if(!n)return null;const r=readBool(e,"saved");const o=(0,_networkSavedStore.flagsForEventId)(_networkSavedStore.networkSavedStore.getState(),t).saved;if(o===r)return{ok:true};return _networkSavedStore.networkSavedStore.toggleSave(n)},removeSavedRecord:e=>{const t=e&&typeof e==="object"?e.key:void 0;if(!t)return null;_networkSavedStore.networkSavedStore.remove(t);return{ok:true}},clearSavedRequests:()=>{_networkSavedStore.networkSavedStore.clearSaved();return{ok:true}},clearPinnedRequests:()=>{_networkSavedStore.networkSavedStore.clearPinned();return{ok:true}},setOverridesEnabled:e=>{_overrideRulesStore.overrideRulesStore.setEnabled(readBool(e,"enabled"));return{ok:true,enabled:_overrideRulesStore.overrideRulesStore.getState().enabled,...inactiveStamp()}},upsertOverrideRule:e=>{const t=e?.rule??e;const n=!!t&&t.body==null&&(isPlainObject(t.bodyPatch)||typeof t.bodyPath==="string");const r=baseFromRequest(e)??preservedBody(e)??(n?existingRule(e):null);if(t&&typeof t.bodyPath==="string"&&t.body==null){const d=r?.body??(typeof t.id==="string"?_overrideRulesStore.overrideRulesStore.getState().rules.find(l=>l.id===t.id)?.body:void 0);if(typeof d!=="string"){return{ok:false,error:"bodyPath needs something to patch: send fromRequestId (the captured request whose real response it addresses) or the id of an existing rule."}}if(t.bodyValue===void 0){return{ok:false,error:`Refused: sent \`bodyPath\` without \`bodyValue\`. Say what to set "${t.bodyPath}" to.`}}let i;try{i=JSON.parse(d)}catch{return{ok:false,error:"The captured response body is not JSON, so it cannot be addressed by path. Send a whole `body` instead."}}const u=(0,_sharedUi.patchFromPath)(i,t.bodyPath,t.bodyValue);if(!u.ok)return{ok:false,error:`Refused: ${u.error}`};t.bodyPatch=u.patch;delete t.bodyPath;delete t.bodyValue}if(t&&isPlainObject(t.bodyPatch)&&t.body==null){const d=r?.body??(typeof t.id==="string"?_overrideRulesStore.overrideRulesStore.getState().rules.find(i=>i.id===t.id)?.body:void 0);if(typeof d!=="string"){return{ok:false,error:"bodyPatch needs something to patch: send fromRequestId (the captured request whose real response the patch is merged into) or the id of an existing rule."}}if(t.force!==true){let i;try{const l=(0,_sharedUi.expandKeyedArrays)(JSON.parse(d),t.bodyPatch);i=l.error;if(l.notes.length)t.bodyPatch=l.patch}catch{}if(i){return{ok:false,error:`Refused: ${i}`}}const u=patchViolations(t,d);if(u.length>0){return{ok:false,error:(0,_sharedUi.refusalText)(u,"response body",(0,_sharedUi.suggestedPatch)(t.bodyPatch,u)),violations:u}}}}const o=readRuleDraft(e,r);if(!o){const d=e?.fromRequestId;return{ok:false,error:d?`No captured request \`${d}\` \u2014 it may have been cleared. Send a urlPattern instead.`:"A rule needs a non-empty urlPattern."}}const s=_overrideRulesStore.overrideRulesStore.upsertRule(o);if(!s)return{ok:false,error:"Override rule limit reached."};if(s.enabled)_overrideRulesStore.overrideRulesStore.setEnabled(true);return{ok:true,rule:{id:s.id,urlPattern:s.urlPattern,enabled:s.enabled,kind:s.kind,status:s.status,times:s.times,bodySize:s.body?s.body.length:0},...s.times===void 0||s.times===null?{lingers:`This rule has no \`times\` budget, so it overrides EVERY matching request until it is disabled or deleted (id \`${s.id}\`). If you meant only the next one, set times:1.`}:{},...inactiveStamp()}},setOverrideRuleEnabled:e=>{const t=readId(e);if(!t)return{ok:false,error:"Missing rule id."};_overrideRulesStore.overrideRulesStore.setRuleEnabled(t,readBool(e,"enabled"));return{ok:true,...inactiveStamp()}},deleteOverrideRule:e=>{const t=readId(e);if(!t)return{ok:false,error:"Missing rule id."};_overrideRulesStore.overrideRulesStore.removeRule(t);return{ok:true}},clearOverrideRules:()=>{_overrideRulesStore.overrideRulesStore.clearRules();return{ok:true}},replaceOverrideRules:async e=>{const t=e??{};if(!Array.isArray(t.rules)){return{ok:false,error:"replaceOverrideRules needs `rules`: an array of rules, first match first."}}if(t.rules.length>_types.MAX_RULES){return{ok:false,error:`Too many rules: ${t.rules.length}. The most is ${_types.MAX_RULES}.`}}await _overrideRulesStore.overrideRulesStore.ensureLoaded();const n=_overrideRulesStore.overrideRulesStore.replaceAllRules(t.rules,t.enabled!==false);if(!n)return{ok:false,error:"This copy of the Network tool only mirrors a device, so it can't replace rules."};return{ok:true,count:n.length,enabled:_overrideRulesStore.overrideRulesStore.getState().enabled,...inactiveStamp()}},listOverrideRules:async()=>{await _overrideRulesStore.overrideRulesStore.ensureLoaded();return _overrideRulesStore.overrideRulesStore.getState()},getOverrideRuleBody:e=>{const t=readId(e);if(!t)return null;const n=_overrideRulesStore.overrideRulesStore.getState().rules.find(r=>r.id===t);if(!n)return null;return{body:n.body??null}},getCaptureStatus:()=>{const e=_networkEventStore.networkEventStore.getSubscriberCounts().total;let t=null;let n=null;try{t=(0,_networkListener.isNetworkListening)();n=(0,_networkListener.getNetworkListenerCount)()}catch{}let r=null;try{r=(0,_networkListener.isNetworkInterceptionLive)()}catch{}return{capturing:e>0,subscribers:e,interceptorInstalled:t,interceptorLive:r,listenerCount:n,eventCount:_networkEventStore.networkEventStore.getEvents().length}},debugOverrides:e=>{const{url:t,method:n}=e&&typeof e==="object"?e:{};const r=typeof t==="string"?t:"https://example.com/";const o=typeof n==="string"&&n.trim()?n.trim().toUpperCase():"GET";return{tested:{url:r,method:o},interceptorInstalled:(0,_networkListener.isNetworkListening)(),listenerCount:(0,_networkListener.getNetworkListenerCount)(),engine:(0,_engine.inspectEngine)(r,o),store:{enabled:_overrideRulesStore.overrideRulesStore.getState().enabled,autoPaused:_overrideRulesStore.overrideRulesStore.getState().autoPaused,ruleCount:_overrideRulesStore.overrideRulesStore.getState().rules.length,rulesVisibleToEngine:_overrideRulesStore.overrideRulesStore.getRules().length}}}}};
@@ -1,7 +1,7 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.stopNetworkListener=exports.startNetworkListener=exports.removeAllNetworkListeners=exports.networkListener=exports.isNetworkListening=exports.isNetworkInterceptionLive=exports.getNetworkListenerCount=exports.addNetworkListener=exports.BUOY_XHR_INTERCEPTOR_FLAG=exports.BUOY_FETCH_INTERCEPTOR_FLAG=void 0;var _sharedUi=require("@buoy-gg/shared-ui");var _resolveRequestUrl=require("./resolveRequestUrl");var _requestId=require("./requestId");var _xhr=require("../conditions/xhr");var _store=require("../conditions/store");var _wait=require("../conditions/wait");var _engine=require("../overrides/engine");var _applyToXhr=require("../overrides/applyToXhr");var _applyToFetch=require("../overrides/applyToFetch");var _types=require("../overrides/types");var _httpCompletion=require("./httpCompletion");var _realNow=require("./realNow");let devOrigin;function injectedHeaders(R){const e=globalThis.__buoyHeaderInjectors;if(!e||e.length===0)return void 0;let t;for(const s of e){try{const c=s(R);if(c)t={...t,...c}}catch{}}return t}function devServerOrigin(){if(devOrigin!==void 0)return devOrigin;devOrigin=null;try{if(typeof __DEV__!=="undefined"&&!__DEV__)return devOrigin;const R=require("react-native");const e=R?.NativeModules?.SourceCode;const t=e?.getConstants?.().scriptURL??e?.scriptURL;if(typeof t==="string"&&/^https?:\/\//.test(t)){const s=new URL(t);devOrigin=`${s.protocol}//${s.host}`}}catch{devOrigin=null}return devOrigin}let insideFetchHandoff=false;function headersToRecord(R){const e={};if(!R)return e;if(typeof Headers!=="undefined"&&R instanceof Headers)R.forEach((t,s)=>{e[s]=t});else if(Array.isArray(R))for(const[t,s]of R)e[t]=s;else Object.assign(e,R);return e}const BUOY_FETCH_INTERCEPTOR_FLAG=exports.BUOY_FETCH_INTERCEPTOR_FLAG="__buoyNetworkFetchIntercepted";const BUOY_XHR_INTERCEPTOR_FLAG=exports.BUOY_XHR_INTERCEPTOR_FLAG="__buoyNetworkXhrIntercepted";const STREAMED_CONTENT_TYPES=["text/event-stream","application/x-ndjson","application/stream+json"];const STREAMING_PLACEHOLDER="[streaming\u2026]";let angularPageSeen=false;function isAngularPage(){if(angularPageSeen)return true;const R=globalThis.document;angularPageSeen=!!R?.querySelector?.("[ng-version]");return angularPageSeen}function isStreamedContentType(R){if(!R)return false;const e=R.toLowerCase();return STREAMED_CONTENT_TYPES.some(t=>e.includes(t))}const INTERNAL_HOSTS_KEY="__BUOY_INTERNAL_HOSTS__";function isInternalBuoyHost(R){const e=globalThis[INTERNAL_HOSTS_KEY];if(!(e instanceof Set)||e.size===0)return false;let t;try{t=new URL(R).host.toLowerCase()}catch{return false}for(const s of e){if(typeof s==="string"&&s&&t===s.toLowerCase())return true}return false}class NetworkListener{listeners=[];isListening=false;patchedFetch=null;patchedXHROpen=null;patchedXHRSend=null;patchedXHRSetRequestHeader=null;fetchGeneration=0;xhrGeneration=0;constructor(){this.originalFetch=globalThis.fetch;this.originalXHROpen=XMLHttpRequest.prototype.open;this.originalXHRSend=XMLHttpRequest.prototype.send;this.originalXHRSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader}shouldIgnoreUrl(e){if((0,_sharedUi.isBuoyRequest)(e))return true;try{const t=new URL(e);if(t.hostname==="keygen.sh"||t.hostname.endsWith(".keygen.sh"))return true;if((t.hostname==="buoy.gg"||t.hostname==="www.buoy.gg")&&(t.pathname.startsWith("/api/license")||t.pathname.startsWith("/api/settings/")))return true;const s=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="10.0.2.2";if(s&&["8081","8802"].includes(t.port))return true;const c=devServerOrigin();if(c&&`${t.protocol}//${t.host}`===c)return true}catch{return false}return isInternalBuoyHost(e)}emit(e){this.listeners.forEach(t=>{try{t(e)}catch(s){}})}parseUrl(e){let t=null;const s=e.indexOf("?");if(s>-1){t={};e.substring(s+1).split("&").forEach(c=>{const[a,n]=c.split("=");if(a&&n!==void 0){t[a]=decodeURIComponent(n.replace(/\+/g," "))}})}return{url:s>-1?e.substring(0,s):e,params:t}}async readStreamedBody(e,t=256*1024){const s=e.body;if(!s||typeof s.getReader!=="function"){const f=await e.text();return f.length>t?{body:`${f.slice(0,t)}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.stopNetworkListener=exports.startNetworkListener=exports.removeAllNetworkListeners=exports.networkListener=exports.isNetworkListening=exports.isNetworkInterceptionLive=exports.getNetworkListenerCount=exports.addNetworkListener=exports.BUOY_XHR_INTERCEPTOR_FLAG=exports.BUOY_FETCH_INTERCEPTOR_FLAG=void 0;var _sharedUi=require("@buoy-gg/shared-ui");var _resolveRequestUrl=require("./resolveRequestUrl");var _requestId=require("./requestId");var _xhr=require("../conditions/xhr");var _store=require("../conditions/store");var _wait=require("../conditions/wait");var _engine=require("../overrides/engine");var _applyToXhr=require("../overrides/applyToXhr");var _applyToFetch=require("../overrides/applyToFetch");var _types=require("../overrides/types");var _httpCompletion=require("./httpCompletion");var _realNow=require("./realNow");let devOrigin;function injectedHeaders(g){const e=globalThis.__buoyHeaderInjectors;if(!e||e.length===0)return void 0;let t;for(const r of e){try{const c=r(g);if(c)t={...t,...c}}catch{}}return t}function devServerOrigin(){if(devOrigin!==void 0)return devOrigin;devOrigin=null;try{if(typeof __DEV__!=="undefined"&&!__DEV__)return devOrigin;const g=require("react-native");const e=g?.NativeModules?.SourceCode;const t=e?.getConstants?.().scriptURL??e?.scriptURL;if(typeof t==="string"&&/^https?:\/\//.test(t)){const r=new URL(t);devOrigin=`${r.protocol}//${r.host}`}}catch{devOrigin=null}return devOrigin}let insideFetchHandoff=false;function headersToRecord(g){const e={};if(!g)return e;if(typeof Headers!=="undefined"&&g instanceof Headers)g.forEach((t,r)=>{e[r]=t});else if(Array.isArray(g))for(const[t,r]of g)e[t]=r;else Object.assign(e,g);return e}const BUOY_FETCH_INTERCEPTOR_FLAG=exports.BUOY_FETCH_INTERCEPTOR_FLAG="__buoyNetworkFetchIntercepted";const BUOY_XHR_INTERCEPTOR_FLAG=exports.BUOY_XHR_INTERCEPTOR_FLAG="__buoyNetworkXhrIntercepted";const STREAMED_CONTENT_TYPES=["text/event-stream","application/x-ndjson","application/stream+json"];const STREAMING_PLACEHOLDER="[streaming\u2026]";let angularPageSeen=false;function isAngularPage(){if(angularPageSeen)return true;const g=globalThis.document;angularPageSeen=!!g?.querySelector?.("[ng-version]");return angularPageSeen}function isStreamedContentType(g){if(!g)return false;const e=g.toLowerCase();return STREAMED_CONTENT_TYPES.some(t=>e.includes(t))}const INTERNAL_HOSTS_KEY="__BUOY_INTERNAL_HOSTS__";function isInternalBuoyHost(g){const e=globalThis[INTERNAL_HOSTS_KEY];if(!(e instanceof Set)||e.size===0)return false;let t;try{t=new URL(g).host.toLowerCase()}catch{return false}for(const r of e){if(typeof r==="string"&&r&&t===r.toLowerCase())return true}return false}class NetworkListener{listeners=[];isListening=false;patchedFetch=null;patchedXHROpen=null;patchedXHRSend=null;patchedXHRSetRequestHeader=null;fetchGeneration=0;xhrGeneration=0;constructor(){this.originalFetch=globalThis.fetch;this.originalXHROpen=XMLHttpRequest.prototype.open;this.originalXHRSend=XMLHttpRequest.prototype.send;this.originalXHRSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader}shouldIgnoreUrl(e){if((0,_sharedUi.isBuoyRequest)(e))return true;try{const t=new URL(e);if(t.hostname==="keygen.sh"||t.hostname.endsWith(".keygen.sh"))return true;if((t.hostname==="buoy.gg"||t.hostname==="www.buoy.gg")&&(t.pathname.startsWith("/api/license")||t.pathname.startsWith("/api/settings/")))return true;const r=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="10.0.2.2";if(r&&["8081","8802"].includes(t.port))return true;const c=devServerOrigin();if(c&&`${t.protocol}//${t.host}`===c)return true}catch{return false}return isInternalBuoyHost(e)}emit(e){this.listeners.forEach(t=>{try{t(e)}catch(r){}})}parseUrl(e){let t=null;const r=e.indexOf("?");if(r>-1){t={};e.substring(r+1).split("&").forEach(c=>{const[a,n]=c.split("=");if(a&&n!==void 0){t[a]=decodeURIComponent(n.replace(/\+/g," "))}})}return{url:r>-1?e.substring(0,r):e,params:t}}async readStreamedBody(e,t=256*1024){const r=e.body;if(!r||typeof r.getReader!=="function"){const f=await e.text();return f.length>t?{body:`${f.slice(0,t)}
2
2
 
3
- ... [truncated]`,size:f.length}:{body:f,size:f.length}}const c=s.getReader();const a=new TextDecoder;let n="";let l=0;let m=false;try{for(;;){const{done:f,value:i}=await c.read();if(f)break;l+=i?.byteLength??0;if(!m){n+=a.decode(i,{stream:true});if(l>=t){n=`${n.slice(0,t)}
3
+ ... [truncated]`,size:f.length}:{body:f,size:f.length}}const c=r.getReader();const a=new TextDecoder;let n="";let l=0;let m=false;try{for(;;){const{done:f,value:i}=await c.read();if(f)break;l+=i?.byteLength??0;if(!m){n+=a.decode(i,{stream:true});if(l>=t){n=`${n.slice(0,t)}
4
4
 
5
- ... [truncated]`;m=true;break}}}if(!m)n+=a.decode()}finally{try{void Promise.resolve(c.cancel()).catch(()=>{})}catch{}try{c.releaseLock()}catch{}}return{body:n,size:l}}async processResponseBody(e,t=1024*1024){try{const s=e.headers.get("content-length");if(s){const n=parseInt(s,10);if(!isNaN(n)&&n>t){return{body:`[Response too large: ${this.formatBytes(n)}]`,size:n,truncated:true}}}const c=await e.text();const a=c.length;if(a>t){const n=c.substring(0,t);const l=a-t;return{body:`${n}
5
+ ... [truncated]`;m=true;break}}}if(!m)n+=a.decode()}finally{try{void Promise.resolve(c.cancel()).catch(()=>{})}catch{}try{c.releaseLock()}catch{}}return{body:n,size:l}}async processResponseBody(e,t=1024*1024){try{const r=e.headers.get("content-length");if(r){const n=parseInt(r,10);if(!isNaN(n)&&n>t){return{body:`[Response too large: ${this.formatBytes(n)}]`,size:n,truncated:true}}}const c=await e.text();const a=c.length;if(a>t){const n=c.substring(0,t);const l=a-t;return{body:`${n}
6
6
 
7
- ... [truncated, ${this.formatBytes(l)} omitted]`,size:a,truncated:true}}try{return{body:JSON.parse(c),size:a,truncated:false}}catch{return{body:c,size:a,truncated:false}}}catch(s){return{body:"~~~ unable to read body ~~~",size:0,truncated:false}}}formatBytes(e){if(e===0)return"0 B";const t=1024;const s=["B","KB","MB","GB"];const c=Math.floor(Math.log(e)/Math.log(t));return`${Math.round(e/Math.pow(t,c)*100)/100} ${s[c]}`}handleXHRResponse(e,t,s,c,a,n,l,m,f=false,i="xhr",d,L){const g=m?(0,_realNow.realNow)()-m:0;const h=e._buoyTtfb;const _=h===void 0?void 0:{ttfb:h,download:Math.max(0,g-h)};if(f||e.status===0){this.emit({type:"error",timestamp:new Date,duration:g,request:{id:t||"unknown",url:s,method:c,headers:a,data:n,params:l||void 0,client:i},error:{message:f?"Request failed":"Network error or request aborted"},override:d,condition:L});return}let r;let p=0;try{const o=e.response;if(e.responseType==="json"&&o){r=o;p=JSON.stringify(o).length}else if(e.responseType===""||e.responseType==="text"){if(e.responseText){p=e.responseText.length;try{r=JSON.parse(e.responseText)}catch{r=e.responseText}}}else if(e.responseType==="arraybuffer"){if(o){try{const y=new TextDecoder("utf-8").decode(o);p=y.length;try{r=JSON.parse(y)}catch{r=y}}catch(y){r=`[arraybuffer response - ${o.byteLength||0} bytes]`;p=o.byteLength||0}}else{r=`[arraybuffer response - no data]`;p=0}}else if(e.responseType==="blob"){if(o instanceof Blob){r=`[blob response - ${o.size} bytes, type: ${o.type||"unknown"}]`;p=o.size}else if(o){try{r=typeof o==="string"?JSON.parse(o):o;p=JSON.stringify(r).length}catch{r=`[blob response - unable to parse]`;p=0}}else{r=`[blob response - no data]`;p=0}}else if(o){if(typeof o==="string"){r=o;p=o.length;try{r=JSON.parse(o)}catch{}}else if(typeof o==="object"){r=o;p=JSON.stringify(o).length}else{r=String(o);p=String(o).length}}}catch(o){r="~~~ unable to read body ~~~"}const w={};try{const o=e.getAllResponseHeaders();if(o){o.split("\r\n").forEach(y=>{if(y){const q=y.indexOf(": ");if(q>0){const u=y.substring(0,q).toLowerCase();const b=y.substring(q+2);w[u]=b}}})}}catch{}if((0,_httpCompletion.xhrCompletionKind)(e.status)==="response"){this.emit({type:"response",timestamp:new Date,duration:g,timings:_,request:{id:t||"unknown",url:s,method:c,headers:a,data:n,params:l||void 0,client:i},response:{status:e.status,statusText:(0,_httpCompletion.httpStatusText)(e.status,e.statusText),headers:w,body:r,size:p},override:d,condition:L})}else{this.emit({type:"error",timestamp:new Date,duration:g,request:{id:t||"unknown",url:s,method:c,headers:a,data:n,params:l||void 0,client:i},response:{status:e.status,statusText:e.statusText,headers:w,body:r,size:p},error:{message:"Network Error"},override:d,condition:L})}}isFetchInterceptionLive(){return globalThis.fetch[BUOY_FETCH_INTERCEPTOR_FLAG]===true}isXhrInterceptionLive(){return XMLHttpRequest.prototype.send[BUOY_XHR_INTERCEPTOR_FLAG]===true}isInterceptionLive(){return this.isFetchInterceptionLive()&&this.isXhrInterceptionLive()}startListening(){const e=this.isListening&&this.isFetchInterceptionLive();const t=this.isListening&&this.isXhrInterceptionLive();if(e&&t){return}if(!e){this.installFetchInterceptor()}if(!t){this.installXhrInterceptor()}this.isListening=true;if(__DEV__){}}installFetchInterceptor(){const e=this;const t=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;const s=++this.fetchGeneration;const c=async(a,n)=>{const l=(0,_resolveRequestUrl.resolveRequestUrl)(typeof a==="string"?a:a instanceof URL?a.href:a.url);if(s!==e.fetchGeneration){return t(a,n)}if(n?.__buoyInternal||e.shouldIgnoreUrl(l)){const u=insideFetchHandoff;insideFetchHandoff=true;try{return t(a,n)}finally{insideFetchHandoff=u}}const m=(0,_realNow.realNow)();const f=(0,_requestId.nextRequestId)("fetch");const i=typeof a==="object"&&"method"in a?a:void 0;const d=n?.method??i?.method??"GET";const L=n?.signal!==void 0?n.signal:i?.signal;(0,_wait.throwIfAborted)(L);const g=(0,_store.snapshotNetworkCondition)(l);const{url:h,params:_}=e.parseUrl(l);let r={};const p=n?.headers??i?.headers;if(p){if(p instanceof Headers){p.forEach((u,b)=>{r[b]=u})}else if(Array.isArray(p)){p.forEach(([u,b])=>{r[u]=b})}else{r={...p}}}Object.assign(r,injectedHeaders(l));let w;if(n?.body){if(typeof n.body==="string"){try{w=JSON.parse(n.body)}catch{w=n.body}}else{w=n.body}}const o=r["X-Request-Client"]||r["x-request-client"]||"fetch";const y=g?.profile!=="offline"&&(0,_applyToFetch.canSynthesizeResponse)()?(0,_engine.overrideForRequest)(l,d,r):null;const q=y?(0,_types.markForOutcome)(y):void 0;e.emit({type:"request",timestamp:new Date,request:{id:f||"unknown",url:h,method:d,headers:r,data:w,params:_||void 0,client:o},override:q,condition:g});if(n?.body===void 0&&i?.body&&!i.bodyUsed){try{const u=i.clone();void e.readStreamedBody(u).then(({body:b})=>{try{w=JSON.parse(b)}catch{w=b}e.emit({type:"request-body",timestamp:new Date,request:{id:f||"unknown",url:h,method:d,data:w,client:o}})}).catch(()=>{})}catch{}}try{if(g||y)await(0,_wait.waitBeforeDispatch)((g?.delayMs??0)+(y?.delayMs??0),L);(0,_wait.throwIfAborted)(L);if(g?.profile==="offline")throw new TypeError("Network request failed (Buoy Offline)");if(y?.kind==="fail")throw(0,_applyToFetch.synthesizeFetchError)(y);let u;if(y?.kind==="respond"){u=(0,_applyToFetch.synthesizeResponse)(l,y)}else{const N=insideFetchHandoff;insideFetchHandoff=true;let H;try{H=t(a,n)}finally{insideFetchHandoff=N}u=await H}const b=(0,_realNow.realNow)()-m;const T=typeof u.body?.getReader==="function"||isStreamedContentType(u.headers?.get?.("content-type"));const k=u.clone();const{body:I,size:x}=T?{body:STREAMING_PLACEHOLDER,size:0}:await e.processResponseBody(k);const E=(0,_realNow.realNow)()-m;const X=Math.max(0,E-b);const O=X>0?{ttfb:b,download:X}:void 0;const S={};u.headers.forEach((N,H)=>{S[H.toLowerCase()]=N});e.emit({type:"response",timestamp:new Date,duration:E,timings:O,request:{id:f||"unknown",url:h,method:d,headers:r,data:w,params:_||void 0,client:o},response:{status:u.status,statusText:u.statusText,headers:S,body:I,size:x},override:q,condition:g});if(T){const N=u.headers?.get?.("content-type");void e.readStreamedBody(k,isStreamedContentType(N)?void 0:1024*1024).then(H=>{let v=H.body;if(N?.includes("json")){try{v=JSON.parse(H.body)}catch{}}e.emit({type:"response",timestamp:new Date,duration:(0,_realNow.realNow)()-m,timings:O,request:{id:f||"unknown",url:h,method:d,headers:r,data:w,params:_||void 0,client:o},response:{status:u.status,statusText:u.statusText,headers:S,body:v,size:H.size},override:q,condition:g})}).catch(()=>{})}return u}catch(u){const b=(0,_realNow.realNow)()-m;e.emit({type:"error",timestamp:new Date,duration:b,request:{id:f||"unknown",url:h,method:d,headers:r,data:w,params:_||void 0,client:o},error:{message:u instanceof Error?u.message:"Network error",stack:u instanceof Error?u.stack:void 0},override:q,condition:g});throw u}};c[BUOY_FETCH_INTERCEPTOR_FLAG]=true;this.patchedFetch=c;globalThis.fetch=this.patchedFetch}installXhrInterceptor(){const e=this;const t=XMLHttpRequest.prototype.open;const s=XMLHttpRequest.prototype.send;const c=XMLHttpRequest.prototype.setRequestHeader;this.originalXHROpen=t;this.originalXHRSend=s;this.originalXHRSetRequestHeader=c;const a=++this.xhrGeneration;const n=new WeakMap;const l=function(i,d,L,g,h){const _=t.call(this,i,d,L??true,g,h);if(a===e.xhrGeneration){n.get(this)?.();const r=this;r._buoyRequestId=(0,_requestId.nextRequestId)("xhr");r._method=i;r._url=(0,_resolveRequestUrl.resolveRequestUrl)(d);r._buoyStartTime=(0,_realNow.realNow)();r._requestHeaders={}}return _};const m=function(i,d){const L=this;if(a===e.xhrGeneration&&L._requestHeaders){L._requestHeaders[i]=d}return c.call(this,i,d)};const f=function(i){if(a!==e.xhrGeneration||insideFetchHandoff){return s.call(this,i)}if((0,_applyToXhr.hasPendingStandardRequest)(this))throw new DOMException("The request has already been sent.","InvalidStateError");if(this.readyState!==1||this._sent){return s.call(this,i)}const d=this;const L=d._buoyRequestId;const g=d._method||"GET";const h=d._url||"";const _=(0,_realNow.realNow)();d._buoyStartTime=_;d._buoyTtfb=void 0;const r=d._requestHeaders||{};Object.assign(r,injectedHeaders(h));if(e.shouldIgnoreUrl(h)){return s.call(this,i)}const{url:p,params:w}=e.parseUrl(h);let o;if(i){if(typeof i==="string"){try{o=JSON.parse(i)}catch{o=i}}else{o=i}}const y=r["X-Request-Client"]||r["x-request-client"];const q=r["Accept"]||r["accept"]||"";const u=q.includes("application/json")&&q.includes("text/plain")&&q.includes("*/*")&&!isAngularPage();const b=y||(u?"axios":"xhr");const T=(0,_store.snapshotNetworkCondition)(h);const k=T?.profile==="offline"?null:(0,_engine.overrideForRequest)(h,g,r);const I=k?(0,_types.markForOutcome)(k):void 0;e.emit({type:"request",timestamp:new Date,request:{id:L||"unknown",url:p,method:g,headers:r,data:o,params:w||void 0,client:b},override:I,condition:T});let x=false;const E=(v=false)=>{if(x)return;x=true;e.handleXHRResponse(this,L||"unknown",p,g,r,o,w,_||0,v,b,I,T);X()};const X=()=>{n.delete(this);this.removeEventListener("load",O);this.removeEventListener("error",S);this.removeEventListener("abort",N);this.removeEventListener("readystatechange",H)};n.set(this,X);const O=()=>{E(false)};const S=()=>{E(true)};const N=()=>{E(true)};const H=()=>{if(this.readyState===2){const v=this;if(v._buoyTtfb===void 0&&v._buoyStartTime){v._buoyTtfb=(0,_realNow.realNow)()-v._buoyStartTime}}if(this.readyState===4&&!x){E(false)}};this.addEventListener("load",O);this.addEventListener("error",S);this.addEventListener("abort",N);this.addEventListener("readystatechange",H);if(T){(0,_xhr.runConditionXhr)(this,h,T,k,()=>s.call(this,i));return}if(k){const v=(0,_applyToXhr.runOverride)(this,h,k,()=>s.call(this,i));if(v)return}return s.call(this,i)};f[BUOY_XHR_INTERCEPTOR_FLAG]=true;this.patchedXHROpen=l;this.patchedXHRSend=f;this.patchedXHRSetRequestHeader=m;XMLHttpRequest.prototype.open=this.patchedXHROpen;XMLHttpRequest.prototype.send=this.patchedXHRSend;XMLHttpRequest.prototype.setRequestHeader=this.patchedXHRSetRequestHeader}stopListening(){if(!this.isListening){return}this.fetchGeneration++;this.xhrGeneration++;if(this.patchedFetch&&globalThis.fetch===this.patchedFetch){globalThis.fetch=this.originalFetch}if(this.patchedXHROpen&&XMLHttpRequest.prototype.open===this.patchedXHROpen){XMLHttpRequest.prototype.open=this.originalXHROpen}if(this.patchedXHRSend&&XMLHttpRequest.prototype.send===this.patchedXHRSend){XMLHttpRequest.prototype.send=this.originalXHRSend}if(this.patchedXHRSetRequestHeader&&XMLHttpRequest.prototype.setRequestHeader===this.patchedXHRSetRequestHeader){XMLHttpRequest.prototype.setRequestHeader=this.originalXHRSetRequestHeader}this.patchedFetch=null;this.patchedXHROpen=null;this.patchedXHRSend=null;this.patchedXHRSetRequestHeader=null;this.isListening=false;if(__DEV__){}}adoptEarlyRequests(){const e=globalThis.__BUOY_EARLY_NETWORK__;if(e?.version!==1)return;for(const t of e.adopt()){try{if(t.kind==="fetch")this.adoptEarlyFetch(t);else this.adoptEarlyXhr(t)}catch{}}}adoptEarlyFetch(e){const{input:t,init:s}=e;const c=typeof t==="object"&&"method"in t?t:void 0;const a=(0,_resolveRequestUrl.resolveRequestUrl)(typeof t==="string"?t:t instanceof URL?t.href:t.url);if(this.shouldIgnoreUrl(a))return;const n=(0,_requestId.nextRequestId)("fetch");const l=s?.method??c?.method??"GET";const{url:m,params:f}=this.parseUrl(a);const i=headersToRecord(s?.headers??c?.headers);let d=s?.body;if(typeof d==="string"){try{d=JSON.parse(d)}catch{}}const L=i["X-Request-Client"]||i["x-request-client"]||"fetch";const g=()=>({id:n,url:m,method:l,headers:i,data:d,params:f||void 0,client:L});this.emit({type:"request",timestamp:new Date(e.start),request:g()});if(e.requestCopy){void this.readStreamedBody(e.requestCopy).then(({body:h})=>{try{d=JSON.parse(h)}catch{d=h}this.emit({type:"request-body",timestamp:new Date,request:{id:n,url:m,method:l,data:d,client:L}})}).catch(()=>{})}void e.settled.then(async({response:h,clone:_,error:r,headersAt:p})=>{if(!h){this.emit({type:"error",timestamp:new Date,duration:p-e.start,request:g(),error:{message:r instanceof Error?r.message:"Network error",stack:r instanceof Error?r.stack:void 0}});return}const{body:w,size:o}=_?await this.processResponseBody(_):{body:STREAMING_PLACEHOLDER,size:0};const y=Math.max(0,(0,_realNow.realNow)()-e.start);const q=p-e.start;const u={};h.headers.forEach((b,T)=>{u[T.toLowerCase()]=b});this.emit({type:"response",timestamp:new Date,duration:y,timings:y>q?{ttfb:q,download:y-q}:void 0,request:g(),response:{status:h.status,statusText:h.statusText,headers:u,body:w,size:o}})})}adoptEarlyXhr(e){const t=(0,_resolveRequestUrl.resolveRequestUrl)(e.url);if(this.shouldIgnoreUrl(t))return;const s=(0,_requestId.nextRequestId)("xhr");const c=e.method.toUpperCase();const{url:a,params:n}=this.parseUrl(t);let l=e.body;if(typeof l==="string"){try{l=JSON.parse(l)}catch{}}const m=e.headers["X-Request-Client"]||e.headers["x-request-client"]||"xhr";this.emit({type:"request",timestamp:new Date(e.start),request:{id:s,url:a,method:c,headers:e.headers,data:l,params:n||void 0,client:m}});const f=e.xhr;const i=()=>{const d=(f._buoyEarlyEnd??(0,_realNow.realNow)())-e.start;this.handleXHRResponse(f,s,a,c,e.headers,l,n,(0,_realNow.realNow)()-d,false,m)};if(f.readyState===4)i();else f.addEventListener("loadend",i,{once:true})}addListener(e){this.listeners.push(e);return()=>{const t=this.listeners.indexOf(e);if(t>-1){this.listeners.splice(t,1)}}}removeAllListeners(){this.listeners=[]}get isActive(){return this.isListening}get listenerCount(){return this.listeners.length}}let _networkListener=null;const getNetworkListener=()=>{if(!_networkListener){_networkListener=new NetworkListener}return _networkListener};const networkListener=exports.networkListener=getNetworkListener;const startNetworkListener=()=>getNetworkListener().startListening();exports.startNetworkListener=startNetworkListener;const stopNetworkListener=()=>_networkListener?.stopListening();exports.stopNetworkListener=stopNetworkListener;const addNetworkListener=R=>getNetworkListener().addListener(R);exports.addNetworkListener=addNetworkListener;const removeAllNetworkListeners=()=>_networkListener?.removeAllListeners();exports.removeAllNetworkListeners=removeAllNetworkListeners;const isNetworkListening=()=>_networkListener?.isActive??false;exports.isNetworkListening=isNetworkListening;const getNetworkListenerCount=()=>_networkListener?.listenerCount??0;exports.getNetworkListenerCount=getNetworkListenerCount;const isNetworkInterceptionLive=()=>_networkListener?.isInterceptionLive()??false;exports.isNetworkInterceptionLive=isNetworkInterceptionLive;
7
+ ... [truncated, ${this.formatBytes(l)} omitted]`,size:a,truncated:true}}try{return{body:JSON.parse(c),size:a,truncated:false}}catch{return{body:c,size:a,truncated:false}}}catch(r){return{body:"~~~ unable to read body ~~~",size:0,truncated:false}}}formatBytes(e){if(e===0)return"0 B";const t=1024;const r=["B","KB","MB","GB"];const c=Math.floor(Math.log(e)/Math.log(t));return`${Math.round(e/Math.pow(t,c)*100)/100} ${r[c]}`}handleXHRResponse(e,t,r,c,a,n,l,m,f=false,i="xhr",d,L){const y=m?(0,_realNow.realNow)()-m:0;const h=e._buoyTtfb;const H=h===void 0?void 0:{ttfb:h,download:Math.max(0,y-h)};if(f||e.status===0){this.emit({type:"error",timestamp:new Date,duration:y,request:{id:t||"unknown",url:r,method:c,headers:a,data:n,params:l||void 0,client:i},error:{message:f?"Request failed":"Network error or request aborted"},override:d,condition:L});return}let s;let p=0;try{const o=e.response;if(e.responseType==="json"&&o){s=o;p=JSON.stringify(o).length}else if(e.responseType===""||e.responseType==="text"){if(e.responseText){p=e.responseText.length;try{s=JSON.parse(e.responseText)}catch{s=e.responseText}}}else if(e.responseType==="arraybuffer"){if(o){try{const q=new TextDecoder("utf-8").decode(o);p=q.length;try{s=JSON.parse(q)}catch{s=q}}catch(q){s=`[arraybuffer response - ${o.byteLength||0} bytes]`;p=o.byteLength||0}}else{s=`[arraybuffer response - no data]`;p=0}}else if(e.responseType==="blob"){if(o instanceof Blob){s=`[blob response - ${o.size} bytes, type: ${o.type||"unknown"}]`;p=o.size}else if(o){try{s=typeof o==="string"?JSON.parse(o):o;p=JSON.stringify(s).length}catch{s=`[blob response - unable to parse]`;p=0}}else{s=`[blob response - no data]`;p=0}}else if(o){if(typeof o==="string"){s=o;p=o.length;try{s=JSON.parse(o)}catch{}}else if(typeof o==="object"){s=o;p=JSON.stringify(o).length}else{s=String(o);p=String(o).length}}}catch(o){s="~~~ unable to read body ~~~"}const w={};try{const o=e.getAllResponseHeaders();if(o){o.split("\r\n").forEach(q=>{if(q){const R=q.indexOf(": ");if(R>0){const v=q.substring(0,R).toLowerCase();const u=q.substring(R+2);w[v]=u}}})}}catch{}if((0,_httpCompletion.xhrCompletionKind)(e.status)==="response"){this.emit({type:"response",timestamp:new Date,duration:y,timings:H,request:{id:t||"unknown",url:r,method:c,headers:a,data:n,params:l||void 0,client:i},response:{status:e.status,statusText:(0,_httpCompletion.httpStatusText)(e.status,e.statusText),headers:w,body:s,size:p},override:d,condition:L})}else{this.emit({type:"error",timestamp:new Date,duration:y,request:{id:t||"unknown",url:r,method:c,headers:a,data:n,params:l||void 0,client:i},response:{status:e.status,statusText:e.statusText,headers:w,body:s,size:p},error:{message:"Network Error"},override:d,condition:L})}}isFetchInterceptionLive(){return globalThis.fetch[BUOY_FETCH_INTERCEPTOR_FLAG]===true}isXhrInterceptionLive(){return XMLHttpRequest.prototype.send[BUOY_XHR_INTERCEPTOR_FLAG]===true}isInterceptionLive(){return this.isFetchInterceptionLive()&&this.isXhrInterceptionLive()}startListening(){const e=this.isListening&&this.isFetchInterceptionLive();const t=this.isListening&&this.isXhrInterceptionLive();if(e&&t){return}if(!e){this.installFetchInterceptor()}if(!t){this.installXhrInterceptor()}this.isListening=true;if(__DEV__){}}installFetchInterceptor(){const e=this;const t=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;const r=++this.fetchGeneration;const c=async(a,n)=>{const l=(0,_resolveRequestUrl.resolveRequestUrl)(typeof a==="string"?a:a instanceof URL?a.href:a.url);if(r!==e.fetchGeneration){return t(a,n)}if(n?.__buoyInternal||e.shouldIgnoreUrl(l)){const u=insideFetchHandoff;insideFetchHandoff=true;try{return t(a,n)}finally{insideFetchHandoff=u}}const m=(0,_realNow.realNow)();const f=(0,_requestId.nextRequestId)("fetch");const i=typeof a==="object"&&"method"in a?a:void 0;const d=n?.method??i?.method??"GET";const L=n?.signal!==void 0?n.signal:i?.signal;(0,_wait.throwIfAborted)(L);const y=(0,_store.snapshotNetworkCondition)(l);const{url:h,params:H}=e.parseUrl(l);let s={};const p=n?.headers??i?.headers;if(p){if(p instanceof Headers){p.forEach((u,b)=>{s[b]=u})}else if(Array.isArray(p)){p.forEach(([u,b])=>{s[u]=b})}else{s={...p}}}Object.assign(s,injectedHeaders(l));let w;if(n?.body){if(typeof n.body==="string"){try{w=JSON.parse(n.body)}catch{w=n.body}}else{w=n.body}}const o=s["X-Request-Client"]||s["x-request-client"]||"fetch";const q=y?.profile!=="offline"&&(0,_applyToFetch.canSynthesizeResponse)()?(0,_engine.accountCheckFor)(l,d,s,typeof n?.body==="string"?n.body:void 0):null;if(q)await q;const R=y?.profile!=="offline"&&(0,_applyToFetch.canSynthesizeResponse)()?(0,_engine.overrideForRequest)(l,d,s,typeof n?.body==="string"?n.body:void 0):null;const v=R?(0,_types.markForOutcome)(R):void 0;e.emit({type:"request",timestamp:new Date,request:{id:f||"unknown",url:h,method:d,headers:s,data:w,params:H||void 0,client:o},override:v,condition:y});if(n?.body===void 0&&i?.body&&!i.bodyUsed){try{const u=i.clone();void e.readStreamedBody(u).then(({body:b})=>{try{w=JSON.parse(b)}catch{w=b}e.emit({type:"request-body",timestamp:new Date,request:{id:f||"unknown",url:h,method:d,data:w,client:o}})}).catch(()=>{})}catch{}}try{if(y||R)await(0,_wait.waitBeforeDispatch)((y?.delayMs??0)+(R?.delayMs??0),L);(0,_wait.throwIfAborted)(L);if(y?.profile==="offline")throw new TypeError("Network request failed (Buoy Offline)");if(R?.kind==="fail")throw(0,_applyToFetch.synthesizeFetchError)(R);let u;if(R?.kind==="respond"){u=(0,_applyToFetch.synthesizeResponse)(l,R)}else{const T=insideFetchHandoff;insideFetchHandoff=true;let _;try{_=t(a,n)}finally{insideFetchHandoff=T}u=await _}const b=(0,_realNow.realNow)()-m;const N=typeof u.body?.getReader==="function"||isStreamedContentType(u.headers?.get?.("content-type"));const S=u.clone();const{body:x,size:k}=N?{body:STREAMING_PLACEHOLDER,size:0}:await e.processResponseBody(S);const X=(0,_realNow.realNow)()-m;const O=Math.max(0,X-b);const I=O>0?{ttfb:b,download:O}:void 0;const E={};u.headers.forEach((T,_)=>{E[_.toLowerCase()]=T});e.emit({type:"response",timestamp:new Date,duration:X,timings:I,request:{id:f||"unknown",url:h,method:d,headers:s,data:w,params:H||void 0,client:o},response:{status:u.status,statusText:u.statusText,headers:E,body:x,size:k},override:v,condition:y});if(N){const T=u.headers?.get?.("content-type");void e.readStreamedBody(S,isStreamedContentType(T)?void 0:1024*1024).then(_=>{let C=_.body;if(T?.includes("json")){try{C=JSON.parse(_.body)}catch{}}e.emit({type:"response",timestamp:new Date,duration:(0,_realNow.realNow)()-m,timings:I,request:{id:f||"unknown",url:h,method:d,headers:s,data:w,params:H||void 0,client:o},response:{status:u.status,statusText:u.statusText,headers:E,body:C,size:_.size},override:v,condition:y})}).catch(()=>{})}return u}catch(u){const b=(0,_realNow.realNow)()-m;e.emit({type:"error",timestamp:new Date,duration:b,request:{id:f||"unknown",url:h,method:d,headers:s,data:w,params:H||void 0,client:o},error:{message:u instanceof Error?u.message:"Network error",stack:u instanceof Error?u.stack:void 0},override:v,condition:y});throw u}};c[BUOY_FETCH_INTERCEPTOR_FLAG]=true;this.patchedFetch=c;globalThis.fetch=this.patchedFetch}installXhrInterceptor(){const e=this;const t=XMLHttpRequest.prototype.open;const r=XMLHttpRequest.prototype.send;const c=XMLHttpRequest.prototype.setRequestHeader;this.originalXHROpen=t;this.originalXHRSend=r;this.originalXHRSetRequestHeader=c;const a=++this.xhrGeneration;const n=new WeakMap;const l=function(i,d,L,y,h){const H=t.call(this,i,d,L??true,y,h);if(a===e.xhrGeneration){n.get(this)?.();const s=this;s._buoyRequestId=(0,_requestId.nextRequestId)("xhr");s._method=i;s._url=(0,_resolveRequestUrl.resolveRequestUrl)(d);s._buoyStartTime=(0,_realNow.realNow)();s._requestHeaders={}}return H};const m=function(i,d){const L=this;if(a===e.xhrGeneration&&L._requestHeaders){L._requestHeaders[i]=d}return c.call(this,i,d)};const f=function(i){if(a!==e.xhrGeneration||insideFetchHandoff){return r.call(this,i)}if((0,_applyToXhr.hasPendingStandardRequest)(this))throw new DOMException("The request has already been sent.","InvalidStateError");if(this.readyState!==1||this._sent){return r.call(this,i)}const d=this;const L=d._buoyRequestId;const y=d._method||"GET";const h=d._url||"";const H=(0,_realNow.realNow)();d._buoyStartTime=H;d._buoyTtfb=void 0;const s=d._requestHeaders||{};Object.assign(s,injectedHeaders(h));if(e.shouldIgnoreUrl(h)){return r.call(this,i)}const{url:p,params:w}=e.parseUrl(h);let o;if(i){if(typeof i==="string"){try{o=JSON.parse(i)}catch{o=i}}else{o=i}}const q=s["X-Request-Client"]||s["x-request-client"];const R=s["Accept"]||s["accept"]||"";const v=R.includes("application/json")&&R.includes("text/plain")&&R.includes("*/*")&&!isAngularPage();const u=q||(v?"axios":"xhr");const b=(0,_store.snapshotNetworkCondition)(h);const N=b?.profile==="offline"?null:(0,_engine.overrideForRequest)(h,y,s,typeof i==="string"?i:void 0);const S=N?(0,_types.markForOutcome)(N):void 0;e.emit({type:"request",timestamp:new Date,request:{id:L||"unknown",url:p,method:y,headers:s,data:o,params:w||void 0,client:u},override:S,condition:b});let x=false;const k=(_=false)=>{if(x)return;x=true;e.handleXHRResponse(this,L||"unknown",p,y,s,o,w,H||0,_,u,S,b);X()};const X=()=>{n.delete(this);this.removeEventListener("load",O);this.removeEventListener("error",I);this.removeEventListener("abort",E);this.removeEventListener("readystatechange",T)};n.set(this,X);const O=()=>{k(false)};const I=()=>{k(true)};const E=()=>{k(true)};const T=()=>{if(this.readyState===2){const _=this;if(_._buoyTtfb===void 0&&_._buoyStartTime){_._buoyTtfb=(0,_realNow.realNow)()-_._buoyStartTime}}if(this.readyState===4&&!x){k(false)}};this.addEventListener("load",O);this.addEventListener("error",I);this.addEventListener("abort",E);this.addEventListener("readystatechange",T);if(b){(0,_xhr.runConditionXhr)(this,h,b,N,()=>r.call(this,i));return}if(N){const _=(0,_applyToXhr.runOverride)(this,h,N,()=>r.call(this,i));if(_)return}return r.call(this,i)};f[BUOY_XHR_INTERCEPTOR_FLAG]=true;this.patchedXHROpen=l;this.patchedXHRSend=f;this.patchedXHRSetRequestHeader=m;XMLHttpRequest.prototype.open=this.patchedXHROpen;XMLHttpRequest.prototype.send=this.patchedXHRSend;XMLHttpRequest.prototype.setRequestHeader=this.patchedXHRSetRequestHeader}stopListening(){if(!this.isListening){return}this.fetchGeneration++;this.xhrGeneration++;if(this.patchedFetch&&globalThis.fetch===this.patchedFetch){globalThis.fetch=this.originalFetch}if(this.patchedXHROpen&&XMLHttpRequest.prototype.open===this.patchedXHROpen){XMLHttpRequest.prototype.open=this.originalXHROpen}if(this.patchedXHRSend&&XMLHttpRequest.prototype.send===this.patchedXHRSend){XMLHttpRequest.prototype.send=this.originalXHRSend}if(this.patchedXHRSetRequestHeader&&XMLHttpRequest.prototype.setRequestHeader===this.patchedXHRSetRequestHeader){XMLHttpRequest.prototype.setRequestHeader=this.originalXHRSetRequestHeader}this.patchedFetch=null;this.patchedXHROpen=null;this.patchedXHRSend=null;this.patchedXHRSetRequestHeader=null;this.isListening=false;if(__DEV__){}}adoptEarlyRequests(){const e=globalThis.__BUOY_EARLY_NETWORK__;if(e?.version!==1)return;for(const t of e.adopt()){try{if(t.kind==="fetch")this.adoptEarlyFetch(t);else this.adoptEarlyXhr(t)}catch{}}}adoptEarlyFetch(e){const{input:t,init:r}=e;const c=typeof t==="object"&&"method"in t?t:void 0;const a=(0,_resolveRequestUrl.resolveRequestUrl)(typeof t==="string"?t:t instanceof URL?t.href:t.url);if(this.shouldIgnoreUrl(a))return;const n=(0,_requestId.nextRequestId)("fetch");const l=r?.method??c?.method??"GET";const{url:m,params:f}=this.parseUrl(a);const i=headersToRecord(r?.headers??c?.headers);let d=r?.body;if(typeof d==="string"){try{d=JSON.parse(d)}catch{}}const L=i["X-Request-Client"]||i["x-request-client"]||"fetch";const y=()=>({id:n,url:m,method:l,headers:i,data:d,params:f||void 0,client:L});this.emit({type:"request",timestamp:new Date(e.start),request:y()});if(e.requestCopy){void this.readStreamedBody(e.requestCopy).then(({body:h})=>{try{d=JSON.parse(h)}catch{d=h}this.emit({type:"request-body",timestamp:new Date,request:{id:n,url:m,method:l,data:d,client:L}})}).catch(()=>{})}void e.settled.then(async({response:h,clone:H,error:s,headersAt:p})=>{if(!h){this.emit({type:"error",timestamp:new Date,duration:p-e.start,request:y(),error:{message:s instanceof Error?s.message:"Network error",stack:s instanceof Error?s.stack:void 0}});return}const{body:w,size:o}=H?await this.processResponseBody(H):{body:STREAMING_PLACEHOLDER,size:0};const q=Math.max(0,(0,_realNow.realNow)()-e.start);const R=p-e.start;const v={};h.headers.forEach((u,b)=>{v[b.toLowerCase()]=u});this.emit({type:"response",timestamp:new Date,duration:q,timings:q>R?{ttfb:R,download:q-R}:void 0,request:y(),response:{status:h.status,statusText:h.statusText,headers:v,body:w,size:o}})})}adoptEarlyXhr(e){const t=(0,_resolveRequestUrl.resolveRequestUrl)(e.url);if(this.shouldIgnoreUrl(t))return;const r=(0,_requestId.nextRequestId)("xhr");const c=e.method.toUpperCase();const{url:a,params:n}=this.parseUrl(t);let l=e.body;if(typeof l==="string"){try{l=JSON.parse(l)}catch{}}const m=e.headers["X-Request-Client"]||e.headers["x-request-client"]||"xhr";this.emit({type:"request",timestamp:new Date(e.start),request:{id:r,url:a,method:c,headers:e.headers,data:l,params:n||void 0,client:m}});const f=e.xhr;const i=()=>{const d=(f._buoyEarlyEnd??(0,_realNow.realNow)())-e.start;this.handleXHRResponse(f,r,a,c,e.headers,l,n,(0,_realNow.realNow)()-d,false,m)};if(f.readyState===4)i();else f.addEventListener("loadend",i,{once:true})}addListener(e){this.listeners.push(e);return()=>{const t=this.listeners.indexOf(e);if(t>-1){this.listeners.splice(t,1)}}}removeAllListeners(){this.listeners=[]}get isActive(){return this.isListening}get listenerCount(){return this.listeners.length}}let _networkListener=null;const getNetworkListener=()=>{if(!_networkListener){_networkListener=new NetworkListener}return _networkListener};const networkListener=exports.networkListener=getNetworkListener;const startNetworkListener=()=>getNetworkListener().startListening();exports.startNetworkListener=startNetworkListener;const stopNetworkListener=()=>_networkListener?.stopListening();exports.stopNetworkListener=stopNetworkListener;const addNetworkListener=g=>getNetworkListener().addListener(g);exports.addNetworkListener=addNetworkListener;const removeAllNetworkListeners=()=>_networkListener?.removeAllListeners();exports.removeAllNetworkListeners=removeAllNetworkListeners;const isNetworkListening=()=>_networkListener?.isActive??false;exports.isNetworkListening=isNetworkListening;const getNetworkListenerCount=()=>_networkListener?.listenerCount??0;exports.getNetworkListenerCount=getNetworkListenerCount;const isNetworkInterceptionLive=()=>_networkListener?.isInterceptionLive()??false;exports.isNetworkInterceptionLive=isNetworkInterceptionLive;
@@ -1 +1 @@
1
- "use strict";export const sleep=e=>e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve();export function canSynthesizeResponse(){return typeof Response==="function"}export function synthesizeResponse(e,t){const s=new Response(t.body,{status:t.status,statusText:t.statusText,headers:t.headers});try{Object.defineProperty(s,"url",{value:e,configurable:true})}catch{}return s}export function synthesizeFetchError(e){return new TypeError(e.failKind==="timeout"?"Network request timed out":"Network request failed")}
1
+ "use strict";export const NULL_BODY_STATUSES=[204,205,304];export const sleep=t=>t>0?new Promise(e=>setTimeout(e,t)):Promise.resolve();export function canSynthesizeResponse(){return typeof Response==="function"}export function synthesizeResponse(t,e){const r=NULL_BODY_STATUSES.includes(e.status)?null:e.body;const s=new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers});try{Object.defineProperty(s,"url",{value:t,configurable:true})}catch{}return s}export function synthesizeFetchError(t){return new TypeError(t.failKind==="timeout"?"Network request timed out":"Network request failed")}
@@ -1 +1 @@
1
- "use strict";import{hasAccountAccess as i}from"@buoy-gg/shared-ui";import{findMatchingRule as u,shouldApply as c,toOutcome as d}from"./resolveOverride";let e=null;export function setOverrideHooks(n){e=n}export function overridesCanApply(){return i()&&!(typeof __DEV__!=="undefined"&&!__DEV__)}export const OVERRIDES_INACTIVE_REASON="Response overrides never apply in a release build \u2014 the rule is saved but will not affect any request.";export function inspectEngine(n,r){return{hooksInstalled:e!==null,devFlag:typeof __DEV__==="undefined"?"undefined":__DEV__,ruleCount:e?e.getRules().length:0,matches:e?u(n,r,e.getRules())!==null:false}}export function overrideForRequest(n,r,o){if(!e)return null;if(!overridesCanApply())return null;const l=e.getRules();if(l.length===0)return null;const t=u(n,r,l,o);if(!t)return null;const s=c(t);e.recordMatch(t.id);if(!s)return null;e.recordHit(t.id);return d(t)}
1
+ "use strict";import{getAccountAccess as c,hasAccountAccess as f,subscribeAccountAccess as a}from"@buoy-gg/shared-ui";import{findMatchingRule as s,shouldApply as d,toOutcome as p}from"./resolveOverride";import{realClearTimeout as g,realSetTimeout as m}from"../utils/realNow";let e=null;export function setOverrideHooks(n){e=n}export function overridesCanApply(){return f()&&!(typeof __DEV__!=="undefined"&&!__DEV__)}export const OVERRIDES_INACTIVE_REASON="Response overrides never apply in a release build \u2014 the rule is saved but will not affect any request.";export function inspectEngine(n,r){return{hooksInstalled:e!==null,devFlag:typeof __DEV__==="undefined"?"undefined":__DEV__,ruleCount:e?e.getRules().length:0,matches:e?s(n,r,e.getRules())!==null:false}}const A=3e3;export function accountCheckFor(n,r,o,i){if(!e||f())return null;if(typeof __DEV__!=="undefined"&&!__DEV__)return null;if(c().status!=="initializing")return null;if(!s(n,r,e.getRules(),o,i))return null;return new Promise(u=>{let t=()=>{};const l=()=>{g(_);t();u()};const _=m(l,A);t=a(()=>{if(c().status!=="initializing")l()})})}export function overrideForRequest(n,r,o,i){if(!e)return null;if(!overridesCanApply())return null;const u=e.getRules();if(u.length===0)return null;const t=s(n,r,u,o,i);if(!t)return null;const l=d(t);e.recordMatch(t.id);if(!l)return null;e.recordHit(t.id);return p(t)}
@@ -1 +1 @@
1
- "use strict";const o="[]{}()\\.^$+|-,?";export function escapeRegex(e){let r="";for(let n=0;n<e.length;n++){const t=e.charAt(n);if(o.indexOf(t)!==-1){r+="\\"}r+=t}return r.split("*").join(".*")}const s=new Map;export function compilePattern(e){const r=s.get(e);if(r)return r;const n=e.startsWith("/")?`[a-zA-Z][a-zA-Z0-9+.-]*://[^/]*${escapeRegex(e)}`:escapeRegex(e);const t=new RegExp(`^${n}$`);if(s.size>200)s.clear();s.set(e,t);return t}function c(e,r){if(!e)return false;const n=r.toLowerCase();for(const t of Object.keys(e)){if(t.toLowerCase()===n&&e[t]!==void 0&&e[t]!=="")return true}return false}export function ruleMatches(e,r,n,t){if(e.methods&&e.methods.length>0){if(!e.methods.includes(n.toUpperCase()))return false}if(e.requireHeader&&!c(t,e.requireHeader))return false;try{return compilePattern(e.urlPattern).test(r)}catch{return false}}
1
+ "use strict";const c="[]{}()\\.^$+|-,?";export function escapeRegex(e){let n="";for(let r=0;r<e.length;r++){const t=e.charAt(r);if(c.indexOf(t)!==-1){n+="\\"}n+=t}return n.split("*").join(".*")}const s=new Map;export function compilePattern(e){const n=s.get(e);if(n)return n;const r=e.startsWith("/")?`[a-zA-Z][a-zA-Z0-9+.-]*://[^/]*${escapeRegex(e)}`:escapeRegex(e);const t=new RegExp(`^${r}$`);if(s.size>200)s.clear();s.set(e,t);return t}function i(e,n){if(!e)return false;const r=n.toLowerCase();for(const t of Object.keys(e)){if(t.toLowerCase()===r&&e[t]!==void 0&&e[t]!=="")return true}return false}export function ruleMatches(e,n,r,t,o){if(e.methods&&e.methods.length>0){if(!e.methods.includes(r.toUpperCase()))return false}if(e.requireHeader&&!i(t,e.requireHeader))return false;if(e.bodyIncludes&&(typeof o!=="string"||!o.includes(e.bodyIncludes)))return false;try{return compilePattern(e.urlPattern).test(n)}catch{return false}}
@@ -1 +1 @@
1
- "use strict";import{devToolsStorageKeys as h,persistentStorage as a}from"@buoy-gg/shared-ui";import{addNetworkListener as f,getNetworkListenerCount as o,startNetworkListener as p,stopNetworkListener as d}from"../utils/networkListener";import{setOverrideHooks as b}from"./engine";import{isSpent as y}from"./resolveOverride";import{MAX_RULES as u,STATUS_MAX as k,STATUS_MIN as E}from"./types";import{realNow as c}from"../utils/realNow";const S=800;const g=3;const A=Object.freeze([]);const R=250;const v=["respond","fail","delay"];function T(n){if(!Array.isArray(n))return[];const t=[];for(const i of n){if(!i||typeof i!=="object")continue;const e=i;if(typeof e.id!=="string"||typeof e.urlPattern!=="string"){continue}if(!e.urlPattern)continue;const s=v.includes(e.kind)?e.kind:"respond";t.push({id:e.id,enabled:e.enabled!==false,name:typeof e.name==="string"?e.name:void 0,urlPattern:e.urlPattern,methods:Array.isArray(e.methods)?e.methods.filter(r=>typeof r==="string"):void 0,requireHeader:typeof e.requireHeader==="string"&&e.requireHeader?e.requireHeader:void 0,kind:s,status:typeof e.status==="number"?Math.min(k,Math.max(E,e.status)):void 0,statusText:typeof e.statusText==="string"?e.statusText:void 0,headers:e.headers&&typeof e.headers==="object"?e.headers:void 0,body:typeof e.body==="string"?e.body:void 0,failKind:e.failKind==="timeout"?"timeout":void 0,delayMs:typeof e.delayMs==="number"?e.delayMs:void 0,times:typeof e.times==="number"?e.times:null,alternate:e.alternate===true,hits:0,seen:0,createdAt:typeof e.createdAt==="number"?e.createdAt:0})}return t.slice(0,u)}class L{rules=[];enabled=true;listeners=new Set;loaded=false;loadPromise=null;dirty=false;idCounter=0;state={enabled:true,rules:[],autoPaused:false};launchStreak=0;autoPaused=false;keepAlive=null;hitEmitTimer=null;engineDisabled=false;remote=null;remoteEchoUntil=0;enableRemoteMode(t){this.remote=t;this.disableEngine()}disableRemoteMode(){this.remote=null}replaceRules(t,i=false){if(!this.remote)return;if(!i&&c()<this.remoteEchoUntil)return;this.enabled=t.enabled;this.rules=t.rules;this.rebuild();this.emit()}markLocalEdit(){if(this.remote)this.remoteEchoUntil=c()+S}disableEngine(){this.engineDisabled=true;if(this.keepAlive){this.keepAlive();this.keepAlive=null;if(o()===0)d()}}getState(){return this.state}getRules(){if(this.engineDisabled||!this.enabled)return A;return this.rules}async fetchRuleBody(t){const i=this.rules.find(e=>e.id===t);if(!i)return null;if(!i.bodyOmitted)return i.body??null;if(!this.remote?.getRuleBody)return null;try{return await this.remote.getRuleBody(t)}catch{return null}}activeCount(){if(!this.enabled)return 0;return this.rules.filter(t=>t.enabled&&!y(t)).length}subscribe(t){this.listeners.add(t);void this.ensureLoaded();return()=>{this.listeners.delete(t)}}setEnabled(t){if(this.enabled===t)return;this.remote?.setEnabled(t);this.markLocalEdit();this.markTouched();this.enabled=t;this.commit(this.rules)}addRule(t){if(this.rules.length>=u)return null;const i={...t,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,hits:0,seen:0,createdAt:Date.now()};this.commit([i,...this.rules]);return i}upsertRule(t){this.remote?.upsertRule(t);this.markLocalEdit();this.markTouched();const{id:i,...e}=t;if(i&&this.rules.some(s=>s.id===i)){this.updateRule(i,e);return this.rules.find(s=>s.id===i)??null}return this.addRule(e)}updateRule(t,i){const e=this.rules.findIndex(r=>r.id===t);if(e===-1)return;const s=[...this.rules];s[e]={...s[e],...i,hits:0,seen:0};this.commit(s)}setRuleEnabled(t,i){const e=this.rules.findIndex(r=>r.id===t);if(e===-1||this.rules[e].enabled===i)return;this.remote?.setRuleEnabled(t,i);this.markLocalEdit();this.markTouched();const s=[...this.rules];s[e]={...s[e],enabled:i,hits:i?0:s[e].hits,seen:i?0:s[e].seen};this.commit(s)}removeRule(t){const i=this.rules.filter(e=>e.id!==t);if(i.length===this.rules.length)return;this.remote?.removeRule(t);this.markLocalEdit();this.markTouched();this.commit(i)}clearRules(){if(this.rules.length===0)return;this.remote?.clearRules();this.markLocalEdit();this.markTouched();this.commit([])}recordMatch(t){const i=this.rules.findIndex(s=>s.id===t);if(i===-1)return;const e=[...this.rules];e[i]={...e[i],seen:e[i].seen+1};this.rules=e;this.rebuild()}recordHit(t){const i=this.rules.findIndex(m=>m.id===t);if(i===-1)return;const e=this.rules[i];const s=e.hits+1;const r=typeof e.times==="number"&&s>=e.times;const l=[...this.rules];l[i]={...e,hits:s,enabled:r?false:e.enabled};if(r){this.commit(l);return}this.rules=l;this.rebuild();this.scheduleHitEmit()}ensureLoaded(){if(this.remote)return Promise.resolve();if(this.loaded)return Promise.resolve();if(this.loadPromise)return this.loadPromise;this.loadPromise=(async()=>{try{const t=await a.getItem(h.network.overrides());if(t&&!this.dirty){const i=JSON.parse(t);this.enabled=i?.enabled!==false;this.rules=T(i?.rules);this.launchStreak=typeof i?.launchStreak==="number"?i.launchStreak:0;this.applyLaunchGuard();this.rebuild()}}catch{}finally{this.loaded=true;this.syncKeepAlive();this.emit()}})();return this.loadPromise}applyLaunchGuard(){if(!this.enabled||this.activeCount()===0){this.launchStreak=0;return}this.launchStreak+=1;if(this.launchStreak>=g){this.enabled=false;this.autoPaused=true;this.launchStreak=0}this.persist()}syncKeepAlive(){const t=!this.engineDisabled&&this.activeCount()>0;if(t&&!this.keepAlive){p();this.keepAlive=f(()=>{});return}if(!t&&this.keepAlive){this.keepAlive();this.keepAlive=null;if(o()===0)d()}}scheduleHitEmit(){if(this.hitEmitTimer!==null)return;this.hitEmitTimer=setTimeout(()=>{this.hitEmitTimer=null;this.emit()},R)}commit(t){this.dirty=true;this.rules=t.slice(0,u);this.rebuild();this.syncKeepAlive();this.emit();this.persist()}rebuild(){this.state={enabled:this.enabled,rules:this.rules,autoPaused:this.autoPaused}}markTouched(){this.launchStreak=0;this.autoPaused=false}noteHealthyLaunch(){if(this.launchStreak===0&&!this.autoPaused)return;this.markTouched();this.persist();this.rebuild();this.emit()}persist(){if(this.remote)return;a.setItem(h.network.overrides(),JSON.stringify({enabled:this.enabled,rules:this.rules,launchStreak:this.launchStreak})).catch(()=>{})}emit(){this.listeners.forEach(t=>t())}}export const overrideRulesStore=new L;b({getRules:()=>overrideRulesStore.getRules(),recordHit:n=>overrideRulesStore.recordHit(n),recordMatch:n=>overrideRulesStore.recordMatch(n)});
1
+ "use strict";import{devToolsStorageKeys as u,persistentStorage as a}from"@buoy-gg/shared-ui";import{addNetworkListener as p,getNetworkListenerCount as d,startNetworkListener as y,stopNetworkListener as h}from"../utils/networkListener";import{setOverrideHooks as b}from"./engine";import{isSpent as k}from"./resolveOverride";import{MAX_RULES as o,STATUS_MAX as g,STATUS_MIN as S}from"./types";import{realNow as c}from"../utils/realNow";const E=800;const v=3;function A(){const r=`${u.network.overrides()}_launch`;try{const t=globalThis.sessionStorage;if(!t)return false;if(t.getItem(r))return true;t.setItem(r,"1")}catch{}return false}const R=Object.freeze([]);const T=250;const P=["respond","fail","delay"];function m(r){if(!Array.isArray(r))return[];const t=[];for(const i of r){if(!i||typeof i!=="object")continue;const e=i;if(typeof e.id!=="string"||typeof e.urlPattern!=="string"){continue}if(!e.urlPattern)continue;const s=P.includes(e.kind)?e.kind:"respond";t.push({id:e.id,enabled:e.enabled!==false,name:typeof e.name==="string"?e.name:void 0,urlPattern:e.urlPattern,methods:Array.isArray(e.methods)?e.methods.filter(n=>typeof n==="string"):void 0,requireHeader:typeof e.requireHeader==="string"&&e.requireHeader?e.requireHeader:void 0,bodyIncludes:typeof e.bodyIncludes==="string"&&e.bodyIncludes?e.bodyIncludes:void 0,kind:s,status:typeof e.status==="number"?Math.min(g,Math.max(S,e.status)):void 0,statusText:typeof e.statusText==="string"?e.statusText:void 0,headers:e.headers&&typeof e.headers==="object"?e.headers:void 0,body:typeof e.body==="string"?e.body:void 0,failKind:e.failKind==="timeout"?"timeout":void 0,delayMs:typeof e.delayMs==="number"?e.delayMs:void 0,times:typeof e.times==="number"?e.times:null,alternate:e.alternate===true,hits:0,seen:0,createdAt:typeof e.createdAt==="number"?e.createdAt:0})}return t.slice(0,o)}class w{rules=[];enabled=true;listeners=new Set;loaded=false;loadPromise=null;dirty=false;idCounter=0;state={enabled:true,rules:[],autoPaused:false};launchStreak=0;autoPaused=false;keepAlive=null;hitEmitTimer=null;engineDisabled=false;remote=null;remoteEchoUntil=0;enableRemoteMode(t){this.remote=t;this.disableEngine()}disableRemoteMode(){this.remote=null}replaceRules(t,i=false){if(!this.remote)return;if(!i&&c()<this.remoteEchoUntil)return;this.enabled=t.enabled;this.rules=t.rules;this.rebuild();this.emit()}markLocalEdit(){if(this.remote)this.remoteEchoUntil=c()+E}disableEngine(){this.engineDisabled=true;if(this.keepAlive){this.keepAlive();this.keepAlive=null;if(d()===0)h()}}getState(){return this.state}getRules(){if(this.engineDisabled||!this.enabled)return R;return this.rules}async fetchRuleBody(t){const i=this.rules.find(e=>e.id===t);if(!i)return null;if(!i.bodyOmitted)return i.body??null;if(!this.remote?.getRuleBody)return null;try{return await this.remote.getRuleBody(t)}catch{return null}}activeCount(){if(!this.enabled)return 0;return this.rules.filter(t=>t.enabled&&!k(t)).length}subscribe(t){this.listeners.add(t);void this.ensureLoaded();return()=>{this.listeners.delete(t)}}setEnabled(t){if(this.enabled===t)return;this.remote?.setEnabled(t);this.markLocalEdit();this.markTouched();this.enabled=t;this.commit(this.rules)}addRule(t){if(this.rules.length>=o)return null;const i={...t,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,hits:0,seen:0,createdAt:Date.now()};this.commit([i,...this.rules]);return i}upsertRule(t){this.remote?.upsertRule(t);this.markLocalEdit();this.markTouched();const{id:i,...e}=t;if(i&&this.rules.some(s=>s.id===i)){this.updateRule(i,e);return this.rules.find(s=>s.id===i)??null}return this.addRule(e)}replaceAllRules(t,i){if(this.remote)return null;this.markTouched();const e=t.map(s=>s&&typeof s==="object"&&typeof s.id==="string"?s:{...s,id:`ovr_${Date.now().toString(36)}_${++this.idCounter}`,createdAt:Date.now()});this.enabled=i;this.commit(m(e));return this.rules.slice()}updateRule(t,i){const e=this.rules.findIndex(n=>n.id===t);if(e===-1)return;const s=[...this.rules];s[e]={...s[e],...i,hits:0,seen:0};this.commit(s)}setRuleEnabled(t,i){const e=this.rules.findIndex(n=>n.id===t);if(e===-1||this.rules[e].enabled===i)return;this.remote?.setRuleEnabled(t,i);this.markLocalEdit();this.markTouched();const s=[...this.rules];s[e]={...s[e],enabled:i,hits:i?0:s[e].hits,seen:i?0:s[e].seen};this.commit(s)}removeRule(t){const i=this.rules.filter(e=>e.id!==t);if(i.length===this.rules.length)return;this.remote?.removeRule(t);this.markLocalEdit();this.markTouched();this.commit(i)}clearRules(){if(this.rules.length===0)return;this.remote?.clearRules();this.markLocalEdit();this.markTouched();this.commit([])}recordMatch(t){const i=this.rules.findIndex(s=>s.id===t);if(i===-1)return;const e=[...this.rules];e[i]={...e[i],seen:e[i].seen+1};this.rules=e;this.rebuild()}recordHit(t){const i=this.rules.findIndex(f=>f.id===t);if(i===-1)return;const e=this.rules[i];const s=e.hits+1;const n=typeof e.times==="number"&&s>=e.times;const l=[...this.rules];l[i]={...e,hits:s,enabled:n?false:e.enabled};if(n){this.commit(l);return}this.rules=l;this.rebuild();this.scheduleHitEmit()}ensureLoaded(){if(this.remote)return Promise.resolve();if(this.loaded)return Promise.resolve();if(this.loadPromise)return this.loadPromise;this.loadPromise=(async()=>{let t=null;try{t=await a.getItem(u.network.overrides())}catch{}this.hydrate(t)})();return this.loadPromise}loadNow(){if(this.remote||this.loaded||this.loadPromise)return;let t;try{t=globalThis.localStorage?.getItem(u.network.overrides())??null}catch{return}if(t===null)return;this.hydrate(t)}hydrate(t){try{if(t&&!this.dirty){const i=JSON.parse(t);this.enabled=i?.enabled!==false;this.rules=m(i?.rules);this.launchStreak=typeof i?.launchStreak==="number"?i.launchStreak:0;this.autoPaused=i?.autoPaused===true&&!this.enabled;this.applyLaunchGuard();this.rebuild()}}catch{}finally{this.loaded=true;this.syncKeepAlive();this.emit()}}applyLaunchGuard(){if(!this.enabled||this.activeCount()===0){this.launchStreak=0;return}if(A())return;this.launchStreak+=1;if(this.launchStreak>=v){this.enabled=false;this.autoPaused=true;this.launchStreak=0}this.persist()}syncKeepAlive(){const t=!this.engineDisabled&&this.activeCount()>0;if(t&&!this.keepAlive){y();this.keepAlive=p(()=>{});return}if(!t&&this.keepAlive){this.keepAlive();this.keepAlive=null;if(d()===0)h()}}scheduleHitEmit(){if(this.hitEmitTimer!==null)return;this.hitEmitTimer=setTimeout(()=>{this.hitEmitTimer=null;this.emit()},T)}commit(t){this.dirty=true;this.rules=t.slice(0,o);this.rebuild();this.syncKeepAlive();this.emit();this.persist()}rebuild(){this.state={enabled:this.enabled,rules:this.rules,autoPaused:this.autoPaused}}markTouched(){this.launchStreak=0;this.autoPaused=false}noteHealthyLaunch(){if(this.launchStreak===0&&!this.autoPaused)return;this.markTouched();this.persist();this.rebuild();this.emit()}persist(){if(this.remote)return;a.setItem(u.network.overrides(),JSON.stringify({enabled:this.enabled,rules:this.rules,launchStreak:this.launchStreak,autoPaused:this.autoPaused})).catch(()=>{})}emit(){this.listeners.forEach(t=>t())}}export const overrideRulesStore=new w;b({getRules:()=>overrideRulesStore.getRules(),recordHit:r=>overrideRulesStore.recordHit(r),recordMatch:r=>overrideRulesStore.recordMatch(r)});if(typeof window!=="undefined"&&typeof document!=="undefined"&&!(typeof navigator!=="undefined"&&navigator.product==="ReactNative")){overrideRulesStore.loadNow()}
@@ -1 +1 @@
1
- "use strict";import{ruleMatches as s}from"./matchRule";import{STATUS_MAX as a,STATUS_MIN as u}from"./types";const f=[/(^|\.)keygen\.sh/i,/^https?:\/\/(www\.)?buoy\.gg\/api\/license(\/|$)/i];function c(t){return f.some(n=>n.test(t))}function p(t){const n=t.trim();if(n==="")return"text/plain; charset=utf-8";if(n.startsWith("{")||n.startsWith("[")){try{JSON.parse(n);return"application/json"}catch{}}return"text/plain; charset=utf-8"}function d(t,n){const e=n.toLowerCase();return Object.keys(t).some(i=>i.toLowerCase()===e)}function o(t){const n=Math.max(0,t.delayMs??0);if(t.kind==="delay"){return{kind:"delay",rule:t,delayMs:n}}if(t.kind==="fail"){return{kind:"fail",rule:t,delayMs:n,failKind:t.failKind??"network"}}const e=t.body??"";const i={...t.headers??{}};if(!d(i,"content-type")){i["content-type"]=p(e)}return{kind:"respond",rule:t,delayMs:n,status:Math.min(a,Math.max(u,t.status??200)),statusText:t.statusText??"",headers:i,body:e}}export function isSpent(t){return typeof t.times==="number"&&t.hits>=t.times}export function shouldApply(t){if(!t.alternate)return true;return t.seen%2===1}export function findMatchingRule(t,n,e,i){if(e.length===0)return null;if(n.toUpperCase()==="OPTIONS")return null;if(c(t))return null;for(const r of e){if(!r.enabled)continue;if(isSpent(r))continue;if(!s(r,t,n,i))continue;return r}return null}export function resolveOverride(t,n,e,i){const r=findMatchingRule(t,n,e,i);if(!r||!shouldApply(r))return null;return o(r)}export{o as toOutcome};
1
+ "use strict";import{NULL_BODY_STATUSES as a}from"./applyToFetch";import{ruleMatches as u}from"./matchRule";import{STATUS_MAX as c,STATUS_MIN as f}from"./types";const p=[/(^|\.)keygen\.sh/i,/^https?:\/\/(www\.)?buoy\.gg\/api\/license(\/|$)/i];function d(t){return p.some(n=>n.test(t))}function l(t){const n=t.trim();if(n==="")return"text/plain; charset=utf-8";if(n.startsWith("{")||n.startsWith("[")){try{JSON.parse(n);return"application/json"}catch{}}return"text/plain; charset=utf-8"}function h(t,n){const e=n.toLowerCase();return Object.keys(t).some(i=>i.toLowerCase()===e)}function s(t){const n=Math.max(0,t.delayMs??0);if(t.kind==="delay"){return{kind:"delay",rule:t,delayMs:n}}if(t.kind==="fail"){return{kind:"fail",rule:t,delayMs:n,failKind:t.failKind??"network"}}const e=Math.min(c,Math.max(f,t.status??200));const i=a.includes(e)?"":t.body??"";const o={...t.headers??{}};if(!h(o,"content-type")){o["content-type"]=l(i)}return{kind:"respond",rule:t,delayMs:n,status:e,statusText:t.statusText??"",headers:o,body:i}}export function isSpent(t){return typeof t.times==="number"&&t.hits>=t.times}export function shouldApply(t){if(!t.alternate)return true;return t.seen%2===1}export function findMatchingRule(t,n,e,i,o){if(e.length===0)return null;if(n.toUpperCase()==="OPTIONS")return null;if(d(t))return null;for(const r of e){if(!r.enabled)continue;if(isSpent(r))continue;if(!u(r,t,n,i,o))continue;return r}return null}export function resolveOverride(t,n,e,i,o){const r=findMatchingRule(t,n,e,i,o);if(!r||!shouldApply(r))return null;return s(r)}export{s as toOutcome};
@@ -1 +1 @@
1
- "use strict";import{getNetworkCondition as E,setNetworkCondition as A,subscribeNetworkConditions as j,conditionsCanApply as g,networkConditionsRuntimeId as h}from"../conditions/store";import{networkEventStore as f}from"../utils/networkEventStore";import{flagsForEventId as O,networkSavedStore as a}from"../utils/networkSavedStore";import{overrideRulesStore as u}from"../overrides/overrideRulesStore";import{draftFromEvent as x}from"../overrides/presets";import{inspectEngine as B,overridesCanApply as T,OVERRIDES_INACTIVE_REASON as C}from"../overrides/engine";import{getNetworkListenerCount as R,isNetworkInterceptionLive as L,isNetworkListening as P}from"../utils/networkListener";import{approxJsonSize as m,isOverWireBudget as M}from"@buoy-gg/shared-ui";import{expandKeyedArrays as _,patchFromPath as $,refusalText as J,shapeKind as w,suggestedPatch as W,typedEditViolations as K}from"@buoy-gg/shared-ui";export const SNAPSHOT_BODY_INLINE_LIMIT=16*1024;export const SNAPSHOT_EVENTS_BUDGET=1.25*1024*1024;function S(e,t){if(e===void 0)return false;if((t??0)>SNAPSHOT_BODY_INLINE_LIMIT)return true;return M(e,SNAPSHOT_BODY_INLINE_LIMIT)}const I=new WeakMap;const N=new WeakMap;function k(e){const t=I.get(e);if(t)return t;let r;try{r=F(e)}catch{r=z(e)}I.set(e,r);return r}function z(e){const t={...e,requestData:void 0,responseData:void 0,graphqlVariables:void 0,requestBodyOmitted:e.requestData!==void 0?true:void 0,responseBodyOmitted:e.responseData!==void 0?true:void 0};let r=1024;try{r=m(t,SNAPSHOT_EVENTS_BUDGET).bytes}catch{}return{event:t,bytes:r}}function F(e){const t=S(e.requestData,e.requestSize);const r=S(e.responseData,e.responseSize);const n=D(e.graphqlVariables);const o=H(e.requestHeaders);const s=H(e.responseHeaders);const d=t||r||n!==e.graphqlVariables||o!==e.requestHeaders||s!==e.responseHeaders;let i=e;if(d){i={...e};if(t){i.requestData=void 0;i.requestBodyOmitted=true}if(r){i.responseData=void 0;i.responseBodyOmitted=true}if(n!==e.graphqlVariables){i.graphqlVariables=n}if(o!==e.requestHeaders){i.requestHeaders=o;i.headersOmitted=true}if(s!==e.responseHeaders){i.responseHeaders=s;i.headersOmitted=true}}return{event:i,bytes:m(i,SNAPSHOT_EVENTS_BUDGET).bytes}}function G(e){const t=N.get(e);if(t)return t;const{event:r}=k(e);const n={...r};if(n.requestData!==void 0){n.requestData=void 0;n.requestBodyOmitted=true}if(n.responseData!==void 0){n.responseData=void 0;n.responseBodyOmitted=true}if(n.graphqlVariables!==void 0){n.graphqlVariables=D(n.graphqlVariables,true)}const o={event:n,bytes:m(n,SNAPSHOT_EVENTS_BUDGET).bytes};N.set(e,o);return o}function U(e){const t=new Array(e.length);let r=0;for(let n=0;n<e.length;n++){const o=k(e[n]);if(r+o.bytes<=SNAPSHOT_EVENTS_BUDGET){t[n]=o.event;r+=o.bytes}else{const s=G(e[n]);t[n]=s.event;r+=s.bytes}}return t}function D(e,t=false){if(!e)return e;if(!t&&!S(e,void 0))return e;const r={};for(const[n,o]of Object.entries(e)){if(typeof o==="string"&&o.length<=64)r[n]=o;else if(typeof o==="number"||typeof o==="boolean"){r[n]=o}}return Object.keys(r).length>0?r:void 0}export const SNAPSHOT_HEADER_VALUE_LIMIT=64;function H(e){if(!e)return e;let t=false;const r={};for(const[n,o]of Object.entries(e)){if(typeof o!=="string")continue;if(o.length<=SNAPSHOT_HEADER_VALUE_LIMIT){r[n]=o}else{r[n]=`${o.slice(0,SNAPSHOT_HEADER_VALUE_LIMIT)}\u2026 [${o.length-SNAPSHOT_HEADER_VALUE_LIMIT} more]`;t=true}}return t?r:e}const Y=e=>{let t=false;const r=e.rules.map(n=>{if(!n.body||n.body.length<=SNAPSHOT_BODY_INLINE_LIMIT){return n}t=true;return{...n,body:void 0,bodyOmitted:true}});return t?{...e,rules:r}:e};const b=e=>f.getEventById(e)??a.getEventById(e);const c=e=>e&&typeof e==="object"?e.id:void 0;const p=(e,t)=>!!(e&&typeof e==="object"&&e[t]);const v=()=>T()?{}:{active:false,inactiveReason:C};const Q=["respond","fail","delay"];function X(e,t){if(!e||typeof e!=="object")return null;const r=e.rule??e;if(!r||typeof r!=="object")return null;const n=r;const o=typeof n.urlPattern==="string"&&n.urlPattern.trim()?n.urlPattern.trim():t?.urlPattern??"";if(!o)return null;const s=Q.includes(n.kind)?n.kind:t?.kind??"respond";return{id:typeof n.id==="string"?n.id:void 0,enabled:n.enabled!==false,name:typeof n.name==="string"?n.name:t?.name,urlPattern:o,methods:Array.isArray(n.methods)?n.methods.filter(d=>typeof d==="string").map(d=>d.toUpperCase()):t?.methods,requireHeader:typeof n.requireHeader==="string"&&n.requireHeader.trim()?n.requireHeader.trim():void 0,kind:s,status:typeof n.status==="number"?n.status:t?.status,statusText:typeof n.statusText==="string"?n.statusText:t?.statusText,headers:n.headers&&typeof n.headers==="object"?n.headers:t?.headers,body:ee(n,t),failKind:n.failKind==="timeout"?"timeout":void 0,delayMs:typeof n.delayMs==="number"?n.delayMs:void 0,times:typeof n.times==="number"?n.times:null,alternate:n.alternate===true}}const y=e=>!!e&&typeof e==="object"&&!Array.isArray(e);function V(e,t,r="",n={shrunk:[],breaks:[]}){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>0&&t.length<e.length){n.shrunk.push({path:r||"(root)",have:e.length,sent:t.length})}return t}if(!y(e)||!y(t))return t;const o={...e};for(const[s,d]of Object.entries(t)){const i=r?`${r}.${s}`:s;if(s in e){const l=w(e[s]);const q=w(d);if((l==="array"||l==="object")&&l!==q){n.breaks.push({path:i,from:l,to:q})}o[s]=V(e[s],d,i,n)}else{o[s]=d}}return o}function Z(e,t){if(e.body!=null||!y(e.bodyPatch)||typeof t!=="string")return[];try{return K(JSON.parse(t),e.bodyPatch,{noun:"response body"})}catch{return[]}}function ee(e,t){if(typeof e.body==="string")return e.body;if(e.body!=null)return JSON.stringify(e.body,null,2);const r=t?.body??(typeof e.id==="string"?u.getState().rules.find(n=>n.id===e.id)?.body:void 0);if(y(e.bodyPatch)&&typeof r==="string"){try{return JSON.stringify(V(JSON.parse(r),e.bodyPatch),null,2)}catch{return r}}return r}function te(e){if(!e||typeof e!=="object")return null;const t=e.rule??e;if(!t||typeof t!=="object")return null;const r=t.id;if(typeof r!=="string")return null;const n=u.getState().rules.find(o=>o.id===r);return n?{...n}:null}function re(e){if(!e||typeof e!=="object")return null;const t=e.rule??e;if(!t||typeof t!=="object")return null;const r=t;if(r.bodyOmitted!==true||typeof r.id!=="string")return null;const n=u.getState().rules.find(o=>o.id===r.id);return n?{body:n.body}:null}function ne(e){if(!e||typeof e!=="object")return null;const t=e.fromRequestId;if(typeof t!=="string"||!t)return null;const r=b(t);return r?x(r):null}export const networkSyncAdapter={dispose:()=>{u.setEnabled(false)},version:6,getSnapshot:()=>{f.ensureInterception();return{conditions:{version:1,runtimeId:h,profile:E(),available:g()},events:U(f.getEvents()),overrides:Y(u.getState()),saved:a.getRecords().map(e=>({...e,event:k(e.event).event}))}},subscribe:e=>{const t=f.subscribeToEvents(e);const r=j(e);const n=a.subscribe(e);const o=u.subscribe(e);return()=>{r();t();n();o()}},actions:{getNetworkConditions:()=>({runtimeId:h,profile:E(),available:g()}),setNetworkConditions:e=>{const t=e&&typeof e==="object"?e.profile:void 0;return{runtimeId:h,profile:A(t),available:g()}},clearEvents:()=>{f.clearEvents()},getEventBody:e=>{const t=c(e);if(!t)return null;const r=b(t);if(!r)return null;return{url:r.url??null,method:r.method??null,status:r.status??null,override:r.override??null,requestData:r.requestData??null,responseData:r.responseData??null,requestHeaders:r.requestHeaders??null,responseHeaders:r.responseHeaders??null}},setPinned:e=>{const t=c(e);if(!t)return null;const r=b(t);if(!r)return null;const n=p(e,"pinned");const o=O(a.getState(),t).pinned;if(o===n)return{ok:true};return a.togglePin(r)},setSaved:e=>{const t=c(e);if(!t)return null;const r=b(t);if(!r)return null;const n=p(e,"saved");const o=O(a.getState(),t).saved;if(o===n)return{ok:true};return a.toggleSave(r)},removeSavedRecord:e=>{const t=e&&typeof e==="object"?e.key:void 0;if(!t)return null;a.remove(t);return{ok:true}},clearSavedRequests:()=>{a.clearSaved();return{ok:true}},clearPinnedRequests:()=>{a.clearPinned();return{ok:true}},setOverridesEnabled:e=>{u.setEnabled(p(e,"enabled"));return{ok:true,enabled:u.getState().enabled,...v()}},upsertOverrideRule:e=>{const t=ne(e)??re(e)??te(e);const r=e?.rule??e;if(r&&typeof r.bodyPath==="string"&&r.body==null){const s=t?.body??(typeof r.id==="string"?u.getState().rules.find(l=>l.id===r.id)?.body:void 0);if(typeof s!=="string"){return{ok:false,error:"bodyPath needs something to patch: send fromRequestId (the captured request whose real response it addresses) or the id of an existing rule."}}if(r.bodyValue===void 0){return{ok:false,error:`Refused: sent \`bodyPath\` without \`bodyValue\`. Say what to set "${r.bodyPath}" to.`}}let d;try{d=JSON.parse(s)}catch{return{ok:false,error:"The captured response body is not JSON, so it cannot be addressed by path. Send a whole `body` instead."}}const i=$(d,r.bodyPath,r.bodyValue);if(!i.ok)return{ok:false,error:`Refused: ${i.error}`};r.bodyPatch=i.patch;delete r.bodyPath;delete r.bodyValue}if(r&&y(r.bodyPatch)&&r.body==null){const s=t?.body??(typeof r.id==="string"?u.getState().rules.find(d=>d.id===r.id)?.body:void 0);if(typeof s!=="string"){return{ok:false,error:"bodyPatch needs something to patch: send fromRequestId (the captured request whose real response the patch is merged into) or the id of an existing rule."}}if(r.force!==true){let d;try{const l=_(JSON.parse(s),r.bodyPatch);d=l.error;if(l.notes.length)r.bodyPatch=l.patch}catch{}if(d){return{ok:false,error:`Refused: ${d}`}}const i=Z(r,s);if(i.length>0){return{ok:false,error:J(i,"response body",W(r.bodyPatch,i)),violations:i}}}}const n=X(e,t);if(!n){const s=e?.fromRequestId;return{ok:false,error:s?`No captured request \`${s}\` \u2014 it may have been cleared. Send a urlPattern instead.`:"A rule needs a non-empty urlPattern."}}const o=u.upsertRule(n);if(!o)return{ok:false,error:"Override rule limit reached."};if(o.enabled)u.setEnabled(true);return{ok:true,rule:{id:o.id,urlPattern:o.urlPattern,enabled:o.enabled,kind:o.kind,status:o.status,times:o.times,bodySize:o.body?o.body.length:0},...o.times===void 0||o.times===null?{lingers:`This rule has no \`times\` budget, so it overrides EVERY matching request until it is disabled or deleted (id \`${o.id}\`). If you meant only the next one, set times:1.`}:{},...v()}},setOverrideRuleEnabled:e=>{const t=c(e);if(!t)return{ok:false,error:"Missing rule id."};u.setRuleEnabled(t,p(e,"enabled"));return{ok:true,...v()}},deleteOverrideRule:e=>{const t=c(e);if(!t)return{ok:false,error:"Missing rule id."};u.removeRule(t);return{ok:true}},clearOverrideRules:()=>{u.clearRules();return{ok:true}},listOverrideRules:async()=>{await u.ensureLoaded();return u.getState()},getOverrideRuleBody:e=>{const t=c(e);if(!t)return null;const r=u.getState().rules.find(n=>n.id===t);if(!r)return null;return{body:r.body??null}},getCaptureStatus:()=>{const e=f.getSubscriberCounts().total;let t=null;let r=null;try{t=P();r=R()}catch{}let n=null;try{n=L()}catch{}return{capturing:e>0,subscribers:e,interceptorInstalled:t,interceptorLive:n,listenerCount:r,eventCount:f.getEvents().length}},debugOverrides:e=>{const t=(e&&typeof e==="object"?e.url:void 0)??"https://example.com/";return{interceptorInstalled:P(),listenerCount:R(),engine:B(t,"GET"),store:{enabled:u.getState().enabled,ruleCount:u.getState().rules.length,rulesVisibleToEngine:u.getRules().length}}}}};
1
+ "use strict";import{getNetworkCondition as E,setNetworkCondition as T,subscribeNetworkConditions as j,conditionsCanApply as m,networkConditionsRuntimeId as k}from"../conditions/store";import{networkEventStore as c}from"../utils/networkEventStore";import{flagsForEventId as O,networkSavedStore as a}from"../utils/networkSavedStore";import{overrideRulesStore as i}from"../overrides/overrideRulesStore";import{draftFromEvent as x}from"../overrides/presets";import{inspectEngine as B,overridesCanApply as C,OVERRIDES_INACTIVE_REASON as L}from"../overrides/engine";import{getNetworkListenerCount as R,isNetworkInterceptionLive as M,isNetworkListening as P}from"../utils/networkListener";import{MAX_RULES as w}from"../overrides/types";import{approxJsonSize as S,isOverWireBudget as _}from"@buoy-gg/shared-ui";import{expandKeyedArrays as $,patchFromPath as J,refusalText as W,shapeKind as I,suggestedPatch as U,typedEditViolations as K}from"@buoy-gg/shared-ui";export const SNAPSHOT_BODY_INLINE_LIMIT=16*1024;export const SNAPSHOT_EVENTS_BUDGET=1.25*1024*1024;function v(e,t){if(e===void 0)return false;if((t??0)>SNAPSHOT_BODY_INLINE_LIMIT)return true;return _(e,SNAPSHOT_BODY_INLINE_LIMIT)}const A=new WeakMap;const N=new WeakMap;function q(e){const t=A.get(e);if(t)return t;let n;try{n=F(e)}catch{n=z(e)}A.set(e,n);return n}function z(e){const t={...e,requestData:void 0,responseData:void 0,graphqlVariables:void 0,requestBodyOmitted:e.requestData!==void 0?true:void 0,responseBodyOmitted:e.responseData!==void 0?true:void 0};let n=1024;try{n=S(t,SNAPSHOT_EVENTS_BUDGET).bytes}catch{}return{event:t,bytes:n}}function F(e){const t=v(e.requestData,e.requestSize);const n=v(e.responseData,e.responseSize);const r=D(e.graphqlVariables);const o=H(e.requestHeaders);const s=H(e.responseHeaders);const d=t||n||r!==e.graphqlVariables||o!==e.requestHeaders||s!==e.responseHeaders;let u=e;if(d){u={...e};if(t){u.requestData=void 0;u.requestBodyOmitted=true}if(n){u.responseData=void 0;u.responseBodyOmitted=true}if(r!==e.graphqlVariables){u.graphqlVariables=r}if(o!==e.requestHeaders){u.requestHeaders=o;u.headersOmitted=true}if(s!==e.responseHeaders){u.responseHeaders=s;u.headersOmitted=true}}return{event:u,bytes:S(u,SNAPSHOT_EVENTS_BUDGET).bytes}}function G(e){const t=N.get(e);if(t)return t;const{event:n}=q(e);const r={...n};if(r.requestData!==void 0){r.requestData=void 0;r.requestBodyOmitted=true}if(r.responseData!==void 0){r.responseData=void 0;r.responseBodyOmitted=true}if(r.graphqlVariables!==void 0){r.graphqlVariables=D(r.graphqlVariables,true)}const o={event:r,bytes:S(r,SNAPSHOT_EVENTS_BUDGET).bytes};N.set(e,o);return o}function Y(e){const t=new Array(e.length);let n=0;for(let r=0;r<e.length;r++){const o=q(e[r]);if(n+o.bytes<=SNAPSHOT_EVENTS_BUDGET){t[r]=o.event;n+=o.bytes}else{const s=G(e[r]);t[r]=s.event;n+=s.bytes}}return t}function D(e,t=false){if(!e)return e;if(!t&&!v(e,void 0))return e;const n={};for(const[r,o]of Object.entries(e)){if(typeof o==="string"&&o.length<=64)n[r]=o;else if(typeof o==="number"||typeof o==="boolean"){n[r]=o}}return Object.keys(n).length>0?n:void 0}export const SNAPSHOT_HEADER_VALUE_LIMIT=64;function H(e){if(!e)return e;let t=false;const n={};for(const[r,o]of Object.entries(e)){if(typeof o!=="string")continue;if(o.length<=SNAPSHOT_HEADER_VALUE_LIMIT){n[r]=o}else{n[r]=`${o.slice(0,SNAPSHOT_HEADER_VALUE_LIMIT)}\u2026 [${o.length-SNAPSHOT_HEADER_VALUE_LIMIT} more]`;t=true}}return t?n:e}const X=e=>{let t=false;const n=e.rules.map(r=>{if(!r.body||r.body.length<=SNAPSHOT_BODY_INLINE_LIMIT){return r}t=true;return{...r,body:void 0,bodyOmitted:true}});return t?{...e,rules:n}:e};const p=e=>c.getEventById(e)??a.getEventById(e);const b=e=>e&&typeof e==="object"?e.id:void 0;const g=(e,t)=>!!(e&&typeof e==="object"&&e[t]);const h=()=>C()?{}:{active:false,inactiveReason:L};const Q=["respond","fail","delay"];function Z(e,t){if(!e||typeof e!=="object")return null;const n=e.rule??e;if(!n||typeof n!=="object")return null;const r=n;const o=typeof r.urlPattern==="string"&&r.urlPattern.trim()?r.urlPattern.trim():t?.urlPattern??"";if(!o)return null;const s=Q.includes(r.kind)?r.kind:t?.kind??"respond";return{id:typeof r.id==="string"?r.id:void 0,enabled:r.enabled!==false,name:typeof r.name==="string"?r.name:t?.name,urlPattern:o,methods:Array.isArray(r.methods)?r.methods.filter(d=>typeof d==="string").map(d=>d.toUpperCase()):t?.methods,requireHeader:typeof r.requireHeader==="string"&&r.requireHeader.trim()?r.requireHeader.trim():void 0,bodyIncludes:typeof r.bodyIncludes==="string"&&r.bodyIncludes?r.bodyIncludes.slice(0,4096):t?.bodyIncludes,kind:s,status:typeof r.status==="number"?r.status:t?.status,statusText:typeof r.statusText==="string"?r.statusText:t?.statusText,headers:r.headers&&typeof r.headers==="object"?r.headers:t?.headers,body:te(r,t),failKind:r.failKind==="timeout"?"timeout":void 0,delayMs:typeof r.delayMs==="number"?r.delayMs:void 0,times:typeof r.times==="number"?r.times:null,alternate:r.alternate===true}}const y=e=>!!e&&typeof e==="object"&&!Array.isArray(e);function V(e,t,n="",r={shrunk:[],breaks:[]}){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>0&&t.length<e.length){r.shrunk.push({path:n||"(root)",have:e.length,sent:t.length})}return t}if(!y(e)||!y(t))return t;const o={...e};for(const[s,d]of Object.entries(t)){const u=n?`${n}.${s}`:s;if(s in e){const l=I(e[s]);const f=I(d);if((l==="array"||l==="object")&&l!==f){r.breaks.push({path:u,from:l,to:f})}o[s]=V(e[s],d,u,r)}else{o[s]=d}}return o}function ee(e,t){if(e.body!=null||!y(e.bodyPatch)||typeof t!=="string")return[];try{return K(JSON.parse(t),e.bodyPatch,{noun:"response body"})}catch{return[]}}function te(e,t){if(typeof e.body==="string")return e.body;if(e.body!=null)return JSON.stringify(e.body,null,2);const n=t?.body??(y(e.bodyPatch)&&typeof e.id==="string"?i.getState().rules.find(r=>r.id===e.id)?.body:void 0);if(y(e.bodyPatch)&&typeof n==="string"){try{return JSON.stringify(V(JSON.parse(n),e.bodyPatch),null,2)}catch{return n}}return n}function re(e){if(!e||typeof e!=="object")return null;const t=e.rule??e;if(!t||typeof t!=="object")return null;const n=t.id;if(typeof n!=="string")return null;const r=i.getState().rules.find(o=>o.id===n);return r?{...r}:null}function ne(e){if(!e||typeof e!=="object")return null;const t=e.rule??e;if(!t||typeof t!=="object")return null;const n=t;if(n.bodyOmitted!==true||typeof n.id!=="string")return null;const r=i.getState().rules.find(o=>o.id===n.id);return r?{body:r.body}:null}function oe(e){if(!e||typeof e!=="object")return null;const t=e.fromRequestId;if(typeof t!=="string"||!t)return null;const n=p(t);return n?x(n):null}export const networkSyncAdapter={dispose:()=>{i.setEnabled(false)},version:6,getSnapshot:()=>{c.ensureInterception();return{conditions:{version:1,runtimeId:k,profile:E(),available:m()},events:Y(c.getEvents()),overrides:X(i.getState()),saved:a.getRecords().map(e=>({...e,event:q(e.event).event}))}},subscribe:e=>{const t=c.subscribeToEvents(e);const n=j(e);const r=a.subscribe(e);const o=i.subscribe(e);return()=>{n();t();r();o()}},actions:{getNetworkConditions:()=>({runtimeId:k,profile:E(),available:m()}),setNetworkConditions:e=>{const t=e&&typeof e==="object"?e.profile:void 0;return{runtimeId:k,profile:T(t),available:m()}},clearEvents:()=>{c.clearEvents()},getEventBody:e=>{const t=b(e);if(!t)return null;const n=p(t);if(!n)return null;return{url:n.url??null,method:n.method??null,status:n.status??null,override:n.override??null,requestData:n.requestData??null,responseData:n.responseData??null,requestHeaders:n.requestHeaders??null,responseHeaders:n.responseHeaders??null}},setPinned:e=>{const t=b(e);if(!t)return null;const n=p(t);if(!n)return null;const r=g(e,"pinned");const o=O(a.getState(),t).pinned;if(o===r)return{ok:true};return a.togglePin(n)},setSaved:e=>{const t=b(e);if(!t)return null;const n=p(t);if(!n)return null;const r=g(e,"saved");const o=O(a.getState(),t).saved;if(o===r)return{ok:true};return a.toggleSave(n)},removeSavedRecord:e=>{const t=e&&typeof e==="object"?e.key:void 0;if(!t)return null;a.remove(t);return{ok:true}},clearSavedRequests:()=>{a.clearSaved();return{ok:true}},clearPinnedRequests:()=>{a.clearPinned();return{ok:true}},setOverridesEnabled:e=>{i.setEnabled(g(e,"enabled"));return{ok:true,enabled:i.getState().enabled,...h()}},upsertOverrideRule:e=>{const t=e?.rule??e;const n=!!t&&t.body==null&&(y(t.bodyPatch)||typeof t.bodyPath==="string");const r=oe(e)??ne(e)??(n?re(e):null);if(t&&typeof t.bodyPath==="string"&&t.body==null){const d=r?.body??(typeof t.id==="string"?i.getState().rules.find(f=>f.id===t.id)?.body:void 0);if(typeof d!=="string"){return{ok:false,error:"bodyPath needs something to patch: send fromRequestId (the captured request whose real response it addresses) or the id of an existing rule."}}if(t.bodyValue===void 0){return{ok:false,error:`Refused: sent \`bodyPath\` without \`bodyValue\`. Say what to set "${t.bodyPath}" to.`}}let u;try{u=JSON.parse(d)}catch{return{ok:false,error:"The captured response body is not JSON, so it cannot be addressed by path. Send a whole `body` instead."}}const l=J(u,t.bodyPath,t.bodyValue);if(!l.ok)return{ok:false,error:`Refused: ${l.error}`};t.bodyPatch=l.patch;delete t.bodyPath;delete t.bodyValue}if(t&&y(t.bodyPatch)&&t.body==null){const d=r?.body??(typeof t.id==="string"?i.getState().rules.find(u=>u.id===t.id)?.body:void 0);if(typeof d!=="string"){return{ok:false,error:"bodyPatch needs something to patch: send fromRequestId (the captured request whose real response the patch is merged into) or the id of an existing rule."}}if(t.force!==true){let u;try{const f=$(JSON.parse(d),t.bodyPatch);u=f.error;if(f.notes.length)t.bodyPatch=f.patch}catch{}if(u){return{ok:false,error:`Refused: ${u}`}}const l=ee(t,d);if(l.length>0){return{ok:false,error:W(l,"response body",U(t.bodyPatch,l)),violations:l}}}}const o=Z(e,r);if(!o){const d=e?.fromRequestId;return{ok:false,error:d?`No captured request \`${d}\` \u2014 it may have been cleared. Send a urlPattern instead.`:"A rule needs a non-empty urlPattern."}}const s=i.upsertRule(o);if(!s)return{ok:false,error:"Override rule limit reached."};if(s.enabled)i.setEnabled(true);return{ok:true,rule:{id:s.id,urlPattern:s.urlPattern,enabled:s.enabled,kind:s.kind,status:s.status,times:s.times,bodySize:s.body?s.body.length:0},...s.times===void 0||s.times===null?{lingers:`This rule has no \`times\` budget, so it overrides EVERY matching request until it is disabled or deleted (id \`${s.id}\`). If you meant only the next one, set times:1.`}:{},...h()}},setOverrideRuleEnabled:e=>{const t=b(e);if(!t)return{ok:false,error:"Missing rule id."};i.setRuleEnabled(t,g(e,"enabled"));return{ok:true,...h()}},deleteOverrideRule:e=>{const t=b(e);if(!t)return{ok:false,error:"Missing rule id."};i.removeRule(t);return{ok:true}},clearOverrideRules:()=>{i.clearRules();return{ok:true}},replaceOverrideRules:async e=>{const t=e??{};if(!Array.isArray(t.rules)){return{ok:false,error:"replaceOverrideRules needs `rules`: an array of rules, first match first."}}if(t.rules.length>w){return{ok:false,error:`Too many rules: ${t.rules.length}. The most is ${w}.`}}await i.ensureLoaded();const n=i.replaceAllRules(t.rules,t.enabled!==false);if(!n)return{ok:false,error:"This copy of the Network tool only mirrors a device, so it can't replace rules."};return{ok:true,count:n.length,enabled:i.getState().enabled,...h()}},listOverrideRules:async()=>{await i.ensureLoaded();return i.getState()},getOverrideRuleBody:e=>{const t=b(e);if(!t)return null;const n=i.getState().rules.find(r=>r.id===t);if(!n)return null;return{body:n.body??null}},getCaptureStatus:()=>{const e=c.getSubscriberCounts().total;let t=null;let n=null;try{t=P();n=R()}catch{}let r=null;try{r=M()}catch{}return{capturing:e>0,subscribers:e,interceptorInstalled:t,interceptorLive:r,listenerCount:n,eventCount:c.getEvents().length}},debugOverrides:e=>{const{url:t,method:n}=e&&typeof e==="object"?e:{};const r=typeof t==="string"?t:"https://example.com/";const o=typeof n==="string"&&n.trim()?n.trim().toUpperCase():"GET";return{tested:{url:r,method:o},interceptorInstalled:P(),listenerCount:R(),engine:B(r,o),store:{enabled:i.getState().enabled,autoPaused:i.getState().autoPaused,ruleCount:i.getState().rules.length,rulesVisibleToEngine:i.getRules().length}}}}};
@@ -1,7 +1,7 @@
1
- "use strict";import{isBuoyRequest as K}from"@buoy-gg/shared-ui";import{resolveRequestUrl as B}from"./resolveRequestUrl";import{nextRequestId as D}from"./requestId";import{runConditionXhr as V}from"../conditions/xhr";import{snapshotNetworkCondition as G}from"../conditions/store";import{throwIfAborted as j,waitBeforeDispatch as Q}from"../conditions/wait";import{overrideForRequest as J}from"../overrides/engine";import{runOverride as Z,hasPendingStandardRequest as ee}from"../overrides/applyToXhr";import{canSynthesizeResponse as te,synthesizeFetchError as se,synthesizeResponse as ne}from"../overrides/applyToFetch";import{markForOutcome as $}from"../overrides/types";import{httpStatusText as re,xhrCompletionKind as oe}from"./httpCompletion";import{realNow as _}from"./realNow";let O;function P(g){const e=globalThis.__buoyHeaderInjectors;if(!e||e.length===0)return void 0;let t;for(const s of e){try{const c=s(g);if(c)t={...t,...c}}catch{}}return t}function ie(){if(O!==void 0)return O;O=null;try{if(typeof __DEV__!=="undefined"&&!__DEV__)return O;const g=require("react-native");const e=g?.NativeModules?.SourceCode;const t=e?.getConstants?.().scriptURL??e?.scriptURL;if(typeof t==="string"&&/^https?:\/\//.test(t)){const s=new URL(t);O=`${s.protocol}//${s.host}`}}catch{O=null}return O}let N=false;function ae(g){const e={};if(!g)return e;if(typeof Headers!=="undefined"&&g instanceof Headers)g.forEach((t,s)=>{e[s]=t});else if(Array.isArray(g))for(const[t,s]of g)e[t]=s;else Object.assign(e,g);return e}export const BUOY_FETCH_INTERCEPTOR_FLAG="__buoyNetworkFetchIntercepted";export const BUOY_XHR_INTERCEPTOR_FLAG="__buoyNetworkXhrIntercepted";const ce=["text/event-stream","application/x-ndjson","application/stream+json"];const Y="[streaming\u2026]";let A=false;function de(){if(A)return true;const g=globalThis.document;A=!!g?.querySelector?.("[ng-version]");return A}function W(g){if(!g)return false;const e=g.toLowerCase();return ce.some(t=>e.includes(t))}const ue="__BUOY_INTERNAL_HOSTS__";function he(g){const e=globalThis[ue];if(!(e instanceof Set)||e.size===0)return false;let t;try{t=new URL(g).host.toLowerCase()}catch{return false}for(const s of e){if(typeof s==="string"&&s&&t===s.toLowerCase())return true}return false}class le{listeners=[];isListening=false;patchedFetch=null;patchedXHROpen=null;patchedXHRSend=null;patchedXHRSetRequestHeader=null;fetchGeneration=0;xhrGeneration=0;constructor(){this.originalFetch=globalThis.fetch;this.originalXHROpen=XMLHttpRequest.prototype.open;this.originalXHRSend=XMLHttpRequest.prototype.send;this.originalXHRSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader}shouldIgnoreUrl(e){if(K(e))return true;try{const t=new URL(e);if(t.hostname==="keygen.sh"||t.hostname.endsWith(".keygen.sh"))return true;if((t.hostname==="buoy.gg"||t.hostname==="www.buoy.gg")&&(t.pathname.startsWith("/api/license")||t.pathname.startsWith("/api/settings/")))return true;const s=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="10.0.2.2";if(s&&["8081","8802"].includes(t.port))return true;const c=ie();if(c&&`${t.protocol}//${t.host}`===c)return true}catch{return false}return he(e)}emit(e){this.listeners.forEach(t=>{try{t(e)}catch(s){}})}parseUrl(e){let t=null;const s=e.indexOf("?");if(s>-1){t={};e.substring(s+1).split("&").forEach(c=>{const[a,r]=c.split("=");if(a&&r!==void 0){t[a]=decodeURIComponent(r.replace(/\+/g," "))}})}return{url:s>-1?e.substring(0,s):e,params:t}}async readStreamedBody(e,t=256*1024){const s=e.body;if(!s||typeof s.getReader!=="function"){const f=await e.text();return f.length>t?{body:`${f.slice(0,t)}
1
+ "use strict";import{isBuoyRequest as Q}from"@buoy-gg/shared-ui";import{resolveRequestUrl as B}from"./resolveRequestUrl";import{nextRequestId as D}from"./requestId";import{runConditionXhr as Z}from"../conditions/xhr";import{snapshotNetworkCondition as j}from"../conditions/store";import{throwIfAborted as J,waitBeforeDispatch as ee}from"../conditions/wait";import{accountCheckFor as te,overrideForRequest as $}from"../overrides/engine";import{runOverride as se,hasPendingStandardRequest as ne}from"../overrides/applyToXhr";import{canSynthesizeResponse as P,synthesizeFetchError as re,synthesizeResponse as oe}from"../overrides/applyToFetch";import{markForOutcome as Y}from"../overrides/types";import{httpStatusText as ie,xhrCompletionKind as ae}from"./httpCompletion";import{realNow as S}from"./realNow";let k;function W(g){const e=globalThis.__buoyHeaderInjectors;if(!e||e.length===0)return void 0;let t;for(const n of e){try{const c=n(g);if(c)t={...t,...c}}catch{}}return t}function ce(){if(k!==void 0)return k;k=null;try{if(typeof __DEV__!=="undefined"&&!__DEV__)return k;const g=require("react-native");const e=g?.NativeModules?.SourceCode;const t=e?.getConstants?.().scriptURL??e?.scriptURL;if(typeof t==="string"&&/^https?:\/\//.test(t)){const n=new URL(t);k=`${n.protocol}//${n.host}`}}catch{k=null}return k}let x=false;function de(g){const e={};if(!g)return e;if(typeof Headers!=="undefined"&&g instanceof Headers)g.forEach((t,n)=>{e[n]=t});else if(Array.isArray(g))for(const[t,n]of g)e[t]=n;else Object.assign(e,g);return e}export const BUOY_FETCH_INTERCEPTOR_FLAG="__buoyNetworkFetchIntercepted";export const BUOY_XHR_INTERCEPTOR_FLAG="__buoyNetworkXhrIntercepted";const ue=["text/event-stream","application/x-ndjson","application/stream+json"];const K="[streaming\u2026]";let A=false;function he(){if(A)return true;const g=globalThis.document;A=!!g?.querySelector?.("[ng-version]");return A}function V(g){if(!g)return false;const e=g.toLowerCase();return ue.some(t=>e.includes(t))}const le="__BUOY_INTERNAL_HOSTS__";function pe(g){const e=globalThis[le];if(!(e instanceof Set)||e.size===0)return false;let t;try{t=new URL(g).host.toLowerCase()}catch{return false}for(const n of e){if(typeof n==="string"&&n&&t===n.toLowerCase())return true}return false}class fe{listeners=[];isListening=false;patchedFetch=null;patchedXHROpen=null;patchedXHRSend=null;patchedXHRSetRequestHeader=null;fetchGeneration=0;xhrGeneration=0;constructor(){this.originalFetch=globalThis.fetch;this.originalXHROpen=XMLHttpRequest.prototype.open;this.originalXHRSend=XMLHttpRequest.prototype.send;this.originalXHRSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader}shouldIgnoreUrl(e){if(Q(e))return true;try{const t=new URL(e);if(t.hostname==="keygen.sh"||t.hostname.endsWith(".keygen.sh"))return true;if((t.hostname==="buoy.gg"||t.hostname==="www.buoy.gg")&&(t.pathname.startsWith("/api/license")||t.pathname.startsWith("/api/settings/")))return true;const n=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="10.0.2.2";if(n&&["8081","8802"].includes(t.port))return true;const c=ce();if(c&&`${t.protocol}//${t.host}`===c)return true}catch{return false}return pe(e)}emit(e){this.listeners.forEach(t=>{try{t(e)}catch(n){}})}parseUrl(e){let t=null;const n=e.indexOf("?");if(n>-1){t={};e.substring(n+1).split("&").forEach(c=>{const[a,r]=c.split("=");if(a&&r!==void 0){t[a]=decodeURIComponent(r.replace(/\+/g," "))}})}return{url:n>-1?e.substring(0,n):e,params:t}}async readStreamedBody(e,t=256*1024){const n=e.body;if(!n||typeof n.getReader!=="function"){const f=await e.text();return f.length>t?{body:`${f.slice(0,t)}
2
2
 
3
- ... [truncated]`,size:f.length}:{body:f,size:f.length}}const c=s.getReader();const a=new TextDecoder;let r="";let h=0;let R=false;try{for(;;){const{done:f,value:i}=await c.read();if(f)break;h+=i?.byteLength??0;if(!R){r+=a.decode(i,{stream:true});if(h>=t){r=`${r.slice(0,t)}
3
+ ... [truncated]`,size:f.length}:{body:f,size:f.length}}const c=n.getReader();const a=new TextDecoder;let r="";let h=0;let R=false;try{for(;;){const{done:f,value:i}=await c.read();if(f)break;h+=i?.byteLength??0;if(!R){r+=a.decode(i,{stream:true});if(h>=t){r=`${r.slice(0,t)}
4
4
 
5
- ... [truncated]`;R=true;break}}}if(!R)r+=a.decode()}finally{try{void Promise.resolve(c.cancel()).catch(()=>{})}catch{}try{c.releaseLock()}catch{}}return{body:r,size:h}}async processResponseBody(e,t=1024*1024){try{const s=e.headers.get("content-length");if(s){const r=parseInt(s,10);if(!isNaN(r)&&r>t){return{body:`[Response too large: ${this.formatBytes(r)}]`,size:r,truncated:true}}}const c=await e.text();const a=c.length;if(a>t){const r=c.substring(0,t);const h=a-t;return{body:`${r}
5
+ ... [truncated]`;R=true;break}}}if(!R)r+=a.decode()}finally{try{void Promise.resolve(c.cancel()).catch(()=>{})}catch{}try{c.releaseLock()}catch{}}return{body:r,size:h}}async processResponseBody(e,t=1024*1024){try{const n=e.headers.get("content-length");if(n){const r=parseInt(n,10);if(!isNaN(r)&&r>t){return{body:`[Response too large: ${this.formatBytes(r)}]`,size:r,truncated:true}}}const c=await e.text();const a=c.length;if(a>t){const r=c.substring(0,t);const h=a-t;return{body:`${r}
6
6
 
7
- ... [truncated, ${this.formatBytes(h)} omitted]`,size:a,truncated:true}}try{return{body:JSON.parse(c),size:a,truncated:false}}catch{return{body:c,size:a,truncated:false}}}catch(s){return{body:"~~~ unable to read body ~~~",size:0,truncated:false}}}formatBytes(e){if(e===0)return"0 B";const t=1024;const s=["B","KB","MB","GB"];const c=Math.floor(Math.log(e)/Math.log(t));return`${Math.round(e/Math.pow(t,c)*100)/100} ${s[c]}`}handleXHRResponse(e,t,s,c,a,r,h,R,f=false,i="xhr",d,L){const m=R?_()-R:0;const l=e._buoyTtfb;const w=l===void 0?void 0:{ttfb:l,download:Math.max(0,m-l)};if(f||e.status===0){this.emit({type:"error",timestamp:new Date,duration:m,request:{id:t||"unknown",url:s,method:c,headers:a,data:r,params:h||void 0,client:i},error:{message:f?"Request failed":"Network error or request aborted"},override:d,condition:L});return}let n;let p=0;try{const o=e.response;if(e.responseType==="json"&&o){n=o;p=JSON.stringify(o).length}else if(e.responseType===""||e.responseType==="text"){if(e.responseText){p=e.responseText.length;try{n=JSON.parse(e.responseText)}catch{n=e.responseText}}}else if(e.responseType==="arraybuffer"){if(o){try{const y=new TextDecoder("utf-8").decode(o);p=y.length;try{n=JSON.parse(y)}catch{n=y}}catch(y){n=`[arraybuffer response - ${o.byteLength||0} bytes]`;p=o.byteLength||0}}else{n=`[arraybuffer response - no data]`;p=0}}else if(e.responseType==="blob"){if(o instanceof Blob){n=`[blob response - ${o.size} bytes, type: ${o.type||"unknown"}]`;p=o.size}else if(o){try{n=typeof o==="string"?JSON.parse(o):o;p=JSON.stringify(n).length}catch{n=`[blob response - unable to parse]`;p=0}}else{n=`[blob response - no data]`;p=0}}else if(o){if(typeof o==="string"){n=o;p=o.length;try{n=JSON.parse(o)}catch{}}else if(typeof o==="object"){n=o;p=JSON.stringify(o).length}else{n=String(o);p=String(o).length}}}catch(o){n="~~~ unable to read body ~~~"}const b={};try{const o=e.getAllResponseHeaders();if(o){o.split("\r\n").forEach(y=>{if(y){const q=y.indexOf(": ");if(q>0){const u=y.substring(0,q).toLowerCase();const H=y.substring(q+2);b[u]=H}}})}}catch{}if(oe(e.status)==="response"){this.emit({type:"response",timestamp:new Date,duration:m,timings:w,request:{id:t||"unknown",url:s,method:c,headers:a,data:r,params:h||void 0,client:i},response:{status:e.status,statusText:re(e.status,e.statusText),headers:b,body:n,size:p},override:d,condition:L})}else{this.emit({type:"error",timestamp:new Date,duration:m,request:{id:t||"unknown",url:s,method:c,headers:a,data:r,params:h||void 0,client:i},response:{status:e.status,statusText:e.statusText,headers:b,body:n,size:p},error:{message:"Network Error"},override:d,condition:L})}}isFetchInterceptionLive(){return globalThis.fetch[BUOY_FETCH_INTERCEPTOR_FLAG]===true}isXhrInterceptionLive(){return XMLHttpRequest.prototype.send[BUOY_XHR_INTERCEPTOR_FLAG]===true}isInterceptionLive(){return this.isFetchInterceptionLive()&&this.isXhrInterceptionLive()}startListening(){const e=this.isListening&&this.isFetchInterceptionLive();const t=this.isListening&&this.isXhrInterceptionLive();if(e&&t){return}if(!e){this.installFetchInterceptor()}if(!t){this.installXhrInterceptor()}this.isListening=true;if(__DEV__){}}installFetchInterceptor(){const e=this;const t=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;const s=++this.fetchGeneration;const c=async(a,r)=>{const h=B(typeof a==="string"?a:a instanceof URL?a.href:a.url);if(s!==e.fetchGeneration){return t(a,r)}if(r?.__buoyInternal||e.shouldIgnoreUrl(h)){const u=N;N=true;try{return t(a,r)}finally{N=u}}const R=_();const f=D("fetch");const i=typeof a==="object"&&"method"in a?a:void 0;const d=r?.method??i?.method??"GET";const L=r?.signal!==void 0?r.signal:i?.signal;j(L);const m=G(h);const{url:l,params:w}=e.parseUrl(h);let n={};const p=r?.headers??i?.headers;if(p){if(p instanceof Headers){p.forEach((u,H)=>{n[H]=u})}else if(Array.isArray(p)){p.forEach(([u,H])=>{n[u]=H})}else{n={...p}}}Object.assign(n,P(h));let b;if(r?.body){if(typeof r.body==="string"){try{b=JSON.parse(r.body)}catch{b=r.body}}else{b=r.body}}const o=n["X-Request-Client"]||n["x-request-client"]||"fetch";const y=m?.profile!=="offline"&&te()?J(h,d,n):null;const q=y?$(y):void 0;e.emit({type:"request",timestamp:new Date,request:{id:f||"unknown",url:l,method:d,headers:n,data:b,params:w||void 0,client:o},override:q,condition:m});if(r?.body===void 0&&i?.body&&!i.bodyUsed){try{const u=i.clone();void e.readStreamedBody(u).then(({body:H})=>{try{b=JSON.parse(H)}catch{b=H}e.emit({type:"request-body",timestamp:new Date,request:{id:f||"unknown",url:l,method:d,data:b,client:o}})}).catch(()=>{})}catch{}}try{if(m||y)await Q((m?.delayMs??0)+(y?.delayMs??0),L);j(L);if(m?.profile==="offline")throw new TypeError("Network request failed (Buoy Offline)");if(y?.kind==="fail")throw se(y);let u;if(y?.kind==="respond"){u=ne(h,y)}else{const E=N;N=true;let S;try{S=t(a,r)}finally{N=E}u=await S}const H=_()-R;const X=typeof u.body?.getReader==="function"||W(u.headers?.get?.("content-type"));const v=u.clone();const{body:U,size:C}=X?{body:Y,size:0}:await e.processResponseBody(v);const x=_()-R;const M=Math.max(0,x-H);const F=M>0?{ttfb:H,download:M}:void 0;const I={};u.headers.forEach((E,S)=>{I[S.toLowerCase()]=E});e.emit({type:"response",timestamp:new Date,duration:x,timings:F,request:{id:f||"unknown",url:l,method:d,headers:n,data:b,params:w||void 0,client:o},response:{status:u.status,statusText:u.statusText,headers:I,body:U,size:C},override:q,condition:m});if(X){const E=u.headers?.get?.("content-type");void e.readStreamedBody(v,W(E)?void 0:1024*1024).then(S=>{let T=S.body;if(E?.includes("json")){try{T=JSON.parse(S.body)}catch{}}e.emit({type:"response",timestamp:new Date,duration:_()-R,timings:F,request:{id:f||"unknown",url:l,method:d,headers:n,data:b,params:w||void 0,client:o},response:{status:u.status,statusText:u.statusText,headers:I,body:T,size:S.size},override:q,condition:m})}).catch(()=>{})}return u}catch(u){const H=_()-R;e.emit({type:"error",timestamp:new Date,duration:H,request:{id:f||"unknown",url:l,method:d,headers:n,data:b,params:w||void 0,client:o},error:{message:u instanceof Error?u.message:"Network error",stack:u instanceof Error?u.stack:void 0},override:q,condition:m});throw u}};c[BUOY_FETCH_INTERCEPTOR_FLAG]=true;this.patchedFetch=c;globalThis.fetch=this.patchedFetch}installXhrInterceptor(){const e=this;const t=XMLHttpRequest.prototype.open;const s=XMLHttpRequest.prototype.send;const c=XMLHttpRequest.prototype.setRequestHeader;this.originalXHROpen=t;this.originalXHRSend=s;this.originalXHRSetRequestHeader=c;const a=++this.xhrGeneration;const r=new WeakMap;const h=function(i,d,L,m,l){const w=t.call(this,i,d,L??true,m,l);if(a===e.xhrGeneration){r.get(this)?.();const n=this;n._buoyRequestId=D("xhr");n._method=i;n._url=B(d);n._buoyStartTime=_();n._requestHeaders={}}return w};const R=function(i,d){const L=this;if(a===e.xhrGeneration&&L._requestHeaders){L._requestHeaders[i]=d}return c.call(this,i,d)};const f=function(i){if(a!==e.xhrGeneration||N){return s.call(this,i)}if(ee(this))throw new DOMException("The request has already been sent.","InvalidStateError");if(this.readyState!==1||this._sent){return s.call(this,i)}const d=this;const L=d._buoyRequestId;const m=d._method||"GET";const l=d._url||"";const w=_();d._buoyStartTime=w;d._buoyTtfb=void 0;const n=d._requestHeaders||{};Object.assign(n,P(l));if(e.shouldIgnoreUrl(l)){return s.call(this,i)}const{url:p,params:b}=e.parseUrl(l);let o;if(i){if(typeof i==="string"){try{o=JSON.parse(i)}catch{o=i}}else{o=i}}const y=n["X-Request-Client"]||n["x-request-client"];const q=n["Accept"]||n["accept"]||"";const u=q.includes("application/json")&&q.includes("text/plain")&&q.includes("*/*")&&!de();const H=y||(u?"axios":"xhr");const X=G(l);const v=X?.profile==="offline"?null:J(l,m,n);const U=v?$(v):void 0;e.emit({type:"request",timestamp:new Date,request:{id:L||"unknown",url:p,method:m,headers:n,data:o,params:b||void 0,client:H},override:U,condition:X});let C=false;const x=(T=false)=>{if(C)return;C=true;e.handleXHRResponse(this,L||"unknown",p,m,n,o,b,w||0,T,H,U,X);M()};const M=()=>{r.delete(this);this.removeEventListener("load",F);this.removeEventListener("error",I);this.removeEventListener("abort",E);this.removeEventListener("readystatechange",S)};r.set(this,M);const F=()=>{x(false)};const I=()=>{x(true)};const E=()=>{x(true)};const S=()=>{if(this.readyState===2){const T=this;if(T._buoyTtfb===void 0&&T._buoyStartTime){T._buoyTtfb=_()-T._buoyStartTime}}if(this.readyState===4&&!C){x(false)}};this.addEventListener("load",F);this.addEventListener("error",I);this.addEventListener("abort",E);this.addEventListener("readystatechange",S);if(X){V(this,l,X,v,()=>s.call(this,i));return}if(v){const T=Z(this,l,v,()=>s.call(this,i));if(T)return}return s.call(this,i)};f[BUOY_XHR_INTERCEPTOR_FLAG]=true;this.patchedXHROpen=h;this.patchedXHRSend=f;this.patchedXHRSetRequestHeader=R;XMLHttpRequest.prototype.open=this.patchedXHROpen;XMLHttpRequest.prototype.send=this.patchedXHRSend;XMLHttpRequest.prototype.setRequestHeader=this.patchedXHRSetRequestHeader}stopListening(){if(!this.isListening){return}this.fetchGeneration++;this.xhrGeneration++;if(this.patchedFetch&&globalThis.fetch===this.patchedFetch){globalThis.fetch=this.originalFetch}if(this.patchedXHROpen&&XMLHttpRequest.prototype.open===this.patchedXHROpen){XMLHttpRequest.prototype.open=this.originalXHROpen}if(this.patchedXHRSend&&XMLHttpRequest.prototype.send===this.patchedXHRSend){XMLHttpRequest.prototype.send=this.originalXHRSend}if(this.patchedXHRSetRequestHeader&&XMLHttpRequest.prototype.setRequestHeader===this.patchedXHRSetRequestHeader){XMLHttpRequest.prototype.setRequestHeader=this.originalXHRSetRequestHeader}this.patchedFetch=null;this.patchedXHROpen=null;this.patchedXHRSend=null;this.patchedXHRSetRequestHeader=null;this.isListening=false;if(__DEV__){}}adoptEarlyRequests(){const e=globalThis.__BUOY_EARLY_NETWORK__;if(e?.version!==1)return;for(const t of e.adopt()){try{if(t.kind==="fetch")this.adoptEarlyFetch(t);else this.adoptEarlyXhr(t)}catch{}}}adoptEarlyFetch(e){const{input:t,init:s}=e;const c=typeof t==="object"&&"method"in t?t:void 0;const a=B(typeof t==="string"?t:t instanceof URL?t.href:t.url);if(this.shouldIgnoreUrl(a))return;const r=D("fetch");const h=s?.method??c?.method??"GET";const{url:R,params:f}=this.parseUrl(a);const i=ae(s?.headers??c?.headers);let d=s?.body;if(typeof d==="string"){try{d=JSON.parse(d)}catch{}}const L=i["X-Request-Client"]||i["x-request-client"]||"fetch";const m=()=>({id:r,url:R,method:h,headers:i,data:d,params:f||void 0,client:L});this.emit({type:"request",timestamp:new Date(e.start),request:m()});if(e.requestCopy){void this.readStreamedBody(e.requestCopy).then(({body:l})=>{try{d=JSON.parse(l)}catch{d=l}this.emit({type:"request-body",timestamp:new Date,request:{id:r,url:R,method:h,data:d,client:L}})}).catch(()=>{})}void e.settled.then(async({response:l,clone:w,error:n,headersAt:p})=>{if(!l){this.emit({type:"error",timestamp:new Date,duration:p-e.start,request:m(),error:{message:n instanceof Error?n.message:"Network error",stack:n instanceof Error?n.stack:void 0}});return}const{body:b,size:o}=w?await this.processResponseBody(w):{body:Y,size:0};const y=Math.max(0,_()-e.start);const q=p-e.start;const u={};l.headers.forEach((H,X)=>{u[X.toLowerCase()]=H});this.emit({type:"response",timestamp:new Date,duration:y,timings:y>q?{ttfb:q,download:y-q}:void 0,request:m(),response:{status:l.status,statusText:l.statusText,headers:u,body:b,size:o}})})}adoptEarlyXhr(e){const t=B(e.url);if(this.shouldIgnoreUrl(t))return;const s=D("xhr");const c=e.method.toUpperCase();const{url:a,params:r}=this.parseUrl(t);let h=e.body;if(typeof h==="string"){try{h=JSON.parse(h)}catch{}}const R=e.headers["X-Request-Client"]||e.headers["x-request-client"]||"xhr";this.emit({type:"request",timestamp:new Date(e.start),request:{id:s,url:a,method:c,headers:e.headers,data:h,params:r||void 0,client:R}});const f=e.xhr;const i=()=>{const d=(f._buoyEarlyEnd??_())-e.start;this.handleXHRResponse(f,s,a,c,e.headers,h,r,_()-d,false,R)};if(f.readyState===4)i();else f.addEventListener("loadend",i,{once:true})}addListener(e){this.listeners.push(e);return()=>{const t=this.listeners.indexOf(e);if(t>-1){this.listeners.splice(t,1)}}}removeAllListeners(){this.listeners=[]}get isActive(){return this.isListening}get listenerCount(){return this.listeners.length}}let k=null;const z=()=>{if(!k){k=new le}return k};export const networkListener=z;export const startNetworkListener=()=>z().startListening();export const stopNetworkListener=()=>k?.stopListening();export const addNetworkListener=g=>z().addListener(g);export const removeAllNetworkListeners=()=>k?.removeAllListeners();export const isNetworkListening=()=>k?.isActive??false;export const getNetworkListenerCount=()=>k?.listenerCount??0;export const isNetworkInterceptionLive=()=>k?.isInterceptionLive()??false;
7
+ ... [truncated, ${this.formatBytes(h)} omitted]`,size:a,truncated:true}}try{return{body:JSON.parse(c),size:a,truncated:false}}catch{return{body:c,size:a,truncated:false}}}catch(n){return{body:"~~~ unable to read body ~~~",size:0,truncated:false}}}formatBytes(e){if(e===0)return"0 B";const t=1024;const n=["B","KB","MB","GB"];const c=Math.floor(Math.log(e)/Math.log(t));return`${Math.round(e/Math.pow(t,c)*100)/100} ${n[c]}`}handleXHRResponse(e,t,n,c,a,r,h,R,f=false,i="xhr",d,H){const y=R?S()-R:0;const l=e._buoyTtfb;const _=l===void 0?void 0:{ttfb:l,download:Math.max(0,y-l)};if(f||e.status===0){this.emit({type:"error",timestamp:new Date,duration:y,request:{id:t||"unknown",url:n,method:c,headers:a,data:r,params:h||void 0,client:i},error:{message:f?"Request failed":"Network error or request aborted"},override:d,condition:H});return}let s;let p=0;try{const o=e.response;if(e.responseType==="json"&&o){s=o;p=JSON.stringify(o).length}else if(e.responseType===""||e.responseType==="text"){if(e.responseText){p=e.responseText.length;try{s=JSON.parse(e.responseText)}catch{s=e.responseText}}}else if(e.responseType==="arraybuffer"){if(o){try{const q=new TextDecoder("utf-8").decode(o);p=q.length;try{s=JSON.parse(q)}catch{s=q}}catch(q){s=`[arraybuffer response - ${o.byteLength||0} bytes]`;p=o.byteLength||0}}else{s=`[arraybuffer response - no data]`;p=0}}else if(e.responseType==="blob"){if(o instanceof Blob){s=`[blob response - ${o.size} bytes, type: ${o.type||"unknown"}]`;p=o.size}else if(o){try{s=typeof o==="string"?JSON.parse(o):o;p=JSON.stringify(s).length}catch{s=`[blob response - unable to parse]`;p=0}}else{s=`[blob response - no data]`;p=0}}else if(o){if(typeof o==="string"){s=o;p=o.length;try{s=JSON.parse(o)}catch{}}else if(typeof o==="object"){s=o;p=JSON.stringify(o).length}else{s=String(o);p=String(o).length}}}catch(o){s="~~~ unable to read body ~~~"}const b={};try{const o=e.getAllResponseHeaders();if(o){o.split("\r\n").forEach(q=>{if(q){const m=q.indexOf(": ");if(m>0){const T=q.substring(0,m).toLowerCase();const u=q.substring(m+2);b[T]=u}}})}}catch{}if(ae(e.status)==="response"){this.emit({type:"response",timestamp:new Date,duration:y,timings:_,request:{id:t||"unknown",url:n,method:c,headers:a,data:r,params:h||void 0,client:i},response:{status:e.status,statusText:ie(e.status,e.statusText),headers:b,body:s,size:p},override:d,condition:H})}else{this.emit({type:"error",timestamp:new Date,duration:y,request:{id:t||"unknown",url:n,method:c,headers:a,data:r,params:h||void 0,client:i},response:{status:e.status,statusText:e.statusText,headers:b,body:s,size:p},error:{message:"Network Error"},override:d,condition:H})}}isFetchInterceptionLive(){return globalThis.fetch[BUOY_FETCH_INTERCEPTOR_FLAG]===true}isXhrInterceptionLive(){return XMLHttpRequest.prototype.send[BUOY_XHR_INTERCEPTOR_FLAG]===true}isInterceptionLive(){return this.isFetchInterceptionLive()&&this.isXhrInterceptionLive()}startListening(){const e=this.isListening&&this.isFetchInterceptionLive();const t=this.isListening&&this.isXhrInterceptionLive();if(e&&t){return}if(!e){this.installFetchInterceptor()}if(!t){this.installXhrInterceptor()}this.isListening=true;if(__DEV__){}}installFetchInterceptor(){const e=this;const t=globalThis.fetch.bind(globalThis);this.originalFetch=globalThis.fetch;const n=++this.fetchGeneration;const c=async(a,r)=>{const h=B(typeof a==="string"?a:a instanceof URL?a.href:a.url);if(n!==e.fetchGeneration){return t(a,r)}if(r?.__buoyInternal||e.shouldIgnoreUrl(h)){const u=x;x=true;try{return t(a,r)}finally{x=u}}const R=S();const f=D("fetch");const i=typeof a==="object"&&"method"in a?a:void 0;const d=r?.method??i?.method??"GET";const H=r?.signal!==void 0?r.signal:i?.signal;J(H);const y=j(h);const{url:l,params:_}=e.parseUrl(h);let s={};const p=r?.headers??i?.headers;if(p){if(p instanceof Headers){p.forEach((u,L)=>{s[L]=u})}else if(Array.isArray(p)){p.forEach(([u,L])=>{s[u]=L})}else{s={...p}}}Object.assign(s,W(h));let b;if(r?.body){if(typeof r.body==="string"){try{b=JSON.parse(r.body)}catch{b=r.body}}else{b=r.body}}const o=s["X-Request-Client"]||s["x-request-client"]||"fetch";const q=y?.profile!=="offline"&&P()?te(h,d,s,typeof r?.body==="string"?r.body:void 0):null;if(q)await q;const m=y?.profile!=="offline"&&P()?$(h,d,s,typeof r?.body==="string"?r.body:void 0):null;const T=m?Y(m):void 0;e.emit({type:"request",timestamp:new Date,request:{id:f||"unknown",url:l,method:d,headers:s,data:b,params:_||void 0,client:o},override:T,condition:y});if(r?.body===void 0&&i?.body&&!i.bodyUsed){try{const u=i.clone();void e.readStreamedBody(u).then(({body:L})=>{try{b=JSON.parse(L)}catch{b=L}e.emit({type:"request-body",timestamp:new Date,request:{id:f||"unknown",url:l,method:d,data:b,client:o}})}).catch(()=>{})}catch{}}try{if(y||m)await ee((y?.delayMs??0)+(m?.delayMs??0),H);J(H);if(y?.profile==="offline")throw new TypeError("Network request failed (Buoy Offline)");if(m?.kind==="fail")throw re(m);let u;if(m?.kind==="respond"){u=oe(h,m)}else{const X=x;x=true;let w;try{w=t(a,r)}finally{x=X}u=await w}const L=S()-R;const E=typeof u.body?.getReader==="function"||V(u.headers?.get?.("content-type"));const I=u.clone();const{body:C,size:O}=E?{body:K,size:0}:await e.processResponseBody(I);const M=S()-R;const F=Math.max(0,M-L);const U=F>0?{ttfb:L,download:F}:void 0;const N={};u.headers.forEach((X,w)=>{N[w.toLowerCase()]=X});e.emit({type:"response",timestamp:new Date,duration:M,timings:U,request:{id:f||"unknown",url:l,method:d,headers:s,data:b,params:_||void 0,client:o},response:{status:u.status,statusText:u.statusText,headers:N,body:C,size:O},override:T,condition:y});if(E){const X=u.headers?.get?.("content-type");void e.readStreamedBody(I,V(X)?void 0:1024*1024).then(w=>{let G=w.body;if(X?.includes("json")){try{G=JSON.parse(w.body)}catch{}}e.emit({type:"response",timestamp:new Date,duration:S()-R,timings:U,request:{id:f||"unknown",url:l,method:d,headers:s,data:b,params:_||void 0,client:o},response:{status:u.status,statusText:u.statusText,headers:N,body:G,size:w.size},override:T,condition:y})}).catch(()=>{})}return u}catch(u){const L=S()-R;e.emit({type:"error",timestamp:new Date,duration:L,request:{id:f||"unknown",url:l,method:d,headers:s,data:b,params:_||void 0,client:o},error:{message:u instanceof Error?u.message:"Network error",stack:u instanceof Error?u.stack:void 0},override:T,condition:y});throw u}};c[BUOY_FETCH_INTERCEPTOR_FLAG]=true;this.patchedFetch=c;globalThis.fetch=this.patchedFetch}installXhrInterceptor(){const e=this;const t=XMLHttpRequest.prototype.open;const n=XMLHttpRequest.prototype.send;const c=XMLHttpRequest.prototype.setRequestHeader;this.originalXHROpen=t;this.originalXHRSend=n;this.originalXHRSetRequestHeader=c;const a=++this.xhrGeneration;const r=new WeakMap;const h=function(i,d,H,y,l){const _=t.call(this,i,d,H??true,y,l);if(a===e.xhrGeneration){r.get(this)?.();const s=this;s._buoyRequestId=D("xhr");s._method=i;s._url=B(d);s._buoyStartTime=S();s._requestHeaders={}}return _};const R=function(i,d){const H=this;if(a===e.xhrGeneration&&H._requestHeaders){H._requestHeaders[i]=d}return c.call(this,i,d)};const f=function(i){if(a!==e.xhrGeneration||x){return n.call(this,i)}if(ne(this))throw new DOMException("The request has already been sent.","InvalidStateError");if(this.readyState!==1||this._sent){return n.call(this,i)}const d=this;const H=d._buoyRequestId;const y=d._method||"GET";const l=d._url||"";const _=S();d._buoyStartTime=_;d._buoyTtfb=void 0;const s=d._requestHeaders||{};Object.assign(s,W(l));if(e.shouldIgnoreUrl(l)){return n.call(this,i)}const{url:p,params:b}=e.parseUrl(l);let o;if(i){if(typeof i==="string"){try{o=JSON.parse(i)}catch{o=i}}else{o=i}}const q=s["X-Request-Client"]||s["x-request-client"];const m=s["Accept"]||s["accept"]||"";const T=m.includes("application/json")&&m.includes("text/plain")&&m.includes("*/*")&&!he();const u=q||(T?"axios":"xhr");const L=j(l);const E=L?.profile==="offline"?null:$(l,y,s,typeof i==="string"?i:void 0);const I=E?Y(E):void 0;e.emit({type:"request",timestamp:new Date,request:{id:H||"unknown",url:p,method:y,headers:s,data:o,params:b||void 0,client:u},override:I,condition:L});let C=false;const O=(w=false)=>{if(C)return;C=true;e.handleXHRResponse(this,H||"unknown",p,y,s,o,b,_||0,w,u,I,L);M()};const M=()=>{r.delete(this);this.removeEventListener("load",F);this.removeEventListener("error",U);this.removeEventListener("abort",N);this.removeEventListener("readystatechange",X)};r.set(this,M);const F=()=>{O(false)};const U=()=>{O(true)};const N=()=>{O(true)};const X=()=>{if(this.readyState===2){const w=this;if(w._buoyTtfb===void 0&&w._buoyStartTime){w._buoyTtfb=S()-w._buoyStartTime}}if(this.readyState===4&&!C){O(false)}};this.addEventListener("load",F);this.addEventListener("error",U);this.addEventListener("abort",N);this.addEventListener("readystatechange",X);if(L){Z(this,l,L,E,()=>n.call(this,i));return}if(E){const w=se(this,l,E,()=>n.call(this,i));if(w)return}return n.call(this,i)};f[BUOY_XHR_INTERCEPTOR_FLAG]=true;this.patchedXHROpen=h;this.patchedXHRSend=f;this.patchedXHRSetRequestHeader=R;XMLHttpRequest.prototype.open=this.patchedXHROpen;XMLHttpRequest.prototype.send=this.patchedXHRSend;XMLHttpRequest.prototype.setRequestHeader=this.patchedXHRSetRequestHeader}stopListening(){if(!this.isListening){return}this.fetchGeneration++;this.xhrGeneration++;if(this.patchedFetch&&globalThis.fetch===this.patchedFetch){globalThis.fetch=this.originalFetch}if(this.patchedXHROpen&&XMLHttpRequest.prototype.open===this.patchedXHROpen){XMLHttpRequest.prototype.open=this.originalXHROpen}if(this.patchedXHRSend&&XMLHttpRequest.prototype.send===this.patchedXHRSend){XMLHttpRequest.prototype.send=this.originalXHRSend}if(this.patchedXHRSetRequestHeader&&XMLHttpRequest.prototype.setRequestHeader===this.patchedXHRSetRequestHeader){XMLHttpRequest.prototype.setRequestHeader=this.originalXHRSetRequestHeader}this.patchedFetch=null;this.patchedXHROpen=null;this.patchedXHRSend=null;this.patchedXHRSetRequestHeader=null;this.isListening=false;if(__DEV__){}}adoptEarlyRequests(){const e=globalThis.__BUOY_EARLY_NETWORK__;if(e?.version!==1)return;for(const t of e.adopt()){try{if(t.kind==="fetch")this.adoptEarlyFetch(t);else this.adoptEarlyXhr(t)}catch{}}}adoptEarlyFetch(e){const{input:t,init:n}=e;const c=typeof t==="object"&&"method"in t?t:void 0;const a=B(typeof t==="string"?t:t instanceof URL?t.href:t.url);if(this.shouldIgnoreUrl(a))return;const r=D("fetch");const h=n?.method??c?.method??"GET";const{url:R,params:f}=this.parseUrl(a);const i=de(n?.headers??c?.headers);let d=n?.body;if(typeof d==="string"){try{d=JSON.parse(d)}catch{}}const H=i["X-Request-Client"]||i["x-request-client"]||"fetch";const y=()=>({id:r,url:R,method:h,headers:i,data:d,params:f||void 0,client:H});this.emit({type:"request",timestamp:new Date(e.start),request:y()});if(e.requestCopy){void this.readStreamedBody(e.requestCopy).then(({body:l})=>{try{d=JSON.parse(l)}catch{d=l}this.emit({type:"request-body",timestamp:new Date,request:{id:r,url:R,method:h,data:d,client:H}})}).catch(()=>{})}void e.settled.then(async({response:l,clone:_,error:s,headersAt:p})=>{if(!l){this.emit({type:"error",timestamp:new Date,duration:p-e.start,request:y(),error:{message:s instanceof Error?s.message:"Network error",stack:s instanceof Error?s.stack:void 0}});return}const{body:b,size:o}=_?await this.processResponseBody(_):{body:K,size:0};const q=Math.max(0,S()-e.start);const m=p-e.start;const T={};l.headers.forEach((u,L)=>{T[L.toLowerCase()]=u});this.emit({type:"response",timestamp:new Date,duration:q,timings:q>m?{ttfb:m,download:q-m}:void 0,request:y(),response:{status:l.status,statusText:l.statusText,headers:T,body:b,size:o}})})}adoptEarlyXhr(e){const t=B(e.url);if(this.shouldIgnoreUrl(t))return;const n=D("xhr");const c=e.method.toUpperCase();const{url:a,params:r}=this.parseUrl(t);let h=e.body;if(typeof h==="string"){try{h=JSON.parse(h)}catch{}}const R=e.headers["X-Request-Client"]||e.headers["x-request-client"]||"xhr";this.emit({type:"request",timestamp:new Date(e.start),request:{id:n,url:a,method:c,headers:e.headers,data:h,params:r||void 0,client:R}});const f=e.xhr;const i=()=>{const d=(f._buoyEarlyEnd??S())-e.start;this.handleXHRResponse(f,n,a,c,e.headers,h,r,S()-d,false,R)};if(f.readyState===4)i();else f.addEventListener("loadend",i,{once:true})}addListener(e){this.listeners.push(e);return()=>{const t=this.listeners.indexOf(e);if(t>-1){this.listeners.splice(t,1)}}}removeAllListeners(){this.listeners=[]}get isActive(){return this.isListening}get listenerCount(){return this.listeners.length}}let v=null;const z=()=>{if(!v){v=new fe}return v};export const networkListener=z;export const startNetworkListener=()=>z().startListening();export const stopNetworkListener=()=>v?.stopListening();export const addNetworkListener=g=>z().addListener(g);export const removeAllNetworkListeners=()=>v?.removeAllListeners();export const isNetworkListening=()=>v?.isActive??false;export const getNetworkListenerCount=()=>v?.listenerCount??0;export const isNetworkInterceptionLive=()=>v?.isInterceptionLive()??false;
@@ -18,6 +18,12 @@
18
18
  * XMLHttpRequest on every platform), and this covers `fetch` on both flavours.
19
19
  */
20
20
  import type { OverrideOutcome } from "./types";
21
+ /**
22
+ * Statuses that never carry a body. A browser's `new Response()` throws if it
23
+ * gets any body for these, even "". Fetch also lists 101 and 103, which
24
+ * STATUS_MIN already rules out.
25
+ */
26
+ export declare const NULL_BODY_STATUSES: readonly number[];
21
27
  export declare const sleep: (ms: number) => Promise<void>;
22
28
  /**
23
29
  * Can we build a `Response` in this runtime?
@@ -42,6 +42,16 @@ export declare function inspectEngine(url: string, method: string): {
42
42
  ruleCount: number;
43
43
  matches: boolean;
44
44
  };
45
+ /**
46
+ * Something to await before `overrideForRequest`, or null when nothing needs it.
47
+ *
48
+ * On the web the rules load with the page (overrideRulesStore `loadNow`), but
49
+ * the account check `overridesCanApply` reads is async and still running when
50
+ * the page makes its first calls, so a saved rule let them all through. Only a
51
+ * request a rule would match waits. The fetch path uses this; XHR decides
52
+ * synchronously inside `send()` and does not wait.
53
+ */
54
+ export declare function accountCheckFor(url: string, method: string, headers?: Record<string, string>, body?: string): Promise<void> | null;
45
55
  /**
46
56
  * Resolve an override for one outgoing request, recording the hit.
47
57
  *
@@ -50,5 +60,5 @@ export declare function inspectEngine(url: string, method: string): {
50
60
  * broken dev tool, so the gate is here — at the single entry point — rather
51
61
  * than trusted to every call site.
52
62
  */
53
- export declare function overrideForRequest(url: string, method: string, headers?: Record<string, string>): OverrideOutcome | null;
63
+ export declare function overrideForRequest(url: string, method: string, headers?: Record<string, string>, body?: string): OverrideOutcome | null;
54
64
  //# sourceMappingURL=engine.d.ts.map
@@ -18,5 +18,5 @@ import type { OverrideRule } from "./types";
18
18
  export declare function escapeRegex(pattern: string): string;
19
19
  export declare function compilePattern(pattern: string): RegExp;
20
20
  /** Does this rule apply to this request? Ignores `enabled` — callers check it. */
21
- export declare function ruleMatches(rule: OverrideRule, url: string, method: string, headers?: Record<string, string>): boolean;
21
+ export declare function ruleMatches(rule: OverrideRule, url: string, method: string, headers?: Record<string, string>, body?: string): boolean;
22
22
  //# sourceMappingURL=matchRule.d.ts.map