import*as Common from"../common/common.js";import{ChunkedFileReader}from"./FileUtils.js";export class TempFile{constructor(){this._lastBlob=null}write(t){this._lastBlob&&t.unshift(this._lastBlob),this._lastBlob=new Blob(t,{type:"text/plain"})}read(){return this.readRange()}size(){return this._lastBlob?this._lastBlob.size:0}async readRange(t,e){if(!this._lastBlob)return Common.Console.Console.instance().error("Attempt to read a temp file that was never written"),"";const s="number"===typeof t||"number"===typeof e?this._lastBlob.slice(t,e):this._lastBlob,i=new FileReader;try{await new Promise(((t,e)=>{i.onloadend=t,i.onerror=e,i.readAsText(s)}))}catch(l){Common.Console.Console.instance().error("Failed to read from temp file: "+l.message)}return i.result}async copyToOutputStream(t,e){if(!this._lastBlob)return t.close(),null;const s=new ChunkedFileReader(this._lastBlob,1e7,e);return s.read(t).then((t=>t?null:s.error()))}remove(){this._lastBlob=null}}export class TempFileBackingStorage{constructor(){this._file=null,this.reset()}appendString(t){this._strings.push(t),this._stringsLength+=t.length;this._stringsLength>10485760&&this._flush()}appendAccessibleString(t){if(this._flush(),!this._file)return async()=>null;const e=this._file.size();return this._strings.push(t),this._flush(),this._file.readRange.bind(this._file,e,this._file.size())}_flush(){this._strings.length&&(this._file||(this._file=new TempFile),this._stringsLength=0,this._file.write(this._strings.splice(0)))}finishWriting(){this._flush()}reset(){this._file&&this._file.remove(),this._file=null,this._strings=[],this._stringsLength=0}writeToStream(t){return this._file?this._file.copyToOutputStream(t):Promise.resolve(null)}}