Socket
Socket
Sign inDemoInstall

mps3

Package Overview
Dependencies
Maintainers
1
Versions
41
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mps3 - npm Package Compare versions

Comparing version 0.0.63 to 0.0.64

2

dist/mps3.js

@@ -1,1 +0,1 @@

var N=(J,W)=>()=>(W||J((W={exports:{}}).exports,W),W.exports);var A=N((G0,d)=>{G0.serialize=function(J){return J&&typeof J.toJSON==="function"?J.toJSON():J}});var p=N((U0,l)=>{var g=A().serialize;l.exports=function J(W,X){if(X=g(X),X===null||typeof X!=="object"||Array.isArray(X))return X;if(W=g(W),W===null||typeof W!=="object"||Array.isArray(W))W={};var $=Object.keys(X);for(var B=0;B<$.length;B++){var D=$[B];if(D==="__proto__"||D==="constructor"||D==="prototype")return W;if(X[D]===null){if(W.hasOwnProperty(D))delete W[D]}else W[D]=J(W[D],X[D])}return W}});var o=N((L0,f)=>{f.exports=function J(W,X){if(W===X)return!0;if(W&&X&&typeof W=="object"&&typeof X=="object"){if(W.constructor!==X.constructor)return!1;var $,B,D;if(Array.isArray(W)){if($=W.length,$!=X.length)return!1;for(B=$;B--!==0;)if(!J(W[B],X[B]))return!1;return!0}if(W.constructor===RegExp)return W.source===X.source&&W.flags===X.flags;if(W.valueOf!==Object.prototype.valueOf)return W.valueOf()===X.valueOf();if(W.toString!==Object.prototype.toString)return W.toString()===X.toString();if(D=Object.keys(W),$=D.length,$!==Object.keys(X).length)return!1;for(B=$;B--!==0;)if(!Object.prototype.hasOwnProperty.call(X,D[B]))return!1;for(B=$;B--!==0;){var G=D[B];if(!J(W[G],X[G]))return!1}return!0}return W!==W&&X!==X}});var i=N((E0,c)=>{var F0=function(J,W){if(J.length!==W.length)return!1;for(var X=0;X<J.length;X++)if(!Z0(W[X],J[X]))return!1;return!0},Z0=o(),U=A().serialize;c.exports=function J(W,X){if(W=U(W),X=U(X),W===null||X===null||typeof W!=="object"||typeof X!=="object"||Array.isArray(W)!==Array.isArray(X))return X;if(Array.isArray(W)){if(!F0(W,X))return X;return}var $={},B=Object.keys(W),D=Object.keys(X),G,Y,F={};for(Y=0;Y<D.length;Y++)if(G=D[Y],B.indexOf(G)===-1)F[G]=!0,$[G]=U(X[G]);var Q={};for(Y=0;Y<B.length;Y++)if(G=B[Y],D.indexOf(G)===-1)Q[G]=!0,$[G]=null;else if(W[G]!==null&&typeof W[G]==="object"){var z=J(W[G],X[G]);if(z!==void 0)$[G]=z}else if(W[G]!==X[G])$[G]=U(X[G]);return Object.keys($).length>0?$:void 0}});var s=N((P0,n)=>{n.exports=function J(W,X){if(W===null||X===null||typeof W!=="object"||typeof X!=="object"||Array.isArray(W)!==Array.isArray(X))return X;var $=JSON.parse(JSON.stringify(W));return Object.keys(X).forEach(function(B){if(W[B]!==void 0)$[B]=J(W[B],X[B]);else $[B]=X[B]}),$}});async function j(J,W){const X=await crypto.subtle.importKey("raw",typeof J==="string"?P.encode(J):J,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",X,P.encode(W))}async function b(J){return crypto.subtle.digest("SHA-256",typeof J==="string"?P.encode(J):J)}var E=function(J){return Array.prototype.map.call(new Uint8Array(J),(W)=>("0"+W.toString(16)).slice(-2)).join("")},h=function(J){return J.replace(/[!'()*]/g,(W)=>"%"+W.charCodeAt(0).toString(16).toUpperCase())},B0=function(J,W){const{hostname:X,pathname:$}=J;if(X.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(X.endsWith(".backblazeb2.com")){const Y=X.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);return Y!=null?["s3",Y[1]]:["",""]}const B=X.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/);let[D,G]=(B||["",""]).slice(1,3);if(G==="us-gov")G="us-gov-west-1";else if(G==="s3"||G==="s3-accelerate")G="us-east-1",D="s3";else if(D==="iot")if(X.startsWith("iot."))D="execute-api";else if(X.startsWith("data.jobs.iot."))D="iot-jobs-data";else D=$==="/mqtt"?"iotdevicegateway":"iotdata";else if(D==="autoscaling"){const Y=(W.get("X-Amz-Target")||"").split(".")[0];if(Y==="AnyScaleFrontendService")D="application-autoscaling";else if(Y==="AnyScaleScalingPlannerFrontendService")D="autoscaling-plans"}else if(G==null&&D.startsWith("s3-"))G=D.slice(3).replace(/^fips-|^external-1/,""),D="s3";else if(D.endsWith("-fips"))D=D.slice(0,-5);else if(G&&/-\d$/.test(D)&&!/-\d$/.test(G))[D,G]=[G,D];return[X0[D]||D,G]},P=new TextEncoder,X0={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},$0=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);class V{constructor({accessKeyId:J,secretAccessKey:W,sessionToken:X,service:$,region:B,cache:D,retries:G,initRetryMs:Y}){if(J==null)throw new TypeError("accessKeyId is a required option");if(W==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=J,this.secretAccessKey=W,this.sessionToken=X,this.service=$,this.region=B,this.cache=D||new Map,this.retries=G!=null?G:10,this.initRetryMs=Y||50}async sign(J,W){if(J instanceof Request){const{method:B,url:D,headers:G,body:Y}=J;if(W=Object.assign({method:B,url:D,headers:G},W),W.body==null&&G.has("Content-Type"))W.body=Y!=null&&G.has("X-Amz-Content-Sha256")?Y:await J.clone().arrayBuffer();J=D}const X=new k(Object.assign({url:J},W,this,W&&W.aws)),$=Object.assign({},W,await X.sign());delete $.aws;try{return new Request($.url.toString(),$)}catch(B){if(B instanceof TypeError)return new Request($.url.toString(),Object.assign({duplex:"half"},$));throw B}}async fetch(J,W){for(let X=0;X<=this.retries;X++){const $=fetch(await this.sign(J,W));if(X===this.retries)return $;const B=await $;if(B.status<500&&B.status!==429)return B;await new Promise((D)=>setTimeout(D,Math.random()*this.initRetryMs*Math.pow(2,X)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class k{constructor({method:J,url:W,headers:X,body:$,accessKeyId:B,secretAccessKey:D,sessionToken:G,service:Y,region:F,cache:Q,datetime:z,signQuery:r,appendSessionToken:e,allHeaders:J0,singleEncode:W0}){if(W==null)throw new TypeError("url is a required option");if(B==null)throw new TypeError("accessKeyId is a required option");if(D==null)throw new TypeError("secretAccessKey is a required option");this.method=J||($?"POST":"GET"),this.url=new URL(W),this.headers=new Headers(X||{}),this.body=$,this.accessKeyId=B,this.secretAccessKey=D,this.sessionToken=G;let S,I;if(!Y||!F)[S,I]=B0(this.url,this.headers);if(this.service=Y||S||"",this.region=F||I||"us-east-1",this.cache=Q||new Map,this.datetime=z||(new Date()).toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=r,this.appendSessionToken=e||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256"))this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");const M=this.signQuery?this.url.searchParams:this.headers;if(M.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)M.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter((Z)=>J0||!$0.has(Z)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map((Z)=>Z+":"+(Z==="host"?this.url.host:(this.headers.get(Z)||"").replace(/\s+/g," "))).join("\n"),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery){if(this.service==="s3"&&!M.has("X-Amz-Expires"))M.set("X-Amz-Expires","86400");M.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),M.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),M.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(Z){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!W0)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=h(this.encodedPath);const R=new Set;this.encodedSearch=[...this.url.searchParams].filter(([Z])=>{if(!Z)return!1;if(this.service==="s3"){if(R.has(Z))return!1;R.add(Z)}return!0}).map((Z)=>Z.map((C)=>h(encodeURIComponent(C)))).sort(([Z,C],[v,u])=>Z<v?-1:Z>v?1:C<u?-1:C>u?1:0).map((Z)=>Z.join("=")).join("&")}async sign(){if(this.signQuery){if(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken)this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)}else this.headers.set("Authorization",await this.authHeader());return{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){const J=this.datetime.slice(0,8),W=[this.secretAccessKey,J,this.region,this.service].join();let X=this.cache.get(W);if(!X){const $=await j("AWS4"+this.secretAccessKey,J),B=await j($,this.region),D=await j(B,this.service);X=await j(D,"aws4_request"),this.cache.set(W,X)}return E(await j(X,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,E(await b(await this.canonicalString()))].join("\n")}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+"\n",this.signedHeaders,await this.hexBodyHash()].join("\n")}async hexBodyHash(){let J=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(J==null){if(this.body&&typeof this.body!=="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");J=E(await b(this.body||""))}return J}}var m=(J,W)=>{const X=W.parseFromString(J,"text/xml"),$=X.getElementsByTagName("ListBucketResult")[0],B=X.getElementsByTagName("Contents"),D=X.getElementsByTagName("CommonPrefixes")[0];if($===null||B===null)throw new Error("Invalid XML");return{$metadata:{},IsTruncated:$.getElementsByTagName("IsTruncated")[0]?.textContent==="true",Contents:Array.from(B).map((G)=>({ChecksumAlgorithm:[G.getElementsByTagName("ChecksumAlgorithm")[0]?.textContent],ETag:G.getElementsByTagName("ETag")[0]?.textContent,Key:G.getElementsByTagName("Key")[0]?.textContent,LastModified:new Date(G.getElementsByTagName("LastModified")[0]?.textContent),Owner:{DisplayName:G.getElementsByTagName("DisplayName")[0]?.textContent,ID:G.getElementsByTagName("ID")[0]?.textContent},Size:Number.parseInt(G.getElementsByTagName("Size")[0]?.textContent),StorageClass:G.getElementsByTagName("StorageClass")[0]?.textContent})),Name:X.getElementsByTagName("Name")[0]?.textContent,Prefix:X.getElementsByTagName("Prefix")[0]?.textContent,Delimiter:X.getElementsByTagName("Delimiter")[0]?.textContent,MaxKeys:Number.parseInt(X.getElementsByTagName("MaxKeys")[0]?.textContent),CommonPrefixes:Array.from(D?D.getElementsByTagName("Prefix"):[],(G)=>({Prefix:G?.textContent})),EncodingType:X.getElementsByTagName("EncodingType")[0]?.textContent,KeyCount:Number.parseInt(X.getElementsByTagName("KeyCount")[0]?.textContent),ContinuationToken:X.getElementsByTagName("ContinuationToken")[0]?.textContent,NextContinuationToken:X.getElementsByTagName("NextContinuationToken")[0]?.textContent,StartAfter:X.getElementsByTagName("StartAfter")[0]?.textContent}};class x{client;endpoint;parser;constructor(J,W,X){this.client=J,this.endpoint=W,this.parser=X}async listObjectV2(J){const W=`${this.endpoint}/${J.Bucket}/?list-type=2&prefix=${J.Prefix}`,$=await(await this.client(W,{})).text();return m($,this.parser)}async putObject(J){const W=`${this.endpoint}/${J.Bucket}/${J.Key}`,X=await this.client(W,{method:"PUT",body:J.Body,headers:{"Content-Type":"application/json",...J.ChecksumSHA256&&{"x-amz-content-sha256":J.ChecksumSHA256}}});if(X.status!=200)throw new Error(`Failed to PUT: ${await X.text()}`);return{$metadata:{httpStatusCode:X.status},ETag:X.headers.get("ETag"),...X.headers.get("x-amz-version-id")&&{VersionId:X.headers.get("x-amz-version-id")}}}async deleteObject(J){const W=`${this.endpoint}/${J.Bucket}/${J.Key}`;return{$metadata:{httpStatusCode:(await this.client(W,{method:"DELETE"})).status}}}async getObject(J){const W=`${this.endpoint}/${J.Bucket}/${J.Key}?${J.VersionId?`versionId=${J.VersionId}`:""}`,X=await this.client(W,{method:"GET",headers:{"If-None-Match":J.IfNoneMatch}});if(X.status==304){const B=new Error;throw B.name="304",B}const $=X.status==404?void 0:await X.json();return{$metadata:{httpStatusCode:X.status},Body:$,ETag:X.headers.get("ETag"),...X.headers.get("x-amz-version-id")&&{VersionId:X.headers.get("x-amz-version-id")}}}}class O{key;_vals;_keys;constructor(J,W){if(this.key=J,this._vals=new Map,this._keys=new Map,W)for(let[X,$]of W)this.set(X,$)}get size(){return this._vals.size}set(J,W){const X=this.key(J);return this._vals.set(X,W),this._keys.set(X,J),this}get(J){return this._vals.get(this.key(J))}delete(J){const W=this.key(J);return this._keys.delete(W),this._vals.delete(W)}has(J){return this._vals.has(this.key(J))}values(){return this._vals.values()}keys(){return this._keys.values()}forEach(J){return this._vals.forEach((W,X,$)=>J(W,this._keys.get(X)))}}var w=()=>`${Date.now()-200}`.padStart(14,"0"),y=()=>`${Date.now()+200}`.padStart(14,"0");var H=()=>crypto.randomUUID();var q=(J)=>`${J.bucket}/${J.key}`;var L=p(),Q0=i(),q0=s();var _={previous:".",files:{},update:{}};class t{ref;handler;lastVersion;queue=Promise.resolve();constructor(J,W){this.ref=J,this.handler=W}notify(J,W,X){this.queue=this.queue.then(()=>X).then(($)=>{if(W===this.lastVersion)return;else console.log(`${J} NOTIFY ${q(this.ref)} ${W}`),this.lastVersion=W,this.handler($)})}}class K{service;ref;subscribers=new Set;poller;cache;pollInProgress=!1;authoritative_key="";authoritative_state=JSON.parse(JSON.stringify(_));optimistic_state=JSON.parse(JSON.stringify(_));pendingWrites=new Map;writtenOperations=new Map;constructor(J,W,X){console.log("New manifest",W),this.service=J,this.ref=W}observeVersionId(J){if(this.writtenOperations.has(J)){const W=this.writtenOperations.get(J);this.pendingWrites.delete(W),this.writtenOperations.delete(J)}}async get(){return this.getLatest().then((J)=>J||this.cache?.data)}async getLatest(){try{const J=await this.service._getObject({operation:"POLL_TIME",ref:this.ref,ifNoneMatch:this.cache?.etag});if(J.$metadata.httpStatusCode===304)return;if(J.data===void 0)this.authoritative_key=".";else this.authoritative_key=J.data;const W=await this.service.s3ClientLite.listObjectV2({Bucket:this.ref.bucket,Prefix:this.ref.key,StartAfter:this.authoritative_key});if(W.Contents===void 0)return this.authoritative_state=JSON.parse(JSON.stringify(_)),this.optimistic_state=JSON.parse(JSON.stringify(_)),this.authoritative_state;for(let X=W.Contents.length-1;X>=0;X--){const $=W.Contents[X].Key;if($==this.ref.key)continue;const B=w(),D=await this.service._getObject({operation:"LOOK_BACK",ref:{bucket:this.ref.bucket,key:$}});if(D.data===void 0)throw new Error("empty data");if(D.data.previous<B){this.authoritative_key=D.data.previous,this.authoritative_state=D.data;break}}for(let X=0;X<W.Contents.length;X++){const $=W.Contents[X].Key;if($==this.ref.key)continue;const B=await this.service._getObject({operation:"SWEEP",ref:{bucket:this.ref.bucket,key:$}}),D=$.substring($.lastIndexOf("@")+1),G=w();if($<this.authoritative_key);else if(D>=G)this.optimistic_state=L(this.optimistic_state,B.data?.update);else this.authoritative_state=L(this.authoritative_state,B.data?.update),this.authoritative_key=$;this.observeVersionId(D)}return this.authoritative_state}catch(J){if(J.name==="NoSuchKey")return this.authoritative_state=_,this.authoritative_state;else throw J}}async poll(){if(this.pollInProgress)return;if(this.pollInProgress=!0,this.subscriberCount===0&&this.poller)clearInterval(this.poller),this.poller=void 0;if(this.subscriberCount>0&&!this.poller)this.poller=setInterval(()=>this.poll(),this.service.config.pollFrequency);const J=await this.getLatest();if(J===void 0){this.pollInProgress=!1;return}this.subscribers.forEach(async(W)=>{const X=J.files[q(W.ref)];if(X){const $=this.service._getObject({operation:"GET_CONTENT",ref:W.ref,version:X.version});W.notify(this.service.config.label,X.version,$.then((B)=>B.data))}else if(X===null)W.notify(this.service.config.label,void 0,Promise.resolve(void 0))}),this.pollInProgress=!1}async updateContent(J,W){this.pendingWrites.set(W,J);try{const X=await W,$=await this.get();$.previous=this.authoritative_key,$.update={files:{}};for(let[Y,F]of X){const Q=q(Y);if(F){const z={version:F};$.update.files[Q]=z}else $.update.files[Q]=null}const B=y()+"_"+H().substring(0,2),D=this.ref.key+"@"+B;await this.service._putObject({operation:"PUT_MANIFEST",ref:{key:D,bucket:this.ref.bucket},value:$});const G=await this.service._putObject({operation:"PUT_POLL",ref:{key:this.ref.key,bucket:this.ref.bucket},value:this.authoritative_key});return this.writtenOperations.set(B,W),this.poll(),G}catch(X){throw console.error(X),this.pendingWrites.delete(W),X}}async getOptimisticVersion(J){return await this.get(),this.optimistic_state.files[q(J)]?.version}subscribe(J,W){console.log(`SUBSCRIBE ${q(J)} ${this.subscriberCount+1}`);const X=new t(J,W);return this.subscribers.add(X),()=>this.subscribers.delete(X)}get subscriberCount(){return this.subscribers.size}}async function a(J){const W=(new TextEncoder()).encode(J),X=await crypto.subtle.digest("SHA-256",W);return[...new Uint8Array(X)].map(($)=>$.toString(16).padStart(2,"0")).join("")}class z0{config;s3ClientLite;manifests=new O(q);getCache=new O((J)=>`${J.Bucket}${J.Key}${J.VersionId}${J.IfNoneMatch}`);constructor(J){if(this.config={...J,label:J.label||H().substring(0,3),useChecksum:J.useChecksum===!1?!1:!0,useVersioning:J.useVersioning||!1,pollFrequency:J.pollFrequency||1000,defaultManifest:{bucket:J.defaultManifest?.bucket||J.defaultBucket,key:J.defaultManifest?.key||"manifest.json"}},this.config.s3Config?.credentials instanceof Function)throw Error("We can't do that yet");const W=J.s3Config.endpoint||`https://s3.${J.s3Config.region}.amazonaws.com`;let X;if(this.config.s3Config?.credentials){const $=new V({accessKeyId:this.config.s3Config.credentials.accessKeyId,secretAccessKey:this.config.s3Config.credentials.secretAccessKey,sessionToken:this.config.s3Config.credentials.sessionToken,service:"s3",retries:0});X=(...B)=>$.fetch(...B)}else X=(global||window).fetch.bind(global||window);this.s3ClientLite=new x(X,W,J.parser||new DOMParser)}getOrCreateManifest(J){if(!this.manifests.has(J))this.manifests.set(J,new K(this,J));return this.manifests.get(J)}async get(J,W={}){const X={...this.config.defaultManifest,...W.manifest},$=this.getOrCreateManifest(X),B={bucket:J.bucket||this.config.defaultBucket||this.config.defaultManifest.bucket,key:typeof J==="string"?J:J.key};let D=!1,G=void 0;for(let[F,Q]of $.pendingWrites)if(Q.has(B))D=!0,G=Q.get(B);if(D)return console.log(`${this.config.label} get (cached) ${q(B)}`),G;const Y=await $.getOptimisticVersion(B);if(Y===void 0)return;return(await this._getObject({operation:"GET",ref:B,version:Y})).data}async _getObject(J){let W;if(this.config.useVersioning)W={Bucket:J.ref.bucket,Key:J.ref.key,IfNoneMatch:J.ifNoneMatch,...J.version&&{VersionId:J.version}};else W={Bucket:J.ref.bucket,Key:`${J.ref.key}${J.version?`@${J.version}`:""}`,IfNoneMatch:J.ifNoneMatch};if(this.getCache.has(W))return await this.getCache.get(W);const X=this.s3ClientLite.getObject(W).then(async($)=>{const B={...$,data:$.Body};return console.log(`${this.config.label} ${J.operation} ${J.ref.bucket}/${J.ref.key}@${J.version} => ${B.VersionId} ${B.data}}`),this.getCache.set(W,X),B}).catch(($)=>{if($?.name==="304")return{$metadata:{httpStatusCode:304},data:void 0};else throw $});return X}async delete(J,W={}){return this.putAll(new Map([[J,void 0]]),W)}async put(J,W,X={}){return this.putAll(new Map([[J,W]]),X)}async putAll(J,W={}){const X=new O(q,[...J].map(([B,D])=>[{bucket:B.bucket||this.config.defaultBucket||this.config.defaultManifest.bucket,key:typeof B==="string"?B:B.key},D])),$=(W?.manifests||[this.config.defaultManifest]).map((B)=>({...this.config.defaultManifest,...B}));return this._putAll(X,{manifests:$})}async _putAll(J,W){const X=new Promise(async($,B)=>{const D=new Map,G=[];J.forEach((Y,F)=>{if(Y!==void 0){let Q=this.config.useVersioning?void 0:H();G.push(this._putObject({operation:"PUT_CONTENT",ref:F,value:Y,version:Q}).then((z)=>{if(this.config.useVersioning)if(z.VersionId===void 0)throw console.error(z),Error(`Bucket ${F.bucket} is not version enabled!`);else Q=z.VersionId;D.set(F,Q)}))}else G.push(this._deleteObject({ref:F}).then((Q)=>{D.set(F,void 0)}))}),await Promise.all(G).catch(B),$(D)});return Promise.all(W.manifests.map(($)=>{return this.getOrCreateManifest($).updateContent(J,X)}))}async _putObject(J){const W=JSON.stringify(J.value,null,2);let X;if(this.config.useVersioning)X={Bucket:J.ref.bucket,Key:J.ref.key,ContentType:"application/json",Body:W,...this.config.useChecksum&&{ChecksumSHA256:await a(W)}};else X={Bucket:J.ref.bucket,Key:`${J.ref.key}${J.version?`@${J.version}`:""}`,ContentType:"application/json",Body:W,...this.config.useChecksum&&{ChecksumSHA256:await a(W)}};const $=await this.s3ClientLite.putObject(X);return console.log(`${this.config.label} ${J.operation} ${X.Bucket}/${X.Key} => ${$.VersionId}`),$}async _deleteObject(J){const W={Bucket:J.ref.bucket,Key:J.ref.key},X=await this.s3ClientLite.deleteObject(W);return console.log(`${this.config.label} DELETE ${J.ref.bucket}/${J.ref.key} => ${X.VersionId}`),X}subscribe(J,W,X){const $={...this.config.defaultManifest,...X?.manifest},B={key:typeof J==="string"?J:J.key,bucket:J.bucket||this.config.defaultBucket||$.bucket},D=this.getOrCreateManifest($),G=D.subscribe(B,W);return this.get(B,{manifest:$}).then((Y)=>{console.log(`${this.config.label} NOTIFY (initial) ${q(B)}`),queueMicrotask(()=>{W(Y),D.poll()})}),G}refresh(){return Promise.all([...this.manifests.values()].map((J)=>J.poll()))}get subscriberCount(){return[...this.manifests.values()].reduce((J,W)=>J+W.subscriberCount,0)}}export{z0 as MPS3};
var z=(W,X)=>()=>(X||W((X={exports:{}}).exports,X),X.exports);var x=z((B0,l)=>{B0.serialize=function(W){return W&&typeof W.toJSON==="function"?W.toJSON():W}});var p=z((_0,g)=>{var d=x().serialize;g.exports=function W(X,$){if($=d($),$===null||typeof $!=="object"||Array.isArray($))return $;if(X=d(X),X===null||typeof X!=="object"||Array.isArray(X))X={};var J=Object.keys($);for(var Y=0;Y<J.length;Y++){var Z=J[Y];if(Z==="__proto__"||Z==="constructor"||Z==="prototype")return X;if($[Z]===null){if(X.hasOwnProperty(Z))delete X[Z]}else X[Z]=W(X[Z],$[Z])}return X}});var c=z((U0,f)=>{f.exports=function W(X,$){if(X===$)return!0;if(X&&$&&typeof X=="object"&&typeof $=="object"){if(X.constructor!==$.constructor)return!1;var J,Y,Z;if(Array.isArray(X)){if(J=X.length,J!=$.length)return!1;for(Y=J;Y--!==0;)if(!W(X[Y],$[Y]))return!1;return!0}if(X.constructor===RegExp)return X.source===$.source&&X.flags===$.flags;if(X.valueOf!==Object.prototype.valueOf)return X.valueOf()===$.valueOf();if(X.toString!==Object.prototype.toString)return X.toString()===$.toString();if(Z=Object.keys(X),J=Z.length,J!==Object.keys($).length)return!1;for(Y=J;Y--!==0;)if(!Object.prototype.hasOwnProperty.call($,Z[Y]))return!1;for(Y=J;Y--!==0;){var B=Z[Y];if(!W(X[B],$[B]))return!1}return!0}return X!==X&&$!==$}});var i=z((E0,o)=>{var Q0=function(W,X){if(W.length!==X.length)return!1;for(var $=0;$<W.length;$++)if(!G0(X[$],W[$]))return!1;return!0},G0=c(),U=x().serialize;o.exports=function W(X,$){if(X=U(X),$=U($),X===null||$===null||typeof X!=="object"||typeof $!=="object"||Array.isArray(X)!==Array.isArray($))return $;if(Array.isArray(X)){if(!Q0(X,$))return $;return}var J={},Y=Object.keys(X),Z=Object.keys($),B,D,Q={};for(D=0;D<Z.length;D++)if(B=Z[D],Y.indexOf(B)===-1)Q[B]=!0,J[B]=U($[B]);var F={};for(D=0;D<Y.length;D++)if(B=Y[D],Z.indexOf(B)===-1)F[B]=!0,J[B]=null;else if(X[B]!==null&&typeof X[B]==="object"){var j=W(X[B],$[B]);if(j!==void 0)J[B]=j}else if(X[B]!==$[B])J[B]=U($[B]);return Object.keys(J).length>0?J:void 0}});var s=z((P0,n)=>{n.exports=function W(X,$){if(X===null||$===null||typeof X!=="object"||typeof $!=="object"||Array.isArray(X)!==Array.isArray($))return $;var J=JSON.parse(JSON.stringify(X));return Object.keys($).forEach(function(Y){if(X[Y]!==void 0)J[Y]=W(X[Y],$[Y]);else J[Y]=$[Y]}),J}});async function M(W,X){const $=await crypto.subtle.importKey("raw",typeof W==="string"?P.encode(W):W,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",$,P.encode(X))}async function b(W){return crypto.subtle.digest("SHA-256",typeof W==="string"?P.encode(W):W)}var E=function(W){return Array.prototype.map.call(new Uint8Array(W),(X)=>("0"+X.toString(16)).slice(-2)).join("")},u=function(W){return W.replace(/[!'()*]/g,(X)=>"%"+X.charCodeAt(0).toString(16).toUpperCase())},Y0=function(W,X){const{hostname:$,pathname:J}=W;if($.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if($.endsWith(".backblazeb2.com")){const D=$.match(/^(?:[^.]+\.)?s3\.([^.]+)\.backblazeb2\.com$/);return D!=null?["s3",D[1]]:["",""]}const Y=$.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/);let[Z,B]=(Y||["",""]).slice(1,3);if(B==="us-gov")B="us-gov-west-1";else if(B==="s3"||B==="s3-accelerate")B="us-east-1",Z="s3";else if(Z==="iot")if($.startsWith("iot."))Z="execute-api";else if($.startsWith("data.jobs.iot."))Z="iot-jobs-data";else Z=J==="/mqtt"?"iotdevicegateway":"iotdata";else if(Z==="autoscaling"){const D=(X.get("X-Amz-Target")||"").split(".")[0];if(D==="AnyScaleFrontendService")Z="application-autoscaling";else if(D==="AnyScaleScalingPlannerFrontendService")Z="autoscaling-plans"}else if(B==null&&Z.startsWith("s3-"))B=Z.slice(3).replace(/^fips-|^external-1/,""),Z="s3";else if(Z.endsWith("-fips"))Z=Z.slice(0,-5);else if(B&&/-\d$/.test(Z)&&!/-\d$/.test(B))[Z,B]=[B,Z];return[$0[Z]||Z,B]},P=new TextEncoder,$0={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},J0=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]);class V{constructor({accessKeyId:W,secretAccessKey:X,sessionToken:$,service:J,region:Y,cache:Z,retries:B,initRetryMs:D}){if(W==null)throw new TypeError("accessKeyId is a required option");if(X==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=W,this.secretAccessKey=X,this.sessionToken=$,this.service=J,this.region=Y,this.cache=Z||new Map,this.retries=B!=null?B:10,this.initRetryMs=D||50}async sign(W,X){if(W instanceof Request){const{method:Y,url:Z,headers:B,body:D}=W;if(X=Object.assign({method:Y,url:Z,headers:B},X),X.body==null&&B.has("Content-Type"))X.body=D!=null&&B.has("X-Amz-Content-Sha256")?D:await W.clone().arrayBuffer();W=Z}const $=new h(Object.assign({url:W},X,this,X&&X.aws)),J=Object.assign({},X,await $.sign());delete J.aws;try{return new Request(J.url.toString(),J)}catch(Y){if(Y instanceof TypeError)return new Request(J.url.toString(),Object.assign({duplex:"half"},J));throw Y}}async fetch(W,X){for(let $=0;$<=this.retries;$++){const J=fetch(await this.sign(W,X));if($===this.retries)return J;const Y=await J;if(Y.status<500&&Y.status!==429)return Y;await new Promise((Z)=>setTimeout(Z,Math.random()*this.initRetryMs*Math.pow(2,$)))}throw new Error("An unknown error occurred, ensure retries is not negative")}}class h{constructor({method:W,url:X,headers:$,body:J,accessKeyId:Y,secretAccessKey:Z,sessionToken:B,service:D,region:Q,cache:F,datetime:j,signQuery:r,appendSessionToken:e,allHeaders:W0,singleEncode:X0}){if(X==null)throw new TypeError("url is a required option");if(Y==null)throw new TypeError("accessKeyId is a required option");if(Z==null)throw new TypeError("secretAccessKey is a required option");this.method=W||(J?"POST":"GET"),this.url=new URL(X),this.headers=new Headers($||{}),this.body=J,this.accessKeyId=Y,this.secretAccessKey=Z,this.sessionToken=B;let K,S;if(!D||!Q)[K,S]=Y0(this.url,this.headers);if(this.service=D||K||"",this.region=Q||S||"us-east-1",this.cache=F||new Map,this.datetime=j||(new Date()).toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=r,this.appendSessionToken=e||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256"))this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");const q=this.signQuery?this.url.searchParams:this.headers;if(q.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken)q.set("X-Amz-Security-Token",this.sessionToken);if(this.signableHeaders=["host",...this.headers.keys()].filter((G)=>W0||!J0.has(G)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map((G)=>G+":"+(G==="host"?this.url.host:(this.headers.get(G)||"").replace(/\s+/g," "))).join("\n"),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery){if(this.service==="s3"&&!q.has("X-Amz-Expires"))q.set("X-Amz-Expires","86400");q.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),q.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),q.set("X-Amz-SignedHeaders",this.signedHeaders)}if(this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch(G){this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");if(!X0)this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/");this.encodedPath=u(this.encodedPath);const I=new Set;this.encodedSearch=[...this.url.searchParams].filter(([G])=>{if(!G)return!1;if(this.service==="s3"){if(I.has(G))return!1;I.add(G)}return!0}).map((G)=>G.map((_)=>u(encodeURIComponent(_)))).sort(([G,_],[R,v])=>G<R?-1:G>R?1:_<v?-1:_>v?1:0).map((G)=>G.join("=")).join("&")}async sign(){if(this.signQuery){if(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken)this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)}else this.headers.set("Authorization",await this.authHeader());return{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){const W=this.datetime.slice(0,8),X=[this.secretAccessKey,W,this.region,this.service].join();let $=this.cache.get(X);if(!$){const J=await M("AWS4"+this.secretAccessKey,W),Y=await M(J,this.region),Z=await M(Y,this.service);$=await M(Z,"aws4_request"),this.cache.set(X,$)}return E(await M($,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,E(await b(await this.canonicalString()))].join("\n")}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+"\n",this.signedHeaders,await this.hexBodyHash()].join("\n")}async hexBodyHash(){let W=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(W==null){if(this.body&&typeof this.body!=="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");W=E(await b(this.body||""))}return W}}var k=(W,X)=>{const $=X.parseFromString(W,"text/xml"),J=$.getElementsByTagName("ListBucketResult")[0],Y=$.getElementsByTagName("Contents"),Z=$.getElementsByTagName("CommonPrefixes")[0];if(J===null||Y===null)throw new Error("Invalid XML");return{$metadata:{},IsTruncated:J.getElementsByTagName("IsTruncated")[0]?.textContent==="true",Contents:Array.from(Y).map((B)=>({ChecksumAlgorithm:[B.getElementsByTagName("ChecksumAlgorithm")[0]?.textContent],ETag:B.getElementsByTagName("ETag")[0]?.textContent,Key:B.getElementsByTagName("Key")[0]?.textContent,LastModified:new Date(B.getElementsByTagName("LastModified")[0]?.textContent),Owner:{DisplayName:B.getElementsByTagName("DisplayName")[0]?.textContent,ID:B.getElementsByTagName("ID")[0]?.textContent},Size:Number.parseInt(B.getElementsByTagName("Size")[0]?.textContent),StorageClass:B.getElementsByTagName("StorageClass")[0]?.textContent})),Name:$.getElementsByTagName("Name")[0]?.textContent,Prefix:$.getElementsByTagName("Prefix")[0]?.textContent,Delimiter:$.getElementsByTagName("Delimiter")[0]?.textContent,MaxKeys:Number.parseInt($.getElementsByTagName("MaxKeys")[0]?.textContent),CommonPrefixes:Array.from(Z?Z.getElementsByTagName("Prefix"):[],(B)=>({Prefix:B?.textContent})),EncodingType:$.getElementsByTagName("EncodingType")[0]?.textContent,KeyCount:Number.parseInt($.getElementsByTagName("KeyCount")[0]?.textContent),ContinuationToken:$.getElementsByTagName("ContinuationToken")[0]?.textContent,NextContinuationToken:$.getElementsByTagName("NextContinuationToken")[0]?.textContent,StartAfter:$.getElementsByTagName("StartAfter")[0]?.textContent}};class w{client;endpoint;parser;constructor(W,X,$){this.client=W,this.endpoint=X,this.parser=$}async listObjectV2(W){const X=`${this.endpoint}/${W.Bucket}/?list-type=2&prefix=${W.Prefix}`,J=await(await this.client(X,{})).text();return k(J,this.parser)}async putObject(W){const X=`${this.endpoint}/${W.Bucket}/${W.Key}`,$=await this.client(X,{method:"PUT",body:W.Body,headers:{"Content-Type":"application/json",...W.ChecksumSHA256&&{"x-amz-content-sha256":W.ChecksumSHA256}}});if($.status!=200)throw new Error(`Failed to PUT: ${await $.text()}`);return{$metadata:{httpStatusCode:$.status},ETag:$.headers.get("ETag"),...$.headers.get("x-amz-version-id")&&{VersionId:$.headers.get("x-amz-version-id")}}}async deleteObject(W){const X=`${this.endpoint}/${W.Bucket}/${W.Key}`;return{$metadata:{httpStatusCode:(await this.client(X,{method:"DELETE"})).status}}}async getObject(W){const X=`${this.endpoint}/${W.Bucket}/${W.Key}?${W.VersionId?`versionId=${W.VersionId}`:""}`,$=await this.client(X,{method:"GET",headers:{"If-None-Match":W.IfNoneMatch}});if($.status==304){const Y=new Error;throw Y.name="304",Y}let J;if($.status==404)J=void 0;else if($.status==403)throw new Error("Access denied");else if($.headers.get("content-type")==="application/json")J=await $.json();else{const Y=await $.text();if(Y==="")J=void 0;else try{J=JSON.parse(Y)}catch(Z){throw new Error(`Failed to parse response as JSON ${X}`)}}return{$metadata:{httpStatusCode:$.status},Body:J,ETag:$.headers.get("ETag"),...$.headers.get("x-amz-version-id")&&{VersionId:$.headers.get("x-amz-version-id")}}}}class C{key;_vals;_keys;constructor(W,X){if(this.key=W,this._vals=new Map,this._keys=new Map,X)for(let[$,J]of X)this.set($,J)}get size(){return this._vals.size}set(W,X){const $=this.key(W);return this._vals.set($,X),this._keys.set($,W),this}get(W){return this._vals.get(this.key(W))}delete(W){const X=this.key(W);return this._keys.delete(X),this._vals.delete(X)}has(W){return this._vals.has(this.key(W))}values(){return this._vals.values()}keys(){return this._keys.values()}forEach(W){return this._vals.forEach((X,$,J)=>W(X,this._keys.get($)))}}var m=()=>`${Date.now()-200}`.padStart(14,"0"),y=()=>`${Date.now()+200}`.padStart(14,"0");var H=()=>crypto.randomUUID();var N=(W)=>`${W.bucket}/${W.key}`;var L=p(),F0=i(),N0=s();var O={previous:".",files:{},update:{}};class t{ref;handler;lastVersion;queue=Promise.resolve();constructor(W,X){this.ref=W,this.handler=X}notify(W,X,$){this.queue=this.queue.then(()=>$).then((J)=>{if(X===this.lastVersion)return;else console.log(`${W} NOTIFY ${N(this.ref)} ${X}`),this.lastVersion=X,this.handler(J)})}}class T{service;ref;subscribers=new Set;poller;cache;pollInProgress=!1;authoritative_key="";authoritative_state=JSON.parse(JSON.stringify(O));optimistic_state=JSON.parse(JSON.stringify(O));pendingWrites=new Map;writtenOperations=new Map;constructor(W,X,$){console.log("New manifest",X),this.service=W,this.ref=X}observeVersionId(W){if(this.writtenOperations.has(W)){const X=this.writtenOperations.get(W);this.pendingWrites.delete(X),this.writtenOperations.delete(W)}}async get(){return this.getLatest().then((W)=>W||this.cache?.data)}async getLatest(){try{const W=await this.service._getObject({operation:"POLL_TIME",ref:this.ref,ifNoneMatch:this.cache?.etag});if(W.$metadata.httpStatusCode===304)return;if(W.data===void 0)this.authoritative_key=".";else this.authoritative_key=W.data;const X=await this.service.s3ClientLite.listObjectV2({Bucket:this.ref.bucket,Prefix:this.ref.key,StartAfter:this.authoritative_key});if(X.Contents===void 0)return this.authoritative_state=JSON.parse(JSON.stringify(O)),this.optimistic_state=JSON.parse(JSON.stringify(O)),this.authoritative_state;const $=`${this.ref.key}@${m()}`;for(let J=X.Contents.length-1;J>=0;J--){const Y=X.Contents[J].Key;if(Y==this.ref.key)continue;const Z={bucket:this.ref.bucket,key:Y},B=await this.service._getObject({operation:"LOOK_BACK",ref:Z});if(B.data===void 0){await this.service._deleteObject({operation:"CLEANUP",ref:Z});continue}if(B.data.previous<$){this.authoritative_key=B.data.previous,this.authoritative_state=B.data;break}}for(let J=0;J<X.Contents.length;J++){const Y=X.Contents[J].Key;if(Y==this.ref.key)continue;if(Y<this.authoritative_key)continue;const Z=await this.service._getObject({operation:"SWEEP",ref:{bucket:this.ref.bucket,key:Y}}),B=Y.substring(Y.lastIndexOf("@")+1);if(B>=$)console.log("Optimistic update"),this.optimistic_state=L(this.optimistic_state,Z.data?.update);else this.authoritative_state=L(this.authoritative_state,Z.data?.update),this.optimistic_state=L(this.optimistic_state,Z.data?.update),this.authoritative_key=Y;this.observeVersionId(B)}return this.authoritative_state}catch(W){if(W.name==="NoSuchKey")return this.authoritative_state=O,this.authoritative_state;else throw W}}async poll(){if(this.pollInProgress)return;if(this.pollInProgress=!0,this.subscriberCount===0&&this.poller)clearInterval(this.poller),this.poller=void 0;if(this.subscriberCount>0&&!this.poller)this.poller=setInterval(()=>this.poll(),this.service.config.pollFrequency);const W=await this.getLatest();if(W===void 0){this.pollInProgress=!1;return}this.subscribers.forEach(async(X)=>{const $=W.files[N(X.ref)];if($){const J=this.service._getObject({operation:"GET_CONTENT",ref:X.ref,version:$.version});X.notify(this.service.config.label,$.version,J.then((Y)=>Y.data))}else if($===null)X.notify(this.service.config.label,void 0,Promise.resolve(void 0))}),this.pollInProgress=!1}async updateContent(W,X){this.pendingWrites.set(X,W);try{const $=await X,J=await this.get();J.previous=this.authoritative_key,J.update={files:{}};for(let[D,Q]of $){const F=N(D);if(Q){const j={version:Q};J.update.files[F]=j}else J.update.files[F]=null}const Y=y()+"_"+H().substring(0,2),Z=this.ref.key+"@"+Y;await this.service._putObject({operation:"PUT_MANIFEST",ref:{key:Z,bucket:this.ref.bucket},value:J});const B=await this.service._putObject({operation:"PUT_POLL",ref:{key:this.ref.key,bucket:this.ref.bucket},value:this.authoritative_key});return this.writtenOperations.set(Y,X),this.poll(),B}catch($){throw console.error($),this.pendingWrites.delete(X),$}}async getOptimisticVersion(W){return await this.get(),this.optimistic_state.files[N(W)]?.version}subscribe(W,X){console.log(`SUBSCRIBE ${N(W)} ${this.subscriberCount+1}`);const $=new t(W,X);return this.subscribers.add($),()=>this.subscribers.delete($)}get subscriberCount(){return this.subscribers.size}}async function a(W){const X=(new TextEncoder()).encode(W),$=await crypto.subtle.digest("SHA-256",X);return[...new Uint8Array($)].map((J)=>J.toString(16).padStart(2,"0")).join("")}class j0{config;s3ClientLite;manifests=new C(N);getCache=new C((W)=>`${W.Bucket}${W.Key}${W.VersionId}${W.IfNoneMatch}`);constructor(W){if(this.config={...W,label:W.label||H().substring(0,3),useChecksum:W.useChecksum===!1?!1:!0,useVersioning:W.useVersioning||!1,pollFrequency:W.pollFrequency||1000,defaultManifest:{bucket:W.defaultManifest?.bucket||W.defaultBucket,key:typeof W.defaultManifest=="string"?W.defaultManifest:W.defaultManifest?.key||"manifest.json"}},this.config.s3Config?.credentials instanceof Function)throw Error("We can't do that yet");const X=W.s3Config.endpoint||`https://s3.${W.s3Config.region}.amazonaws.com`;let $;if(this.config.s3Config?.credentials){const J=new V({accessKeyId:this.config.s3Config.credentials.accessKeyId,secretAccessKey:this.config.s3Config.credentials.secretAccessKey,sessionToken:this.config.s3Config.credentials.sessionToken,service:"s3",retries:0});$=(...Y)=>J.fetch(...Y)}else $=(global||window).fetch.bind(global||window);this.s3ClientLite=new w($,X,W.parser||new DOMParser)}getOrCreateManifest(W){if(!this.manifests.has(W))this.manifests.set(W,new T(this,W));return this.manifests.get(W)}async get(W,X={}){const $={...this.config.defaultManifest,...X.manifest},J=this.getOrCreateManifest($),Y={bucket:W.bucket||this.config.defaultBucket||this.config.defaultManifest.bucket,key:typeof W==="string"?W:W.key};let Z=!1,B=void 0;for(let[Q,F]of J.pendingWrites)if(F.has(Y))Z=!0,B=F.get(Y);if(Z)return console.log(`${this.config.label} get (cached) ${N(Y)}`),B;const D=await J.getOptimisticVersion(Y);if(D===void 0)return;return(await this._getObject({operation:"GET",ref:Y,version:D})).data}async _getObject(W){let X;if(this.config.useVersioning)X={Bucket:W.ref.bucket,Key:W.ref.key,IfNoneMatch:W.ifNoneMatch,...W.version&&{VersionId:W.version}};else X={Bucket:W.ref.bucket,Key:`${W.ref.key}${W.version?`@${W.version}`:""}`,IfNoneMatch:W.ifNoneMatch};if(this.getCache.has(X))return await this.getCache.get(X);const $=this.s3ClientLite.getObject(X).then(async(J)=>{const Y={...J,data:J.Body};return console.log(`${this.config.label} ${W.operation} ${W.ref.bucket}/${W.ref.key}@${W.version} => ${Y.VersionId} ${Y.data}`),this.getCache.set(X,$),Y}).catch((J)=>{if(J?.name==="304")return{$metadata:{httpStatusCode:304},data:void 0};else throw J});return $}async delete(W,X={}){return this.putAll(new Map([[W,void 0]]),X)}async put(W,X,$={}){return this.putAll(new Map([[W,X]]),$)}async putAll(W,X={}){const $=new C(N,[...W].map(([Y,Z])=>[{bucket:Y.bucket||this.config.defaultBucket||this.config.defaultManifest.bucket,key:typeof Y==="string"?Y:Y.key},Z])),J=(X?.manifests||[this.config.defaultManifest]).map((Y)=>({...this.config.defaultManifest,...Y}));return this._putAll($,{manifests:J})}async _putAll(W,X){const $=new Promise(async(J,Y)=>{const Z=new Map,B=[];W.forEach((D,Q)=>{if(D!==void 0){let F=this.config.useVersioning?void 0:H();B.push(this._putObject({operation:"PUT_CONTENT",ref:Q,value:D,version:F}).then((j)=>{if(this.config.useVersioning)if(j.VersionId===void 0)throw console.error(j),Error(`Bucket ${Q.bucket} is not version enabled!`);else F=j.VersionId;Z.set(Q,F)}))}else B.push(this._deleteObject({ref:Q}).then((F)=>{Z.set(Q,void 0)}))}),await Promise.all(B).catch(Y),J(Z)});return Promise.all(X.manifests.map((J)=>{return this.getOrCreateManifest(J).updateContent(W,$)}))}async _putObject(W){const X=JSON.stringify(W.value,null,2);let $;if(this.config.useVersioning)$={Bucket:W.ref.bucket,Key:W.ref.key,ContentType:"application/json",Body:X,...this.config.useChecksum&&{ChecksumSHA256:await a(X)}};else $={Bucket:W.ref.bucket,Key:`${W.ref.key}${W.version?`@${W.version}`:""}`,ContentType:"application/json",Body:X,...this.config.useChecksum&&{ChecksumSHA256:await a(X)}};const J=await this.s3ClientLite.putObject($);return console.log(`${this.config.label} ${W.operation} ${$.Bucket}/${$.Key} => ${J.VersionId}`),J}async _deleteObject(W){const X={Bucket:W.ref.bucket,Key:W.ref.key},$=await this.s3ClientLite.deleteObject(X);return console.log(`${this.config.label} ${W.operation||"DELETE"} ${W.ref.bucket}/${W.ref.key} => ${$.VersionId}`),$}subscribe(W,X,$){const J={...this.config.defaultManifest,...$?.manifest},Y={key:typeof W==="string"?W:W.key,bucket:W.bucket||this.config.defaultBucket||J.bucket},Z=this.getOrCreateManifest(J),B=Z.subscribe(Y,X);return this.get(Y,{manifest:J}).then((D)=>{console.log(`${this.config.label} NOTIFY (initial) ${N(Y)}`),queueMicrotask(()=>{X(D),Z.poll()})}),B}refresh(){return Promise.all([...this.manifests.values()].map((W)=>W.poll()))}get subscriberCount(){return[...this.manifests.values()].reduce((W,X)=>W+X.subscriberCount,0)}}export{j0 as MPS3};
{
"name": "mps3",
"description": "Provide clientside multiplayer and optimistic updates over any s3-compatible storage API",
"version": "0.0.63",
"version": "0.0.64",
"license": "MIT",

@@ -6,0 +6,0 @@ "author": {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc