import*as Common from"../common/common.js";import*as i18n from"../i18n/i18n.js";import*as Platform from"../platform/platform.js";import*as SDK from"../sdk/sdk.js";const UIStrings={collectingContent:"Collecting content\u2026",writingFile:"Writing file\u2026"},str_=i18n.i18n.registerUIStrings("network/HARWriter.ts",UIStrings),i18nString=i18n.i18n.getLocalizedString.bind(void 0,str_);export class HARWriter{static async write(t,e,n){const i=new Common.Progress.CompositeProgress(n),r=await HARWriter._harStringForRequests(e,i);n.isCanceled()||await HARWriter._writeToStream(t,i,r)}static async _harStringForRequests(t,e){const n=e.createSubProgress();n.setTitle(i18nString(UIStrings.collectingContent)),n.setTotalWork(t.length),t.sort(((t,e)=>t.issueTime()-e.issueTime()));const i=await SDK.HARLog.HARLog.build(t),r=[];for(let s=0;s<t.length;s++){const e=t[s].contentData();r.push(e.then(o.bind(null,i.entries[s])))}return await Promise.all(r),n.done(),n.isCanceled()?"":JSON.stringify({log:i},null,_jsonIndent);function o(t,e){n.worked();let i=e.encoded;if(null!==e.content){let n=e.content;n&&!i&&function(t){for(let n=0;n<t.length;n++)if(!((e=t.charCodeAt(n))<55296||e>=57344&&e<64976||e>65007&&e<=1114111&&65534!==(65534&e)))return!0;var e;return!1}(n)&&(n=Platform.StringUtilities.toBase64(n),i=!0),t.response.content.text=n}i&&(t.response.content.encoding="base64")}}static async _writeToStream(t,e,n){const i=e.createSubProgress();i.setTitle(i18nString(UIStrings.writingFile)),i.setTotalWork(n.length);for(let r=0;r<n.length&&!i.isCanceled();r+=_chunkSize){const e=n.substr(r,_chunkSize);await t.write(e),i.worked(e.length)}i.done()}}export const _jsonIndent=2;export const _chunkSize=1e5;