@milaboratories/pl-drivers 1.6.13 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/drivers/download_blob_url/driver.d.ts.map +1 -1
- package/dist/drivers/download_blob_url/url.d.ts +0 -5
- package/dist/drivers/download_blob_url/url.d.ts.map +1 -1
- package/dist/drivers/{download_url.d.ts → download_url/driver.d.ts} +25 -41
- package/dist/drivers/download_url/driver.d.ts.map +1 -0
- package/dist/drivers/download_url/task.d.ts +40 -0
- package/dist/drivers/download_url/task.d.ts.map +1 -0
- package/dist/drivers/urls/url.d.ts +13 -0
- package/dist/drivers/urls/url.d.ts.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +506 -484
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
- package/src/drivers/download_blob_url/driver.ts +2 -2
- package/src/drivers/download_blob_url/task.ts +1 -1
- package/src/drivers/download_blob_url/url.ts +0 -43
- package/src/drivers/{download_url.test.ts → download_url/driver.test.ts} +32 -25
- package/src/drivers/{download_url.ts → download_url/driver.ts} +55 -156
- package/src/drivers/download_url/task.ts +151 -0
- package/src/drivers/{download_blob_url → urls}/url.test.ts +26 -3
- package/src/drivers/urls/url.ts +68 -0
- package/src/index.ts +1 -1
- package/dist/drivers/download_url.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var wt=Object.defineProperty;var mt=(i,e,t)=>e in i?wt(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var h=(i,e,t)=>mt(i,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@milaboratories/pl-client"),yt=require("node:fs/promises"),Ne=require("undici"),y=require("@protobuf-ts/runtime-rpc"),a=require("@protobuf-ts/runtime"),g=require("@milaboratories/ts-helpers"),R=require("node:fs"),U=require("node:path"),P=require("node:stream"),de=require("node:stream/consumers"),f=require("@milaboratories/computable"),_=require("@milaboratories/pl-model-common"),m=require("@milaboratories/pl-tree"),Tt=require("denque"),L=require("node:crypto"),$e=require("node:os"),bt=require("node:readline/promises"),k=require("zod"),kt=require("@milaboratories/helpers"),Ut=require("node:zlib"),Pt=require("tar-fs"),Lt=require("decompress"),ve=require("node:timers/promises"),Rt=require("node:assert"),It=require("node:util"),St=require("node:child_process");function I(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const w=I(yt),ce=I(R),b=I(U),Ue=I($e),Dt=I(bt),Ce=I(Ut),ie=I(Pt);class Nt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new Nt;class $t extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Init",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new $t;class vt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Init.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Ct=new vt;class Ft extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Init.Response",[{no:1,name:"parts_count",kind:"scalar",T:4,L:0},{no:2,name:"uploaded_parts",kind:"scalar",repeat:1,T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.partsCount=0n,t.uploadedParts=[],e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.partsCount=e.uint64().toBigInt();break;case 2:if(c===a.WireType.LengthDelimited)for(let G=e.int32()+e.pos;e.pos<G;)o.uploadedParts.push(e.uint64().toBigInt());else o.uploadedParts.push(e.uint64().toBigInt());break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){if(e.partsCount!==0n&&t.tag(1,a.WireType.Varint).uint64(e.partsCount),e.uploadedParts.length){t.tag(2,a.WireType.LengthDelimited).fork();for(let o=0;o<e.uploadedParts.length;o++)t.uint64(e.uploadedParts[o]);t.join()}let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Bt=new Ft;class Wt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.UpdateProgress",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new Wt;class Et extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.UpdateProgress.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"bytes_processed",kind:"scalar",T:3,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.bytesProcessed=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.bytesProcessed=e.int64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.bytesProcessed!==0n&&t.tag(2,a.WireType.Varint).int64(e.bytesProcessed);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const _t=new Et;class Mt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.UpdateProgress.Response",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Ot=new Mt;class Ht extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new Ht;class zt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"part_number",kind:"scalar",T:4,L:0},{no:3,name:"uploaded_part_size",kind:"scalar",T:4,L:0},{no:4,name:"is_internal_use",kind:"scalar",T:8}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.partNumber=0n,t.uploadedPartSize=0n,t.isInternalUse=!1,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.partNumber=e.uint64().toBigInt();break;case 3:o.uploadedPartSize=e.uint64().toBigInt();break;case 4:o.isInternalUse=e.bool();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.partNumber!==0n&&t.tag(2,a.WireType.Varint).uint64(e.partNumber),e.uploadedPartSize!==0n&&t.tag(3,a.WireType.Varint).uint64(e.uploadedPartSize),e.isInternalUse!==!1&&t.tag(4,a.WireType.Varint).bool(e.isInternalUse);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const xt=new zt;class At extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL.HTTPHeader",[{no:1,name:"Name",kind:"scalar",jsonName:"Name",T:9},{no:2,name:"Value",kind:"scalar",jsonName:"Value",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.name="",t.value="",e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.name=e.string();break;case 2:o.value=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.name!==""&&t.tag(1,a.WireType.LengthDelimited).string(e.name),e.value!==""&&t.tag(2,a.WireType.LengthDelimited).string(e.value);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const V=new At;class jt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL.Response",[{no:1,name:"upload_url",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"headers",kind:"message",repeat:2,T:()=>V},{no:4,name:"chunk_start",kind:"scalar",T:4,L:0},{no:5,name:"chunk_end",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.uploadUrl="",t.method="",t.headers=[],t.chunkStart=0n,t.chunkEnd=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.uploadUrl=e.string();break;case 2:o.method=e.string();break;case 3:o.headers.push(V.internalBinaryRead(e,e.uint32(),r));break;case 4:o.chunkStart=e.uint64().toBigInt();break;case 5:o.chunkEnd=e.uint64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.uploadUrl!==""&&t.tag(1,a.WireType.LengthDelimited).string(e.uploadUrl),e.method!==""&&t.tag(2,a.WireType.LengthDelimited).string(e.method);for(let o=0;o<e.headers.length;o++)V.internalBinaryWrite(e.headers[o],t.tag(3,a.WireType.LengthDelimited).fork(),r).join();e.chunkStart!==0n&&t.tag(4,a.WireType.Varint).uint64(e.chunkStart),e.chunkEnd!==0n&&t.tag(5,a.WireType.Varint).uint64(e.chunkEnd);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Gt=new jt;class Vt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Finalize",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new Vt;class qt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Finalize.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Jt=new qt;class Zt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Finalize.Response",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Qt=new Zt,q=new y.ServiceType("MiLaboratories.Controller.Shared.Upload",[{name:"Init",options:{},I:Ct,O:Bt},{name:"GetPartURL",options:{},I:xt,O:Gt},{name:"UpdateProgress",options:{},I:_t,O:Ot},{name:"Finalize",options:{},I:Jt,O:Qt}]);class Kt{constructor(e){h(this,"typeName",q.typeName);h(this,"methods",q.methods);h(this,"options",q.options);this._transport=e}init(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}getPartURL(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}updateProgress(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}finalize(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}}function Fe(i,e,t){const r=Object.fromEntries(i.map(({name:n,value:o})=>[n,o]));return e!==void 0&&t!==void 0&&(r.Range=`bytes=${e}-${t-1}`),r}class he extends Error{constructor(){super(...arguments);h(this,"name","MTimeError")}}class ue extends Error{constructor(){super(...arguments);h(this,"name","UnexpectedEOF")}}class pe extends Error{constructor(){super(...arguments);h(this,"name","NetworkError")}}class ge extends Error{constructor(){super(...arguments);h(this,"name","NoFileForUploading")}}class Be{constructor(e,t,r,n){h(this,"grpcClient");this.httpClient=t,this.logger=n,this.grpcClient=e.createGrpcClientProvider(o=>new Kt(o))}close(){}async initUpload({id:e,type:t},r){const n=await this.grpcInit(e,t,r);return{overall:n.partsCount,toUpload:this.partsToUpload(n.partsCount,n.uploadedParts)}}async partUpload({id:e,type:t},r,n,o,d){const s=await this.grpcGetPartUrl({id:e,type:t},o,0n,d),c=await Xt(r,s.chunkStart,s.chunkEnd);await er(r,n);try{const{body:l,statusCode:u,headers:G}=await Ne.request(s.uploadUrl,{dispatcher:this.httpClient,body:c,headersTimeout:6e4,bodyTimeout:6e4,headers:Fe(s.headers),method:s.method.toUpperCase()}),ft=await l.text();tr(u,ft,G,s)}catch(l){throw l instanceof pe?l:new Error(`partUpload: error ${JSON.stringify(l)} happened while trying to do part upload to the url ${s.uploadUrl}, headers: ${JSON.stringify(s.headers)}`)}await this.grpcUpdateProgress({id:e,type:t},BigInt(s.chunkEnd-s.chunkStart),d)}async finalize(e,t){return await this.grpcFinalize(e,t)}partsToUpload(e,t){const r=[],n=new Set(t);for(let o=1n;o<=e;o++)n.has(o)||r.push(o);return r}async grpcInit(e,t,r){return await this.grpcClient.get().init({resourceId:e},p.addRTypeToMetadata(t,r)).response}async grpcGetPartUrl({id:e,type:t},r,n,o){return await this.grpcClient.get().getPartURL({resourceId:e,partNumber:r,uploadedPartSize:n,isInternalUse:!1},p.addRTypeToMetadata(t,o)).response}async grpcUpdateProgress({id:e,type:t},r,n){await this.grpcClient.get().updateProgress({resourceId:e,bytesProcessed:r},p.addRTypeToMetadata(t,n)).response}async grpcFinalize({id:e,type:t},r){return await this.grpcClient.get().finalize({resourceId:e},p.addRTypeToMetadata(t,r)).response}}async function Xt(i,e,t){let r;try{r=await w.open(i);const n=Number(t-e),o=Number(e),d=Buffer.alloc(n),s=await Yt(r,d,n,o);return d.subarray(0,s)}catch(n){throw n&&typeof n=="object"&&"code"in n&&n.code=="ENOENT"?new ge(`there is no file ${i} for uploading`):n}finally{await(r==null?void 0:r.close())}}async function Yt(i,e,t,r){let n=0;for(;n<t;){const{bytesRead:o}=await i.read(e,n,t-n,r+n);if(o===0)throw new ue("file ended earlier than expected.");n+=o}return n}async function er(i,e){const t=BigInt(Math.floor((await w.stat(i)).mtimeMs/1e3));if(t>e)throw new he(`file was modified, expected mtime: ${e}, got: ${t}.`)}function tr(i,e,t,r){if(i!=200)throw new pe(`response is not ok, status code: ${i}, body: ${e}, headers: ${JSON.stringify(t)}, url: ${r.uploadUrl}`)}class rr extends a.MessageType{constructor(){super("google.protobuf.Duration",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}internalJsonWrite(e,t){let r=a.PbLong.from(e.seconds).toNumber();if(r>315576e6||r<-315576e6)throw new Error("Duration value out of range.");let n=e.seconds.toString();if(r===0&&e.nanos<0&&(n="-"+n),e.nanos!==0){let o=Math.abs(e.nanos).toString();o="0".repeat(9-o.length)+o,o.substring(3)==="000000"?o=o.substring(0,3):o.substring(6)==="000"&&(o=o.substring(0,6)),n+="."+o}return n+"s"}internalJsonRead(e,t,r){if(typeof e!="string")throw new Error("Unable to parse Duration from JSON "+a.typeofJsonValue(e)+". Expected string.");let n=e.match(/^(-?)([0-9]+)(?:\.([0-9]+))?s/);if(n===null)throw new Error("Unable to parse Duration from JSON string. Invalid format.");r||(r=this.create());let[,o,d,s]=n,c=a.PbLong.from(o+d);if(c.toNumber()>315576e6||c.toNumber()<-315576e6)throw new Error("Unable to parse Duration from JSON string. Value out of range.");if(r.seconds=c.toBigInt(),typeof s=="string"){let l=o+s+"0".repeat(9-s.length);r.nanos=parseInt(l)}return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0n,t.nanos=0,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.seconds=e.int64().toBigInt();break;case 2:o.nanos=e.int32();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.seconds!==0n&&t.tag(1,a.WireType.Varint).int64(e.seconds),e.nanos!==0&&t.tag(2,a.WireType.Varint).int32(e.nanos);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const E=new rr;class nr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new nr;class or extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.Report",[{no:1,name:"progress",kind:"scalar",T:2},{no:2,name:"bytes_processed",kind:"scalar",T:4,L:0},{no:3,name:"bytes_total",kind:"scalar",T:4,L:0},{no:4,name:"done",kind:"scalar",T:8},{no:5,name:"name",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.progress=0,t.bytesProcessed=0n,t.bytesTotal=0n,t.done=!1,t.name="",e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.progress=e.float();break;case 2:o.bytesProcessed=e.uint64().toBigInt();break;case 3:o.bytesTotal=e.uint64().toBigInt();break;case 4:o.done=e.bool();break;case 5:o.name=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.progress!==0&&t.tag(1,a.WireType.Bit32).float(e.progress),e.bytesProcessed!==0n&&t.tag(2,a.WireType.Varint).uint64(e.bytesProcessed),e.bytesTotal!==0n&&t.tag(3,a.WireType.Varint).uint64(e.bytesTotal),e.done!==!1&&t.tag(4,a.WireType.Varint).bool(e.done),e.name!==""&&t.tag(5,a.WireType.LengthDelimited).string(e.name);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const D=new or;class ir extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new ir;class sr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const ar=new sr;class lr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus.Response",[{no:1,name:"report",kind:"message",T:()=>D}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.report=D.internalBinaryRead(e,e.uint32(),r,o.report);break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.report&&D.internalBinaryWrite(e.report,t.tag(1,a.WireType.LengthDelimited).fork(),r).join();let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const dr=new lr;class cr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new cr;class hr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"update_interval",kind:"message",T:()=>E}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.updateInterval=E.internalBinaryRead(e,e.uint32(),r,o.updateInterval);break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.updateInterval&&E.internalBinaryWrite(e.updateInterval,t.tag(2,a.WireType.LengthDelimited).fork(),r).join();let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const ur=new hr;class pr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus.Response",[{no:1,name:"report",kind:"message",T:()=>D}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.report=D.internalBinaryRead(e,e.uint32(),r,o.report);break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.report&&D.internalBinaryWrite(e.report,t.tag(1,a.WireType.LengthDelimited).fork(),r).join();let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const gr=new pr,J=new y.ServiceType("MiLaboratories.Controller.Shared.Progress",[{name:"GetStatus",options:{"google.api.http":{get:"/resources/{resource_id}/get-progress"}},I:ar,O:dr},{name:"RealtimeStatus",serverStreaming:!0,options:{},I:ur,O:gr}]);class fr{constructor(e){h(this,"typeName",J.typeName);h(this,"methods",J.methods);h(this,"options",J.options);this._transport=e}getStatus(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}realtimeStatus(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return y.stackIntercept("serverStreaming",this._transport,r,n,e)}}class We{constructor(e,t,r,n){h(this,"grpcClient");this.client=r,this.logger=n,this.grpcClient=e.createGrpcClientProvider(o=>new fr(o))}close(){}async getStatus({id:e,type:t},r){const n=await this.grpcClient.get().getStatus({resourceId:e},p.addRTypeToMetadata(t,r)),o=g.notEmpty(n.response.report);return{done:o.done,progress:o.progress,bytesProcessed:String(o.bytesProcessed),bytesTotal:String(o.bytesTotal)}}async*realtimeStatus({id:e,type:t},r=100,n){n=p.addRTypeToMetadata(t,n);const o=Math.floor(r/1e3),d=(r-o*1e3)*1e6,s=E.create({seconds:BigInt(o),nanos:d});try{const{responses:c}=this.grpcClient.get().realtimeStatus({resourceId:e,updateInterval:s},n);yield*c}catch(c){throw this.logger.warn("Failed to get realtime status"+String(c)),c}}}class z extends Error{constructor(){super(...arguments);h(this,"name","NetworkError400")}}class Ee{constructor(e){this.httpClient=e}async download(e,t,r){const{statusCode:n,body:o,headers:d}=await Ne.request(e,{dispatcher:this.httpClient,headers:t,signal:r}),s=P.Readable.toWeb(o);return await wr(n,s,e),{content:s,size:Number(d["content-length"])}}}async function wr(i,e,t){if(i!=200&&i!=206){const r=(await de.text(e)).substring(0,1e3);throw 400<=i&&i<500?new z(`Http error: statusCode: ${i} url: ${t.toString()}, beginning of body: ${r}`):new Error(`Http error: statusCode: ${i} url: ${t.toString()}`)}}function S(i){if(!U.isAbsolute(i))throw new Error(`Path ${i} is not absolute.`);return i}class mr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new mr;class yr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new yr;class Tr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"is_internal_use",kind:"scalar",T:8}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.isInternalUse=!1,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.isInternalUse=e.bool();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.isInternalUse!==!1&&t.tag(2,a.WireType.Varint).bool(e.isInternalUse);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const br=new Tr;class kr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL.HTTPHeader",[{no:1,name:"Name",kind:"scalar",jsonName:"Name",T:9},{no:2,name:"Value",kind:"scalar",jsonName:"Value",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.name="",t.value="",e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.name=e.string();break;case 2:o.value=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.name!==""&&t.tag(1,a.WireType.LengthDelimited).string(e.name),e.value!==""&&t.tag(2,a.WireType.LengthDelimited).string(e.value);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Z=new kr;class Ur extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL.Response",[{no:1,name:"download_url",kind:"scalar",T:9},{no:2,name:"headers",kind:"message",repeat:2,T:()=>Z}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.downloadUrl="",t.headers=[],e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.downloadUrl=e.string();break;case 2:o.headers.push(Z.internalBinaryRead(e,e.uint32(),r));break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.downloadUrl!==""&&t.tag(1,a.WireType.LengthDelimited).string(e.downloadUrl);for(let o=0;o<e.headers.length;o++)Z.internalBinaryWrite(e.headers[o],t.tag(2,a.WireType.LengthDelimited).fork(),r).join();let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Pr=new Ur,Q=new y.ServiceType("MiLaboratories.Controller.Shared.Download",[{name:"GetDownloadURL",options:{"google.api.http":{get:"/resources/{resource_id}/get-download-url"}},I:br,O:Pr}]);class Lr{constructor(e){h(this,"typeName",Q.typeName);h(this,"methods",Q.methods);h(this,"options",Q.options);this._transport=e}getDownloadURL(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}}class _e{constructor(e,t,r,n){h(this,"grpcClient");h(this,"remoteFileDownloader");h(this,"localStorageIdsToRoot");this.httpClient=t,this.logger=r,this.grpcClient=e.createGrpcClientProvider(o=>new Lr(o)),this.remoteFileDownloader=new Ee(t),this.localStorageIdsToRoot=He(n)}close(){}async downloadBlob(e,t,r,n,o){const{downloadUrl:d,headers:s}=await this.grpcGetDownloadUrl(e,t,r),c=Fe(s,n,o);return this.logger.info(`download blob ${p.stringifyWithResourceId(e)} from url ${d}, headers: ${JSON.stringify(c)}`),Ir(d)?await this.readLocalFile(d,n,o):await this.remoteFileDownloader.download(d,c,r)}async readLocalFile(e,t,r){const{storageId:n,relativePath:o}=Me(e),d=Oe(n,this.localStorageIdsToRoot,o);return{content:P.Readable.toWeb(ce.createReadStream(d,{start:t,end:r!==void 0?r-1:void 0})),size:(await w.stat(d)).size}}async grpcGetDownloadUrl({id:e,type:t},r,n){const o=r??{};return o.abort=n,await this.grpcClient.get().getDownloadURL({resourceId:e,isInternalUse:!1},p.addRTypeToMetadata(t,o)).response}}function Me(i){const e=new URL(i);if(e.pathname=="")throw new x(`url for local filepath ${i} does not match url scheme`);return{storageId:e.host,relativePath:decodeURIComponent(e.pathname.slice(1))}}function Oe(i,e,t){const r=e.get(i);if(r===void 0)throw new A(`Unknown storage location: ${i}`);return r===""?t:b.join(r,t)}const Rr="storage://";function Ir(i){return i.startsWith(Rr)}class x extends Error{constructor(){super(...arguments);h(this,"name","WrongLocalFileUrl")}}class A extends Error{constructor(){super(...arguments);h(this,"name","UnknownStorageError")}}function He(i){const e=new Map;for(const t of i)t.localPath!==""&&S(t.localPath),e.set(t.storageId,t.localPath);return e}class Sr extends a.MessageType{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=a.PbLong.from(Math.floor(t/1e3)).toBigInt(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(a.PbLong.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=a.PbLong.from(Math.floor(r/1e3)).toBigInt(),t.nanos=(r%1e3+(r<0&&r%1e3!==0?1e3:0))*1e6,t}internalJsonWrite(e,t){let r=a.PbLong.from(e.seconds).toNumber()*1e3;if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let o=(e.nanos+1e9).toString().substring(1);o.substring(3)==="000000"?n="."+o.substring(0,3)+"Z":o.substring(6)==="000"?n="."+o.substring(0,6)+"Z":n="."+o+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if(typeof e!="string")throw new Error("Unable to parse Timestamp from JSON "+a.typeofJsonValue(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let o=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(o))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(o<Date.parse("0001-01-01T00:00:00Z")||o>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=a.PbLong.from(o/1e3).toBigInt(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0n,t.nanos=0,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.seconds=e.int64().toBigInt();break;case 2:o.nanos=e.int32();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.seconds!==0n&&t.tag(1,a.WireType.Varint).int64(e.seconds),e.nanos!==0&&t.tag(2,a.WireType.Varint).int32(e.nanos);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const K=new Sr;class Dr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new Dr;class Nr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.ListItem",[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"size",kind:"scalar",T:4,L:0},{no:3,name:"is_dir",kind:"scalar",T:8},{no:10,name:"full_name",kind:"scalar",T:9},{no:11,name:"directory",kind:"scalar",T:9},{no:12,name:"last_modified",kind:"message",T:()=>K},{no:13,name:"version",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.name="",t.size=0n,t.isDir=!1,t.fullName="",t.directory="",t.version="",e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.name=e.string();break;case 2:o.size=e.uint64().toBigInt();break;case 3:o.isDir=e.bool();break;case 10:o.fullName=e.string();break;case 11:o.directory=e.string();break;case 12:o.lastModified=K.internalBinaryRead(e,e.uint32(),r,o.lastModified);break;case 13:o.version=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.name!==""&&t.tag(1,a.WireType.LengthDelimited).string(e.name),e.size!==0n&&t.tag(2,a.WireType.Varint).uint64(e.size),e.isDir!==!1&&t.tag(3,a.WireType.Varint).bool(e.isDir),e.fullName!==""&&t.tag(10,a.WireType.LengthDelimited).string(e.fullName),e.directory!==""&&t.tag(11,a.WireType.LengthDelimited).string(e.directory),e.lastModified&&K.internalBinaryWrite(e.lastModified,t.tag(12,a.WireType.LengthDelimited).fork(),r).join(),e.version!==""&&t.tag(13,a.WireType.LengthDelimited).string(e.version);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const X=new Nr;class $r extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new $r;class vr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"location",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.location="",e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.location=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.location!==""&&t.tag(2,a.WireType.LengthDelimited).string(e.location);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Cr=new vr;class Fr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List.Response",[{no:1,name:"items",kind:"message",repeat:2,T:()=>X},{no:2,name:"delimiter",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.items=[],t.delimiter="",e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.items.push(X.internalBinaryRead(e,e.uint32(),r));break;case 2:o.delimiter=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){for(let o=0;o<e.items.length;o++)X.internalBinaryWrite(e.items[o],t.tag(1,a.WireType.LengthDelimited).fork(),r).join();e.delimiter!==""&&t.tag(2,a.WireType.LengthDelimited).string(e.delimiter);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Br=new Fr,Y=new y.ServiceType("MiLaboratories.Controller.Shared.LS",[{name:"List",options:{},I:Cr,O:Br}]);class Wr{constructor(e){h(this,"typeName",Y.typeName);h(this,"methods",Y.methods);h(this,"options",Y.options);this._transport=e}list(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}}class ze{constructor(e,t){h(this,"grpcClient");this.logger=t,this.grpcClient=e.createGrpcClientProvider(r=>new Wr(r))}close(){}async list(e,t,r){return await this.grpcClient.get().list({resourceId:e.id,location:t},p.addRTypeToMetadata(e.type,r)).response}}class Er extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new Er;class _r extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.StreamBinary",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:11,name:"chunk_size",kind:"scalar",opt:!0,T:13},{no:20,name:"read_limit",kind:"scalar",opt:!0,T:3,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 11:o.chunkSize=e.uint32();break;case 20:o.readLimit=e.int64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,a.WireType.Varint).int64(e.offset),e.chunkSize!==void 0&&t.tag(11,a.WireType.Varint).uint32(e.chunkSize),e.readLimit!==void 0&&t.tag(20,a.WireType.Varint).int64(e.readLimit);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Mr=new _r;class Or extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.ReadBinary",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:11,name:"chunk_size",kind:"scalar",opt:!0,T:13}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 11:o.chunkSize=e.uint32();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,a.WireType.Varint).int64(e.offset),e.chunkSize!==void 0&&t.tag(11,a.WireType.Varint).uint32(e.chunkSize);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Hr=new Or;class zr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.StreamText",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:20,name:"read_limit",kind:"scalar",opt:!0,T:3,L:0},{no:21,name:"search",kind:"scalar",opt:!0,T:9},{no:22,name:"search_re",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 20:o.readLimit=e.int64().toBigInt();break;case 21:o.search=e.string();break;case 22:o.searchRe=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,a.WireType.Varint).int64(e.offset),e.readLimit!==void 0&&t.tag(20,a.WireType.Varint).int64(e.readLimit),e.search!==void 0&&t.tag(21,a.WireType.LengthDelimited).string(e.search),e.searchRe!==void 0&&t.tag(22,a.WireType.LengthDelimited).string(e.searchRe);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const xr=new zr;class Ar extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.ReadText",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:20,name:"read_limit",kind:"scalar",opt:!0,T:3,L:0},{no:21,name:"search",kind:"scalar",opt:!0,T:9},{no:22,name:"search_re",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 20:o.readLimit=e.int64().toBigInt();break;case 21:o.search=e.string();break;case 22:o.searchRe=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,a.WireType.Varint).int64(e.offset),e.readLimit!==void 0&&t.tag(20,a.WireType.Varint).int64(e.readLimit),e.search!==void 0&&t.tag(21,a.WireType.LengthDelimited).string(e.search),e.searchRe!==void 0&&t.tag(22,a.WireType.LengthDelimited).string(e.searchRe);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const jr=new Ar;class Gr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.LastLines",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",opt:!0,T:3,L:0},{no:3,name:"line_count",kind:"scalar",opt:!0,T:5},{no:21,name:"search",kind:"scalar",opt:!0,T:9},{no:22,name:"search_re",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 3:o.lineCount=e.int32();break;case 21:o.search=e.string();break;case 22:o.searchRe=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.offset!==void 0&&t.tag(2,a.WireType.Varint).int64(e.offset),e.lineCount!==void 0&&t.tag(3,a.WireType.Varint).int32(e.lineCount),e.search!==void 0&&t.tag(21,a.WireType.LengthDelimited).string(e.search),e.searchRe!==void 0&&t.tag(22,a.WireType.LengthDelimited).string(e.searchRe);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Vr=new Gr;class qr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.Response",[{no:1,name:"data",kind:"scalar",T:12},{no:2,name:"size",kind:"scalar",T:4,L:0},{no:3,name:"new_offset",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.data=new Uint8Array(0),t.size=0n,t.newOffset=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.data=e.bytes();break;case 2:o.size=e.uint64().toBigInt();break;case 3:o.newOffset=e.uint64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.data.length&&t.tag(1,a.WireType.LengthDelimited).bytes(e.data),e.size!==0n&&t.tag(2,a.WireType.Varint).uint64(e.size),e.newOffset!==0n&&t.tag(3,a.WireType.Varint).uint64(e.newOffset);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const N=new qr,ee=new y.ServiceType("MiLaboratories.Controller.Shared.Streaming",[{name:"StreamBinary",serverStreaming:!0,options:{},I:Mr,O:N},{name:"ReadBinary",options:{},I:Hr,O:N},{name:"StreamText",serverStreaming:!0,options:{},I:xr,O:N},{name:"ReadText",options:{},I:jr,O:N},{name:"LastLines",options:{},I:Vr,O:N}]);class Jr{constructor(e){h(this,"typeName",ee.typeName);h(this,"methods",ee.methods);h(this,"options",ee.options);this._transport=e}streamBinary(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return y.stackIntercept("serverStreaming",this._transport,r,n,e)}readBinary(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}streamText(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return y.stackIntercept("serverStreaming",this._transport,r,n,e)}readText(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}lastLines(e,t){const r=this.methods[4],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}}class xe{constructor(e,t,r){h(this,"grpcClient");this.httpClient=t,this.logger=r,this.grpcClient=e.createGrpcClientProvider(n=>new Jr(n))}close(){}async lastLines({id:e,type:t},r,n=0n,o,d){return(await this.grpcClient.get().lastLines({resourceId:e,lineCount:r,offset:n,search:o},p.addRTypeToMetadata(t,d))).response}async readText({id:e,type:t},r,n=0n,o,d){return(await this.grpcClient.get().readText({resourceId:g.notEmpty(e),readLimit:BigInt(r),offset:n,search:o},p.addRTypeToMetadata(t,d))).response}}function Zr(i,e,t){return e.getDriver({name:"DownloadBlob",init:(r,n,o)=>new _e(n,o,i,t)})}function Qr(i,e){return i.getDriver({name:"StreamLogs",init:(t,r,n)=>new xe(r,n,e)})}function Kr(i,e){return i.getDriver({name:"UploadProgress",init:(t,r,n)=>new We(r,n,i,e)})}function Xr(i,e){return i.getDriver({name:"UploadBlob",init:(t,r,n)=>new Be(r,n,i,e)})}function Ae(i,e){return i.getDriver({name:"LsFiles",init:(t,r,n)=>new ze(r,e)})}const je=/^blob\+local:\/\/download\/(?<path>.*)#(?<signature>.*)$/;function Yr(i,e){return`blob+local://download/${i}#${e.sign(i)}`}function en(i){return!!i.match(je)}function te(i,e){const t=i.match(je);if(t===null)throw new Error(`Local handle is malformed: ${i}, matches: ${t}`);const{path:r,signature:n}=t.groups;return e.verify(r,n,`Signature verification failed for: ${i}`),{path:r,signature:n}}const Ge=m.rsSchema({kv:{"ctl/file/blobInfo":k.z.object({sizeBytes:k.z.coerce.number()})}});function fe(i,e){const t=i.kv["ctl/file/blobInfo"].sizeBytes;if(e){const r=e.to-e.from;if(r>t)throw new Error(`getSize: range (${JSON.stringify(e)}, newSize: ${r}) is greater than size (${t})`);return r}return t}const v=k.z.object({localPath:k.z.string(),pathSignature:k.z.string(),sizeBytes:k.z.string(),modificationTime:k.z.string()}),we=k.z.object({storageId:k.z.string(),path:k.z.string()}),tn=k.z.union([v,we]),Ve=m.rsSchema({data:v,fields:{blob:!1}}),qe=m.rsSchema({fields:{incarnation:!1}}),Je=/^blob\+remote:\/\/download\/(?<content>(?<resourceType>.+)\/(?<resourceVersion>.+?)\/(?<resourceId>\d+?)\/(?<size>\d+?))#(?<signature>.*)$/;function rn(i,e){let t=`${i.type.name}/${i.type.version}/${BigInt(i.id)}/${fe(i)}`;return`blob+remote://download/${t}#${e.sign(t)}`}function nn(i){return!!i.match(Je)}function on(i,e){const t=i.match(Je);if(t===null)throw new Error(`Remote handle is malformed: ${i}, matches: ${t}`);const{content:r,resourceType:n,resourceVersion:o,resourceId:d,size:s,signature:c}=t.groups;return e.verify(r,c,`Signature verification failed for ${i}`),{info:{id:p.bigintToResourceId(BigInt(d)),type:{name:n,version:o}},size:Number(s)}}class j extends Error{constructor(){super(...arguments);h(this,"name","WrongResourceTypeError")}}class Ze{constructor(e){h(this,"updating");this.onUpdate=e}schedule(){this.updating==null&&(this.updating=(async()=>{try{await this.onUpdate()}catch(e){console.log(`error while updating in Updater: ${e}`)}finally{this.updating=void 0}})())}}function Qe(i,e){return i?`log+live://log/${e.type.name}/${e.type.version}/${BigInt(e.id)}`:`log+ready://log/${e.type.name}/${e.type.version}/${BigInt(e.id)}`}const Ke=/^log\+live:\/\/log\/(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*)$/;function M(i){return Ke.test(i)}const Xe=/^log\+ready:\/\/log\/(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*)$/;function sn(i){return Xe.test(i)}function O(i){let e;if(M(i))e=i.match(Ke);else if(sn(i))e=i.match(Xe);else throw new Error(`Log handle is malformed: ${i}`);if(e==null)throw new Error(`Log handle wasn't parsed: ${i}`);const{resourceType:t,resourceVersion:r,resourceId:n}=e.groups;return{id:p.bigintToResourceId(BigInt(n)),type:{name:t,version:r}}}function T(i){return`${BigInt(i)}`}function Pe(i){return b.basename(i)}class an{constructor(e,t,r,n,o){h(this,"change",new f.ChangeSource);h(this,"signalCtl",new AbortController);h(this,"counter",new g.CallersCounter);h(this,"error");h(this,"done",!1);h(this,"size",0);h(this,"state",{});this.logger=e,this.clientDownload=t,this.rInfo=r,this.handle=n,this.path=o}info(){return{rInfo:this.rInfo,fPath:this.path,done:this.done,error:this.error,state:this.state}}attach(e,t){this.counter.inc(t),this.done||this.change.attachWatcher(e)}async download(){try{const e=await this.ensureDownloaded();this.setDone(e),this.change.markChanged(`blob download for ${p.resourceIdToString(this.rInfo.id)} finished`)}catch(e){throw this.logger.error(`download blob ${p.stringifyWithResourceId(this.rInfo)} failed: ${e}, state: ${JSON.stringify(this.state)}`),me(e)&&(this.setError(e),this.change.markChanged(`blob download for ${p.resourceIdToString(this.rInfo.id)} failed`),await w.rm(this.path,{force:!0})),e}}async ensureDownloaded(){this.signalCtl.signal.throwIfAborted(),this.state={},this.state.filePath=this.path,await g.ensureDirExists(b.dirname(this.state.filePath)),this.signalCtl.signal.throwIfAborted(),this.state.dirExists=!0;const e=await g.fileExists(this.state.filePath);if(this.signalCtl.signal.throwIfAborted(),e){this.state.fileExists=!0,this.logger.info(`a blob was already downloaded: ${this.state.filePath}`);const n=await w.stat(this.state.filePath);return this.signalCtl.signal.throwIfAborted(),this.state.fileSize=n.size,this.state.fileSize}const{content:t,size:r}=await this.clientDownload.downloadBlob(this.rInfo,{},this.signalCtl.signal);return this.state.fileSize=r,this.state.downloaded=!0,await g.createPathAtomically(this.logger,this.state.filePath,async n=>{const o=P.Writable.toWeb(R.createWriteStream(n,{flags:"wx"}));await t.pipeTo(o,{signal:this.signalCtl.signal}),this.state.tempWritten=!0}),this.state.done=!0,r}abort(e){this.signalCtl.abort(new Ye(e))}getBlob(){return this.done?{done:this.done,result:ln(this.handle,this.size,this.error)}:{done:!1}}setDone(e){this.done=!0,this.size=e}setError(e){this.done=!0,this.error=e}}function me(i){return i instanceof Ye||i instanceof z||i instanceof A||i instanceof x||(i==null?void 0:i.code)=="ENOENT"||i.name=="RpcError"&&(i.code=="NOT_FOUND"||i.code=="ABORTED")}class Ye extends Error{constructor(){super(...arguments);h(this,"name","DownloadAborted")}}function ln(i,e,t){return t?{ok:!1,error:t}:i?{ok:!0,value:{handle:i,size:e}}:{ok:!1,error:new Error("No file or handle provided")}}class ye{constructor(e){h(this,"cache",new Map);h(this,"totalSizeBytes",0);this.softSizeBytes=e}existsFile(e){return this.cache.get(e)!=null}getFile(e,t){const r=this.cache.get(e);return r!=null&&r.counter.inc(t),r}removeFile(e,t){return g.mapGet(this.cache,e).counter.dec(t),this.toDelete()}toDelete(){if(this.totalSizeBytes<=this.softSizeBytes)return[];const e=[];let t=0;return g.mapEntries(this.cache).filter(([r,n])=>n.counter.isZero()).forEach(([r,n])=>{if(this.totalSizeBytes-t<=this.softSizeBytes)return;const o=g.mapGet(this.cache,r);t+=o.size,e.push(o)}),e}addCache(e,t){const r=this.cache.get(e.path)==null;if(this.cache.set(e.path,e),e.counter.inc(t),e.size<0)throw new Error(`empty sizeBytes: ${e}`);r&&(this.totalSizeBytes+=e.size)}removeCache(e){this.cache.delete(e.path),this.totalSizeBytes-=e.size}}const dn=k.z.object({ranges:k.z.array(_.RangeBytes)}),cn=".ranges.json";function hn(i){return i+cn}async function un(i,e){let t={ranges:[]};try{const r=await w.readFile(e,"utf8");t=dn.parse(JSON.parse(r))}catch(r){if(r instanceof SyntaxError||r instanceof k.z.ZodError){const n=`readRangesFile: the file ${e} was corrupted: ${r}`;throw i.error(n),new tt(n)}if(!(r instanceof Error&&"code"in r&&r.code==="ENOENT"))throw r}return et(t),t}async function pn(i,e,t){await g.createPathAtomically(i,e,async r=>{await w.writeFile(r,JSON.stringify(t,null,2),{flag:"wx"})})}function et(i){i.ranges.sort((e,t)=>e.from-t.from);for(let e=0;e<i.ranges.length-1;e++)i.ranges[e].to>=i.ranges[e+1].from&&(gn(i,e),e--)}function gn(i,e){const t=Math.min(i.ranges[e].from,i.ranges[e+1].from),r=Math.max(i.ranges[e].to,i.ranges[e+1].to);i.ranges.splice(e,2,{from:t,to:r})}function C(i){return i.ranges.reduce((e,t)=>e+t.to-t.from,0)}function fn(i,e){for(const t of i.ranges)if(t.from<=e.from&&e.to<=t.to)return!0;return!1}function wn(i,e){return i.ranges.push(e),et(i),i}async function mn(i,e,t){try{await(await w.open(e,"w")).close(),await yn(e,t)}catch(r){i.error(`Error creating file ${e} on platform ${t}: ${r}`)}}async function yn(i,e){e==="win32"&&await g.spawnAsync("fsutil",["sparse","setflag",`"${i}"`],{stdio:"pipe"})}async function Tn(i,e,t,r,n){await g.fileExists(t)||await mn(i,t,e);const o=await w.open(t,"r+");await o.write(r,0,r.length,n),await o.close()}class tt extends Error{constructor(){super(...arguments);h(this,"name","CorruptedRangesError")}}class bn{constructor(e,t){this.logger=e,this.cacheDir=t}fPath(e){return U.join(this.cacheDir,hn(e))}async get(e){return await un(this.logger,this.fPath(e))}async set(e,t){return await pn(this.logger,this.fPath(e),t)}async delete(e){await R.promises.rm(this.fPath(e))}}class kn{constructor(e,t){h(this,"suffix",".sparse.bin");this.logger=e,this.cacheDir=t}async all(){return await g.ensureDirExists(this.cacheDir),(await R.promises.readdir(this.cacheDir)).filter(t=>t.endsWith(this.suffix))}async exists(e){return await g.fileExists(this.path(e))}path(e){return U.join(this.cacheDir,e+this.suffix)}async write(e,t,r){await g.ensureDirExists(this.cacheDir),await Tn(this.logger,process.platform,this.path(e),t,r)}async delete(e){await R.promises.rm(this.path(e))}}class Un{constructor(e,t,r,n){h(this,"lock",new kt.functions.AwaitLock);h(this,"keyToLastAccessTime",new Map);h(this,"size",0);this.logger=e,this.maxSize=t,this.ranges=r,this.storage=n}async reset(){await re(this.lock,async()=>{await this.resetUnsafe()})}async get(e,t){return await re(this.lock,async()=>await this.getUnsafe(e,t))}async set(e,t,r){await re(this.lock,async()=>{await this.setUnsafe(e,t,r)})}async resetUnsafe(){this.size=0,this.keyToLastAccessTime=new Map;const e=new Date;for(const t of await this.storage.all()){const r=await this.ranges.get(t);this.size+=C(r),this.keyToLastAccessTime.set(t,e)}}async getUnsafe(e,t){if(await this.storage.exists(e)){this.keyToLastAccessTime.set(e,new Date);const r=await this.getRanges(e);return fn(r,t)?this.storage.path(e):void 0}}async setUnsafe(e,t,r){await this.setWithoutEviction(e,t,r),await this.ensureEvicted()}async setWithoutEviction(e,t,r){if(t.to-t.from!==r.length)throw new Error(`SparseCache.set: trying to set ${e} with wrong range length: range: ${JSON.stringify(t)}, data: ${r.length}`);this.keyToLastAccessTime.set(e,new Date);const n=await this.getRanges(e);this.size-=C(n),await this.storage.write(e,r,t.from);const o=wn(n,t);this.size+=C(o),await this.ranges.set(e,o)}async ensureEvicted(){const e=g.mapEntries(this.keyToLastAccessTime);for(e.sort(([t,r],[n,o])=>o.getTime()-r.getTime());this.size>this.maxSize;){const t=e.pop();if(!t)break;const[r,n]=t,o=await this.getRanges(r);this.size-=C(o),this.rmKey(r)}}async getRanges(e){try{return await this.ranges.get(e)}catch(t){if(t instanceof tt)return await this.rmKey(e),await this.resetUnsafe(),await this.ranges.get(e);throw t}}async rmKey(e){await this.storage.delete(e),await this.ranges.delete(e),this.keyToLastAccessTime.delete(e)}}async function re(i,e){try{return await i.acquireAsync(),await e()}finally{i.release()}}class Te{constructor(e,t,r,n,o,d,s){h(this,"keyToDownload",new Map);h(this,"cache");h(this,"rangesCache");h(this,"downloadQueue");h(this,"keyToOnDemand",new Map);h(this,"idToLastLines",new Map);h(this,"idToProgressLog",new Map);h(this,"saveDir");this.logger=e,this.clientDownload=t,this.clientLogs=r,this.rangesCacheDir=o,this.signer=d,this.ops=s,this.cache=new ye(this.ops.cacheSoftSizeBytes);const c=new bn(this.logger,this.rangesCacheDir),l=new kn(this.logger,this.rangesCacheDir);this.rangesCache=new Un(this.logger,this.ops.rangesCacheMaxSizeBytes,c,l),this.downloadQueue=new g.TaskProcessor(this.logger,s.nConcurrentDownloads),this.saveDir=b.resolve(n)}static async init(e,t,r,n,o,d,s){const c=new Te(e,t,r,n,o,d,s);return await c.rangesCache.reset(),c}getDownloadedBlob(e,t){if(t===void 0)return f.Computable.make(d=>this.getDownloadedBlob(e,d));const r=m.treeEntryToResourceInfo(e,t),n=L.randomUUID();t.addOnDestroy(()=>this.releaseBlob(r,n));const o=this.getDownloadedBlobNoCtx(t.watcher,r,n);return o==null&&t.markUnstable("download blob is still undefined"),o}getDownloadedBlobNoCtx(e,t,r){$("getDownloadedBlob",t.type);const n=this.getOrSetNewTask(t,r);n.attach(e,r);const o=n.getBlob();if(o.done){if(o.result.ok)return o.result.value;throw o.result.error}}getOrSetNewTask(e,t){const r=T(e.id),n=this.keyToDownload.get(r);if(n)return n;const o=b.resolve(this.saveDir,r),d=new an(this.logger,this.clientDownload,e,Yr(o,this.signer),o);return this.keyToDownload.set(r,d),this.downloadQueue.push({fn:()=>this.downloadBlob(d,t),recoverableErrorPredicate:s=>!me(s)}),d}async downloadBlob(e,t){await e.download();const r=e.getBlob();r.done&&r.result.ok&&this.cache.addCache(e,t)}getOnDemandBlob(e,t){if(t===void 0)return f.Computable.make(d=>this.getOnDemandBlob(e,d));const r=m.isPlTreeEntry(e)?m.makeResourceSnapshot(e,Ge,t):e,n=L.randomUUID();return t.addOnDestroy(()=>this.releaseOnDemandBlob(r.id,n)),this.getOnDemandBlobNoCtx(r,n)}getOnDemandBlobNoCtx(e,t){$("getOnDemandBlob",e.type);let r=this.keyToOnDemand.get(T(e.id));return r===void 0&&(r=new Pn(fe(e),rn(e,this.signer)),this.keyToOnDemand.set(T(e.id),r)),r.attach(t),r.getHandle()}getLocalPath(e){const{path:t}=te(e,this.signer);return t}async getContent(e,t){if(t&&_.validateRangeBytes(t,"getContent"),en(e))return await Re(this.getLocalPath(e),t);if(nn(e)){const r=on(e,this.signer),n=T(r.info.id),o=await this.rangesCache.get(n,t??{from:0,to:r.size});if(o)return await Re(o,t);const{content:d}=await this.clientDownload.downloadBlob({id:r.info.id,type:r.info.type},void 0,void 0,t==null?void 0:t.from,t==null?void 0:t.to),s=await de.buffer(d);return await this.rangesCache.set(n,t??{from:0,to:r.size},s),s}throw new Error("Malformed remote handle")}getComputableContent(e,t){return t&&_.validateRangeBytes(t,"getComputableContent"),f.Computable.make(r=>this.getDownloadedBlob(e,r),{postprocessValue:r=>r?this.getContent(r.handle,t):void 0}).withStableType()}getLastLogs(e,t,r){if(r==null)return f.Computable.make(s=>this.getLastLogs(e,t,s));const n=m.treeEntryToResourceInfo(e,r),o=L.randomUUID();r.addOnDestroy(()=>this.releaseBlob(n,o));const d=this.getLastLogsNoCtx(r.watcher,n,t,o);return d==null&&r.markUnstable("either a file was not downloaded or logs was not read"),d}getLastLogsNoCtx(e,t,r,n){$("getLastLogs",t.type);const o=this.getDownloadedBlobNoCtx(e,t,n);if(o==null)return;const{path:d}=te(o.handle,this.signer);let s=this.idToLastLines.get(T(t.id));if(s==null){const l=new Le(d,r);this.idToLastLines.set(T(t.id),l),s=l}const c=s.getOrSchedule(e);if(c.error)throw c.error;return c.log}getProgressLog(e,t,r){if(r==null)return f.Computable.make(s=>this.getProgressLog(e,t,s));const n=m.treeEntryToResourceInfo(e,r),o=L.randomUUID();r.addOnDestroy(()=>this.releaseBlob(n,o));const d=this.getProgressLogNoCtx(r.watcher,n,t,o);return d===void 0&&r.markUnstable("either a file was not downloaded or a progress log was not read"),d}getProgressLogNoCtx(e,t,r,n){$("getProgressLog",t.type);const o=this.getDownloadedBlobNoCtx(e,t,n);if(o==null)return;const{path:d}=te(o.handle,this.signer);let s=this.idToProgressLog.get(T(t.id));if(s==null){const l=new Le(d,1,r);this.idToProgressLog.set(T(t.id),l),s=l}const c=s.getOrSchedule(e);if(c.error)throw c.error;return c.log}getLogHandle(e,t){if(t==null)return f.Computable.make(n=>this.getLogHandle(e,n));const r=m.treeEntryToResourceInfo(e,t);return this.getLogHandleNoCtx(r)}getLogHandleNoCtx(e){return $("getLogHandle",e.type),Qe(!1,e)}async lastLines(e,t,r,n){const o=await this.clientLogs.lastLines(O(e),t,BigInt(r??0),n);return{live:!1,shouldUpdateHandle:!1,data:o.data,size:Number(o.size),newOffset:Number(o.newOffset)}}async readText(e,t,r,n){const o=await this.clientLogs.readText(O(e),t,BigInt(r??0),n);return{live:!1,shouldUpdateHandle:!1,data:o.data,size:Number(o.size),newOffset:Number(o.newOffset)}}async releaseBlob(e,t){const r=this.keyToDownload.get(T(e.id));if(r!=null)if(this.cache.existsFile(T(e.id))){const n=this.cache.removeFile(T(e.id),t);await Promise.all(n.map(async o=>{await w.rm(o.path),this.cache.removeCache(o),this.removeTask(g.mapGet(this.keyToDownload,Pe(o.path)),`the task ${p.stringifyWithResourceId(o)} was removedfrom cache along with ${p.stringifyWithResourceId(n.map(d=>d.path))}`)}))}else r.counter.dec(t)&&this.removeTask(r,`the task ${p.stringifyWithResourceId(r.info())} was removed from cache`)}removeTask(e,t){e.abort(t),e.change.markChanged(`download task for ${e.path} removed: ${t}`),this.keyToDownload.delete(Pe(e.path)),this.idToLastLines.delete(T(e.rInfo.id)),this.idToProgressLog.delete(T(e.rInfo.id))}async releaseOnDemandBlob(e,t){var n;(((n=this.keyToOnDemand.get(T(e)))==null?void 0:n.release(t))??!1)&&this.keyToOnDemand.delete(T(e))}async releaseAll(){this.downloadQueue.stop(),this.keyToDownload.forEach((e,t)=>{this.keyToDownload.delete(t),e.change.markChanged(`task ${p.resourceIdToString(e.rInfo.id)} released`)})}}class Pn{constructor(e,t){h(this,"counter",new g.CallersCounter);this.size=e,this.handle=t}getHandle(){return{handle:this.handle,size:this.size}}attach(e){this.counter.inc(e)}release(e){return this.counter.dec(e)}}class Le{constructor(e,t,r){h(this,"updater");h(this,"log");h(this,"change",new f.ChangeSource);h(this,"error");this.path=e,this.lines=t,this.patternToSearch=r,this.updater=new Ze(async()=>this.update())}getOrSchedule(e){return this.change.attachWatcher(e),this.updater.schedule(),{log:this.log,error:this.error}}async update(){try{const e=await Ln(this.path,this.lines,this.patternToSearch);this.log!=e&&this.change.markChanged(`logs for ${this.path} updated`),this.log=e}catch(e){if(e.name=="RpcError"&&e.code=="NOT_FOUND"){this.log="",this.error=e,this.change.markChanged(`log update for ${this.path} failed, resource not found`);return}throw e}}}function Ln(i,e,t){const r=ce.createReadStream(i),n=new P.Writable;return new Promise((o,d)=>{const s=Dt.createInterface(r,n),c=new Tt;s.on("line",function(l){t!=null&&!l.includes(t)||(c.push(l),c.length>e&&c.shift())}),s.on("error",d),s.on("close",function(){o(c.toArray().join(Ue.EOL)+Ue.EOL)})})}async function Re(i,e){const t={};e&&(t.start=e.from,t.end=e.to-1);const r=ce.createReadStream(i,t);return await de.buffer(P.Readable.toWeb(r))}function $(i,e){if(!e.name.startsWith("Blob/")){let t=`${i}: wrong resource type: ${e.name}, expected: a resource of type that starts with 'Blob/'.`;throw e.name=="Blob"&&(t+=" If it's called from workflow, should a file be exported with 'file.exportFile' function?"),new j(t)}}const rt=m.rsSchema({});function nt(i,e){const t=m.isPlTreeEntry(i)?e.accessor(i).node():m.isPlTreeEntryAccessor(i)?i.node():i;return m.makeResourceSnapshot(t,rt)}function Rn(i,e,t){const r=U.relative(e,t);return`plblob+folder://${i.sign(r)}.${r}.blob`}function In(i){return new URL(i).protocol=="plblob+folder:"}function Sn(i,e,t){const r=new URL(e),[n,o,d]=r.host.split(".");i.verify(o,n,`signature verification failed for url: ${e}, subfolder: ${o}`);let s=Dn(U.join(t,`${o}`),r.pathname.slice(1));return(r.pathname==""||r.pathname=="/")&&(s=U.join(s,"index.html")),U.resolve(s)}function Dn(i,e){const t=U.resolve(i,e),r=U.resolve(i);if(!t.startsWith(r))throw new Error("Path validation failed.");return t}class Nn{constructor(e,t,r,n,o,d,s){h(this,"counter",new g.CallersCounter);h(this,"change",new f.ChangeSource);h(this,"signalCtl",new AbortController);h(this,"error");h(this,"done",!1);h(this,"size",0);h(this,"url");h(this,"state");this.logger=e,this.signer=t,this.saveDir=r,this.path=n,this.rInfo=o,this.format=d,this.clientDownload=s}info(){return{rInfo:this.rInfo,format:this.format,path:this.path,done:this.done,size:this.size,error:this.error,taskHistory:this.state}}attach(e,t){this.counter.inc(t),this.done||this.change.attachWatcher(e)}async download(){try{const e=await this.downloadAndDecompress(this.signalCtl.signal);this.setDone(e),this.change.markChanged(`download and decompress for ${p.resourceIdToString(this.rInfo.id)} finished`),this.logger.info(`blob to URL task is done: ${p.stringifyWithResourceId(this.info())}`)}catch(e){if(this.logger.warn(`a error was produced: ${e} for blob to URL task: ${p.stringifyWithResourceId(this.info())}`),$n(e)){this.setError(e),this.change.markChanged(`download and decompress for ${p.resourceIdToString(this.rInfo.id)} failed`),await se(this.path);return}throw e}}async downloadAndDecompress(e){if(this.state={},this.state.parentDir=U.dirname(this.path),await g.ensureDirExists(this.state.parentDir),this.state.fileExisted=await g.fileExists(this.path),this.state.fileExisted)return await ot(this.path);const{content:t,size:r}=await this.clientDownload.downloadBlob(this.rInfo,{},e);return this.state.downloaded=!0,await g.createPathAtomically(this.logger,this.path,async n=>{switch(this.state.tempPath=n,this.state.archiveFormat=this.format,this.format){case"tar":await w.mkdir(n);const o=P.Writable.toWeb(ie.extract(n));await t.pipeTo(o,{signal:e});return;case"tgz":await w.mkdir(n);const d=P.Transform.toWeb(Ce.createGunzip()),s=P.Writable.toWeb(ie.extract(n));await t.pipeThrough(d,{signal:e}).pipeTo(s,{signal:e});return;case"zip":this.state.zipPath=this.path+".zip";const c=P.Writable.toWeb(R.createWriteStream(this.state.zipPath));await t.pipeTo(c,{signal:e}),this.state.zipPathCreated=!0,await Lt(this.state.zipPath,n,{filter:l=>!l.path.endsWith("/")}),this.state.zipDecompressed=!0,await R.promises.rm(this.state.zipPath),this.state.zipPathDeleted=!0;return;default:a.assertNever(this.format)}}),this.state.pathCreated=!0,r}getURL(){if(this.done)return{url:g.notEmpty(this.url)};if(this.error)return{error:this.error}}setDone(e){this.done=!0,this.size=e,this.url=Rn(this.signer,this.saveDir,this.path)}setError(e){this.error=String(e)}abort(e){this.signalCtl.abort(new it(e))}}async function ot(i){const e=await w.readdir(i,{withFileTypes:!0});return(await Promise.all(e.map(async r=>{const n=U.join(i,r.name);return r.isDirectory()?await ot(n):(await w.stat(n)).size}))).reduce((r,n)=>r+n,0)}async function se(i){await w.rm(i,{recursive:!0,force:!0})}let it=class extends Error{constructor(){super(...arguments);h(this,"name","URLAborted")}};function $n(i){return i instanceof it||i instanceof z||i instanceof A||i instanceof x||(i==null?void 0:i.code)=="ENOENT"||i.name=="RpcError"&&(i.code=="NOT_FOUND"||i.code=="ABORTED")||String(i).includes("incorrect header check")}function F(i,e){return`id:${String(BigInt(i))}-${e}`}class vn{constructor(e,t,r,n,o={cacheSoftSizeBytes:50*1024*1024,nConcurrentDownloads:50}){h(this,"idToDownload",new Map);h(this,"downloadQueue");h(this,"cache");this.logger=e,this.signer=t,this.clientDownload=r,this.saveDir=n,this.opts=o,this.downloadQueue=new g.TaskProcessor(this.logger,this.opts.nConcurrentDownloads,{type:"exponentialWithMaxDelayBackoff",initialDelay:1e4,maxDelay:3e4,backoffMultiplier:1.5,jitter:.5}),this.cache=new ye(this.opts.cacheSoftSizeBytes)}info(){return{saveDir:this.saveDir,opts:this.opts,idToDownloadSize:this.idToDownload.size,idToDownloadKeys:this.idToDownload.keys(),idToDownload:Array.from(this.idToDownload.entries()).map(([e,t])=>[e,t.info()])}}getPathForCustomProtocol(e){if(In(e))return Sn(this.signer,e,this.saveDir);throw new Error(`getPathForCustomProtocol: ${e} is invalid`)}extractArchiveAndGetURL(e,t,r){if(r===void 0)return f.Computable.make(s=>this.extractArchiveAndGetURL(e,t,s));const n=m.isPlTreeEntry(e)?nt(e,r):e,o=L.randomUUID();r.addOnDestroy(()=>this.releasePath(n.id,t,o));const d=this.extractArchiveAndGetURLNoCtx(n,t,r.watcher,o);if((d==null?void 0:d.url)===void 0&&r.markUnstable(`a path to the downloaded archive might be undefined. The current result: ${d}`),(d==null?void 0:d.error)!==void 0)throw d==null?void 0:d.error;return d==null?void 0:d.url}extractArchiveAndGetURLNoCtx(e,t,r,n){const o=this.idToDownload.get(F(e.id,t));if(o!=null)return o.attach(r,n),o.getURL();const d=this.setNewTask(r,e,t,n);return this.downloadQueue.push({fn:async()=>this.downloadUrl(d,n),recoverableErrorPredicate:s=>!me(s)}),d.getURL()}async downloadUrl(e,t){var r;await e.download(),((r=e.getURL())==null?void 0:r.url)!=null&&this.cache.addCache(e,t)}async releasePath(e,t,r){const n=this.idToDownload.get(F(e,t));if(n!=null)if(this.cache.existsFile(n.path)){const o=this.cache.removeFile(n.path,r);await Promise.all(o.map(async d=>{await se(d.path),this.cache.removeCache(d),this.removeTask(d,`the task ${p.stringifyWithResourceId(d.info())} was removedfrom cache along with ${p.stringifyWithResourceId(o.map(s=>s.info()))}`)}))}else n.counter.dec(r)&&this.removeTask(n,`the task ${p.stringifyWithResourceId(n.info())} was removed from cache`)}async releaseAll(){this.downloadQueue.stop(),await Promise.all(Array.from(this.idToDownload.entries()).map(async([e,t])=>{await se(t.path),this.cache.removeCache(t),this.removeTask(t,`the task ${p.stringifyWithResourceId(t.info())} was released when the driver was closed`)}))}setNewTask(e,t,r,n){const o=new Nn(this.logger,this.signer,this.saveDir,this.getFilePath(t.id,r),t,r,this.clientDownload);return o.attach(e,n),this.idToDownload.set(F(t.id,r),o),o}removeTask(e,t){e.abort(t),e.change.markChanged(`task for ${p.resourceIdToString(e.rInfo.id)} removed: ${t}`),this.idToDownload.delete(F(e.rInfo.id,e.format))}getFilePath(e,t){return b.join(this.saveDir,`${String(BigInt(e))}_${t}`)}}class st{constructor(e,t,r,n,o,d){h(this,"change",new f.ChangeSource);h(this,"counter",new g.CallersCounter);h(this,"nMaxUploads");h(this,"nPartsWithThisUploadSpeed",0);h(this,"nPartsToIncreaseUpload",10);h(this,"uploadData");h(this,"progress");h(this,"failed");h(this,"alreadyExisted",!1);this.logger=e,this.clientBlob=t,this.clientProgress=r,this.maxNConcurrentPartsUpload=n,this.res=d,this.nMaxUploads=this.maxNConcurrentPartsUpload;const{uploadData:s,progress:c}=Cn(d,o);this.uploadData=s,this.progress=c}getProgress(e,t){if(this.incCounter(e,t),this.failed)throw this.logger.error(`Uploading terminally failed: ${this.progress.lastError}`),new Error(this.progress.lastError);return Fn(this.progress)}shouldScheduleUpload(){return lt(this.progress)}async uploadBlobTask(){try{await at(this.logger,this.clientBlob,this.res,this.uploadData,this.isComputableDone.bind(this),{nPartsWithThisUploadSpeed:this.nPartsWithThisUploadSpeed,nPartsToIncreaseUpload:this.nPartsToIncreaseUpload,currentSpeed:this.nMaxUploads,maxSpeed:this.maxNConcurrentPartsUpload}),this.change.markChanged(`blob upload for ${p.resourceIdToString(this.res.id)} finished`)}catch(e){if(this.setRetriableError(e),ae(e)){this.logger.warn(`resource was deleted while uploading a blob: ${e}`),this.change.markChanged(`blob upload for ${p.resourceIdToString(this.res.id)} aborted, resource was deleted`),this.setDone(!0);return}if(this.logger.error(`error while uploading a blob: ${e}`),this.change.markChanged(`blob upload for ${p.resourceIdToString(this.res.id)} failed`),be(e)){this.setTerminalError(e);return}throw _n(e)&&(this.nMaxUploads=On(this.logger,this.nMaxUploads,1)),e}}async updateStatus(){var e;try{const t=await this.clientProgress.getStatus(this.res,{timeout:1e4}),r=this.progress.status,n=En(this.alreadyExisted,Wn(t));this.progress.status=n,this.setDone(t.done),(t.done||this.progress.status.progress!=(r==null?void 0:r.progress))&&this.change.markChanged(`upload status for ${p.resourceIdToString(this.res.id)} changed`)}catch(t){if(this.setRetriableError(t),t.name=="RpcError"&&t.code=="DEADLINE_EXCEEDED"||(e=t==null?void 0:t.message)!=null&&e.includes("DEADLINE_EXCEEDED")){this.logger.warn("deadline exceeded while getting a status of BlobImport");return}if(ae(t)){this.logger.warn(`resource was not found while updating a status of BlobImport: ${t}, ${p.stringifyWithResourceId(this.res)}`),this.change.markChanged(`upload status for ${p.resourceIdToString(this.res.id)} changed, resource not found`),this.setDone(!0);return}this.logger.error(`retryable error while updating a status of BlobImport: ${t}`)}}setRetriableError(e){this.progress.lastError=String(e)}setTerminalError(e){this.progress.lastError=String(e),this.progress.done=!1,this.failed=!0}setDoneIfOutputSet(e){Bn(e)&&(this.setDone(!0),this.alreadyExisted=!0)}setDone(e){this.progress.done=e,e&&(this.progress.lastError=void 0)}incCounter(e,t){this.change.attachWatcher(e),this.counter.inc(t)}decCounter(e){return this.counter.dec(e)}isComputableDone(){return this.counter.isZero()}}async function at(i,e,t,r,n,o){Rt(H(t),"the upload operation can be done only for BlobUploads");const d=1e4;if(n())return;const s=await e.initUpload(t,{timeout:d});i.info(`started to upload blob ${t.id}, parts overall: ${s.overall}, parts remained: ${s.toUpload.length}, number of concurrent uploads: ${o.currentSpeed}`);const c=l=>async u=>{n()||(await e.partUpload(t,r.localPath,BigInt(r.modificationTime),l,{timeout:d}),i.info(`uploaded chunk ${l}/${s.overall} of resource: ${t.id}`),o.nPartsWithThisUploadSpeed++,o.nPartsWithThisUploadSpeed>=o.nPartsToIncreaseUpload&&(o.nPartsWithThisUploadSpeed=0,o.currentSpeed=Mn(i,o.currentSpeed,o.maxSpeed),u.setConcurrency(o.currentSpeed)))};await g.asyncPool(o.currentSpeed,s.toUpload.map(c)),!n()&&(await e.finalize(t,{timeout:d}),i.info(`uploading of resource ${t.id} finished.`))}function Cn(i,e){let t,r;return H(i)&&(r=v.parse(i.data),t=dt(e,r.localPath,r.pathSignature)),{uploadData:r,progress:{done:!1,status:void 0,isUpload:H(i),isUploadSignMatch:t,lastError:void 0}}}function lt(i){return i.isUpload&&(i.isUploadSignMatch??!1)}function Fn(i){return i.done,i.isUpload,i.isUploadSignMatch,i.lastError,i.status&&(i.status.progress,i.status.bytesProcessed,i.status.bytesTotal),i}function Bn(i){return"blob"in i.fields?i.fields.blob!==void 0:i.fields.incarnation!==void 0}function H(i){return i.type.name.startsWith("BlobUpload")}function dt(i,e,t){try{return i.verify(e,t),!0}catch{return!1}}function Wn(i){return{progress:i.progress??0,bytesProcessed:Number(i.bytesProcessed),bytesTotal:Number(i.bytesTotal)}}function En(i,e){return i&&e.bytesTotal!=0&&e.bytesProcessed==0?{progress:1,bytesProcessed:Number(e.bytesTotal),bytesTotal:Number(e.bytesTotal)}:e}function ae(i){return i.name=="RpcError"&&(i.code=="NOT_FOUND"||i.code=="ABORTED"||i.code=="ALREADY_EXISTS")}function be(i){return i instanceof he||i instanceof ue||i instanceof ge}function _n(i){return i==null?void 0:i.message.includes("UND_ERR_HEADERS_TIMEOUT")}function Mn(i,e,t){const r=Math.min(e+2,t);return r!=e&&i.info(`uploadTask.increaseConcurrency: increased from ${e} to ${r}`),r}function On(i,e,t){const r=Math.max(Math.round(e/2),t);return r!=e&&i.info(`uploadTask.decreaseConcurrency: decreased from ${e} to ${r}`),r}function ct(i,e){const t=m.isPlTreeEntry(i)?e.accessor(i).node():m.isPlTreeEntryAccessor(i)?i.node():i;return t.resourceType.name.startsWith("BlobUpload")?m.makeResourceSnapshot(t,Ve):m.makeResourceSnapshot(t,qe)}class Hn{constructor(e,t,r,n,o={nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3}){h(this,"idToProgress",new Map);h(this,"uploadQueue");h(this,"hooks");h(this,"scheduledOnNextState",[]);h(this,"keepRunning",!1);h(this,"currentLoop");this.logger=e,this.signer=t,this.clientBlob=r,this.clientProgress=n,this.opts=o,this.uploadQueue=new g.TaskProcessor(this.logger,1,{type:"exponentialWithMaxDelayBackoff",initialDelay:20,maxDelay:15e3,backoffMultiplier:1.5,jitter:.5}),this.hooks=new f.PollingComputableHooks(()=>this.startUpdating(),()=>this.stopUpdating(),{stopDebounce:o.stopPollingDelay},(d,s)=>this.scheduleOnNextState(d,s))}getProgressId(e,t){if(t==null)return f.Computable.make(d=>this.getProgressId(e,d));const r=m.isPlTreeEntry(e)?ct(e,t):e,n=L.randomUUID();return t.attacheHooks(this.hooks),t.addOnDestroy(()=>this.release(r.id,n)),this.getProgressIdNoCtx(t.watcher,r,n)}getProgressIdNoCtx(e,t,r){xn("getProgressId",t.type);const n=this.idToProgress.get(t.id);if(n!=null)return n.setDoneIfOutputSet(t),n.getProgress(e,r);const o=new st(this.logger,this.clientBlob,this.clientProgress,this.opts.nConcurrentPartUploads,this.signer,t);return this.idToProgress.set(t.id,o),o.shouldScheduleUpload()&&this.uploadQueue.push({fn:()=>o.uploadBlobTask(),recoverableErrorPredicate:d=>!be(d)}),o.setDoneIfOutputSet(t),o.getProgress(e,r)}async release(e,t){const r=this.idToProgress.get(e);if(r===void 0)return;r.decCounter(t)&&this.idToProgress.delete(e)}async releaseAll(){this.uploadQueue.stop()}scheduleOnNextState(e,t){this.scheduledOnNextState.push({resolve:e,reject:t})}startUpdating(){this.keepRunning=!0,this.currentLoop===void 0&&(this.currentLoop=this.mainLoop())}stopUpdating(){this.keepRunning=!1}async mainLoop(){for(;this.keepRunning;){const e=this.scheduledOnNextState;this.scheduledOnNextState=[];try{await g.asyncPool(this.opts.nConcurrentGetProgresses,this.getAllNotDoneProgresses().map(t=>async()=>await t.updateStatus())),e.forEach(t=>t.resolve())}catch(t){console.error(t),e.forEach(r=>r.reject(t))}if(!this.keepRunning)break;await ve.scheduler.wait(this.opts.pollingInterval)}this.currentLoop=void 0}getAllNotDoneProgresses(){return Array.from(this.idToProgress.entries()).filter(([e,t])=>!zn(t.progress)).map(([e,t])=>t)}}function zn(i){var e;return i.done&&(((e=i.status)==null?void 0:e.progress)??0)>=1}function xn(i,e){if(!e.name.startsWith("BlobUpload")&&!e.name.startsWith("BlobIndex"))throw new j(`${i}: wrong resource type: ${e.name}, expected: a resource of either type 'BlobUpload' or 'BlobIndex'.`)}class An{constructor(e,t,r={nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}){h(this,"idToLastLines",new Map);h(this,"idToProgressLog",new Map);h(this,"hooks");h(this,"scheduledOnNextState",[]);h(this,"keepRunning",!1);h(this,"currentLoop");this.logger=e,this.clientLogs=t,this.opts=r,this.hooks=new f.PollingComputableHooks(()=>this.startUpdating(),()=>this.stopUpdating(),{stopDebounce:r.stopPollingDelay},(n,o)=>this.scheduleOnNextState(n,o))}getLastLogs(e,t,r){if(r==null)return f.Computable.make(s=>this.getLastLogs(e,t,s));const n=m.treeEntryToResourceInfo(e,r),o=L.randomUUID();r.attacheHooks(this.hooks),r.addOnDestroy(()=>this.releaseLastLogs(n.id,o));const d=this.getLastLogsNoCtx(r.watcher,n,t,o);return r.markUnstable("The logs are from stream, so we consider them unstable. Final values will be got from blobs."),d}getLastLogsNoCtx(e,t,r,n){ne("getLastLogs",t.type);let o=this.idToLastLines.get(t.id);if(o==null){const s=new Ie(this.logger,this.clientLogs,t,r);this.idToLastLines.set(t.id,s),o=s}o.attach(e,n);const d=o.getLog();if(d.error!=null)throw d.error;return d.log}getProgressLog(e,t,r){if(r==null)return f.Computable.make(s=>this.getProgressLog(e,t,s));const n=m.treeEntryToResourceInfo(e,r),o=L.randomUUID();r.attacheHooks(this.hooks),r.addOnDestroy(()=>this.releaseProgressLog(n.id,o));const d=this.getProgressLogNoCtx(r.watcher,n,t,o);return r.markUnstable("The progress log is from the stream, so we consider it unstable. Final value will be got from blobs."),d}getProgressLogNoCtx(e,t,r,n){ne("getProgressLog",t.type);let o=this.idToProgressLog.get(t.id);if(o==null){const s=new Ie(this.logger,this.clientLogs,t,1,r);this.idToProgressLog.set(t.id,s),o=s}o.attach(e,n);const d=o.getLog();if(d.error)throw d.error;return d.log}getLogHandle(e,t){if(t==null)return f.Computable.make(o=>this.getLogHandle(e,o));const r=m.treeEntryToResourceInfo(e,t),n=this.getLogHandleNoCtx(r);return t.markUnstable(`live_log:${p.resourceIdToString(r.id)}`),n}getLogHandleNoCtx(e){return ne("getLogHandle",e.type),Qe(!0,e)}async lastLines(e,t,r,n){return await this.tryWithNotFound(e,()=>this.clientLogs.lastLines(O(e),t,BigInt(r??0),n))}async readText(e,t,r,n){return await this.tryWithNotFound(e,()=>this.clientLogs.readText(O(e),t,BigInt(r??0),n))}async tryWithNotFound(e,t){if(!M(e))throw new Error(`Not live log handle was passed to live log driver, handle: ${e}`);try{const r=await t();return{live:!0,shouldUpdateHandle:!1,data:r.data,size:Number(r.size),newOffset:Number(r.newOffset)}}catch(r){if(r.name=="RpcError"&&r.code=="NOT_FOUND")return{shouldUpdateHandle:!0};throw r}}async releaseLastLogs(e,t){var n;((n=this.idToLastLines.get(e))==null?void 0:n.release(t))&&this.idToLastLines.delete(e)}async releaseProgressLog(e,t){var n;((n=this.idToProgressLog.get(e))==null?void 0:n.release(t))&&this.idToProgressLog.delete(e)}async releaseAll(){}scheduleOnNextState(e,t){this.scheduledOnNextState.push({resolve:e,reject:t})}startUpdating(){this.keepRunning=!0,this.currentLoop===void 0&&(this.currentLoop=this.mainLoop())}stopUpdating(){this.keepRunning=!1}async mainLoop(){for(;this.keepRunning;){const e=this.scheduledOnNextState;this.scheduledOnNextState=[];try{const t=this.getAllLogs();await g.asyncPool(this.opts.nConcurrentGetLogs,t.map(r=>async()=>await r.update())),e.forEach(r=>r.resolve())}catch(t){console.error(t),e.forEach(r=>r.reject(t))}if(!this.keepRunning)break;await ve.scheduler.wait(this.opts.pollingInterval)}this.currentLoop=void 0}getAllLogs(){return Array.from(this.idToLastLines.entries()).concat(Array.from(this.idToProgressLog.entries())).map(([e,t])=>t)}}class Ie{constructor(e,t,r,n,o){h(this,"logs");h(this,"error");h(this,"change",new f.ChangeSource);h(this,"counter",new g.CallersCounter);this.logger=e,this.clientLogs=t,this.rInfo=r,this.lines=n,this.patternToSearch=o}getLog(){return{log:this.logs,error:this.error}}attach(e,t){this.change.attachWatcher(e),this.counter.inc(t)}release(e){return this.counter.dec(e)}async update(){try{const e=await this.clientLogs.lastLines(this.rInfo,this.lines,0n,this.patternToSearch),t=new TextDecoder().decode(e.data);this.logs!=t&&this.change.markChanged(`logs for ${p.resourceIdToString(this.rInfo.id)} updated`),this.logs=t,this.error=void 0;return}catch(e){if(e.name=="RpcError"&&e.code=="NOT_FOUND"){this.logs="",this.error=e,this.change.markChanged();return}throw this.logger.error(`Stream log lines for ${p.stringifyWithResourceId(this.rInfo.id)} failed, reason: ${e}`),e}}}function ne(i,e){if(!e.name.startsWith("StreamWorkdir"))throw new j(`${i}: wrong resource type: ${e.name}, expected: a resource of type 'StreamWorkdir'.`)}class jn{constructor(e,t,r){this.logger=e,this.logsStreamDriver=t,this.downloadDriver=r}getLastLogs(e,t,r){if(r===void 0)return f.Computable.make(o=>this.getLastLogs(e,t,o));const n=W(r,e);if(n===void 0){r.markUnstable("no stream in stream manager");return}if(B(n))return this.downloadDriver.getLastLogs(n,t,r);try{return this.logsStreamDriver.getLastLogs(n,t,r)}catch(o){if(o.name=="RpcError"&&o.code=="NOT_FOUND"){r.markUnstable(`NOT_FOUND in logs stream driver while getting last logs: ${o}`);return}throw o}}getProgressLog(e,t,r){if(r===void 0)return f.Computable.make(o=>this.getProgressLog(e,t,o));const n=W(r,e);if(n===void 0){r.markUnstable("no stream in stream manager");return}if(B(n))return this.downloadDriver.getProgressLog(n,t,r);try{return this.logsStreamDriver.getProgressLog(n,t,r)}catch(o){if(o.name=="RpcError"&&o.code=="NOT_FOUND"){r.markUnstable(`NOT_FOUND in logs stream driver while getting a progress log: ${o}`);return}throw o}}getProgressLogWithInfo(e,t,r){if(r===void 0)return f.Computable.make(o=>this.getProgressLogWithInfo(e,t,o));const n=W(r,e);if(n===void 0){r.markUnstable("no stream in stream manager");return}if(B(n))return{progressLine:this.downloadDriver.getProgressLog(n,t,r),live:!1};try{return{progressLine:this.logsStreamDriver.getProgressLog(n,t,r),live:!0}}catch(o){if(o.name=="RpcError"&&o.code=="NOT_FOUND"){r.markUnstable(`NOT_FOUND in logs stream driver while getting a progress log with info: ${o}`);return}throw o}}getLogHandle(e,t){if(t===void 0)return f.Computable.make(n=>this.getLogHandle(e,n));const r=W(t,e);if(r===void 0){t.markUnstable("no stream in stream manager");return}return B(r)?this.downloadDriver.getLogHandle(r,t):this.logsStreamDriver.getLogHandle(r,t)}async lastLines(e,t,r,n){return M(e)?await this.logsStreamDriver.lastLines(e,t,r,n):await this.downloadDriver.lastLines(e,t,r,n)}async readText(e,t,r,n){return M(e)?await this.logsStreamDriver.readText(e,t,r,n):await this.downloadDriver.readText(e,t,r,n)}}function B(i){return!i.type.name.startsWith("StreamWorkdir")}function W(i,e){var t;return(t=i.accessor(e).node().traverse("stream"))==null?void 0:t.resourceInfo}class Gn{constructor(e,t,r,n={cacheSoftSizeBytes:1*1024*1024*1024,withGunzip:!0,nConcurrentDownloads:50}){h(this,"downloadHelper");h(this,"urlToDownload",new Map);h(this,"downloadQueue");h(this,"cache");this.logger=e,this.saveDir=r,this.opts=n,this.downloadQueue=new g.TaskProcessor(this.logger,this.opts.nConcurrentDownloads),this.cache=new ye(this.opts.cacheSoftSizeBytes),this.downloadHelper=new Ee(t)}getPath(e,t){if(t===void 0)return f.Computable.make(o=>this.getPath(e,o));const r=L.randomUUID();t.addOnDestroy(()=>this.releasePath(e,r));const n=this.getPathNoCtx(e,t.watcher,r);return(n==null?void 0:n.path)===void 0&&t.markUnstable(`a path to the downloaded and untared archive might be undefined. The current result: ${n}`),n}getPathNoCtx(e,t,r){const n=e.toString(),o=this.urlToDownload.get(n);if(o!=null)return o.attach(t,r),o.getPath();const d=this.setNewTask(t,e,r);return this.downloadQueue.push({fn:async()=>this.downloadUrl(d,r),recoverableErrorPredicate:s=>!0}),d.getPath()}async downloadUrl(e,t){var r;await e.download(this.downloadHelper,this.opts.withGunzip),((r=e.getPath())==null?void 0:r.path)!=null&&this.cache.addCache(e,t)}async releasePath(e,t){const r=e.toString(),n=this.urlToDownload.get(r);if(n!=null)if(this.cache.existsFile(n.path)){const o=this.cache.removeFile(n.path,t);await Promise.all(o.map(async d=>{await le(d.path),this.cache.removeCache(d),this.removeTask(d,`the task ${p.stringifyWithResourceId(d.info())} was removedfrom cache along with ${p.stringifyWithResourceId(o.map(s=>s.info()))}`)}))}else n.counter.dec(t)&&this.removeTask(n,`the task ${p.stringifyWithResourceId(n.info())} was removed from cache`)}async releaseAll(){this.downloadQueue.stop(),await Promise.all(Array.from(this.urlToDownload.entries()).map(async([e,t])=>{await le(t.path),this.cache.removeCache(t),this.removeTask(t,`the task ${p.stringifyWithResourceId(t.info())} was released when the driver was closed`)}))}setNewTask(e,t,r){const n=new Vn(this.logger,this.getFilePath(t),t);return n.attach(e,r),this.urlToDownload.set(t.toString(),n),n}removeTask(e,t){e.abort(t),e.change.markChanged(`task for url ${e.url} removed: ${t}`),this.urlToDownload.delete(e.url.toString())}getFilePath(e){const t=L.createHash("sha256").update(e.toString()).digest("hex");return b.join(this.saveDir,t)}}class Vn{constructor(e,t,r){h(this,"counter",new g.CallersCounter);h(this,"change",new f.ChangeSource);h(this,"signalCtl",new AbortController);h(this,"error");h(this,"done",!1);h(this,"size",0);this.logger=e,this.path=t,this.url=r}info(){return{url:this.url.toString(),path:this.path,done:this.done,size:this.size,error:this.error}}attach(e,t){this.counter.inc(t),this.done||this.change.attachWatcher(e)}async download(e,t){try{const r=await this.downloadAndUntar(e,t,this.signalCtl.signal);this.setDone(r),this.change.markChanged(`download of ${this.url} finished`)}catch(r){if(r instanceof Se||r instanceof z){this.setError(r),this.change.markChanged(`download of ${this.url} failed`),await le(this.path);return}throw r}}async downloadAndUntar(e,t,r){if(await g.ensureDirExists(b.dirname(this.path)),await g.fileExists(this.path))return await ht(this.path);const n=await e.download(this.url.toString(),{},r);let o=n.content;if(t){const d=P.Transform.toWeb(Ce.createGunzip());o=o.pipeThrough(d,{signal:r})}return await g.createPathAtomically(this.logger,this.path,async d=>{await w.mkdir(d);const s=P.Writable.toWeb(ie.extract(d));await o.pipeTo(s,{signal:r})}),n.size}getPath(){if(this.done)return{path:g.notEmpty(this.path)};if(this.error)return{error:this.error}}setDone(e){this.done=!0,this.size=e}setError(e){this.error=String(e)}abort(e){this.signalCtl.abort(new Se(e))}}class Se extends Error{constructor(){super(...arguments);h(this,"name","URLAborted")}}async function ht(i){const e=await w.readdir(i,{withFileTypes:!0});return(await Promise.all(e.map(async r=>{const n=b.join(i,r.name);return r.isDirectory()?await ht(n):(await w.stat(n)).size}))).reduce((r,n)=>r+n,0)}async function le(i){await w.rm(i,{recursive:!0,force:!0})}function oe(i,e){return`index://index/${encodeURIComponent(JSON.stringify({storageId:i,path:e}))}`}function qn(i,e,t,r){const n={localPath:i,pathSignature:e.sign(i),sizeBytes:String(t),modificationTime:String(r)};return`upload://upload/${encodeURIComponent(JSON.stringify(n))}`}function Jn(i){const e=new URL(i);return v.parse(JSON.parse(decodeURIComponent(e.pathname.substring(1))))}function Zn(i){const e=new URL(i);return we.parse(JSON.parse(decodeURIComponent(e.pathname.substring(1))))}function De(i){if(Yn(i))return to(i);if(Qn(i))return Xn(i);g.assertNever(i)}const ut=/^local:\/\/(?<name>.*)\/(?<path>.*)$/;function Qn(i){return ut.test(i)}function Kn(i,e){return`local://${i}/${encodeURIComponent(e)}`}function Xn(i){const e=i.match(ut);if(e==null)throw new Error(`Local list handle wasn't parsed: ${i}`);const{name:t,path:r}=e.groups;return{rootPath:decodeURIComponent(r),name:t,isRemote:!1}}const pt=/^remote:\/\/(?<name>.*)\/(?<resourceId>.*)$/;function Yn(i){return pt.test(i)}function eo(i,e){return`remote://${i}/${BigInt(e)}`}function to(i){const e=i.match(pt);if(e==null)throw new Error(`Remote list handle wasn't parsed: ${i}`);const{name:t,resourceId:r}=e.groups;return{id:p.bigintToResourceId(BigInt(r)),type:ro(t),name:t,isRemote:!0}}function ro(i){return{name:`LS/${i}`,version:"1"}}async function gt(){const i=$e.homedir();if(U.sep=="/")return[{name:"local",root:"/",initialPath:i}];{const t=U.parse(i).root.replaceAll(":\\","");try{return(await It.promisify(St.exec)("wmic logicaldisk get name")).stdout.split(`\r
|
|
2
|
-
`).filter(o=>o.includes(":")).map(o=>o.trim().replaceAll(":","")).map(o=>{const d=o==t;return{name:`local_disk_${o}`,root:`${o}:\\`,initialPath:d?i:`${o}:\\`}})}catch{return[{name:`local_disk_${t}`,root:`${t}:\\`,initialPath:i}]}}}class ke{constructor(e,t,r,n,o,d,s){this.logger=e,this.lsClient=t,this.storageIdToResourceId=r,this.signer=n,this.virtualStoragesMap=o,this.localProjectionsMap=d,this.openFileDialogCallback=s}async getLocalFileContent(e,t){const r=await this.tryResolveLocalFileHandle(e);if(t)throw new Error("Range request not yet supported.");return await w.readFile(r)}async getLocalFileSize(e){const t=await this.tryResolveLocalFileHandle(e);return(await w.stat(t)).size}async showOpenMultipleFilesDialog(e){const t=await this.openFileDialogCallback(!0,e);return t===void 0?{}:{files:await Promise.all(t.map(r=>this.getLocalFileHandle(r)))}}async showOpenSingleFileDialog(e){const t=await this.openFileDialogCallback(!1,e);return t===void 0?{}:{file:await this.getLocalFileHandle(t[0])}}async tryResolveLocalFileHandle(e){if(
|
|
1
|
+
"use strict";var mt=Object.defineProperty;var yt=(i,e,t)=>e in i?mt(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var h=(i,e,t)=>yt(i,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@milaboratories/pl-client"),Tt=require("node:fs/promises"),Ne=require("undici"),y=require("@protobuf-ts/runtime-rpc"),a=require("@protobuf-ts/runtime"),g=require("@milaboratories/ts-helpers"),R=require("node:fs"),k=require("node:path"),L=require("node:stream"),de=require("node:stream/consumers"),f=require("@milaboratories/computable"),N=require("@milaboratories/pl-model-common"),m=require("@milaboratories/pl-tree"),bt=require("denque"),P=require("node:crypto"),$e=require("node:os"),kt=require("node:readline/promises"),U=require("zod"),Ut=require("@milaboratories/helpers"),Lt=require("node:zlib"),Pt=require("tar-fs"),Rt=require("decompress"),ve=require("node:timers/promises"),It=require("node:assert"),St=require("node:util"),Dt=require("node:child_process");function I(i){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const t in i)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(i,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>i[t]})}}return e.default=i,Object.freeze(e)}const w=I(Tt),ce=I(R),b=I(k),Ue=I($e),Nt=I(kt),Ce=I(Lt),ie=I(Pt);class $t extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new $t;class vt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Init",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new vt;class Ct extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Init.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Ft=new Ct;class Bt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Init.Response",[{no:1,name:"parts_count",kind:"scalar",T:4,L:0},{no:2,name:"uploaded_parts",kind:"scalar",repeat:1,T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.partsCount=0n,t.uploadedParts=[],e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.partsCount=e.uint64().toBigInt();break;case 2:if(c===a.WireType.LengthDelimited)for(let G=e.int32()+e.pos;e.pos<G;)o.uploadedParts.push(e.uint64().toBigInt());else o.uploadedParts.push(e.uint64().toBigInt());break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){if(e.partsCount!==0n&&t.tag(1,a.WireType.Varint).uint64(e.partsCount),e.uploadedParts.length){t.tag(2,a.WireType.LengthDelimited).fork();for(let o=0;o<e.uploadedParts.length;o++)t.uint64(e.uploadedParts[o]);t.join()}let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Wt=new Bt;class Et extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.UpdateProgress",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new Et;class _t extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.UpdateProgress.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"bytes_processed",kind:"scalar",T:3,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.bytesProcessed=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.bytesProcessed=e.int64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.bytesProcessed!==0n&&t.tag(2,a.WireType.Varint).int64(e.bytesProcessed);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Mt=new _t;class Ot extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.UpdateProgress.Response",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Ht=new Ot;class zt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new zt;class xt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"part_number",kind:"scalar",T:4,L:0},{no:3,name:"uploaded_part_size",kind:"scalar",T:4,L:0},{no:4,name:"is_internal_use",kind:"scalar",T:8}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.partNumber=0n,t.uploadedPartSize=0n,t.isInternalUse=!1,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.partNumber=e.uint64().toBigInt();break;case 3:o.uploadedPartSize=e.uint64().toBigInt();break;case 4:o.isInternalUse=e.bool();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.partNumber!==0n&&t.tag(2,a.WireType.Varint).uint64(e.partNumber),e.uploadedPartSize!==0n&&t.tag(3,a.WireType.Varint).uint64(e.uploadedPartSize),e.isInternalUse!==!1&&t.tag(4,a.WireType.Varint).bool(e.isInternalUse);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const At=new xt;class jt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL.HTTPHeader",[{no:1,name:"Name",kind:"scalar",jsonName:"Name",T:9},{no:2,name:"Value",kind:"scalar",jsonName:"Value",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.name="",t.value="",e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.name=e.string();break;case 2:o.value=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.name!==""&&t.tag(1,a.WireType.LengthDelimited).string(e.name),e.value!==""&&t.tag(2,a.WireType.LengthDelimited).string(e.value);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const V=new jt;class Gt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.GetPartURL.Response",[{no:1,name:"upload_url",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"headers",kind:"message",repeat:2,T:()=>V},{no:4,name:"chunk_start",kind:"scalar",T:4,L:0},{no:5,name:"chunk_end",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.uploadUrl="",t.method="",t.headers=[],t.chunkStart=0n,t.chunkEnd=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.uploadUrl=e.string();break;case 2:o.method=e.string();break;case 3:o.headers.push(V.internalBinaryRead(e,e.uint32(),r));break;case 4:o.chunkStart=e.uint64().toBigInt();break;case 5:o.chunkEnd=e.uint64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.uploadUrl!==""&&t.tag(1,a.WireType.LengthDelimited).string(e.uploadUrl),e.method!==""&&t.tag(2,a.WireType.LengthDelimited).string(e.method);for(let o=0;o<e.headers.length;o++)V.internalBinaryWrite(e.headers[o],t.tag(3,a.WireType.LengthDelimited).fork(),r).join();e.chunkStart!==0n&&t.tag(4,a.WireType.Varint).uint64(e.chunkStart),e.chunkEnd!==0n&&t.tag(5,a.WireType.Varint).uint64(e.chunkEnd);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Vt=new Gt;class qt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Finalize",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new qt;class Jt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Finalize.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Zt=new Jt;class Qt extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.uploadapi.Finalize.Response",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Kt=new Qt,q=new y.ServiceType("MiLaboratories.Controller.Shared.Upload",[{name:"Init",options:{},I:Ft,O:Wt},{name:"GetPartURL",options:{},I:At,O:Vt},{name:"UpdateProgress",options:{},I:Mt,O:Ht},{name:"Finalize",options:{},I:Zt,O:Kt}]);class Xt{constructor(e){h(this,"typeName",q.typeName);h(this,"methods",q.methods);h(this,"options",q.options);this._transport=e}init(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}getPartURL(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}updateProgress(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}finalize(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}}function Fe(i,e,t){const r=Object.fromEntries(i.map(({name:n,value:o})=>[n,o]));return e!==void 0&&t!==void 0&&(r.Range=`bytes=${e}-${t-1}`),r}class he extends Error{constructor(){super(...arguments);h(this,"name","MTimeError")}}class ue extends Error{constructor(){super(...arguments);h(this,"name","UnexpectedEOF")}}class pe extends Error{constructor(){super(...arguments);h(this,"name","NetworkError")}}class ge extends Error{constructor(){super(...arguments);h(this,"name","NoFileForUploading")}}class Be{constructor(e,t,r,n){h(this,"grpcClient");this.httpClient=t,this.logger=n,this.grpcClient=e.createGrpcClientProvider(o=>new Xt(o))}close(){}async initUpload({id:e,type:t},r){const n=await this.grpcInit(e,t,r);return{overall:n.partsCount,toUpload:this.partsToUpload(n.partsCount,n.uploadedParts)}}async partUpload({id:e,type:t},r,n,o,d){const s=await this.grpcGetPartUrl({id:e,type:t},o,0n,d),c=await Yt(r,s.chunkStart,s.chunkEnd);await tr(r,n);try{const{body:l,statusCode:u,headers:G}=await Ne.request(s.uploadUrl,{dispatcher:this.httpClient,body:c,headersTimeout:6e4,bodyTimeout:6e4,headers:Fe(s.headers),method:s.method.toUpperCase()}),wt=await l.text();rr(u,wt,G,s)}catch(l){throw l instanceof pe?l:new Error(`partUpload: error ${JSON.stringify(l)} happened while trying to do part upload to the url ${s.uploadUrl}, headers: ${JSON.stringify(s.headers)}`)}await this.grpcUpdateProgress({id:e,type:t},BigInt(s.chunkEnd-s.chunkStart),d)}async finalize(e,t){return await this.grpcFinalize(e,t)}partsToUpload(e,t){const r=[],n=new Set(t);for(let o=1n;o<=e;o++)n.has(o)||r.push(o);return r}async grpcInit(e,t,r){return await this.grpcClient.get().init({resourceId:e},p.addRTypeToMetadata(t,r)).response}async grpcGetPartUrl({id:e,type:t},r,n,o){return await this.grpcClient.get().getPartURL({resourceId:e,partNumber:r,uploadedPartSize:n,isInternalUse:!1},p.addRTypeToMetadata(t,o)).response}async grpcUpdateProgress({id:e,type:t},r,n){await this.grpcClient.get().updateProgress({resourceId:e,bytesProcessed:r},p.addRTypeToMetadata(t,n)).response}async grpcFinalize({id:e,type:t},r){return await this.grpcClient.get().finalize({resourceId:e},p.addRTypeToMetadata(t,r)).response}}async function Yt(i,e,t){let r;try{r=await w.open(i);const n=Number(t-e),o=Number(e),d=Buffer.alloc(n),s=await er(r,d,n,o);return d.subarray(0,s)}catch(n){throw n&&typeof n=="object"&&"code"in n&&n.code=="ENOENT"?new ge(`there is no file ${i} for uploading`):n}finally{await(r==null?void 0:r.close())}}async function er(i,e,t,r){let n=0;for(;n<t;){const{bytesRead:o}=await i.read(e,n,t-n,r+n);if(o===0)throw new ue("file ended earlier than expected.");n+=o}return n}async function tr(i,e){const t=BigInt(Math.floor((await w.stat(i)).mtimeMs/1e3));if(t>e)throw new he(`file was modified, expected mtime: ${e}, got: ${t}.`)}function rr(i,e,t,r){if(i!=200)throw new pe(`response is not ok, status code: ${i}, body: ${e}, headers: ${JSON.stringify(t)}, url: ${r.uploadUrl}`)}class nr extends a.MessageType{constructor(){super("google.protobuf.Duration",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}internalJsonWrite(e,t){let r=a.PbLong.from(e.seconds).toNumber();if(r>315576e6||r<-315576e6)throw new Error("Duration value out of range.");let n=e.seconds.toString();if(r===0&&e.nanos<0&&(n="-"+n),e.nanos!==0){let o=Math.abs(e.nanos).toString();o="0".repeat(9-o.length)+o,o.substring(3)==="000000"?o=o.substring(0,3):o.substring(6)==="000"&&(o=o.substring(0,6)),n+="."+o}return n+"s"}internalJsonRead(e,t,r){if(typeof e!="string")throw new Error("Unable to parse Duration from JSON "+a.typeofJsonValue(e)+". Expected string.");let n=e.match(/^(-?)([0-9]+)(?:\.([0-9]+))?s/);if(n===null)throw new Error("Unable to parse Duration from JSON string. Invalid format.");r||(r=this.create());let[,o,d,s]=n,c=a.PbLong.from(o+d);if(c.toNumber()>315576e6||c.toNumber()<-315576e6)throw new Error("Unable to parse Duration from JSON string. Value out of range.");if(r.seconds=c.toBigInt(),typeof s=="string"){let l=o+s+"0".repeat(9-s.length);r.nanos=parseInt(l)}return r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0n,t.nanos=0,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.seconds=e.int64().toBigInt();break;case 2:o.nanos=e.int32();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.seconds!==0n&&t.tag(1,a.WireType.Varint).int64(e.seconds),e.nanos!==0&&t.tag(2,a.WireType.Varint).int32(e.nanos);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const _=new nr;class or extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new or;class ir extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.Report",[{no:1,name:"progress",kind:"scalar",T:2},{no:2,name:"bytes_processed",kind:"scalar",T:4,L:0},{no:3,name:"bytes_total",kind:"scalar",T:4,L:0},{no:4,name:"done",kind:"scalar",T:8},{no:5,name:"name",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.progress=0,t.bytesProcessed=0n,t.bytesTotal=0n,t.done=!1,t.name="",e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.progress=e.float();break;case 2:o.bytesProcessed=e.uint64().toBigInt();break;case 3:o.bytesTotal=e.uint64().toBigInt();break;case 4:o.done=e.bool();break;case 5:o.name=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.progress!==0&&t.tag(1,a.WireType.Bit32).float(e.progress),e.bytesProcessed!==0n&&t.tag(2,a.WireType.Varint).uint64(e.bytesProcessed),e.bytesTotal!==0n&&t.tag(3,a.WireType.Varint).uint64(e.bytesTotal),e.done!==!1&&t.tag(4,a.WireType.Varint).bool(e.done),e.name!==""&&t.tag(5,a.WireType.LengthDelimited).string(e.name);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const D=new ir;class sr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new sr;class ar extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const lr=new ar;class dr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.GetStatus.Response",[{no:1,name:"report",kind:"message",T:()=>D}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.report=D.internalBinaryRead(e,e.uint32(),r,o.report);break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.report&&D.internalBinaryWrite(e.report,t.tag(1,a.WireType.LengthDelimited).fork(),r).join();let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const cr=new dr;class hr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new hr;class ur extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"update_interval",kind:"message",T:()=>_}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.updateInterval=_.internalBinaryRead(e,e.uint32(),r,o.updateInterval);break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.updateInterval&&_.internalBinaryWrite(e.updateInterval,t.tag(2,a.WireType.LengthDelimited).fork(),r).join();let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const pr=new ur;class gr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.ProgressAPI.RealtimeStatus.Response",[{no:1,name:"report",kind:"message",T:()=>D}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.report=D.internalBinaryRead(e,e.uint32(),r,o.report);break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.report&&D.internalBinaryWrite(e.report,t.tag(1,a.WireType.LengthDelimited).fork(),r).join();let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const fr=new gr,J=new y.ServiceType("MiLaboratories.Controller.Shared.Progress",[{name:"GetStatus",options:{"google.api.http":{get:"/resources/{resource_id}/get-progress"}},I:lr,O:cr},{name:"RealtimeStatus",serverStreaming:!0,options:{},I:pr,O:fr}]);class wr{constructor(e){h(this,"typeName",J.typeName);h(this,"methods",J.methods);h(this,"options",J.options);this._transport=e}getStatus(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}realtimeStatus(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return y.stackIntercept("serverStreaming",this._transport,r,n,e)}}class We{constructor(e,t,r,n){h(this,"grpcClient");this.client=r,this.logger=n,this.grpcClient=e.createGrpcClientProvider(o=>new wr(o))}close(){}async getStatus({id:e,type:t},r){const n=await this.grpcClient.get().getStatus({resourceId:e},p.addRTypeToMetadata(t,r)),o=g.notEmpty(n.response.report);return{done:o.done,progress:o.progress,bytesProcessed:String(o.bytesProcessed),bytesTotal:String(o.bytesTotal)}}async*realtimeStatus({id:e,type:t},r=100,n){n=p.addRTypeToMetadata(t,n);const o=Math.floor(r/1e3),d=(r-o*1e3)*1e6,s=_.create({seconds:BigInt(o),nanos:d});try{const{responses:c}=this.grpcClient.get().realtimeStatus({resourceId:e,updateInterval:s},n);yield*c}catch(c){throw this.logger.warn("Failed to get realtime status"+String(c)),c}}}class z extends Error{constructor(){super(...arguments);h(this,"name","NetworkError400")}}class Ee{constructor(e){this.httpClient=e}async download(e,t,r){const{statusCode:n,body:o,headers:d}=await Ne.request(e,{dispatcher:this.httpClient,headers:t,signal:r}),s=L.Readable.toWeb(o);return await mr(n,s,e),{content:s,size:Number(d["content-length"])}}}async function mr(i,e,t){if(i!=200&&i!=206){const r=(await de.text(e)).substring(0,1e3);throw 400<=i&&i<500?new z(`Http error: statusCode: ${i} url: ${t.toString()}, beginning of body: ${r}`):new Error(`Http error: statusCode: ${i} url: ${t.toString()}`)}}function S(i){if(!k.isAbsolute(i))throw new Error(`Path ${i} is not absolute.`);return i}class yr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new yr;class Tr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new Tr;class br extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"is_internal_use",kind:"scalar",T:8}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.isInternalUse=!1,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.isInternalUse=e.bool();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.isInternalUse!==!1&&t.tag(2,a.WireType.Varint).bool(e.isInternalUse);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const kr=new br;class Ur extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL.HTTPHeader",[{no:1,name:"Name",kind:"scalar",jsonName:"Name",T:9},{no:2,name:"Value",kind:"scalar",jsonName:"Value",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.name="",t.value="",e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.name=e.string();break;case 2:o.value=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.name!==""&&t.tag(1,a.WireType.LengthDelimited).string(e.name),e.value!==""&&t.tag(2,a.WireType.LengthDelimited).string(e.value);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Z=new Ur;class Lr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.DownloadAPI.GetDownloadURL.Response",[{no:1,name:"download_url",kind:"scalar",T:9},{no:2,name:"headers",kind:"message",repeat:2,T:()=>Z}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.downloadUrl="",t.headers=[],e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.downloadUrl=e.string();break;case 2:o.headers.push(Z.internalBinaryRead(e,e.uint32(),r));break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.downloadUrl!==""&&t.tag(1,a.WireType.LengthDelimited).string(e.downloadUrl);for(let o=0;o<e.headers.length;o++)Z.internalBinaryWrite(e.headers[o],t.tag(2,a.WireType.LengthDelimited).fork(),r).join();let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Pr=new Lr,Q=new y.ServiceType("MiLaboratories.Controller.Shared.Download",[{name:"GetDownloadURL",options:{"google.api.http":{get:"/resources/{resource_id}/get-download-url"}},I:kr,O:Pr}]);class Rr{constructor(e){h(this,"typeName",Q.typeName);h(this,"methods",Q.methods);h(this,"options",Q.options);this._transport=e}getDownloadURL(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}}class _e{constructor(e,t,r,n){h(this,"grpcClient");h(this,"remoteFileDownloader");h(this,"localStorageIdsToRoot");this.httpClient=t,this.logger=r,this.grpcClient=e.createGrpcClientProvider(o=>new Rr(o)),this.remoteFileDownloader=new Ee(t),this.localStorageIdsToRoot=He(n)}close(){}async downloadBlob(e,t,r,n,o){const{downloadUrl:d,headers:s}=await this.grpcGetDownloadUrl(e,t,r),c=Fe(s,n,o);return this.logger.info(`download blob ${p.stringifyWithResourceId(e)} from url ${d}, headers: ${JSON.stringify(c)}`),Sr(d)?await this.readLocalFile(d,n,o):await this.remoteFileDownloader.download(d,c,r)}async readLocalFile(e,t,r){const{storageId:n,relativePath:o}=Me(e),d=Oe(n,this.localStorageIdsToRoot,o);return{content:L.Readable.toWeb(ce.createReadStream(d,{start:t,end:r!==void 0?r-1:void 0})),size:(await w.stat(d)).size}}async grpcGetDownloadUrl({id:e,type:t},r,n){const o=r??{};return o.abort=n,await this.grpcClient.get().getDownloadURL({resourceId:e,isInternalUse:!1},p.addRTypeToMetadata(t,o)).response}}function Me(i){const e=new URL(i);if(e.pathname=="")throw new x(`url for local filepath ${i} does not match url scheme`);return{storageId:e.host,relativePath:decodeURIComponent(e.pathname.slice(1))}}function Oe(i,e,t){const r=e.get(i);if(r===void 0)throw new A(`Unknown storage location: ${i}`);return r===""?t:b.join(r,t)}const Ir="storage://";function Sr(i){return i.startsWith(Ir)}class x extends Error{constructor(){super(...arguments);h(this,"name","WrongLocalFileUrl")}}class A extends Error{constructor(){super(...arguments);h(this,"name","UnknownStorageError")}}function He(i){const e=new Map;for(const t of i)t.localPath!==""&&S(t.localPath),e.set(t.storageId,t.localPath);return e}class Dr extends a.MessageType{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),t=Date.now();return e.seconds=a.PbLong.from(Math.floor(t/1e3)).toBigInt(),e.nanos=t%1e3*1e6,e}toDate(e){return new Date(a.PbLong.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const t=this.create(),r=e.getTime();return t.seconds=a.PbLong.from(Math.floor(r/1e3)).toBigInt(),t.nanos=(r%1e3+(r<0&&r%1e3!==0?1e3:0))*1e6,t}internalJsonWrite(e,t){let r=a.PbLong.from(e.seconds).toNumber()*1e3;if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let n="Z";if(e.nanos>0){let o=(e.nanos+1e9).toString().substring(1);o.substring(3)==="000000"?n="."+o.substring(0,3)+"Z":o.substring(6)==="000"?n="."+o.substring(0,6)+"Z":n="."+o+"Z"}return new Date(r).toISOString().replace(".000Z",n)}internalJsonRead(e,t,r){if(typeof e!="string")throw new Error("Unable to parse Timestamp from JSON "+a.typeofJsonValue(e)+".");let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let o=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(o))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(o<Date.parse("0001-01-01T00:00:00Z")||o>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return r||(r=this.create()),r.seconds=a.PbLong.from(o/1e3).toBigInt(),r.nanos=0,n[7]&&(r.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),r}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.seconds=0n,t.nanos=0,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.seconds=e.int64().toBigInt();break;case 2:o.nanos=e.int32();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.seconds!==0n&&t.tag(1,a.WireType.Varint).int64(e.seconds),e.nanos!==0&&t.tag(2,a.WireType.Varint).int32(e.nanos);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const K=new Dr;class Nr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new Nr;class $r extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.ListItem",[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"size",kind:"scalar",T:4,L:0},{no:3,name:"is_dir",kind:"scalar",T:8},{no:10,name:"full_name",kind:"scalar",T:9},{no:11,name:"directory",kind:"scalar",T:9},{no:12,name:"last_modified",kind:"message",T:()=>K},{no:13,name:"version",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.name="",t.size=0n,t.isDir=!1,t.fullName="",t.directory="",t.version="",e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.name=e.string();break;case 2:o.size=e.uint64().toBigInt();break;case 3:o.isDir=e.bool();break;case 10:o.fullName=e.string();break;case 11:o.directory=e.string();break;case 12:o.lastModified=K.internalBinaryRead(e,e.uint32(),r,o.lastModified);break;case 13:o.version=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.name!==""&&t.tag(1,a.WireType.LengthDelimited).string(e.name),e.size!==0n&&t.tag(2,a.WireType.Varint).uint64(e.size),e.isDir!==!1&&t.tag(3,a.WireType.Varint).bool(e.isDir),e.fullName!==""&&t.tag(10,a.WireType.LengthDelimited).string(e.fullName),e.directory!==""&&t.tag(11,a.WireType.LengthDelimited).string(e.directory),e.lastModified&&K.internalBinaryWrite(e.lastModified,t.tag(12,a.WireType.LengthDelimited).fork(),r).join(),e.version!==""&&t.tag(13,a.WireType.LengthDelimited).string(e.version);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const X=new $r;class vr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new vr;class Cr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List.Request",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"location",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.location="",e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.location=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.location!==""&&t.tag(2,a.WireType.LengthDelimited).string(e.location);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Fr=new Cr;class Br extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.LsAPI.List.Response",[{no:1,name:"items",kind:"message",repeat:2,T:()=>X},{no:2,name:"delimiter",kind:"scalar",T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.items=[],t.delimiter="",e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.items.push(X.internalBinaryRead(e,e.uint32(),r));break;case 2:o.delimiter=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){for(let o=0;o<e.items.length;o++)X.internalBinaryWrite(e.items[o],t.tag(1,a.WireType.LengthDelimited).fork(),r).join();e.delimiter!==""&&t.tag(2,a.WireType.LengthDelimited).string(e.delimiter);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Wr=new Br,Y=new y.ServiceType("MiLaboratories.Controller.Shared.LS",[{name:"List",options:{},I:Fr,O:Wr}]);class Er{constructor(e){h(this,"typeName",Y.typeName);h(this,"methods",Y.methods);h(this,"options",Y.options);this._transport=e}list(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}}class ze{constructor(e,t){h(this,"grpcClient");this.logger=t,this.grpcClient=e.createGrpcClientProvider(r=>new Er(r))}close(){}async list(e,t,r){return await this.grpcClient.get().list({resourceId:e.id,location:t},p.addRTypeToMetadata(e.type,r)).response}}class _r extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI",[])}create(e){const t=globalThis.Object.create(this.messagePrototype);return e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}new _r;class Mr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.StreamBinary",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:11,name:"chunk_size",kind:"scalar",opt:!0,T:13},{no:20,name:"read_limit",kind:"scalar",opt:!0,T:3,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 11:o.chunkSize=e.uint32();break;case 20:o.readLimit=e.int64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,a.WireType.Varint).int64(e.offset),e.chunkSize!==void 0&&t.tag(11,a.WireType.Varint).uint32(e.chunkSize),e.readLimit!==void 0&&t.tag(20,a.WireType.Varint).int64(e.readLimit);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Or=new Mr;class Hr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.ReadBinary",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:11,name:"chunk_size",kind:"scalar",opt:!0,T:13}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 11:o.chunkSize=e.uint32();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,a.WireType.Varint).int64(e.offset),e.chunkSize!==void 0&&t.tag(11,a.WireType.Varint).uint32(e.chunkSize);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const zr=new Hr;class xr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.StreamText",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:20,name:"read_limit",kind:"scalar",opt:!0,T:3,L:0},{no:21,name:"search",kind:"scalar",opt:!0,T:9},{no:22,name:"search_re",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 20:o.readLimit=e.int64().toBigInt();break;case 21:o.search=e.string();break;case 22:o.searchRe=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,a.WireType.Varint).int64(e.offset),e.readLimit!==void 0&&t.tag(20,a.WireType.Varint).int64(e.readLimit),e.search!==void 0&&t.tag(21,a.WireType.LengthDelimited).string(e.search),e.searchRe!==void 0&&t.tag(22,a.WireType.LengthDelimited).string(e.searchRe);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Ar=new xr;class jr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.ReadText",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",T:3,L:0},{no:20,name:"read_limit",kind:"scalar",opt:!0,T:3,L:0},{no:21,name:"search",kind:"scalar",opt:!0,T:9},{no:22,name:"search_re",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,t.offset=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 20:o.readLimit=e.int64().toBigInt();break;case 21:o.search=e.string();break;case 22:o.searchRe=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.offset!==0n&&t.tag(2,a.WireType.Varint).int64(e.offset),e.readLimit!==void 0&&t.tag(20,a.WireType.Varint).int64(e.readLimit),e.search!==void 0&&t.tag(21,a.WireType.LengthDelimited).string(e.search),e.searchRe!==void 0&&t.tag(22,a.WireType.LengthDelimited).string(e.searchRe);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const Gr=new jr;class Vr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.LastLines",[{no:1,name:"resource_id",kind:"scalar",T:4,L:0},{no:2,name:"offset",kind:"scalar",opt:!0,T:3,L:0},{no:3,name:"line_count",kind:"scalar",opt:!0,T:5},{no:21,name:"search",kind:"scalar",opt:!0,T:9},{no:22,name:"search_re",kind:"scalar",opt:!0,T:9}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.resourceId=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.resourceId=e.uint64().toBigInt();break;case 2:o.offset=e.int64().toBigInt();break;case 3:o.lineCount=e.int32();break;case 21:o.search=e.string();break;case 22:o.searchRe=e.string();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.resourceId!==0n&&t.tag(1,a.WireType.Varint).uint64(e.resourceId),e.offset!==void 0&&t.tag(2,a.WireType.Varint).int64(e.offset),e.lineCount!==void 0&&t.tag(3,a.WireType.Varint).int32(e.lineCount),e.search!==void 0&&t.tag(21,a.WireType.LengthDelimited).string(e.search),e.searchRe!==void 0&&t.tag(22,a.WireType.LengthDelimited).string(e.searchRe);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const qr=new Vr;class Jr extends a.MessageType{constructor(){super("MiLaboratories.Controller.Shared.StreamingAPI.Response",[{no:1,name:"data",kind:"scalar",T:12},{no:2,name:"size",kind:"scalar",T:4,L:0},{no:3,name:"new_offset",kind:"scalar",T:4,L:0}])}create(e){const t=globalThis.Object.create(this.messagePrototype);return t.data=new Uint8Array(0),t.size=0n,t.newOffset=0n,e!==void 0&&a.reflectionMergePartial(this,t,e),t}internalBinaryRead(e,t,r,n){let o=n??this.create(),d=e.pos+t;for(;e.pos<d;){let[s,c]=e.tag();switch(s){case 1:o.data=e.bytes();break;case 2:o.size=e.uint64().toBigInt();break;case 3:o.newOffset=e.uint64().toBigInt();break;default:let l=r.readUnknownField;if(l==="throw")throw new globalThis.Error(`Unknown field ${s} (wire type ${c}) for ${this.typeName}`);let u=e.skip(c);l!==!1&&(l===!0?a.UnknownFieldHandler.onRead:l)(this.typeName,o,s,c,u)}}return o}internalBinaryWrite(e,t,r){e.data.length&&t.tag(1,a.WireType.LengthDelimited).bytes(e.data),e.size!==0n&&t.tag(2,a.WireType.Varint).uint64(e.size),e.newOffset!==0n&&t.tag(3,a.WireType.Varint).uint64(e.newOffset);let n=r.writeUnknownFields;return n!==!1&&(n==!0?a.UnknownFieldHandler.onWrite:n)(this.typeName,e,t),t}}const $=new Jr,ee=new y.ServiceType("MiLaboratories.Controller.Shared.Streaming",[{name:"StreamBinary",serverStreaming:!0,options:{},I:Or,O:$},{name:"ReadBinary",options:{},I:zr,O:$},{name:"StreamText",serverStreaming:!0,options:{},I:Ar,O:$},{name:"ReadText",options:{},I:Gr,O:$},{name:"LastLines",options:{},I:qr,O:$}]);class Zr{constructor(e){h(this,"typeName",ee.typeName);h(this,"methods",ee.methods);h(this,"options",ee.options);this._transport=e}streamBinary(e,t){const r=this.methods[0],n=this._transport.mergeOptions(t);return y.stackIntercept("serverStreaming",this._transport,r,n,e)}readBinary(e,t){const r=this.methods[1],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}streamText(e,t){const r=this.methods[2],n=this._transport.mergeOptions(t);return y.stackIntercept("serverStreaming",this._transport,r,n,e)}readText(e,t){const r=this.methods[3],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}lastLines(e,t){const r=this.methods[4],n=this._transport.mergeOptions(t);return y.stackIntercept("unary",this._transport,r,n,e)}}class xe{constructor(e,t,r){h(this,"grpcClient");this.httpClient=t,this.logger=r,this.grpcClient=e.createGrpcClientProvider(n=>new Zr(n))}close(){}async lastLines({id:e,type:t},r,n=0n,o,d){return(await this.grpcClient.get().lastLines({resourceId:e,lineCount:r,offset:n,search:o},p.addRTypeToMetadata(t,d))).response}async readText({id:e,type:t},r,n=0n,o,d){return(await this.grpcClient.get().readText({resourceId:g.notEmpty(e),readLimit:BigInt(r),offset:n,search:o},p.addRTypeToMetadata(t,d))).response}}function Qr(i,e,t){return e.getDriver({name:"DownloadBlob",init:(r,n,o)=>new _e(n,o,i,t)})}function Kr(i,e){return i.getDriver({name:"StreamLogs",init:(t,r,n)=>new xe(r,n,e)})}function Xr(i,e){return i.getDriver({name:"UploadProgress",init:(t,r,n)=>new We(r,n,i,e)})}function Yr(i,e){return i.getDriver({name:"UploadBlob",init:(t,r,n)=>new Be(r,n,i,e)})}function Ae(i,e){return i.getDriver({name:"LsFiles",init:(t,r,n)=>new ze(r,e)})}const je=/^blob\+local:\/\/download\/(?<path>.*)#(?<signature>.*)$/;function en(i,e){return`blob+local://download/${i}#${e.sign(i)}`}function tn(i){return!!i.match(je)}function te(i,e){const t=i.match(je);if(t===null)throw new Error(`Local handle is malformed: ${i}, matches: ${t}`);const{path:r,signature:n}=t.groups;return e.verify(r,n,`Signature verification failed for: ${i}`),{path:r,signature:n}}const Ge=m.rsSchema({kv:{"ctl/file/blobInfo":U.z.object({sizeBytes:U.z.coerce.number()})}});function fe(i,e){const t=i.kv["ctl/file/blobInfo"].sizeBytes;if(e){const r=e.to-e.from;if(r>t)throw new Error(`getSize: range (${JSON.stringify(e)}, newSize: ${r}) is greater than size (${t})`);return r}return t}const C=U.z.object({localPath:U.z.string(),pathSignature:U.z.string(),sizeBytes:U.z.string(),modificationTime:U.z.string()}),we=U.z.object({storageId:U.z.string(),path:U.z.string()}),rn=U.z.union([C,we]),Ve=m.rsSchema({data:C,fields:{blob:!1}}),qe=m.rsSchema({fields:{incarnation:!1}}),Je=/^blob\+remote:\/\/download\/(?<content>(?<resourceType>.+)\/(?<resourceVersion>.+?)\/(?<resourceId>\d+?)\/(?<size>\d+?))#(?<signature>.*)$/;function nn(i,e){let t=`${i.type.name}/${i.type.version}/${BigInt(i.id)}/${fe(i)}`;return`blob+remote://download/${t}#${e.sign(t)}`}function on(i){return!!i.match(Je)}function sn(i,e){const t=i.match(Je);if(t===null)throw new Error(`Remote handle is malformed: ${i}, matches: ${t}`);const{content:r,resourceType:n,resourceVersion:o,resourceId:d,size:s,signature:c}=t.groups;return e.verify(r,c,`Signature verification failed for ${i}`),{info:{id:p.bigintToResourceId(BigInt(d)),type:{name:n,version:o}},size:Number(s)}}class j extends Error{constructor(){super(...arguments);h(this,"name","WrongResourceTypeError")}}class Ze{constructor(e){h(this,"updating");this.onUpdate=e}schedule(){this.updating==null&&(this.updating=(async()=>{try{await this.onUpdate()}catch(e){console.log(`error while updating in Updater: ${e}`)}finally{this.updating=void 0}})())}}function Qe(i,e){return i?`log+live://log/${e.type.name}/${e.type.version}/${BigInt(e.id)}`:`log+ready://log/${e.type.name}/${e.type.version}/${BigInt(e.id)}`}const Ke=/^log\+live:\/\/log\/(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*)$/;function M(i){return Ke.test(i)}const Xe=/^log\+ready:\/\/log\/(?<resourceType>.*)\/(?<resourceVersion>.*)\/(?<resourceId>.*)$/;function an(i){return Xe.test(i)}function O(i){let e;if(M(i))e=i.match(Ke);else if(an(i))e=i.match(Xe);else throw new Error(`Log handle is malformed: ${i}`);if(e==null)throw new Error(`Log handle wasn't parsed: ${i}`);const{resourceType:t,resourceVersion:r,resourceId:n}=e.groups;return{id:p.bigintToResourceId(BigInt(n)),type:{name:t,version:r}}}function T(i){return`${BigInt(i)}`}function Le(i){return b.basename(i)}class ln{constructor(e,t,r,n,o){h(this,"change",new f.ChangeSource);h(this,"signalCtl",new AbortController);h(this,"counter",new g.CallersCounter);h(this,"error");h(this,"done",!1);h(this,"size",0);h(this,"state",{});this.logger=e,this.clientDownload=t,this.rInfo=r,this.handle=n,this.path=o}info(){return{rInfo:this.rInfo,fPath:this.path,done:this.done,error:this.error,state:this.state}}attach(e,t){this.counter.inc(t),this.done||this.change.attachWatcher(e)}async download(){try{const e=await this.ensureDownloaded();this.setDone(e),this.change.markChanged(`blob download for ${p.resourceIdToString(this.rInfo.id)} finished`)}catch(e){throw this.logger.error(`download blob ${p.stringifyWithResourceId(this.rInfo)} failed: ${e}, state: ${JSON.stringify(this.state)}`),me(e)&&(this.setError(e),this.change.markChanged(`blob download for ${p.resourceIdToString(this.rInfo.id)} failed`),await w.rm(this.path,{force:!0})),e}}async ensureDownloaded(){this.signalCtl.signal.throwIfAborted(),this.state={},this.state.filePath=this.path,await g.ensureDirExists(b.dirname(this.state.filePath)),this.signalCtl.signal.throwIfAborted(),this.state.dirExists=!0;const e=await g.fileExists(this.state.filePath);if(this.signalCtl.signal.throwIfAborted(),e){this.state.fileExists=!0,this.logger.info(`a blob was already downloaded: ${this.state.filePath}`);const n=await w.stat(this.state.filePath);return this.signalCtl.signal.throwIfAborted(),this.state.fileSize=n.size,this.state.fileSize}const{content:t,size:r}=await this.clientDownload.downloadBlob(this.rInfo,{},this.signalCtl.signal);return this.state.fileSize=r,this.state.downloaded=!0,await g.createPathAtomically(this.logger,this.state.filePath,async n=>{const o=L.Writable.toWeb(R.createWriteStream(n,{flags:"wx"}));await t.pipeTo(o,{signal:this.signalCtl.signal}),this.state.tempWritten=!0}),this.state.done=!0,r}abort(e){this.signalCtl.abort(new Ye(e))}getBlob(){return this.done?{done:this.done,result:dn(this.handle,this.size,this.error)}:{done:!1}}setDone(e){this.done=!0,this.size=e}setError(e){this.done=!0,this.error=e}}function me(i){return i instanceof Ye||i instanceof z||i instanceof A||i instanceof x||(i==null?void 0:i.code)=="ENOENT"||i.name=="RpcError"&&(i.code=="NOT_FOUND"||i.code=="ABORTED")}class Ye extends Error{constructor(){super(...arguments);h(this,"name","DownloadAborted")}}function dn(i,e,t){return t?{ok:!1,error:t}:i?{ok:!0,value:{handle:i,size:e}}:{ok:!1,error:new Error("No file or handle provided")}}class ye{constructor(e){h(this,"cache",new Map);h(this,"totalSizeBytes",0);this.softSizeBytes=e}existsFile(e){return this.cache.get(e)!=null}getFile(e,t){const r=this.cache.get(e);return r!=null&&r.counter.inc(t),r}removeFile(e,t){return g.mapGet(this.cache,e).counter.dec(t),this.toDelete()}toDelete(){if(this.totalSizeBytes<=this.softSizeBytes)return[];const e=[];let t=0;return g.mapEntries(this.cache).filter(([r,n])=>n.counter.isZero()).forEach(([r,n])=>{if(this.totalSizeBytes-t<=this.softSizeBytes)return;const o=g.mapGet(this.cache,r);t+=o.size,e.push(o)}),e}addCache(e,t){const r=this.cache.get(e.path)==null;if(this.cache.set(e.path,e),e.counter.inc(t),e.size<0)throw new Error(`empty sizeBytes: ${e}`);r&&(this.totalSizeBytes+=e.size)}removeCache(e){this.cache.delete(e.path),this.totalSizeBytes-=e.size}}const cn=U.z.object({ranges:U.z.array(N.RangeBytes)}),hn=".ranges.json";function un(i){return i+hn}async function pn(i,e){let t={ranges:[]};try{const r=await w.readFile(e,"utf8");t=cn.parse(JSON.parse(r))}catch(r){if(r instanceof SyntaxError||r instanceof U.z.ZodError){const n=`readRangesFile: the file ${e} was corrupted: ${r}`;throw i.error(n),new tt(n)}if(!(r instanceof Error&&"code"in r&&r.code==="ENOENT"))throw r}return et(t),t}async function gn(i,e,t){await g.createPathAtomically(i,e,async r=>{await w.writeFile(r,JSON.stringify(t,null,2),{flag:"wx"})})}function et(i){i.ranges.sort((e,t)=>e.from-t.from);for(let e=0;e<i.ranges.length-1;e++)i.ranges[e].to>=i.ranges[e+1].from&&(fn(i,e),e--)}function fn(i,e){const t=Math.min(i.ranges[e].from,i.ranges[e+1].from),r=Math.max(i.ranges[e].to,i.ranges[e+1].to);i.ranges.splice(e,2,{from:t,to:r})}function F(i){return i.ranges.reduce((e,t)=>e+t.to-t.from,0)}function wn(i,e){for(const t of i.ranges)if(t.from<=e.from&&e.to<=t.to)return!0;return!1}function mn(i,e){return i.ranges.push(e),et(i),i}async function yn(i,e,t){try{await(await w.open(e,"w")).close(),await Tn(e,t)}catch(r){i.error(`Error creating file ${e} on platform ${t}: ${r}`)}}async function Tn(i,e){e==="win32"&&await g.spawnAsync("fsutil",["sparse","setflag",`"${i}"`],{stdio:"pipe"})}async function bn(i,e,t,r,n){await g.fileExists(t)||await yn(i,t,e);const o=await w.open(t,"r+");await o.write(r,0,r.length,n),await o.close()}class tt extends Error{constructor(){super(...arguments);h(this,"name","CorruptedRangesError")}}class kn{constructor(e,t){this.logger=e,this.cacheDir=t}fPath(e){return k.join(this.cacheDir,un(e))}async get(e){return await pn(this.logger,this.fPath(e))}async set(e,t){return await gn(this.logger,this.fPath(e),t)}async delete(e){await R.promises.rm(this.fPath(e))}}class Un{constructor(e,t){h(this,"suffix",".sparse.bin");this.logger=e,this.cacheDir=t}async all(){return await g.ensureDirExists(this.cacheDir),(await R.promises.readdir(this.cacheDir)).filter(t=>t.endsWith(this.suffix))}async exists(e){return await g.fileExists(this.path(e))}path(e){return k.join(this.cacheDir,e+this.suffix)}async write(e,t,r){await g.ensureDirExists(this.cacheDir),await bn(this.logger,process.platform,this.path(e),t,r)}async delete(e){await R.promises.rm(this.path(e))}}class Ln{constructor(e,t,r,n){h(this,"lock",new Ut.functions.AwaitLock);h(this,"keyToLastAccessTime",new Map);h(this,"size",0);this.logger=e,this.maxSize=t,this.ranges=r,this.storage=n}async reset(){await re(this.lock,async()=>{await this.resetUnsafe()})}async get(e,t){return await re(this.lock,async()=>await this.getUnsafe(e,t))}async set(e,t,r){await re(this.lock,async()=>{await this.setUnsafe(e,t,r)})}async resetUnsafe(){this.size=0,this.keyToLastAccessTime=new Map;const e=new Date;for(const t of await this.storage.all()){const r=await this.ranges.get(t);this.size+=F(r),this.keyToLastAccessTime.set(t,e)}}async getUnsafe(e,t){if(await this.storage.exists(e)){this.keyToLastAccessTime.set(e,new Date);const r=await this.getRanges(e);return wn(r,t)?this.storage.path(e):void 0}}async setUnsafe(e,t,r){await this.setWithoutEviction(e,t,r),await this.ensureEvicted()}async setWithoutEviction(e,t,r){if(t.to-t.from!==r.length)throw new Error(`SparseCache.set: trying to set ${e} with wrong range length: range: ${JSON.stringify(t)}, data: ${r.length}`);this.keyToLastAccessTime.set(e,new Date);const n=await this.getRanges(e);this.size-=F(n),await this.storage.write(e,r,t.from);const o=mn(n,t);this.size+=F(o),await this.ranges.set(e,o)}async ensureEvicted(){const e=g.mapEntries(this.keyToLastAccessTime);for(e.sort(([t,r],[n,o])=>o.getTime()-r.getTime());this.size>this.maxSize;){const t=e.pop();if(!t)break;const[r,n]=t,o=await this.getRanges(r);this.size-=F(o),this.rmKey(r)}}async getRanges(e){try{return await this.ranges.get(e)}catch(t){if(t instanceof tt)return await this.rmKey(e),await this.resetUnsafe(),await this.ranges.get(e);throw t}}async rmKey(e){await this.storage.delete(e),await this.ranges.delete(e),this.keyToLastAccessTime.delete(e)}}async function re(i,e){try{return await i.acquireAsync(),await e()}finally{i.release()}}class Te{constructor(e,t,r,n,o,d,s){h(this,"keyToDownload",new Map);h(this,"cache");h(this,"rangesCache");h(this,"downloadQueue");h(this,"keyToOnDemand",new Map);h(this,"idToLastLines",new Map);h(this,"idToProgressLog",new Map);h(this,"saveDir");this.logger=e,this.clientDownload=t,this.clientLogs=r,this.rangesCacheDir=o,this.signer=d,this.ops=s,this.cache=new ye(this.ops.cacheSoftSizeBytes);const c=new kn(this.logger,this.rangesCacheDir),l=new Un(this.logger,this.rangesCacheDir);this.rangesCache=new Ln(this.logger,this.ops.rangesCacheMaxSizeBytes,c,l),this.downloadQueue=new g.TaskProcessor(this.logger,s.nConcurrentDownloads),this.saveDir=b.resolve(n)}static async init(e,t,r,n,o,d,s){const c=new Te(e,t,r,n,o,d,s);return await c.rangesCache.reset(),c}getDownloadedBlob(e,t){if(t===void 0)return f.Computable.make(d=>this.getDownloadedBlob(e,d));const r=m.treeEntryToResourceInfo(e,t),n=P.randomUUID();t.addOnDestroy(()=>this.releaseBlob(r,n));const o=this.getDownloadedBlobNoCtx(t.watcher,r,n);return o==null&&t.markUnstable("download blob is still undefined"),o}getDownloadedBlobNoCtx(e,t,r){v("getDownloadedBlob",t.type);const n=this.getOrSetNewTask(t,r);n.attach(e,r);const o=n.getBlob();if(o.done){if(o.result.ok)return o.result.value;throw o.result.error}}getOrSetNewTask(e,t){const r=T(e.id),n=this.keyToDownload.get(r);if(n)return n;const o=b.resolve(this.saveDir,r),d=new ln(this.logger,this.clientDownload,e,en(o,this.signer),o);return this.keyToDownload.set(r,d),this.downloadQueue.push({fn:()=>this.downloadBlob(d,t),recoverableErrorPredicate:s=>!me(s)}),d}async downloadBlob(e,t){await e.download();const r=e.getBlob();r.done&&r.result.ok&&this.cache.addCache(e,t)}getOnDemandBlob(e,t){if(t===void 0)return f.Computable.make(d=>this.getOnDemandBlob(e,d));const r=m.isPlTreeEntry(e)?m.makeResourceSnapshot(e,Ge,t):e,n=P.randomUUID();return t.addOnDestroy(()=>this.releaseOnDemandBlob(r.id,n)),this.getOnDemandBlobNoCtx(r,n)}getOnDemandBlobNoCtx(e,t){v("getOnDemandBlob",e.type);let r=this.keyToOnDemand.get(T(e.id));return r===void 0&&(r=new Pn(fe(e),nn(e,this.signer)),this.keyToOnDemand.set(T(e.id),r)),r.attach(t),r.getHandle()}getLocalPath(e){const{path:t}=te(e,this.signer);return t}async getContent(e,t){if(t&&N.validateRangeBytes(t,"getContent"),tn(e))return await Re(this.getLocalPath(e),t);if(on(e)){const r=sn(e,this.signer),n=T(r.info.id),o=await this.rangesCache.get(n,t??{from:0,to:r.size});if(o)return await Re(o,t);const{content:d}=await this.clientDownload.downloadBlob({id:r.info.id,type:r.info.type},void 0,void 0,t==null?void 0:t.from,t==null?void 0:t.to),s=await de.buffer(d);return await this.rangesCache.set(n,t??{from:0,to:r.size},s),s}throw new Error("Malformed remote handle")}getComputableContent(e,t){return t&&N.validateRangeBytes(t,"getComputableContent"),f.Computable.make(r=>this.getDownloadedBlob(e,r),{postprocessValue:r=>r?this.getContent(r.handle,t):void 0}).withStableType()}getLastLogs(e,t,r){if(r==null)return f.Computable.make(s=>this.getLastLogs(e,t,s));const n=m.treeEntryToResourceInfo(e,r),o=P.randomUUID();r.addOnDestroy(()=>this.releaseBlob(n,o));const d=this.getLastLogsNoCtx(r.watcher,n,t,o);return d==null&&r.markUnstable("either a file was not downloaded or logs was not read"),d}getLastLogsNoCtx(e,t,r,n){v("getLastLogs",t.type);const o=this.getDownloadedBlobNoCtx(e,t,n);if(o==null)return;const{path:d}=te(o.handle,this.signer);let s=this.idToLastLines.get(T(t.id));if(s==null){const l=new Pe(d,r);this.idToLastLines.set(T(t.id),l),s=l}const c=s.getOrSchedule(e);if(c.error)throw c.error;return c.log}getProgressLog(e,t,r){if(r==null)return f.Computable.make(s=>this.getProgressLog(e,t,s));const n=m.treeEntryToResourceInfo(e,r),o=P.randomUUID();r.addOnDestroy(()=>this.releaseBlob(n,o));const d=this.getProgressLogNoCtx(r.watcher,n,t,o);return d===void 0&&r.markUnstable("either a file was not downloaded or a progress log was not read"),d}getProgressLogNoCtx(e,t,r,n){v("getProgressLog",t.type);const o=this.getDownloadedBlobNoCtx(e,t,n);if(o==null)return;const{path:d}=te(o.handle,this.signer);let s=this.idToProgressLog.get(T(t.id));if(s==null){const l=new Pe(d,1,r);this.idToProgressLog.set(T(t.id),l),s=l}const c=s.getOrSchedule(e);if(c.error)throw c.error;return c.log}getLogHandle(e,t){if(t==null)return f.Computable.make(n=>this.getLogHandle(e,n));const r=m.treeEntryToResourceInfo(e,t);return this.getLogHandleNoCtx(r)}getLogHandleNoCtx(e){return v("getLogHandle",e.type),Qe(!1,e)}async lastLines(e,t,r,n){const o=await this.clientLogs.lastLines(O(e),t,BigInt(r??0),n);return{live:!1,shouldUpdateHandle:!1,data:o.data,size:Number(o.size),newOffset:Number(o.newOffset)}}async readText(e,t,r,n){const o=await this.clientLogs.readText(O(e),t,BigInt(r??0),n);return{live:!1,shouldUpdateHandle:!1,data:o.data,size:Number(o.size),newOffset:Number(o.newOffset)}}async releaseBlob(e,t){const r=this.keyToDownload.get(T(e.id));if(r!=null)if(this.cache.existsFile(T(e.id))){const n=this.cache.removeFile(T(e.id),t);await Promise.all(n.map(async o=>{await w.rm(o.path),this.cache.removeCache(o),this.removeTask(g.mapGet(this.keyToDownload,Le(o.path)),`the task ${p.stringifyWithResourceId(o)} was removedfrom cache along with ${p.stringifyWithResourceId(n.map(d=>d.path))}`)}))}else r.counter.dec(t)&&this.removeTask(r,`the task ${p.stringifyWithResourceId(r.info())} was removed from cache`)}removeTask(e,t){e.abort(t),e.change.markChanged(`download task for ${e.path} removed: ${t}`),this.keyToDownload.delete(Le(e.path)),this.idToLastLines.delete(T(e.rInfo.id)),this.idToProgressLog.delete(T(e.rInfo.id))}async releaseOnDemandBlob(e,t){var n;(((n=this.keyToOnDemand.get(T(e)))==null?void 0:n.release(t))??!1)&&this.keyToOnDemand.delete(T(e))}async releaseAll(){this.downloadQueue.stop(),this.keyToDownload.forEach((e,t)=>{this.keyToDownload.delete(t),e.change.markChanged(`task ${p.resourceIdToString(e.rInfo.id)} released`)})}}class Pn{constructor(e,t){h(this,"counter",new g.CallersCounter);this.size=e,this.handle=t}getHandle(){return{handle:this.handle,size:this.size}}attach(e){this.counter.inc(e)}release(e){return this.counter.dec(e)}}class Pe{constructor(e,t,r){h(this,"updater");h(this,"log");h(this,"change",new f.ChangeSource);h(this,"error");this.path=e,this.lines=t,this.patternToSearch=r,this.updater=new Ze(async()=>this.update())}getOrSchedule(e){return this.change.attachWatcher(e),this.updater.schedule(),{log:this.log,error:this.error}}async update(){try{const e=await Rn(this.path,this.lines,this.patternToSearch);this.log!=e&&this.change.markChanged(`logs for ${this.path} updated`),this.log=e}catch(e){if(e.name=="RpcError"&&e.code=="NOT_FOUND"){this.log="",this.error=e,this.change.markChanged(`log update for ${this.path} failed, resource not found`);return}throw e}}}function Rn(i,e,t){const r=ce.createReadStream(i),n=new L.Writable;return new Promise((o,d)=>{const s=Nt.createInterface(r,n),c=new bt;s.on("line",function(l){t!=null&&!l.includes(t)||(c.push(l),c.length>e&&c.shift())}),s.on("error",d),s.on("close",function(){o(c.toArray().join(Ue.EOL)+Ue.EOL)})})}async function Re(i,e){const t={};e&&(t.start=e.from,t.end=e.to-1);const r=ce.createReadStream(i,t);return await de.buffer(L.Readable.toWeb(r))}function v(i,e){if(!e.name.startsWith("Blob/")){let t=`${i}: wrong resource type: ${e.name}, expected: a resource of type that starts with 'Blob/'.`;throw e.name=="Blob"&&(t+=" If it's called from workflow, should a file be exported with 'file.exportFile' function?"),new j(t)}}const rt=m.rsSchema({});function nt(i,e){const t=m.isPlTreeEntry(i)?e.accessor(i).node():m.isPlTreeEntryAccessor(i)?i.node():i;return m.makeResourceSnapshot(t,rt)}function In(i,e,t){const r=k.relative(e,t);return`plblob+folder://${i.sign(r)}.${r}.blob`}function Sn(i,e,t){const r=k.relative(e,t);return`block-ui://${i.sign(r)}.${r}.uidir`}function Dn(i,e,t){return ot(i,e,t)}function Nn(i,e,t){return ot(i,e,t)}function ot(i,e,t){const r=new URL(e),[n,o,d]=r.host.split(".");i.verify(o,n,`signature verification failed for url: ${e}, subfolder: ${o}`);const s=decodeURIComponent(r.pathname.slice(1));let c=$n(k.join(t,`${o}`),s);return(r.pathname==""||r.pathname=="/")&&(c=k.join(c,"index.html")),k.resolve(c)}function $n(i,e){const t=k.resolve(i,e),r=k.resolve(i);if(!t.startsWith(r))throw new Error("Path validation failed.");return t}class vn{constructor(e,t,r,n,o,d,s){h(this,"counter",new g.CallersCounter);h(this,"change",new f.ChangeSource);h(this,"signalCtl",new AbortController);h(this,"error");h(this,"done",!1);h(this,"size",0);h(this,"url");h(this,"state");this.logger=e,this.signer=t,this.saveDir=r,this.path=n,this.rInfo=o,this.format=d,this.clientDownload=s}info(){return{rInfo:this.rInfo,format:this.format,path:this.path,done:this.done,size:this.size,error:this.error,taskHistory:this.state}}attach(e,t){this.counter.inc(t),this.done||this.change.attachWatcher(e)}async download(){try{const e=await this.downloadAndDecompress(this.signalCtl.signal);this.setDone(e),this.change.markChanged(`download and decompress for ${p.resourceIdToString(this.rInfo.id)} finished`),this.logger.info(`blob to URL task is done: ${p.stringifyWithResourceId(this.info())}`)}catch(e){if(this.logger.warn(`a error was produced: ${e} for blob to URL task: ${p.stringifyWithResourceId(this.info())}`),Cn(e)){this.setError(e),this.change.markChanged(`download and decompress for ${p.resourceIdToString(this.rInfo.id)} failed`),await se(this.path);return}throw e}}async downloadAndDecompress(e){if(this.state={},this.state.parentDir=k.dirname(this.path),await g.ensureDirExists(this.state.parentDir),this.state.fileExisted=await g.fileExists(this.path),this.state.fileExisted)return await it(this.path);const{content:t,size:r}=await this.clientDownload.downloadBlob(this.rInfo,{},e);return this.state.downloaded=!0,await g.createPathAtomically(this.logger,this.path,async n=>{switch(this.state.tempPath=n,this.state.archiveFormat=this.format,this.format){case"tar":await w.mkdir(n);const o=L.Writable.toWeb(ie.extract(n));await t.pipeTo(o,{signal:e});return;case"tgz":await w.mkdir(n);const d=L.Transform.toWeb(Ce.createGunzip()),s=L.Writable.toWeb(ie.extract(n));await t.pipeThrough(d,{signal:e}).pipeTo(s,{signal:e});return;case"zip":this.state.zipPath=this.path+".zip";const c=L.Writable.toWeb(R.createWriteStream(this.state.zipPath));await t.pipeTo(c,{signal:e}),this.state.zipPathCreated=!0,await Rt(this.state.zipPath,n,{filter:l=>!l.path.endsWith("/")}),this.state.zipDecompressed=!0,await R.promises.rm(this.state.zipPath),this.state.zipPathDeleted=!0;return;default:a.assertNever(this.format)}}),this.state.pathCreated=!0,r}getURL(){if(this.done)return{url:g.notEmpty(this.url)};if(this.error)return{error:this.error}}setDone(e){this.done=!0,this.size=e,this.url=In(this.signer,this.saveDir,this.path)}setError(e){this.error=String(e)}abort(e){this.signalCtl.abort(new st(e))}}async function it(i){const e=await w.readdir(i,{withFileTypes:!0});return(await Promise.all(e.map(async r=>{const n=k.join(i,r.name);return r.isDirectory()?await it(n):(await w.stat(n)).size}))).reduce((r,n)=>r+n,0)}async function se(i){await w.rm(i,{recursive:!0,force:!0})}let st=class extends Error{constructor(){super(...arguments);h(this,"name","URLAborted")}};function Cn(i){return i instanceof st||i instanceof z||i instanceof A||i instanceof x||(i==null?void 0:i.code)=="ENOENT"||i.name=="RpcError"&&(i.code=="NOT_FOUND"||i.code=="ABORTED")||String(i).includes("incorrect header check")}function B(i,e){return`id:${String(BigInt(i))}-${e}`}class Fn{constructor(e,t,r,n,o={cacheSoftSizeBytes:50*1024*1024,nConcurrentDownloads:50}){h(this,"idToDownload",new Map);h(this,"downloadQueue");h(this,"cache");this.logger=e,this.signer=t,this.clientDownload=r,this.saveDir=n,this.opts=o,this.downloadQueue=new g.TaskProcessor(this.logger,this.opts.nConcurrentDownloads,{type:"exponentialWithMaxDelayBackoff",initialDelay:1e4,maxDelay:3e4,backoffMultiplier:1.5,jitter:.5}),this.cache=new ye(this.opts.cacheSoftSizeBytes)}info(){return{saveDir:this.saveDir,opts:this.opts,idToDownloadSize:this.idToDownload.size,idToDownloadKeys:this.idToDownload.keys(),idToDownload:Array.from(this.idToDownload.entries()).map(([e,t])=>[e,t.info()])}}getPathForCustomProtocol(e){if(N.isFolderURL(e))return Dn(this.signer,e,this.saveDir);throw new Error(`getPathForCustomProtocol: ${e} is invalid`)}extractArchiveAndGetURL(e,t,r){if(r===void 0)return f.Computable.make(s=>this.extractArchiveAndGetURL(e,t,s));const n=m.isPlTreeEntry(e)?nt(e,r):e,o=P.randomUUID();r.addOnDestroy(()=>this.releasePath(n.id,t,o));const d=this.extractArchiveAndGetURLNoCtx(n,t,r.watcher,o);if((d==null?void 0:d.url)===void 0&&r.markUnstable(`a path to the downloaded archive might be undefined. The current result: ${d}`),(d==null?void 0:d.error)!==void 0)throw d==null?void 0:d.error;return d==null?void 0:d.url}extractArchiveAndGetURLNoCtx(e,t,r,n){const o=this.idToDownload.get(B(e.id,t));if(o!=null)return o.attach(r,n),o.getURL();const d=this.setNewTask(r,e,t,n);return this.downloadQueue.push({fn:async()=>this.downloadUrl(d,n),recoverableErrorPredicate:s=>!me(s)}),d.getURL()}async downloadUrl(e,t){var r;await e.download(),((r=e.getURL())==null?void 0:r.url)!=null&&this.cache.addCache(e,t)}async releasePath(e,t,r){const n=this.idToDownload.get(B(e,t));if(n!=null)if(this.cache.existsFile(n.path)){const o=this.cache.removeFile(n.path,r);await Promise.all(o.map(async d=>{await se(d.path),this.cache.removeCache(d),this.removeTask(d,`the task ${p.stringifyWithResourceId(d.info())} was removedfrom cache along with ${p.stringifyWithResourceId(o.map(s=>s.info()))}`)}))}else n.counter.dec(r)&&this.removeTask(n,`the task ${p.stringifyWithResourceId(n.info())} was removed from cache`)}async releaseAll(){this.downloadQueue.stop(),await Promise.all(Array.from(this.idToDownload.entries()).map(async([e,t])=>{await se(t.path),this.cache.removeCache(t),this.removeTask(t,`the task ${p.stringifyWithResourceId(t.info())} was released when the driver was closed`)}))}setNewTask(e,t,r,n){const o=new vn(this.logger,this.signer,this.saveDir,this.getFilePath(t.id,r),t,r,this.clientDownload);return o.attach(e,n),this.idToDownload.set(B(t.id,r),o),o}removeTask(e,t){e.abort(t),e.change.markChanged(`task for ${p.resourceIdToString(e.rInfo.id)} removed: ${t}`),this.idToDownload.delete(B(e.rInfo.id,e.format))}getFilePath(e,t){return b.join(this.saveDir,`${String(BigInt(e))}_${t}`)}}class at{constructor(e,t,r,n,o,d){h(this,"change",new f.ChangeSource);h(this,"counter",new g.CallersCounter);h(this,"nMaxUploads");h(this,"nPartsWithThisUploadSpeed",0);h(this,"nPartsToIncreaseUpload",10);h(this,"uploadData");h(this,"progress");h(this,"failed");h(this,"alreadyExisted",!1);this.logger=e,this.clientBlob=t,this.clientProgress=r,this.maxNConcurrentPartsUpload=n,this.res=d,this.nMaxUploads=this.maxNConcurrentPartsUpload;const{uploadData:s,progress:c}=Bn(d,o);this.uploadData=s,this.progress=c}getProgress(e,t){if(this.incCounter(e,t),this.failed)throw this.logger.error(`Uploading terminally failed: ${this.progress.lastError}`),new Error(this.progress.lastError);return Wn(this.progress)}shouldScheduleUpload(){return dt(this.progress)}async uploadBlobTask(){try{await lt(this.logger,this.clientBlob,this.res,this.uploadData,this.isComputableDone.bind(this),{nPartsWithThisUploadSpeed:this.nPartsWithThisUploadSpeed,nPartsToIncreaseUpload:this.nPartsToIncreaseUpload,currentSpeed:this.nMaxUploads,maxSpeed:this.maxNConcurrentPartsUpload}),this.change.markChanged(`blob upload for ${p.resourceIdToString(this.res.id)} finished`)}catch(e){if(this.setRetriableError(e),ae(e)){this.logger.warn(`resource was deleted while uploading a blob: ${e}`),this.change.markChanged(`blob upload for ${p.resourceIdToString(this.res.id)} aborted, resource was deleted`),this.setDone(!0);return}if(this.logger.error(`error while uploading a blob: ${e}`),this.change.markChanged(`blob upload for ${p.resourceIdToString(this.res.id)} failed`),be(e)){this.setTerminalError(e);return}throw On(e)&&(this.nMaxUploads=zn(this.logger,this.nMaxUploads,1)),e}}async updateStatus(){var e;try{const t=await this.clientProgress.getStatus(this.res,{timeout:1e4}),r=this.progress.status,n=Mn(this.alreadyExisted,_n(t));this.progress.status=n,this.setDone(t.done),(t.done||this.progress.status.progress!=(r==null?void 0:r.progress))&&this.change.markChanged(`upload status for ${p.resourceIdToString(this.res.id)} changed`)}catch(t){if(this.setRetriableError(t),t.name=="RpcError"&&t.code=="DEADLINE_EXCEEDED"||(e=t==null?void 0:t.message)!=null&&e.includes("DEADLINE_EXCEEDED")){this.logger.warn("deadline exceeded while getting a status of BlobImport");return}if(ae(t)){this.logger.warn(`resource was not found while updating a status of BlobImport: ${t}, ${p.stringifyWithResourceId(this.res)}`),this.change.markChanged(`upload status for ${p.resourceIdToString(this.res.id)} changed, resource not found`),this.setDone(!0);return}this.logger.error(`retryable error while updating a status of BlobImport: ${t}`)}}setRetriableError(e){this.progress.lastError=String(e)}setTerminalError(e){this.progress.lastError=String(e),this.progress.done=!1,this.failed=!0}setDoneIfOutputSet(e){En(e)&&(this.setDone(!0),this.alreadyExisted=!0)}setDone(e){this.progress.done=e,e&&(this.progress.lastError=void 0)}incCounter(e,t){this.change.attachWatcher(e),this.counter.inc(t)}decCounter(e){return this.counter.dec(e)}isComputableDone(){return this.counter.isZero()}}async function lt(i,e,t,r,n,o){It(H(t),"the upload operation can be done only for BlobUploads");const d=1e4;if(n())return;const s=await e.initUpload(t,{timeout:d});i.info(`started to upload blob ${t.id}, parts overall: ${s.overall}, parts remained: ${s.toUpload.length}, number of concurrent uploads: ${o.currentSpeed}`);const c=l=>async u=>{n()||(await e.partUpload(t,r.localPath,BigInt(r.modificationTime),l,{timeout:d}),i.info(`uploaded chunk ${l}/${s.overall} of resource: ${t.id}`),o.nPartsWithThisUploadSpeed++,o.nPartsWithThisUploadSpeed>=o.nPartsToIncreaseUpload&&(o.nPartsWithThisUploadSpeed=0,o.currentSpeed=Hn(i,o.currentSpeed,o.maxSpeed),u.setConcurrency(o.currentSpeed)))};await g.asyncPool(o.currentSpeed,s.toUpload.map(c)),!n()&&(await e.finalize(t,{timeout:d}),i.info(`uploading of resource ${t.id} finished.`))}function Bn(i,e){let t,r;return H(i)&&(r=C.parse(i.data),t=ct(e,r.localPath,r.pathSignature)),{uploadData:r,progress:{done:!1,status:void 0,isUpload:H(i),isUploadSignMatch:t,lastError:void 0}}}function dt(i){return i.isUpload&&(i.isUploadSignMatch??!1)}function Wn(i){return i.done,i.isUpload,i.isUploadSignMatch,i.lastError,i.status&&(i.status.progress,i.status.bytesProcessed,i.status.bytesTotal),i}function En(i){return"blob"in i.fields?i.fields.blob!==void 0:i.fields.incarnation!==void 0}function H(i){return i.type.name.startsWith("BlobUpload")}function ct(i,e,t){try{return i.verify(e,t),!0}catch{return!1}}function _n(i){return{progress:i.progress??0,bytesProcessed:Number(i.bytesProcessed),bytesTotal:Number(i.bytesTotal)}}function Mn(i,e){return i&&e.bytesTotal!=0&&e.bytesProcessed==0?{progress:1,bytesProcessed:Number(e.bytesTotal),bytesTotal:Number(e.bytesTotal)}:e}function ae(i){return i.name=="RpcError"&&(i.code=="NOT_FOUND"||i.code=="ABORTED"||i.code=="ALREADY_EXISTS")}function be(i){return i instanceof he||i instanceof ue||i instanceof ge}function On(i){return i==null?void 0:i.message.includes("UND_ERR_HEADERS_TIMEOUT")}function Hn(i,e,t){const r=Math.min(e+2,t);return r!=e&&i.info(`uploadTask.increaseConcurrency: increased from ${e} to ${r}`),r}function zn(i,e,t){const r=Math.max(Math.round(e/2),t);return r!=e&&i.info(`uploadTask.decreaseConcurrency: decreased from ${e} to ${r}`),r}function ht(i,e){const t=m.isPlTreeEntry(i)?e.accessor(i).node():m.isPlTreeEntryAccessor(i)?i.node():i;return t.resourceType.name.startsWith("BlobUpload")?m.makeResourceSnapshot(t,Ve):m.makeResourceSnapshot(t,qe)}class xn{constructor(e,t,r,n,o={nConcurrentPartUploads:10,nConcurrentGetProgresses:10,pollingInterval:1e3,stopPollingDelay:1e3}){h(this,"idToProgress",new Map);h(this,"uploadQueue");h(this,"hooks");h(this,"scheduledOnNextState",[]);h(this,"keepRunning",!1);h(this,"currentLoop");this.logger=e,this.signer=t,this.clientBlob=r,this.clientProgress=n,this.opts=o,this.uploadQueue=new g.TaskProcessor(this.logger,1,{type:"exponentialWithMaxDelayBackoff",initialDelay:20,maxDelay:15e3,backoffMultiplier:1.5,jitter:.5}),this.hooks=new f.PollingComputableHooks(()=>this.startUpdating(),()=>this.stopUpdating(),{stopDebounce:o.stopPollingDelay},(d,s)=>this.scheduleOnNextState(d,s))}getProgressId(e,t){if(t==null)return f.Computable.make(d=>this.getProgressId(e,d));const r=m.isPlTreeEntry(e)?ht(e,t):e,n=P.randomUUID();return t.attacheHooks(this.hooks),t.addOnDestroy(()=>this.release(r.id,n)),this.getProgressIdNoCtx(t.watcher,r,n)}getProgressIdNoCtx(e,t,r){jn("getProgressId",t.type);const n=this.idToProgress.get(t.id);if(n!=null)return n.setDoneIfOutputSet(t),n.getProgress(e,r);const o=new at(this.logger,this.clientBlob,this.clientProgress,this.opts.nConcurrentPartUploads,this.signer,t);return this.idToProgress.set(t.id,o),o.shouldScheduleUpload()&&this.uploadQueue.push({fn:()=>o.uploadBlobTask(),recoverableErrorPredicate:d=>!be(d)}),o.setDoneIfOutputSet(t),o.getProgress(e,r)}async release(e,t){const r=this.idToProgress.get(e);if(r===void 0)return;r.decCounter(t)&&this.idToProgress.delete(e)}async releaseAll(){this.uploadQueue.stop()}scheduleOnNextState(e,t){this.scheduledOnNextState.push({resolve:e,reject:t})}startUpdating(){this.keepRunning=!0,this.currentLoop===void 0&&(this.currentLoop=this.mainLoop())}stopUpdating(){this.keepRunning=!1}async mainLoop(){for(;this.keepRunning;){const e=this.scheduledOnNextState;this.scheduledOnNextState=[];try{await g.asyncPool(this.opts.nConcurrentGetProgresses,this.getAllNotDoneProgresses().map(t=>async()=>await t.updateStatus())),e.forEach(t=>t.resolve())}catch(t){console.error(t),e.forEach(r=>r.reject(t))}if(!this.keepRunning)break;await ve.scheduler.wait(this.opts.pollingInterval)}this.currentLoop=void 0}getAllNotDoneProgresses(){return Array.from(this.idToProgress.entries()).filter(([e,t])=>!An(t.progress)).map(([e,t])=>t)}}function An(i){var e;return i.done&&(((e=i.status)==null?void 0:e.progress)??0)>=1}function jn(i,e){if(!e.name.startsWith("BlobUpload")&&!e.name.startsWith("BlobIndex"))throw new j(`${i}: wrong resource type: ${e.name}, expected: a resource of either type 'BlobUpload' or 'BlobIndex'.`)}class Gn{constructor(e,t,r={nConcurrentGetLogs:10,pollingInterval:1e3,stopPollingDelay:1e3}){h(this,"idToLastLines",new Map);h(this,"idToProgressLog",new Map);h(this,"hooks");h(this,"scheduledOnNextState",[]);h(this,"keepRunning",!1);h(this,"currentLoop");this.logger=e,this.clientLogs=t,this.opts=r,this.hooks=new f.PollingComputableHooks(()=>this.startUpdating(),()=>this.stopUpdating(),{stopDebounce:r.stopPollingDelay},(n,o)=>this.scheduleOnNextState(n,o))}getLastLogs(e,t,r){if(r==null)return f.Computable.make(s=>this.getLastLogs(e,t,s));const n=m.treeEntryToResourceInfo(e,r),o=P.randomUUID();r.attacheHooks(this.hooks),r.addOnDestroy(()=>this.releaseLastLogs(n.id,o));const d=this.getLastLogsNoCtx(r.watcher,n,t,o);return r.markUnstable("The logs are from stream, so we consider them unstable. Final values will be got from blobs."),d}getLastLogsNoCtx(e,t,r,n){ne("getLastLogs",t.type);let o=this.idToLastLines.get(t.id);if(o==null){const s=new Ie(this.logger,this.clientLogs,t,r);this.idToLastLines.set(t.id,s),o=s}o.attach(e,n);const d=o.getLog();if(d.error!=null)throw d.error;return d.log}getProgressLog(e,t,r){if(r==null)return f.Computable.make(s=>this.getProgressLog(e,t,s));const n=m.treeEntryToResourceInfo(e,r),o=P.randomUUID();r.attacheHooks(this.hooks),r.addOnDestroy(()=>this.releaseProgressLog(n.id,o));const d=this.getProgressLogNoCtx(r.watcher,n,t,o);return r.markUnstable("The progress log is from the stream, so we consider it unstable. Final value will be got from blobs."),d}getProgressLogNoCtx(e,t,r,n){ne("getProgressLog",t.type);let o=this.idToProgressLog.get(t.id);if(o==null){const s=new Ie(this.logger,this.clientLogs,t,1,r);this.idToProgressLog.set(t.id,s),o=s}o.attach(e,n);const d=o.getLog();if(d.error)throw d.error;return d.log}getLogHandle(e,t){if(t==null)return f.Computable.make(o=>this.getLogHandle(e,o));const r=m.treeEntryToResourceInfo(e,t),n=this.getLogHandleNoCtx(r);return t.markUnstable(`live_log:${p.resourceIdToString(r.id)}`),n}getLogHandleNoCtx(e){return ne("getLogHandle",e.type),Qe(!0,e)}async lastLines(e,t,r,n){return await this.tryWithNotFound(e,()=>this.clientLogs.lastLines(O(e),t,BigInt(r??0),n))}async readText(e,t,r,n){return await this.tryWithNotFound(e,()=>this.clientLogs.readText(O(e),t,BigInt(r??0),n))}async tryWithNotFound(e,t){if(!M(e))throw new Error(`Not live log handle was passed to live log driver, handle: ${e}`);try{const r=await t();return{live:!0,shouldUpdateHandle:!1,data:r.data,size:Number(r.size),newOffset:Number(r.newOffset)}}catch(r){if(r.name=="RpcError"&&r.code=="NOT_FOUND")return{shouldUpdateHandle:!0};throw r}}async releaseLastLogs(e,t){var n;((n=this.idToLastLines.get(e))==null?void 0:n.release(t))&&this.idToLastLines.delete(e)}async releaseProgressLog(e,t){var n;((n=this.idToProgressLog.get(e))==null?void 0:n.release(t))&&this.idToProgressLog.delete(e)}async releaseAll(){}scheduleOnNextState(e,t){this.scheduledOnNextState.push({resolve:e,reject:t})}startUpdating(){this.keepRunning=!0,this.currentLoop===void 0&&(this.currentLoop=this.mainLoop())}stopUpdating(){this.keepRunning=!1}async mainLoop(){for(;this.keepRunning;){const e=this.scheduledOnNextState;this.scheduledOnNextState=[];try{const t=this.getAllLogs();await g.asyncPool(this.opts.nConcurrentGetLogs,t.map(r=>async()=>await r.update())),e.forEach(r=>r.resolve())}catch(t){console.error(t),e.forEach(r=>r.reject(t))}if(!this.keepRunning)break;await ve.scheduler.wait(this.opts.pollingInterval)}this.currentLoop=void 0}getAllLogs(){return Array.from(this.idToLastLines.entries()).concat(Array.from(this.idToProgressLog.entries())).map(([e,t])=>t)}}class Ie{constructor(e,t,r,n,o){h(this,"logs");h(this,"error");h(this,"change",new f.ChangeSource);h(this,"counter",new g.CallersCounter);this.logger=e,this.clientLogs=t,this.rInfo=r,this.lines=n,this.patternToSearch=o}getLog(){return{log:this.logs,error:this.error}}attach(e,t){this.change.attachWatcher(e),this.counter.inc(t)}release(e){return this.counter.dec(e)}async update(){try{const e=await this.clientLogs.lastLines(this.rInfo,this.lines,0n,this.patternToSearch),t=new TextDecoder().decode(e.data);this.logs!=t&&this.change.markChanged(`logs for ${p.resourceIdToString(this.rInfo.id)} updated`),this.logs=t,this.error=void 0;return}catch(e){if(e.name=="RpcError"&&e.code=="NOT_FOUND"){this.logs="",this.error=e,this.change.markChanged();return}throw this.logger.error(`Stream log lines for ${p.stringifyWithResourceId(this.rInfo.id)} failed, reason: ${e}`),e}}}function ne(i,e){if(!e.name.startsWith("StreamWorkdir"))throw new j(`${i}: wrong resource type: ${e.name}, expected: a resource of type 'StreamWorkdir'.`)}class Vn{constructor(e,t,r){this.logger=e,this.logsStreamDriver=t,this.downloadDriver=r}getLastLogs(e,t,r){if(r===void 0)return f.Computable.make(o=>this.getLastLogs(e,t,o));const n=E(r,e);if(n===void 0){r.markUnstable("no stream in stream manager");return}if(W(n))return this.downloadDriver.getLastLogs(n,t,r);try{return this.logsStreamDriver.getLastLogs(n,t,r)}catch(o){if(o.name=="RpcError"&&o.code=="NOT_FOUND"){r.markUnstable(`NOT_FOUND in logs stream driver while getting last logs: ${o}`);return}throw o}}getProgressLog(e,t,r){if(r===void 0)return f.Computable.make(o=>this.getProgressLog(e,t,o));const n=E(r,e);if(n===void 0){r.markUnstable("no stream in stream manager");return}if(W(n))return this.downloadDriver.getProgressLog(n,t,r);try{return this.logsStreamDriver.getProgressLog(n,t,r)}catch(o){if(o.name=="RpcError"&&o.code=="NOT_FOUND"){r.markUnstable(`NOT_FOUND in logs stream driver while getting a progress log: ${o}`);return}throw o}}getProgressLogWithInfo(e,t,r){if(r===void 0)return f.Computable.make(o=>this.getProgressLogWithInfo(e,t,o));const n=E(r,e);if(n===void 0){r.markUnstable("no stream in stream manager");return}if(W(n))return{progressLine:this.downloadDriver.getProgressLog(n,t,r),live:!1};try{return{progressLine:this.logsStreamDriver.getProgressLog(n,t,r),live:!0}}catch(o){if(o.name=="RpcError"&&o.code=="NOT_FOUND"){r.markUnstable(`NOT_FOUND in logs stream driver while getting a progress log with info: ${o}`);return}throw o}}getLogHandle(e,t){if(t===void 0)return f.Computable.make(n=>this.getLogHandle(e,n));const r=E(t,e);if(r===void 0){t.markUnstable("no stream in stream manager");return}return W(r)?this.downloadDriver.getLogHandle(r,t):this.logsStreamDriver.getLogHandle(r,t)}async lastLines(e,t,r,n){return M(e)?await this.logsStreamDriver.lastLines(e,t,r,n):await this.downloadDriver.lastLines(e,t,r,n)}async readText(e,t,r,n){return M(e)?await this.logsStreamDriver.readText(e,t,r,n):await this.downloadDriver.readText(e,t,r,n)}}function W(i){return!i.type.name.startsWith("StreamWorkdir")}function E(i,e){var t;return(t=i.accessor(e).node().traverse("stream"))==null?void 0:t.resourceInfo}class qn{constructor(e,t,r,n,o){h(this,"counter",new g.CallersCounter);h(this,"change",new f.ChangeSource);h(this,"signalCtl",new AbortController);h(this,"error");h(this,"done",!1);h(this,"size",0);this.logger=e,this.path=t,this.url=r,this.signer=n,this.saveDir=o}info(){return{url:this.url.toString(),path:this.path,done:this.done,size:this.size,error:this.error}}attach(e,t){this.counter.inc(t),this.done||this.change.attachWatcher(e)}async download(e,t){try{const r=await this.downloadAndUntar(e,t,this.signalCtl.signal);this.setDone(r),this.change.markChanged(`download of ${this.url} finished`)}catch(r){if(r instanceof Se||r instanceof z){this.setError(r),this.change.markChanged(`download of ${this.url} failed`),await le(this.path);return}throw r}}async downloadAndUntar(e,t,r){if(await g.ensureDirExists(b.dirname(this.path)),await g.fileExists(this.path))return await ut(this.path);const n=await e.download(this.url.toString(),{},r);let o=n.content;if(t){const d=L.Transform.toWeb(Ce.createGunzip());o=o.pipeThrough(d,{signal:r})}return await g.createPathAtomically(this.logger,this.path,async d=>{await w.mkdir(d);const s=L.Writable.toWeb(ie.extract(d));await o.pipeTo(s,{signal:r})}),n.size}getUrl(){if(this.done)return{url:Sn(this.signer,this.saveDir,g.notEmpty(this.path))};if(this.error)return{error:this.error}}setDone(e){this.done=!0,this.size=e}setError(e){this.error=String(e)}abort(e){this.signalCtl.abort(new Se(e))}}class Se extends Error{constructor(){super(...arguments);h(this,"name","URLAborted")}}async function ut(i){const e=await w.readdir(i,{withFileTypes:!0});return(await Promise.all(e.map(async r=>{const n=b.join(i,r.name);return r.isDirectory()?await ut(n):(await w.stat(n)).size}))).reduce((r,n)=>r+n,0)}async function le(i){await w.rm(i,{recursive:!0,force:!0})}class Jn{constructor(e,t,r,n,o={cacheSoftSizeBytes:1*1024*1024*1024,withGunzip:!0,nConcurrentDownloads:50}){h(this,"downloadHelper");h(this,"urlToDownload",new Map);h(this,"downloadQueue");h(this,"cache");this.logger=e,this.saveDir=r,this.signer=n,this.opts=o,this.downloadQueue=new g.TaskProcessor(this.logger,this.opts.nConcurrentDownloads),this.cache=new ye(this.opts.cacheSoftSizeBytes),this.downloadHelper=new Ee(t)}getUrl(e,t){if(t===void 0)return f.Computable.make(o=>this.getUrl(e,o));const r=P.randomUUID();t.addOnDestroy(()=>this.releasePath(e,r));const n=this.getUrlNoCtx(e,t.watcher,r);return(n==null?void 0:n.url)===void 0&&t.markUnstable(`a path to the downloaded and untared archive might be undefined. The current result: ${n}`),n}getUrlNoCtx(e,t,r){const n=e.toString(),o=this.urlToDownload.get(n);if(o!==void 0)return o.attach(t,r),o.getUrl();const d=this.setNewTask(t,e,r);return this.downloadQueue.push({fn:async()=>this.downloadUrl(d,r),recoverableErrorPredicate:s=>!0}),d.getUrl()}getPathForBlockUI(e){if(!N.isBlockUIURL(e))throw new Error(`getPathForBlockUI: ${e} is invalid`);return Nn(this.signer,e,this.saveDir)}async downloadUrl(e,t){var r;await e.download(this.downloadHelper,this.opts.withGunzip),((r=e.getUrl())==null?void 0:r.url)!==void 0&&this.cache.addCache(e,t)}async releasePath(e,t){const r=e.toString(),n=this.urlToDownload.get(r);if(n!=null)if(this.cache.existsFile(n.path)){const o=this.cache.removeFile(n.path,t);await Promise.all(o.map(async d=>{await le(d.path),this.cache.removeCache(d),this.removeTask(d,`the task ${p.stringifyWithResourceId(d.info())} was removedfrom cache along with ${p.stringifyWithResourceId(o.map(s=>s.info()))}`)}))}else n.counter.dec(t)&&this.removeTask(n,`the task ${p.stringifyWithResourceId(n.info())} was removed from cache`)}async releaseAll(){this.downloadQueue.stop(),await Promise.all(Array.from(this.urlToDownload.entries()).map(async([e,t])=>{await le(t.path),this.cache.removeCache(t),this.removeTask(t,`the task ${p.stringifyWithResourceId(t.info())} was released when the driver was closed`)}))}setNewTask(e,t,r){const n=new qn(this.logger,this.getFilePath(t),t,this.signer,this.saveDir);return n.attach(e,r),this.urlToDownload.set(t.toString(),n),n}removeTask(e,t){e.abort(t),e.change.markChanged(`task for url ${e.url} removed: ${t}`),this.urlToDownload.delete(e.url.toString())}getFilePath(e){const t=P.createHash("sha256").update(e.toString()).digest("hex");return b.join(this.saveDir,t)}}function oe(i,e){return`index://index/${encodeURIComponent(JSON.stringify({storageId:i,path:e}))}`}function Zn(i,e,t,r){const n={localPath:i,pathSignature:e.sign(i),sizeBytes:String(t),modificationTime:String(r)};return`upload://upload/${encodeURIComponent(JSON.stringify(n))}`}function Qn(i){const e=new URL(i);return C.parse(JSON.parse(decodeURIComponent(e.pathname.substring(1))))}function Kn(i){const e=new URL(i);return we.parse(JSON.parse(decodeURIComponent(e.pathname.substring(1))))}function De(i){if(to(i))return no(i);if(Xn(i))return eo(i);g.assertNever(i)}const pt=/^local:\/\/(?<name>.*)\/(?<path>.*)$/;function Xn(i){return pt.test(i)}function Yn(i,e){return`local://${i}/${encodeURIComponent(e)}`}function eo(i){const e=i.match(pt);if(e==null)throw new Error(`Local list handle wasn't parsed: ${i}`);const{name:t,path:r}=e.groups;return{rootPath:decodeURIComponent(r),name:t,isRemote:!1}}const gt=/^remote:\/\/(?<name>.*)\/(?<resourceId>.*)$/;function to(i){return gt.test(i)}function ro(i,e){return`remote://${i}/${BigInt(e)}`}function no(i){const e=i.match(gt);if(e==null)throw new Error(`Remote list handle wasn't parsed: ${i}`);const{name:t,resourceId:r}=e.groups;return{id:p.bigintToResourceId(BigInt(r)),type:oo(t),name:t,isRemote:!0}}function oo(i){return{name:`LS/${i}`,version:"1"}}async function ft(){const i=$e.homedir();if(k.sep=="/")return[{name:"local",root:"/",initialPath:i}];{const t=k.parse(i).root.replaceAll(":\\","");try{return(await St.promisify(Dt.exec)("wmic logicaldisk get name")).stdout.split(`\r
|
|
2
|
+
`).filter(o=>o.includes(":")).map(o=>o.trim().replaceAll(":","")).map(o=>{const d=o==t;return{name:`local_disk_${o}`,root:`${o}:\\`,initialPath:d?i:`${o}:\\`}})}catch{return[{name:`local_disk_${t}`,root:`${t}:\\`,initialPath:i}]}}}class ke{constructor(e,t,r,n,o,d,s){this.logger=e,this.lsClient=t,this.storageIdToResourceId=r,this.signer=n,this.virtualStoragesMap=o,this.localProjectionsMap=d,this.openFileDialogCallback=s}async getLocalFileContent(e,t){const r=await this.tryResolveLocalFileHandle(e);if(t)throw new Error("Range request not yet supported.");return await w.readFile(r)}async getLocalFileSize(e){const t=await this.tryResolveLocalFileHandle(e);return(await w.stat(t)).size}async showOpenMultipleFilesDialog(e){const t=await this.openFileDialogCallback(!0,e);return t===void 0?{}:{files:await Promise.all(t.map(r=>this.getLocalFileHandle(r)))}}async showOpenSingleFileDialog(e){const t=await this.openFileDialogCallback(!1,e);return t===void 0?{}:{file:await this.getLocalFileHandle(t[0])}}async tryResolveLocalFileHandle(e){if(N.isImportFileHandleIndex(e)){const t=Kn(e),r=this.localProjectionsMap.get(t.storageId);if(!r)throw new Error(`Storage ${t.storageId} is not mounted locally.`);return b.join(r.localPath,t.path)}else{const t=Qn(e);this.signer.verify(t.localPath,t.pathSignature,"Failed to validate local file handle signature.");const r=t.localPath,n=await w.stat(r,{bigint:!0});if(String(n.mtimeMs/1000n)!==t.modificationTime)throw new Error("File has changed since the handle was created.");return r}}async getLocalFileHandle(e){S(e);for(const r of this.localProjectionsMap.values())if(e.startsWith(r.localPath)){const n=r.localPath===""?e:b.relative(r.localPath,e);return oe(r.storageId,n)}const t=await w.stat(e,{bigint:!0});return Zn(e,this.signer,t.size,t.mtimeMs/1000n)}async getStorageList(){const e=[...this.virtualStoragesMap.values()].map(n=>({name:n.name,handle:Yn(n.name,n.root),initialFullPath:n.initialPath})),r=Object.entries(this.storageIdToResourceId).map(([n,o])=>({name:n,handle:ro(n,o),initialFullPath:"",isInitialPathHome:!1})).filter(n=>n.name!=="root");return[...e,...r]}async listFiles(e,t){const r=De(e);if(r.isRemote)return{entries:(await this.lsClient.list(r,t)).items.map(s=>({type:s.isDir?"dir":"file",name:s.name,fullPath:s.fullName,handle:oe(r.name,s.fullName)}))};b.sep==="/"&&t===""&&(t="/"),r.rootPath===""&&S(t);const n=b.isAbsolute(t)?t:b.join(r.rootPath,t),o=[];for await(const d of await w.opendir(n)){if(!d.isFile()&&!d.isDirectory())continue;const s=b.join(n,d.name);o.push({type:d.isFile()?"file":"dir",name:d.name,fullPath:s,handle:await this.getLocalFileHandle(s)})}return{entries:o}}async listRemoteFilesWithAdditionalInfo(e,t){const r=De(e);if(!r.isRemote)throw new Error(`Storage ${r.name} is not remote`);return{entries:(await this.lsClient.list(r,t)).items.map(o=>({type:o.isDir?"dir":"file",name:o.name,fullPath:o.fullName,handle:oe(r.name,o.fullName),size:Number(o.size)}))}}async fileToImportHandle(e){throw new Error("Not implemented. This method must be implemented and intercepted in desktop preload script.")}static async init(e,t,r,n,o,d){const s=Ae(t,e);d||(d=await ft());for(const u of d)S(u.root);for(const u of n)u.localPath!==""&&S(u.localPath);const c=new Map(d.map(u=>[u.name,u])),l=new Map(n.map(u=>[u.storageId,u]));if(new Set([...c.keys(),...l.keys()]).size!==c.size+l.size)throw new Error("Intersection between local projection storage ids and virtual storages names detected.");return new ke(e,s,await io(t),r,c,l,o)}}async function io(i){return i.withReadTx("GetAvailableStorageIds",async e=>{const t=await e.getResourceByName("LSProvider"),r=await e.getResourceData(t,!0);return so(r)})}function so(i){return Object.fromEntries(i.fields.filter(e=>e.type=="Dynamic"&&p.isNotNullResourceId(e.value)).map(e=>[e.name.substring(8),e.value]))}exports.ClientDownload=_e;exports.ClientLogs=xe;exports.ClientLs=ze;exports.ClientProgress=We;exports.ClientUpload=Be;exports.DefaultVirtualLocalStorages=ft;exports.DownloadBlobToURLDriver=Fn;exports.DownloadDriver=Te;exports.DownloadUrlDriver=Jn;exports.DownloadableBlobSnapshot=rt;exports.ImportFileHandleData=rn;exports.ImportFileHandleIndexData=we;exports.ImportFileHandleUploadData=C;exports.IndexResourceSnapshot=qe;exports.LogsDriver=Vn;exports.LogsStreamDriver=Gn;exports.LsDriver=ke;exports.MTimeError=he;exports.NetworkError=pe;exports.NoFileForUploading=ge;exports.OnDemandBlobResourceSnapshot=Ge;exports.UnexpectedEOF=ue;exports.UnknownStorageError=A;exports.Updater=Ze;exports.UploadDriver=xn;exports.UploadResourceSnapshot=Ve;exports.UploadTask=at;exports.WrongLocalFileUrl=x;exports.WrongResourceTypeError=j;exports.createDownloadClient=Qr;exports.createLogsClient=Kr;exports.createLsFilesClient=Ae;exports.createUploadBlobClient=Yr;exports.createUploadProgressClient=Xr;exports.getFullPath=Oe;exports.getSize=fe;exports.isMyUpload=dt;exports.isResourceWasDeletedError=ae;exports.isSignMatch=ct;exports.isUpload=H;exports.makeBlobImportSnapshot=ht;exports.makeDownloadableBlobSnapshot=nt;exports.newLocalStorageIdsToRoot=He;exports.nonRecoverableError=be;exports.parseLocalUrl=Me;exports.uploadBlob=lt;exports.validateAbsolute=S;
|
|
3
3
|
//# sourceMappingURL=index.js.map
|