amoosedweb-cli 0.21.0 → 0.22.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/README.md +1 -1
- package/amw.mjs +2 -0
- package/package.json +8 -5
- package/reader.mjs +1 -2
- package/amw.cjs +0 -424
- package/runtime/amoosed.com/boot.css +0 -1
- package/runtime/amoosed.com/boot.html +0 -1
- package/runtime/amoosed.com/boot.js +0 -59
- package/runtime/amoosed.com/download.js +0 -1
- package/runtime/amoosed.com/sw.js +0 -1
package/amw.cjs
DELETED
|
@@ -1,424 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
var Vl=Object.create;var Ko=Object.defineProperty;var Jl=Object.getOwnPropertyDescriptor;var Xl=Object.getOwnPropertyNames;var Ql=Object.getPrototypeOf,Zl=Object.prototype.hasOwnProperty;var k=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ec=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Xl(e))!Zl.call(t,o)&&o!==r&&Ko(t,o,{get:()=>e[o],enumerable:!(n=Jl(e,o))||n.enumerable});return t};var En=(t,e,r)=>(r=t!=null?Vl(Ql(t)):{},ec(e||!t||!t.__esModule?Ko(r,"default",{value:t,enumerable:!0}):r,t));var Sn=k((Rh,wi)=>{"use strict";var hc=require("util"),gi=require("stream"),_e=wi.exports=function(){gi.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};hc.inherits(_e,gi);_e.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))};_e.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let r;return Buffer.isBuffer(t)?r=t:r=Buffer.from(t,e||this._encoding),this._buffers.push(r),this._buffered+=r.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};_e.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))};_e.prototype.destroySoon=_e.prototype.end;_e.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};_e.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};_e.prototype._processReadAllowingLess=function(t){this._reads.shift();let e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))};_e.prototype._processRead=function(t){this._reads.shift();let e=0,r=0,n=Buffer.alloc(t.length);for(;e<t.length;){let o=this._buffers[r++],i=Math.min(o.length,t.length-e);o.copy(n,e,0,i),e+=i,i!==o.length&&(this._buffers[--r]=o.slice(i))}r>0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,n)};_e.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var Tn=k(Bn=>{"use strict";var Ve=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];Bn.getImagePasses=function(t,e){let r=[],n=t%8,o=e%8,i=(t-n)/8,a=(e-o)/8;for(let s=0;s<Ve.length;s++){let l=Ve[s],c=i*l.x.length,f=a*l.y.length;for(let u=0;u<l.x.length&&l.x[u]<n;u++)c++;for(let u=0;u<l.y.length&&l.y[u]<o;u++)f++;c>0&&f>0&&r.push({width:c,height:f,index:s})}return r};Bn.getInterlaceIterator=function(t){return function(e,r,n){let o=e%Ve[n].x.length,i=(e-o)/Ve[n].x.length*8+Ve[n].x[o],a=r%Ve[n].y.length,s=(r-a)/Ve[n].y.length*8+Ve[n].y[a];return i*4+s*t*4}}});var Mn=k((Nh,yi)=>{"use strict";yi.exports=function(e,r,n){let o=e+r-n,i=Math.abs(o-e),a=Math.abs(o-r),s=Math.abs(o-n);return i<=a&&i<=s?e:a<=s?r:n}});var Ln=k((Uh,Ei)=>{"use strict";var dc=Tn(),pc=Mn();function bi(t,e,r){let n=t*e;return r!==8&&(n=Math.ceil(n/(8/r))),n}var _t=Ei.exports=function(t,e){let r=t.width,n=t.height,o=t.interlace,i=t.bpp,a=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],o){let s=dc.getImagePasses(r,n);for(let l=0;l<s.length;l++)this._images.push({byteWidth:bi(s[l].width,i,a),height:s[l].height,lineIndex:0})}else this._images.push({byteWidth:bi(r,i,a),height:n,lineIndex:0});a===8?this._xComparison=i:a===16?this._xComparison=i*2:this._xComparison=1};_t.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};_t.prototype._unFilterType1=function(t,e,r){let n=this._xComparison,o=n-1;for(let i=0;i<r;i++){let a=t[1+i],s=i>o?e[i-n]:0;e[i]=a+s}};_t.prototype._unFilterType2=function(t,e,r){let n=this._lastLine;for(let o=0;o<r;o++){let i=t[1+o],a=n?n[o]:0;e[o]=i+a}};_t.prototype._unFilterType3=function(t,e,r){let n=this._xComparison,o=n-1,i=this._lastLine;for(let a=0;a<r;a++){let s=t[1+a],l=i?i[a]:0,c=a>o?e[a-n]:0,f=Math.floor((c+l)/2);e[a]=s+f}};_t.prototype._unFilterType4=function(t,e,r){let n=this._xComparison,o=n-1,i=this._lastLine;for(let a=0;a<r;a++){let s=t[1+a],l=i?i[a]:0,c=a>o?e[a-n]:0,f=a>o&&i?i[a-n]:0,u=pc(c,l,f);e[a]=s+u}};_t.prototype._reverseFilterLine=function(t){let e=t[0],r,n=this._images[this._imageIndex],o=n.byteWidth;if(e===0)r=t.slice(1,o+1);else switch(r=Buffer.alloc(o),e){case 1:this._unFilterType1(t,r,o);break;case 2:this._unFilterType2(t,r,o);break;case 3:this._unFilterType3(t,r,o);break;case 4:this._unFilterType4(t,r,o);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(r),n.lineIndex++,n.lineIndex>=n.height?(this._lastLine=null,this._imageIndex++,n=this._images[this._imageIndex]):this._lastLine=r,n?this.read(n.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var ki=k(($h,Ai)=>{"use strict";var mc=require("util"),xi=Sn(),gc=Ln(),wc=Ai.exports=function(t){xi.call(this);let e=[],r=this;this._filter=new gc(t,{read:this.read.bind(this),write:function(n){e.push(n)},complete:function(){r.emit("complete",Buffer.concat(e))}}),this._filter.start()};mc.inherits(wc,xi)});var Ct=k((jh,vi)=>{"use strict";vi.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var On=k((Dh,Ii)=>{"use strict";var Pn=[];(function(){for(let t=0;t<256;t++){let e=t;for(let r=0;r<8;r++)e&1?e=3988292384^e>>>1:e=e>>>1;Pn[t]=e}})();var Rn=Ii.exports=function(){this._crc=-1};Rn.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Pn[(this._crc^t[e])&255]^this._crc>>>8;return!0};Rn.prototype.crc32=function(){return this._crc^-1};Rn.crc32=function(t){let e=-1;for(let r=0;r<t.length;r++)e=Pn[(e^t[r])&255]^e>>>8;return e^-1}});var Nn=k((Fh,_i)=>{"use strict";var J=Ct(),yc=On(),ee=_i.exports=function(t,e){this._options=t,t.checkCRC=t.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[J.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[J.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[J.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[J.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[J.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[J.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};ee.prototype.start=function(){this.read(J.PNG_SIGNATURE.length,this._parseSignature.bind(this))};ee.prototype._parseSignature=function(t){let e=J.PNG_SIGNATURE;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};ee.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n="";for(let i=4;i<8;i++)n+=String.fromCharCode(t[i]);let o=!!(t[4]&32);if(!this._hasIHDR&&r!==J.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new yc,this._crc.write(Buffer.from(n)),this._chunks[r])return this._chunks[r](e);if(!o){this.error(new Error("Unsupported critical chunk type "+n));return}this.read(e+4,this._skipChunk.bind(this))};ee.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};ee.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};ee.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),r=this._crc.crc32();if(this._options.checkCRC&&r!==e){this.error(new Error("Crc error - "+e+" - "+r));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};ee.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};ee.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),r=t.readUInt32BE(4),n=t[8],o=t[9],i=t[10],a=t[11],s=t[12];if(n!==8&&n!==4&&n!==2&&n!==1&&n!==16){this.error(new Error("Unsupported bit depth "+n));return}if(!(o in J.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(i!==0){this.error(new Error("Unsupported compression method"));return}if(a!==0){this.error(new Error("Unsupported filter method"));return}if(s!==0&&s!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=o;let l=J.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:n,interlace:!!s,palette:!!(o&J.COLORTYPE_PALETTE),color:!!(o&J.COLORTYPE_COLOR),alpha:!!(o&J.COLORTYPE_ALPHA),bpp:l,colorType:o}),this._handleChunkEnd()};ee.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};ee.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let r=0;r<e;r++)this._palette.push([t[r*3],t[r*3+1],t[r*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};ee.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};ee.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===J.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(t.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===J.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===J.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};ee.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};ee.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/J.GAMMA_DIVISION),this._handleChunkEnd()};ee.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};ee.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===J.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let r=t-e.length;r>0?this._handleIDAT(r):this._handleChunkEnd()};ee.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};ee.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Un=k(Si=>{"use strict";var Ci=Tn(),bc=[function(){},function(t,e,r,n){if(n===e.length)throw new Error("Ran out of data");let o=e[n];t[r]=o,t[r+1]=o,t[r+2]=o,t[r+3]=255},function(t,e,r,n){if(n+1>=e.length)throw new Error("Ran out of data");let o=e[n];t[r]=o,t[r+1]=o,t[r+2]=o,t[r+3]=e[n+1]},function(t,e,r,n){if(n+2>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=255},function(t,e,r,n){if(n+3>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=e[n+3]}],Ec=[function(){},function(t,e,r,n){let o=e[0];t[r]=o,t[r+1]=o,t[r+2]=o,t[r+3]=n},function(t,e,r){let n=e[0];t[r]=n,t[r+1]=n,t[r+2]=n,t[r+3]=e[1]},function(t,e,r,n){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=n},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function xc(t,e){let r=[],n=0;function o(){if(n===t.length)throw new Error("Ran out of data");let i=t[n];n++;let a,s,l,c,f,u,h,p;switch(e){default:throw new Error("unrecognised depth");case 16:h=t[n],n++,r.push((i<<8)+h);break;case 4:h=i&15,p=i>>4,r.push(p,h);break;case 2:f=i&3,u=i>>2&3,h=i>>4&3,p=i>>6&3,r.push(p,h,u,f);break;case 1:a=i&1,s=i>>1&1,l=i>>2&1,c=i>>3&1,f=i>>4&1,u=i>>5&1,h=i>>6&1,p=i>>7&1,r.push(p,h,u,f,c,l,s,a);break}}return{get:function(i){for(;r.length<i;)o();let a=r.slice(0,i);return r=r.slice(i),a},resetAfterLine:function(){r.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function Ac(t,e,r,n,o,i){let a=t.width,s=t.height,l=t.index;for(let c=0;c<s;c++)for(let f=0;f<a;f++){let u=r(f,c,l);bc[n](e,o,u,i),i+=n}return i}function kc(t,e,r,n,o,i){let a=t.width,s=t.height,l=t.index;for(let c=0;c<s;c++){for(let f=0;f<a;f++){let u=o.get(n),h=r(f,c,l);Ec[n](e,u,h,i)}o.resetAfterLine()}}Si.dataToBitMap=function(t,e){let r=e.width,n=e.height,o=e.depth,i=e.bpp,a=e.interlace,s;o!==8&&(s=xc(t,o));let l;o<=8?l=Buffer.alloc(r*n*4):l=new Uint16Array(r*n*4);let c=Math.pow(2,o)-1,f=0,u,h;if(a)u=Ci.getImagePasses(r,n),h=Ci.getInterlaceIterator(r,n);else{let p=0;h=function(){let d=p;return p+=4,d},u=[{width:r,height:n}]}for(let p=0;p<u.length;p++)o===8?f=Ac(u[p],l,h,i,t,f):kc(u[p],l,h,i,s,c);if(o===8){if(f!==t.length)throw new Error("extra data found")}else s.end();return l}});var $n=k((Wh,Bi)=>{"use strict";function vc(t,e,r,n,o){let i=0;for(let a=0;a<n;a++)for(let s=0;s<r;s++){let l=o[t[i]];if(!l)throw new Error("index "+t[i]+" not in palette");for(let c=0;c<4;c++)e[i+c]=l[c];i+=4}}function Ic(t,e,r,n,o){let i=0;for(let a=0;a<n;a++)for(let s=0;s<r;s++){let l=!1;if(o.length===1?o[0]===t[i]&&(l=!0):o[0]===t[i]&&o[1]===t[i+1]&&o[2]===t[i+2]&&(l=!0),l)for(let c=0;c<4;c++)e[i+c]=0;i+=4}}function _c(t,e,r,n,o){let i=255,a=Math.pow(2,o)-1,s=0;for(let l=0;l<n;l++)for(let c=0;c<r;c++){for(let f=0;f<4;f++)e[s+f]=Math.floor(t[s+f]*i/a+.5);s+=4}}Bi.exports=function(t,e){let r=e.depth,n=e.width,o=e.height,i=e.colorType,a=e.transColor,s=e.palette,l=t;return i===3?vc(t,l,n,o,s):(a&&Ic(t,l,n,o,a),r!==8&&(r===16&&(l=Buffer.alloc(n*o*4)),_c(t,l,n,o,r))),l}});var Li=k((qh,Mi)=>{"use strict";var Cc=require("util"),jn=require("zlib"),Ti=Sn(),Sc=ki(),Bc=Nn(),Tc=Un(),Mc=$n(),Te=Mi.exports=function(t){Ti.call(this),this._parser=new Bc(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};Cc.inherits(Te,Ti);Te.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",function(){})),this.errord=!0};Te.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=jn.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let r=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,n=Math.max(r,jn.Z_MIN_CHUNK);this._inflate=jn.createInflate({chunkSize:n});let o=r,i=this.emit.bind(this,"error");this._inflate.on("error",function(s){o&&i(s)}),this._filter.on("complete",this._complete.bind(this));let a=this._filter.write.bind(this._filter);this._inflate.on("data",function(s){o&&(s.length>o&&(s=s.slice(0,o)),o-=s.length,a(s))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};Te.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new Sc(this._bitmapInfo)};Te.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Te.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Te.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Te.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Te.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Te.prototype._complete=function(t){if(this.errord)return;let e;try{let r=Tc.dataToBitMap(t,this._bitmapInfo);e=Mc(r,this._bitmapInfo),r=null}catch(r){this._handleError(r);return}this.emit("parsed",e)}});var Ri=k((Gh,Pi)=>{"use strict";var xe=Ct();Pi.exports=function(t,e,r,n){let o=[xe.COLORTYPE_COLOR_ALPHA,xe.COLORTYPE_ALPHA].indexOf(n.colorType)!==-1;if(n.colorType===n.inputColorType){let d=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(n.bitDepth===8||n.bitDepth===16&&d)return t}let i=n.bitDepth!==16?t:new Uint16Array(t.buffer),a=255,s=xe.COLORTYPE_TO_BPP_MAP[n.inputColorType];s===4&&!n.inputHasAlpha&&(s=3);let l=xe.COLORTYPE_TO_BPP_MAP[n.colorType];n.bitDepth===16&&(a=65535,l*=2);let c=Buffer.alloc(e*r*l),f=0,u=0,h=n.bgColor||{};h.red===void 0&&(h.red=a),h.green===void 0&&(h.green=a),h.blue===void 0&&(h.blue=a);function p(){let d,g,m,E=a;switch(n.inputColorType){case xe.COLORTYPE_COLOR_ALPHA:E=i[f+3],d=i[f],g=i[f+1],m=i[f+2];break;case xe.COLORTYPE_COLOR:d=i[f],g=i[f+1],m=i[f+2];break;case xe.COLORTYPE_ALPHA:E=i[f+1],d=i[f],g=d,m=d;break;case xe.COLORTYPE_GRAYSCALE:d=i[f],g=d,m=d;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(o||(E/=a,d=Math.min(Math.max(Math.round((1-E)*h.red+E*d),0),a),g=Math.min(Math.max(Math.round((1-E)*h.green+E*g),0),a),m=Math.min(Math.max(Math.round((1-E)*h.blue+E*m),0),a))),{red:d,green:g,blue:m,alpha:E}}for(let d=0;d<r;d++)for(let g=0;g<e;g++){let m=p(i,f);switch(n.colorType){case xe.COLORTYPE_COLOR_ALPHA:case xe.COLORTYPE_COLOR:n.bitDepth===8?(c[u]=m.red,c[u+1]=m.green,c[u+2]=m.blue,o&&(c[u+3]=m.alpha)):(c.writeUInt16BE(m.red,u),c.writeUInt16BE(m.green,u+2),c.writeUInt16BE(m.blue,u+4),o&&c.writeUInt16BE(m.alpha,u+6));break;case xe.COLORTYPE_ALPHA:case xe.COLORTYPE_GRAYSCALE:{let E=(m.red+m.green+m.blue)/3;n.bitDepth===8?(c[u]=E,o&&(c[u+1]=m.alpha)):(c.writeUInt16BE(E,u),o&&c.writeUInt16BE(m.alpha,u+2));break}default:throw new Error("unrecognised color Type "+n.colorType)}f+=s,u+=l}return c}});var Ui=k((zh,Ni)=>{"use strict";var Oi=Mn();function Lc(t,e,r,n,o){for(let i=0;i<r;i++)n[o+i]=t[e+i]}function Pc(t,e,r){let n=0,o=e+r;for(let i=e;i<o;i++)n+=Math.abs(t[i]);return n}function Rc(t,e,r,n,o,i){for(let a=0;a<r;a++){let s=a>=i?t[e+a-i]:0,l=t[e+a]-s;n[o+a]=l}}function Oc(t,e,r,n){let o=0;for(let i=0;i<r;i++){let a=i>=n?t[e+i-n]:0,s=t[e+i]-a;o+=Math.abs(s)}return o}function Nc(t,e,r,n,o){for(let i=0;i<r;i++){let a=e>0?t[e+i-r]:0,s=t[e+i]-a;n[o+i]=s}}function Uc(t,e,r){let n=0,o=e+r;for(let i=e;i<o;i++){let a=e>0?t[i-r]:0,s=t[i]-a;n+=Math.abs(s)}return n}function $c(t,e,r,n,o,i){for(let a=0;a<r;a++){let s=a>=i?t[e+a-i]:0,l=e>0?t[e+a-r]:0,c=t[e+a]-(s+l>>1);n[o+a]=c}}function jc(t,e,r,n){let o=0;for(let i=0;i<r;i++){let a=i>=n?t[e+i-n]:0,s=e>0?t[e+i-r]:0,l=t[e+i]-(a+s>>1);o+=Math.abs(l)}return o}function Dc(t,e,r,n,o,i){for(let a=0;a<r;a++){let s=a>=i?t[e+a-i]:0,l=e>0?t[e+a-r]:0,c=e>0&&a>=i?t[e+a-(r+i)]:0,f=t[e+a]-Oi(s,l,c);n[o+a]=f}}function Fc(t,e,r,n){let o=0;for(let i=0;i<r;i++){let a=i>=n?t[e+i-n]:0,s=e>0?t[e+i-r]:0,l=e>0&&i>=n?t[e+i-(r+n)]:0,c=t[e+i]-Oi(a,s,l);o+=Math.abs(c)}return o}var Hc={0:Lc,1:Rc,2:Nc,3:$c,4:Dc},Wc={0:Pc,1:Oc,2:Uc,3:jc,4:Fc};Ni.exports=function(t,e,r,n,o){let i;if(!("filterType"in n)||n.filterType===-1)i=[0,1,2,3,4];else if(typeof n.filterType=="number")i=[n.filterType];else throw new Error("unrecognised filter types");n.bitDepth===16&&(o*=2);let a=e*o,s=0,l=0,c=Buffer.alloc((a+1)*r),f=i[0];for(let u=0;u<r;u++){if(i.length>1){let h=1/0;for(let p=0;p<i.length;p++){let d=Wc[i[p]](t,l,a,o);d<h&&(f=i[p],h=d)}}c[s]=f,s++,Hc[f](t,l,a,c,s,o),s+=a,l+=a}return c}});var Dn=k((Yh,$i)=>{"use strict";var ie=Ct(),qc=On(),Gc=Ri(),zc=Ui(),Yc=require("zlib"),Je=$i.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32*1024,t.deflateLevel=t.deflateLevel!=null?t.deflateLevel:9,t.deflateStrategy=t.deflateStrategy!=null?t.deflateStrategy:3,t.inputHasAlpha=t.inputHasAlpha!=null?t.inputHasAlpha:!0,t.deflateFactory=t.deflateFactory||Yc.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:ie.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:ie.COLORTYPE_COLOR_ALPHA,[ie.COLORTYPE_GRAYSCALE,ie.COLORTYPE_COLOR,ie.COLORTYPE_COLOR_ALPHA,ie.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([ie.COLORTYPE_GRAYSCALE,ie.COLORTYPE_COLOR,ie.COLORTYPE_COLOR_ALPHA,ie.COLORTYPE_ALPHA].indexOf(t.inputColorType)===-1)throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(t.bitDepth!==8&&t.bitDepth!==16)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};Je.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Je.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Je.prototype.filterData=function(t,e,r){let n=Gc(t,e,r,this._options),o=ie.COLORTYPE_TO_BPP_MAP[this._options.colorType];return zc(n,e,r,this._options,o)};Je.prototype._packChunk=function(t,e){let r=e?e.length:0,n=Buffer.alloc(r+12);return n.writeUInt32BE(r,0),n.writeUInt32BE(t,4),e&&e.copy(n,8),n.writeInt32BE(qc.crc32(n.slice(4,n.length-4)),n.length-4),n};Je.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*ie.GAMMA_DIVISION),0),this._packChunk(ie.TYPE_gAMA,e)};Je.prototype.packIHDR=function(t,e){let r=Buffer.alloc(13);return r.writeUInt32BE(t,0),r.writeUInt32BE(e,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(ie.TYPE_IHDR,r)};Je.prototype.packIDAT=function(t){return this._packChunk(ie.TYPE_IDAT,t)};Je.prototype.packIEND=function(){return this._packChunk(ie.TYPE_IEND,null)}});var Hi=k((Kh,Fi)=>{"use strict";var Kc=require("util"),ji=require("stream"),Vc=Ct(),Jc=Dn(),Di=Fi.exports=function(t){ji.call(this);let e=t||{};this._packer=new Jc(e),this._deflate=this._packer.createDeflate(),this.readable=!0};Kc.inherits(Di,ji);Di.prototype.pack=function(t,e,r,n){this.emit("data",Buffer.from(Vc.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,r)),n&&this.emit("data",this._packer.packGAMA(n));let o=this._packer.filterData(t,e,r);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(i){this.emit("data",this._packer.packIDAT(i))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(o)}});var Ki=k((er,Yi)=>{"use strict";var Wi=require("assert").ok,St=require("zlib"),Xc=require("util"),qi=require("buffer").kMaxLength;function ht(t){if(!(this instanceof ht))return new ht(t);t&&t.chunkSize<St.Z_MIN_CHUNK&&(t.chunkSize=St.Z_MIN_CHUNK),St.Inflate.call(this,t),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&t.maxLength!=null&&(this._maxLength=t.maxLength)}function Qc(t){return new ht(t)}function Gi(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}ht.prototype._processChunk=function(t,e,r){if(typeof r=="function")return St.Inflate._processChunk.call(this,t,e,r);let n=this,o=t&&t.length,i=this._chunkSize-this._offset,a=this._maxLength,s=0,l=[],c=0,f;this.on("error",function(d){f=d});function u(d,g){if(n._hadError)return;let m=i-g;if(Wi(m>=0,"have should not go down"),m>0){let E=n._buffer.slice(n._offset,n._offset+m);if(n._offset+=m,E.length>a&&(E=E.slice(0,a)),l.push(E),c+=E.length,a-=E.length,a===0)return!1}return(g===0||n._offset>=n._chunkSize)&&(i=n._chunkSize,n._offset=0,n._buffer=Buffer.allocUnsafe(n._chunkSize)),g===0?(s+=o-d,o=d,!0):!1}Wi(this._handle,"zlib binding closed");let h;do h=this._handle.writeSync(e,t,s,o,this._buffer,this._offset,i),h=h||this._writeState;while(!this._hadError&&u(h[0],h[1]));if(this._hadError)throw f;if(c>=qi)throw Gi(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+qi.toString(16)+" bytes");let p=Buffer.concat(l,c);return Gi(this),p};Xc.inherits(ht,St.Inflate);function Zc(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let r=t._finishFlushFlag;return r==null&&(r=St.Z_FINISH),t._processChunk(e,r)}function zi(t,e){return Zc(new ht(e),t)}Yi.exports=er=zi;er.Inflate=ht;er.createInflate=Qc;er.inflateSync=zi});var Fn=k((Vh,Ji)=>{"use strict";var Vi=Ji.exports=function(t){this._buffer=t,this._reads=[]};Vi.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Vi.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let t=this._reads[0];if(this._buffer.length&&(this._buffer.length>=t.length||t.allowLess)){this._reads.shift();let e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}else break}if(this._reads.length>0)return new Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)return new Error("unrecognised content at end of stream")}});var Qi=k(Xi=>{"use strict";var ef=Fn(),tf=Ln();Xi.process=function(t,e){let r=[],n=new ef(t);return new tf(e,{read:n.read.bind(n),write:function(i){r.push(i)},complete:function(){}}).start(),n.process(),Buffer.concat(r)}});var ra=k((Xh,ta)=>{"use strict";var Zi=!0,ea=require("zlib"),rf=Ki();ea.deflateSync||(Zi=!1);var nf=Fn(),of=Qi(),af=Nn(),sf=Un(),lf=$n();ta.exports=function(t,e){if(!Zi)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r;function n(S){r=S}let o;function i(S){o=S}function a(S){o.transColor=S}function s(S){o.palette=S}function l(){o.alpha=!0}let c;function f(S){c=S}let u=[];function h(S){u.push(S)}let p=new nf(t);if(new af(e,{read:p.read.bind(p),error:n,metadata:i,gamma:f,palette:s,transColor:a,inflateData:h,simpleTransparency:l}).start(),p.process(),r)throw r;let g=Buffer.concat(u);u.length=0;let m;if(o.interlace)m=ea.inflateSync(g);else{let v=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;m=rf(g,{chunkSize:v,maxLength:v})}if(g=null,!m||!m.length)throw new Error("bad png - invalid inflate data response");let E=of.process(m,o);g=null;let _=sf.dataToBitMap(E,o);E=null;let P=lf(_,o);return o.data=P,o.gamma=c||0,o}});var aa=k((Qh,ia)=>{"use strict";var na=!0,oa=require("zlib");oa.deflateSync||(na=!1);var cf=Ct(),ff=Dn();ia.exports=function(t,e){if(!na)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let r=e||{},n=new ff(r),o=[];o.push(Buffer.from(cf.PNG_SIGNATURE)),o.push(n.packIHDR(t.width,t.height)),t.gamma&&o.push(n.packGAMA(t.gamma));let i=n.filterData(t.data,t.width,t.height),a=oa.deflateSync(i,n.getDeflateOptions());if(i=null,!a||!a.length)throw new Error("bad png - invalid compressed data response");return o.push(n.packIDAT(a)),o.push(n.packIEND()),Buffer.concat(o)}});var sa=k(Hn=>{"use strict";var uf=ra(),hf=aa();Hn.read=function(t,e){return uf(t,e||{})};Hn.write=function(t,e){return hf(t,e)}});var Fr=k(ca=>{"use strict";var df=require("util"),la=require("stream"),pf=Li(),mf=Hi(),gf=sa(),ue=ca.PNG=function(t){la.call(this),t=t||{},this.width=t.width|0,this.height=t.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new pf(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(e){this.data=e,this.emit("parsed",e)}.bind(this)),this._packer=new mf(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};df.inherits(ue,la);ue.sync=gf;ue.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};ue.prototype.parse=function(t,e){if(e){let r,n;r=function(o){this.removeListener("error",n),this.data=o,e(null,this)}.bind(this),n=function(o){this.removeListener("parsed",r),e(o,null)}.bind(this),this.once("parsed",r),this.once("error",n)}return this.end(t),this};ue.prototype.write=function(t){return this._parser.write(t),!0};ue.prototype.end=function(t){this._parser.end(t)};ue.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};ue.prototype._gamma=function(t){this.gamma=t};ue.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};ue.bitblt=function(t,e,r,n,o,i,a,s){if(r|=0,n|=0,o|=0,i|=0,a|=0,s|=0,r>t.width||n>t.height||r+o>t.width||n+i>t.height)throw new Error("bitblt reading outside image");if(a>e.width||s>e.height||a+o>e.width||s+i>e.height)throw new Error("bitblt writing outside image");for(let l=0;l<i;l++)t.data.copy(e.data,(s+l)*e.width+a<<2,(n+l)*t.width+r<<2,(n+l)*t.width+r+o<<2)};ue.prototype.bitblt=function(t,e,r,n,o,i,a){return ue.bitblt(this,t,e,r,n,o,i,a),this};ue.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let r=0;r<t.width;r++){let n=t.width*e+r<<2;for(let o=0;o<3;o++){let i=t.data[n+o]/255;i=Math.pow(i,1/2.2/t.gamma),t.data[n+o]=Math.round(i*255)}}t.gamma=0}};ue.prototype.adjustGamma=function(){ue.adjustGamma(this)}});var yo=k((up,Ts)=>{Ts.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var tt=k(yt=>{var bo,su=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];yt.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};yt.getSymbolTotalCodewords=function(e){return su[e]};yt.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};yt.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');bo=e};yt.isKanjiModeEnabled=function(){return typeof bo<"u"};yt.toSJIS=function(e){return bo(e)}});var an=k(ke=>{ke.L={bit:1};ke.M={bit:0};ke.Q={bit:3};ke.H={bit:2};function lu(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ke.L;case"m":case"medium":return ke.M;case"q":case"quartile":return ke.Q;case"h":case"high":return ke.H;default:throw new Error("Unknown EC Level: "+t)}}ke.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ke.from=function(e,r){if(ke.isValid(e))return e;try{return lu(e)}catch{return r}}});var Ps=k((pp,Ls)=>{function Ms(){this.buffer=[],this.length=0}Ms.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};Ls.exports=Ms});var Os=k((mp,Rs)=>{function yr(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}yr.prototype.set=function(t,e,r,n){let o=t*this.size+e;this.data[o]=r,n&&(this.reservedBit[o]=!0)};yr.prototype.get=function(t,e){return this.data[t*this.size+e]};yr.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r};yr.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};Rs.exports=yr});var Ns=k(sn=>{var cu=tt().getSymbolSize;sn.getRowColCoords=function(e){if(e===1)return[];let r=Math.floor(e/7)+2,n=cu(e),o=n===145?26:Math.ceil((n-13)/(2*r-2))*2,i=[n-7];for(let a=1;a<r-1;a++)i[a]=i[a-1]-o;return i.push(6),i.reverse()};sn.getPositions=function(e){let r=[],n=sn.getRowColCoords(e),o=n.length;for(let i=0;i<o;i++)for(let a=0;a<o;a++)i===0&&a===0||i===0&&a===o-1||i===o-1&&a===0||r.push([n[i],n[a]]);return r}});var js=k($s=>{var fu=tt().getSymbolSize,Us=7;$s.getPositions=function(e){let r=fu(e);return[[0,0],[r-Us,0],[0,r-Us]]}});var Ds=k(F=>{F.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var bt={N1:3,N2:3,N3:40,N4:10};F.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};F.from=function(e){return F.isValid(e)?parseInt(e,10):void 0};F.getPenaltyN1=function(e){let r=e.size,n=0,o=0,i=0,a=null,s=null;for(let l=0;l<r;l++){o=i=0,a=s=null;for(let c=0;c<r;c++){let f=e.get(l,c);f===a?o++:(o>=5&&(n+=bt.N1+(o-5)),a=f,o=1),f=e.get(c,l),f===s?i++:(i>=5&&(n+=bt.N1+(i-5)),s=f,i=1)}o>=5&&(n+=bt.N1+(o-5)),i>=5&&(n+=bt.N1+(i-5))}return n};F.getPenaltyN2=function(e){let r=e.size,n=0;for(let o=0;o<r-1;o++)for(let i=0;i<r-1;i++){let a=e.get(o,i)+e.get(o,i+1)+e.get(o+1,i)+e.get(o+1,i+1);(a===4||a===0)&&n++}return n*bt.N2};F.getPenaltyN3=function(e){let r=e.size,n=0,o=0,i=0;for(let a=0;a<r;a++){o=i=0;for(let s=0;s<r;s++)o=o<<1&2047|e.get(a,s),s>=10&&(o===1488||o===93)&&n++,i=i<<1&2047|e.get(s,a),s>=10&&(i===1488||i===93)&&n++}return n*bt.N3};F.getPenaltyN4=function(e){let r=0,n=e.data.length;for(let i=0;i<n;i++)r+=e.data[i];return Math.abs(Math.ceil(r*100/n/5)-10)*bt.N4};function uu(t,e,r){switch(t){case F.Patterns.PATTERN000:return(e+r)%2===0;case F.Patterns.PATTERN001:return e%2===0;case F.Patterns.PATTERN010:return r%3===0;case F.Patterns.PATTERN011:return(e+r)%3===0;case F.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2===0;case F.Patterns.PATTERN101:return e*r%2+e*r%3===0;case F.Patterns.PATTERN110:return(e*r%2+e*r%3)%2===0;case F.Patterns.PATTERN111:return(e*r%3+(e+r)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}F.applyMask=function(e,r){let n=r.size;for(let o=0;o<n;o++)for(let i=0;i<n;i++)r.isReserved(i,o)||r.xor(i,o,uu(e,i,o))};F.getBestMask=function(e,r){let n=Object.keys(F.Patterns).length,o=0,i=1/0;for(let a=0;a<n;a++){r(a),F.applyMask(a,e);let s=F.getPenaltyN1(e)+F.getPenaltyN2(e)+F.getPenaltyN3(e)+F.getPenaltyN4(e);F.applyMask(a,e),s<i&&(i=s,o=a)}return o}});var xo=k(Eo=>{var rt=an(),ln=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],cn=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];Eo.getBlocksCount=function(e,r){switch(r){case rt.L:return ln[(e-1)*4+0];case rt.M:return ln[(e-1)*4+1];case rt.Q:return ln[(e-1)*4+2];case rt.H:return ln[(e-1)*4+3];default:return}};Eo.getTotalCodewordsCount=function(e,r){switch(r){case rt.L:return cn[(e-1)*4+0];case rt.M:return cn[(e-1)*4+1];case rt.Q:return cn[(e-1)*4+2];case rt.H:return cn[(e-1)*4+3];default:return}}});var Fs=k(un=>{var br=new Uint8Array(512),fn=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)br[r]=e,fn[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)br[r]=br[r-255]})();un.log=function(e){if(e<1)throw new Error("log("+e+")");return fn[e]};un.exp=function(e){return br[e]};un.mul=function(e,r){return e===0||r===0?0:br[fn[e]+fn[r]]}});var Hs=k(Er=>{var Ao=Fs();Er.mul=function(e,r){let n=new Uint8Array(e.length+r.length-1);for(let o=0;o<e.length;o++)for(let i=0;i<r.length;i++)n[o+i]^=Ao.mul(e[o],r[i]);return n};Er.mod=function(e,r){let n=new Uint8Array(e);for(;n.length-r.length>=0;){let o=n[0];for(let a=0;a<r.length;a++)n[a]^=Ao.mul(r[a],o);let i=0;for(;i<n.length&&n[i]===0;)i++;n=n.slice(i)}return n};Er.generateECPolynomial=function(e){let r=new Uint8Array([1]);for(let n=0;n<e;n++)r=Er.mul(r,new Uint8Array([1,Ao.exp(n)]));return r}});var Gs=k((Ap,qs)=>{var Ws=Hs();function ko(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}ko.prototype.initialize=function(e){this.degree=e,this.genPoly=Ws.generateECPolynomial(this.degree)};ko.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let r=new Uint8Array(e.length+this.degree);r.set(e);let n=Ws.mod(r,this.genPoly),o=this.degree-n.length;if(o>0){let i=new Uint8Array(this.degree);return i.set(n,o),i}return n};qs.exports=ko});var vo=k(zs=>{zs.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Io=k(He=>{var Ys="[0-9]+",hu="[A-Z $%*+\\-./:]+",xr="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";xr=xr.replace(/u/g,"\\u");var du="(?:(?![A-Z0-9 $%*+\\-./:]|"+xr+`)(?:.|[\r
|
|
3
|
-
]))+`;He.KANJI=new RegExp(xr,"g");He.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");He.BYTE=new RegExp(du,"g");He.NUMERIC=new RegExp(Ys,"g");He.ALPHANUMERIC=new RegExp(hu,"g");var pu=new RegExp("^"+xr+"$"),mu=new RegExp("^"+Ys+"$"),gu=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");He.testKanji=function(e){return pu.test(e)};He.testNumeric=function(e){return mu.test(e)};He.testAlphanumeric=function(e){return gu.test(e)}});var nt=k(V=>{var wu=vo(),_o=Io();V.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};V.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};V.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};V.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};V.MIXED={bit:-1};V.getCharCountIndicator=function(e,r){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!wu.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?e.ccBits[0]:r<27?e.ccBits[1]:e.ccBits[2]};V.getBestModeForData=function(e){return _o.testNumeric(e)?V.NUMERIC:_o.testAlphanumeric(e)?V.ALPHANUMERIC:_o.testKanji(e)?V.KANJI:V.BYTE};V.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};V.isValid=function(e){return e&&e.bit&&e.ccBits};function yu(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return V.NUMERIC;case"alphanumeric":return V.ALPHANUMERIC;case"kanji":return V.KANJI;case"byte":return V.BYTE;default:throw new Error("Unknown mode: "+t)}}V.from=function(e,r){if(V.isValid(e))return e;try{return yu(e)}catch{return r}}});var Qs=k(Et=>{var hn=tt(),bu=xo(),Ks=an(),ot=nt(),Co=vo(),Js=7973,Vs=hn.getBCHDigit(Js);function Eu(t,e,r){for(let n=1;n<=40;n++)if(e<=Et.getCapacity(n,r,t))return n}function Xs(t,e){return ot.getCharCountIndicator(t,e)+4}function xu(t,e){let r=0;return t.forEach(function(n){let o=Xs(n.mode,e);r+=o+n.getBitsLength()}),r}function Au(t,e){for(let r=1;r<=40;r++)if(xu(t,r)<=Et.getCapacity(r,e,ot.MIXED))return r}Et.from=function(e,r){return Co.isValid(e)?parseInt(e,10):r};Et.getCapacity=function(e,r,n){if(!Co.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=ot.BYTE);let o=hn.getSymbolTotalCodewords(e),i=bu.getTotalCodewordsCount(e,r),a=(o-i)*8;if(n===ot.MIXED)return a;let s=a-Xs(n,e);switch(n){case ot.NUMERIC:return Math.floor(s/10*3);case ot.ALPHANUMERIC:return Math.floor(s/11*2);case ot.KANJI:return Math.floor(s/13);case ot.BYTE:default:return Math.floor(s/8)}};Et.getBestVersionForData=function(e,r){let n,o=Ks.from(r,Ks.M);if(Array.isArray(e)){if(e.length>1)return Au(e,o);if(e.length===0)return 1;n=e[0]}else n=e;return Eu(n.mode,n.getLength(),o)};Et.getEncodedBits=function(e){if(!Co.isValid(e)||e<7)throw new Error("Invalid QR Code version");let r=e<<12;for(;hn.getBCHDigit(r)-Vs>=0;)r^=Js<<hn.getBCHDigit(r)-Vs;return e<<12|r}});var rl=k(tl=>{var So=tt(),el=1335,ku=21522,Zs=So.getBCHDigit(el);tl.getEncodedBits=function(e,r){let n=e.bit<<3|r,o=n<<10;for(;So.getBCHDigit(o)-Zs>=0;)o^=el<<So.getBCHDigit(o)-Zs;return(n<<10|o)^ku}});var ol=k((Sp,nl)=>{var vu=nt();function Ht(t){this.mode=vu.NUMERIC,this.data=t.toString()}Ht.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Ht.prototype.getLength=function(){return this.data.length};Ht.prototype.getBitsLength=function(){return Ht.getBitsLength(this.data.length)};Ht.prototype.write=function(e){let r,n,o;for(r=0;r+3<=this.data.length;r+=3)n=this.data.substr(r,3),o=parseInt(n,10),e.put(o,10);let i=this.data.length-r;i>0&&(n=this.data.substr(r),o=parseInt(n,10),e.put(o,i*3+1))};nl.exports=Ht});var al=k((Bp,il)=>{var Iu=nt(),Bo=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Wt(t){this.mode=Iu.ALPHANUMERIC,this.data=t}Wt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Wt.prototype.getLength=function(){return this.data.length};Wt.prototype.getBitsLength=function(){return Wt.getBitsLength(this.data.length)};Wt.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let n=Bo.indexOf(this.data[r])*45;n+=Bo.indexOf(this.data[r+1]),e.put(n,11)}this.data.length%2&&e.put(Bo.indexOf(this.data[r]),6)};il.exports=Wt});var ll=k((Tp,sl)=>{var _u=nt();function qt(t){this.mode=_u.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}qt.getBitsLength=function(e){return e*8};qt.prototype.getLength=function(){return this.data.length};qt.prototype.getBitsLength=function(){return qt.getBitsLength(this.data.length)};qt.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};sl.exports=qt});var fl=k((Mp,cl)=>{var Cu=nt(),Su=tt();function Gt(t){this.mode=Cu.KANJI,this.data=t}Gt.getBitsLength=function(e){return e*13};Gt.prototype.getLength=function(){return this.data.length};Gt.prototype.getBitsLength=function(){return Gt.getBitsLength(this.data.length)};Gt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=Su.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
|
|
4
|
-
Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};cl.exports=Gt});var ul=k((Lp,To)=>{"use strict";var Ar={single_source_shortest_paths:function(t,e,r){var n={},o={};o[e]=0;var i=Ar.PriorityQueue.make();i.push(e,0);for(var a,s,l,c,f,u,h,p,d;!i.empty();){a=i.pop(),s=a.value,c=a.cost,f=t[s]||{};for(l in f)f.hasOwnProperty(l)&&(u=f[l],h=c+u,p=o[l],d=typeof o[l]>"u",(d||p>h)&&(o[l]=h,i.push(l,h),n[l]=s))}if(typeof r<"u"&&typeof o[r]>"u"){var g=["Could not find a path from ",e," to ",r,"."].join("");throw new Error(g)}return n},extract_shortest_path_from_predecessor_list:function(t,e){for(var r=[],n=e,o;n;)r.push(n),o=t[n],n=t[n];return r.reverse(),r},find_path:function(t,e,r){var n=Ar.single_source_shortest_paths(t,e,r);return Ar.extract_shortest_path_from_predecessor_list(n,r)},PriorityQueue:{make:function(t){var e=Ar.PriorityQueue,r={},n;t=t||{};for(n in e)e.hasOwnProperty(n)&&(r[n]=e[n]);return r.queue=[],r.sorter=t.sorter||e.default_sorter,r},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var r={value:t,cost:e};this.queue.push(r),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof To<"u"&&(To.exports=Ar)});var bl=k(zt=>{var N=nt(),pl=ol(),ml=al(),gl=ll(),wl=fl(),kr=Io(),dn=tt(),Bu=ul();function hl(t){return unescape(encodeURIComponent(t)).length}function vr(t,e,r){let n=[],o;for(;(o=t.exec(r))!==null;)n.push({data:o[0],index:o.index,mode:e,length:o[0].length});return n}function yl(t){let e=vr(kr.NUMERIC,N.NUMERIC,t),r=vr(kr.ALPHANUMERIC,N.ALPHANUMERIC,t),n,o;return dn.isKanjiModeEnabled()?(n=vr(kr.BYTE,N.BYTE,t),o=vr(kr.KANJI,N.KANJI,t)):(n=vr(kr.BYTE_KANJI,N.BYTE,t),o=[]),e.concat(r,n,o).sort(function(a,s){return a.index-s.index}).map(function(a){return{data:a.data,mode:a.mode,length:a.length}})}function Mo(t,e){switch(e){case N.NUMERIC:return pl.getBitsLength(t);case N.ALPHANUMERIC:return ml.getBitsLength(t);case N.KANJI:return wl.getBitsLength(t);case N.BYTE:return gl.getBitsLength(t)}}function Tu(t){return t.reduce(function(e,r){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===r.mode?(e[e.length-1].data+=r.data,e):(e.push(r),e)},[])}function Mu(t){let e=[];for(let r=0;r<t.length;r++){let n=t[r];switch(n.mode){case N.NUMERIC:e.push([n,{data:n.data,mode:N.ALPHANUMERIC,length:n.length},{data:n.data,mode:N.BYTE,length:n.length}]);break;case N.ALPHANUMERIC:e.push([n,{data:n.data,mode:N.BYTE,length:n.length}]);break;case N.KANJI:e.push([n,{data:n.data,mode:N.BYTE,length:hl(n.data)}]);break;case N.BYTE:e.push([{data:n.data,mode:N.BYTE,length:hl(n.data)}])}}return e}function Lu(t,e){let r={},n={start:{}},o=["start"];for(let i=0;i<t.length;i++){let a=t[i],s=[];for(let l=0;l<a.length;l++){let c=a[l],f=""+i+l;s.push(f),r[f]={node:c,lastCount:0},n[f]={};for(let u=0;u<o.length;u++){let h=o[u];r[h]&&r[h].node.mode===c.mode?(n[h][f]=Mo(r[h].lastCount+c.length,c.mode)-Mo(r[h].lastCount,c.mode),r[h].lastCount+=c.length):(r[h]&&(r[h].lastCount=c.length),n[h][f]=Mo(c.length,c.mode)+4+N.getCharCountIndicator(c.mode,e))}}o=s}for(let i=0;i<o.length;i++)n[o[i]].end=0;return{map:n,table:r}}function dl(t,e){let r,n=N.getBestModeForData(t);if(r=N.from(e,n),r!==N.BYTE&&r.bit<n.bit)throw new Error('"'+t+'" cannot be encoded with mode '+N.toString(r)+`.
|
|
5
|
-
Suggested mode is: `+N.toString(n));switch(r===N.KANJI&&!dn.isKanjiModeEnabled()&&(r=N.BYTE),r){case N.NUMERIC:return new pl(t);case N.ALPHANUMERIC:return new ml(t);case N.KANJI:return new wl(t);case N.BYTE:return new gl(t)}}zt.fromArray=function(e){return e.reduce(function(r,n){return typeof n=="string"?r.push(dl(n,null)):n.data&&r.push(dl(n.data,n.mode)),r},[])};zt.fromString=function(e,r){let n=yl(e,dn.isKanjiModeEnabled()),o=Mu(n),i=Lu(o,r),a=Bu.find_path(i.map,"start","end"),s=[];for(let l=1;l<a.length-1;l++)s.push(i.table[a[l]].node);return zt.fromArray(Tu(s))};zt.rawSplit=function(e){return zt.fromArray(yl(e,dn.isKanjiModeEnabled()))}});var Uo=k(El=>{var mn=tt(),Lo=an(),Pu=Ps(),Ru=Os(),Ou=Ns(),Nu=js(),Oo=Ds(),No=xo(),Uu=Gs(),pn=Qs(),$u=rl(),ju=nt(),Po=bl();function Du(t,e){let r=t.size,n=Nu.getPositions(e);for(let o=0;o<n.length;o++){let i=n[o][0],a=n[o][1];for(let s=-1;s<=7;s++)if(!(i+s<=-1||r<=i+s))for(let l=-1;l<=7;l++)a+l<=-1||r<=a+l||(s>=0&&s<=6&&(l===0||l===6)||l>=0&&l<=6&&(s===0||s===6)||s>=2&&s<=4&&l>=2&&l<=4?t.set(i+s,a+l,!0,!0):t.set(i+s,a+l,!1,!0))}}function Fu(t){let e=t.size;for(let r=8;r<e-8;r++){let n=r%2===0;t.set(r,6,n,!0),t.set(6,r,n,!0)}}function Hu(t,e){let r=Ou.getPositions(e);for(let n=0;n<r.length;n++){let o=r[n][0],i=r[n][1];for(let a=-2;a<=2;a++)for(let s=-2;s<=2;s++)a===-2||a===2||s===-2||s===2||a===0&&s===0?t.set(o+a,i+s,!0,!0):t.set(o+a,i+s,!1,!0)}}function Wu(t,e){let r=t.size,n=pn.getEncodedBits(e),o,i,a;for(let s=0;s<18;s++)o=Math.floor(s/3),i=s%3+r-8-3,a=(n>>s&1)===1,t.set(o,i,a,!0),t.set(i,o,a,!0)}function Ro(t,e,r){let n=t.size,o=$u.getEncodedBits(e,r),i,a;for(i=0;i<15;i++)a=(o>>i&1)===1,i<6?t.set(i,8,a,!0):i<8?t.set(i+1,8,a,!0):t.set(n-15+i,8,a,!0),i<8?t.set(8,n-i-1,a,!0):i<9?t.set(8,15-i-1+1,a,!0):t.set(8,15-i-1,a,!0);t.set(n-8,8,1,!0)}function qu(t,e){let r=t.size,n=-1,o=r-1,i=7,a=0;for(let s=r-1;s>0;s-=2)for(s===6&&s--;;){for(let l=0;l<2;l++)if(!t.isReserved(o,s-l)){let c=!1;a<e.length&&(c=(e[a]>>>i&1)===1),t.set(o,s-l,c),i--,i===-1&&(a++,i=7)}if(o+=n,o<0||r<=o){o-=n,n=-n;break}}}function Gu(t,e,r){let n=new Pu;r.forEach(function(l){n.put(l.mode.bit,4),n.put(l.getLength(),ju.getCharCountIndicator(l.mode,t)),l.write(n)});let o=mn.getSymbolTotalCodewords(t),i=No.getTotalCodewordsCount(t,e),a=(o-i)*8;for(n.getLengthInBits()+4<=a&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let s=(a-n.getLengthInBits())/8;for(let l=0;l<s;l++)n.put(l%2?17:236,8);return zu(n,t,e)}function zu(t,e,r){let n=mn.getSymbolTotalCodewords(e),o=No.getTotalCodewordsCount(e,r),i=n-o,a=No.getBlocksCount(e,r),s=n%a,l=a-s,c=Math.floor(n/a),f=Math.floor(i/a),u=f+1,h=c-f,p=new Uu(h),d=0,g=new Array(a),m=new Array(a),E=0,_=new Uint8Array(t.buffer);for(let $=0;$<a;$++){let j=$<l?f:u;g[$]=_.slice(d,d+j),m[$]=p.encode(g[$]),d+=j,E=Math.max(E,j)}let P=new Uint8Array(n),S=0,v,R;for(v=0;v<E;v++)for(R=0;R<a;R++)v<g[R].length&&(P[S++]=g[R][v]);for(v=0;v<h;v++)for(R=0;R<a;R++)P[S++]=m[R][v];return P}function Yu(t,e,r,n){let o;if(Array.isArray(t))o=Po.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){let f=Po.rawSplit(t);c=pn.getBestVersionForData(f,r)}o=Po.fromString(t,c||40)}else throw new Error("Invalid data");let i=pn.getBestVersionForData(o,r);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
|
|
6
|
-
The chosen QR Code version cannot contain this amount of data.
|
|
7
|
-
Minimum version required to store current data is: `+i+`.
|
|
8
|
-
`);let a=Gu(e,r,o),s=mn.getSymbolSize(e),l=new Ru(s);return Du(l,e),Fu(l),Hu(l,e),Ro(l,r,0),e>=7&&Wu(l,e),qu(l,a),isNaN(n)&&(n=Oo.getBestMask(l,Ro.bind(null,l,r))),Oo.applyMask(n,l),Ro(l,r,n),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:n,segments:o}}El.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let n=Lo.M,o,i;return typeof r<"u"&&(n=Lo.from(r.errorCorrectionLevel,Lo.M),o=pn.from(r.version),i=Oo.from(r.maskPattern),r.toSJISFunc&&mn.setToSJISFunction(r.toSJISFunc)),Yu(e,o,n,i)}});var Ir=k(xt=>{function xl(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let r=parseInt(e.join(""),16);return{r:r>>24&255,g:r>>16&255,b:r>>8&255,a:r&255,hex:"#"+e.slice(0,6).join("")}}xt.getOptions=function(e){e||(e={}),e.color||(e.color={});let r=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,o=e.scale||4;return{width:n,scale:n?4:o,margin:r,color:{dark:xl(e.color.dark||"#000000ff"),light:xl(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};xt.getScale=function(e,r){return r.width&&r.width>=e+r.margin*2?r.width/(e+r.margin*2):r.scale};xt.getImageWidth=function(e,r){let n=xt.getScale(e,r);return Math.floor((e+r.margin*2)*n)};xt.qrToImageData=function(e,r,n){let o=r.modules.size,i=r.modules.data,a=xt.getScale(o,n),s=Math.floor((o+n.margin*2)*a),l=n.margin*a,c=[n.color.light,n.color.dark];for(let f=0;f<s;f++)for(let u=0;u<s;u++){let h=(f*s+u)*4,p=n.color.light;if(f>=l&&u>=l&&f<s-l&&u<s-l){let d=Math.floor((f-l)/a),g=Math.floor((u-l)/a);p=c[i[d*o+g]?1:0]}e[h++]=p.r,e[h++]=p.g,e[h++]=p.b,e[h]=p.a}}});var Al=k(Re=>{var Ku=require("fs"),Vu=Fr().PNG,$o=Ir();Re.render=function(e,r){let n=$o.getOptions(r),o=n.rendererOpts,i=$o.getImageWidth(e.modules.size,n);o.width=i,o.height=i;let a=new Vu(o);return $o.qrToImageData(a.data,e,n),a};Re.renderToDataURL=function(e,r,n){typeof n>"u"&&(n=r,r=void 0),Re.renderToBuffer(e,r,function(o,i){o&&n(o);let a="data:image/png;base64,";a+=i.toString("base64"),n(null,a)})};Re.renderToBuffer=function(e,r,n){typeof n>"u"&&(n=r,r=void 0);let o=Re.render(e,r),i=[];o.on("error",n),o.on("data",function(a){i.push(a)}),o.on("end",function(){n(null,Buffer.concat(i))}),o.pack()};Re.renderToFile=function(e,r,n,o){typeof o>"u"&&(o=n,n=void 0);let i=!1,a=(...l)=>{i||(i=!0,o.apply(null,l))},s=Ku.createWriteStream(e);s.on("error",a),s.on("close",a),Re.renderToFileStream(s,r,n)};Re.renderToFileStream=function(e,r,n){Re.render(r,n).pack().pipe(e)}});var kl=k(gn=>{var Ju=Ir(),Xu={WW:" ",WB:"\u2584",BB:"\u2588",BW:"\u2580"},Qu={BB:" ",BW:"\u2584",WW:"\u2588",WB:"\u2580"};function Zu(t,e,r){return t&&e?r.BB:t&&!e?r.BW:!t&&e?r.WB:r.WW}gn.render=function(t,e,r){let n=Ju.getOptions(e),o=Xu;(n.color.dark.hex==="#ffffff"||n.color.light.hex==="#000000")&&(o=Qu);let i=t.modules.size,a=t.modules.data,s="",l=Array(i+n.margin*2+1).join(o.WW);l=Array(n.margin/2+1).join(l+`
|
|
9
|
-
`);let c=Array(n.margin+1).join(o.WW);s+=l;for(let f=0;f<i;f+=2){s+=c;for(let u=0;u<i;u++){let h=a[f*i+u],p=a[(f+1)*i+u];s+=Zu(h,p,o)}s+=c+`
|
|
10
|
-
`}return s+=l.slice(0,-1),typeof r=="function"&&r(null,s),s};gn.renderToFile=function(e,r,n,o){typeof o>"u"&&(o=n,n=void 0);let i=require("fs"),a=gn.render(r,n);i.writeFile(e,a,o)}});var Il=k(vl=>{vl.render=function(t,e,r){let n=t.modules.size,o=t.modules.data,i="\x1B[40m \x1B[0m",a="\x1B[47m \x1B[0m",s="",l=Array(n+3).join(a),c=Array(2).join(a);s+=l+`
|
|
11
|
-
`;for(let f=0;f<n;++f){s+=a;for(let u=0;u<n;u++)s+=o[f*n+u]?i:a;s+=c+`
|
|
12
|
-
`}return s+=l+`
|
|
13
|
-
`,typeof r=="function"&&r(null,s),s}});var Bl=k(Sl=>{var eh="\x1B[47m",th="\x1B[40m",jo="\x1B[37m",Do="\x1B[30m",At="\x1B[0m",rh=eh+Do,nh=th+jo,oh=function(t,e,r){return{"00":At+" "+t,"01":At+e+"\u2584"+t,"02":At+r+"\u2584"+t,10:At+e+"\u2580"+t,11:" ",12:"\u2584",20:At+r+"\u2580"+t,21:"\u2580",22:"\u2588"}},_l=function(t,e,r,n){let o=e+1;if(r>=o||n>=o||n<-1||r<-1)return"0";if(r>=e||n>=e||n<0||r<0)return"1";let i=n*e+r;return t[i]?"2":"1"},Cl=function(t,e,r,n){return _l(t,e,r,n)+_l(t,e,r,n+1)};Sl.render=function(t,e,r){let n=t.modules.size,o=t.modules.data,i=!!(e&&e.inverse),a=e&&e.inverse?nh:rh,c=oh(a,i?Do:jo,i?jo:Do),f=At+`
|
|
14
|
-
`+a,u=a;for(let h=-1;h<n+1;h+=2){for(let p=-1;p<n;p++)u+=c[Cl(o,n,p,h)];u+=c[Cl(o,n,n,h)]+f}return u+=At,typeof r=="function"&&r(null,u),u}});var Ml=k(Tl=>{var ih=Il(),ah=Bl();Tl.render=function(t,e,r){return e&&e.small?ah.render(t,e,r):ih.render(t,e,r)}});var Ho=k(Pl=>{var sh=Ir();function Ll(t,e){let r=t.a/255,n=e+'="'+t.hex+'"';return r<1?n+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':n}function Fo(t,e,r){let n=t+e;return typeof r<"u"&&(n+=" "+r),n}function lh(t,e,r){let n="",o=0,i=!1,a=0;for(let s=0;s<t.length;s++){let l=Math.floor(s%e),c=Math.floor(s/e);!l&&!i&&(i=!0),t[s]?(a++,s>0&&l>0&&t[s-1]||(n+=i?Fo("M",l+r,.5+c+r):Fo("m",o,0),o=0,i=!1),l+1<e&&t[s+1]||(n+=Fo("h",a),a=0)):o++}return n}Pl.render=function(e,r,n){let o=sh.getOptions(r),i=e.modules.size,a=e.modules.data,s=i+o.margin*2,l=o.color.light.a?"<path "+Ll(o.color.light,"fill")+' d="M0 0h'+s+"v"+s+'H0z"/>':"",c="<path "+Ll(o.color.dark,"stroke")+' d="'+lh(a,i,o.margin)+'"/>',f='viewBox="0 0 '+s+" "+s+'"',h='<svg xmlns="http://www.w3.org/2000/svg" '+(o.width?'width="'+o.width+'" height="'+o.width+'" ':"")+f+' shape-rendering="crispEdges">'+l+c+`</svg>
|
|
15
|
-
`;return typeof n=="function"&&n(null,h),h}});var Rl=k(wn=>{var ch=Ho();wn.render=ch.render;wn.renderToFile=function(e,r,n,o){typeof o>"u"&&(o=n,n=void 0);let i=require("fs"),s='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+wn.render(r,n);i.writeFile(e,s,o)}});var Ol=k(yn=>{var Wo=Ir();function fh(t,e,r){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=r,e.width=r,e.style.height=r+"px",e.style.width=r+"px"}function uh(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}yn.render=function(e,r,n){let o=n,i=r;typeof o>"u"&&(!r||!r.getContext)&&(o=r,r=void 0),r||(i=uh()),o=Wo.getOptions(o);let a=Wo.getImageWidth(e.modules.size,o),s=i.getContext("2d"),l=s.createImageData(a,a);return Wo.qrToImageData(l.data,e,o),fh(s,i,a),s.putImageData(l,0,0),i};yn.renderToDataURL=function(e,r,n){let o=n;typeof o>"u"&&(!r||!r.getContext)&&(o=r,r=void 0),o||(o={});let i=yn.render(e,r,o),a=o.type||"image/png",s=o.rendererOpts||{};return i.toDataURL(a,s.quality)}});var Ul=k(_r=>{var hh=yo(),qo=Uo(),Nl=Ol(),dh=Ho();function Go(t,e,r,n,o){let i=[].slice.call(arguments,1),a=i.length,s=typeof i[a-1]=="function";if(!s&&!hh())throw new Error("Callback required as last argument");if(s){if(a<2)throw new Error("Too few arguments provided");a===2?(o=r,r=e,e=n=void 0):a===3&&(e.getContext&&typeof o>"u"?(o=n,n=void 0):(o=n,n=r,r=e,e=void 0))}else{if(a<1)throw new Error("Too few arguments provided");return a===1?(r=e,e=n=void 0):a===2&&!e.getContext&&(n=r,r=e,e=void 0),new Promise(function(l,c){try{let f=qo.create(r,n);l(t(f,e,n))}catch(f){c(f)}})}try{let l=qo.create(r,n);o(null,t(l,e,n))}catch(l){o(l)}}_r.create=qo.create;_r.toCanvas=Go.bind(null,Nl.render);_r.toDataURL=Go.bind(null,Nl.renderToDataURL);_r.toString=Go.bind(null,function(t,e,r){return dh.render(t,r)})});var Fl=k(it=>{var $l=yo(),zo=Uo(),ph=Al(),jl=kl(),mh=Ml(),Dl=Rl();function Cr(t,e,r){if(typeof t>"u")throw new Error("String required as first argument");if(typeof r>"u"&&(r=e,e={}),typeof r!="function")if($l())e=r||{},r=null;else throw new Error("Callback required as last argument");return{opts:e,cb:r}}function gh(t){return t.slice((t.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function bn(t){switch(t){case"svg":return Dl;case"txt":case"utf8":return jl;case"png":case"image/png":default:return ph}}function wh(t){switch(t){case"svg":return Dl;case"terminal":return mh;case"utf8":default:return jl}}function Sr(t,e,r){if(!r.cb)return new Promise(function(n,o){try{let i=zo.create(e,r.opts);return t(i,r.opts,function(a,s){return a?o(a):n(s)})}catch(i){o(i)}});try{let n=zo.create(e,r.opts);return t(n,r.opts,r.cb)}catch(n){r.cb(n)}}it.create=zo.create;it.toCanvas=Ul().toCanvas;it.toString=function(e,r,n){let o=Cr(e,r,n),i=o.opts?o.opts.type:void 0,a=wh(i);return Sr(a.render,e,o)};it.toDataURL=function(e,r,n){let o=Cr(e,r,n),i=bn(o.opts.type);return Sr(i.renderToDataURL,e,o)};it.toBuffer=function(e,r,n){let o=Cr(e,r,n),i=bn(o.opts.type);return Sr(i.renderToBuffer,e,o)};it.toFile=function(e,r,n,o){if(typeof e!="string"||!(typeof r=="string"||typeof r=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!$l())throw new Error("Too few arguments provided");let i=Cr(r,n,o),a=i.opts.type||gh(e),l=bn(a).renderToFile.bind(null,e);return Sr(l,r,i)};it.toFileStream=function(e,r,n){if(arguments.length<2)throw new Error("Too few arguments provided");let o=Cr(r,n,e.emit.bind(e,"error")),a=bn("png").renderToFileStream.bind(null,e);Sr(a,r,o)}});var Wl=k((zp,Hl)=>{Hl.exports=Fl()});var B=require("node:fs/promises");var Xo=require("node:crypto");var Yt=/^[0-9a-f]{64}$/,tc=/^\/amoosed\.com\/app\/[A-Za-z0-9._/-]+$/,Vo=/^\/(?!\/)[A-Za-z0-9._/-]+$/,rc=/^[a-z0-9.+-]+\/[a-z0-9.+-]+(?:; charset=utf-8)?$/,nc=/^[A-Za-z0-9._-]{1,64}$/;function Vt(t,e,r){return new TextEncoder().encode(`AMW1-SEALED\0${t.path}\0${t.mime}\0${e}\0${r}`)}function Kt(t){return typeof t=="string"&&tc.test(t)&&!t.slice(1).split("/").some(e=>e==="."||e===".."||e==="")&&!t.endsWith("/")}function st(t,e){return!!t.encryption&&e.access!=="public"}function lt(t){if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(a=>!["launch","entry","resources","encryption","encoding","identity","audioCarriers"].includes(a))||t.launch!=="/amoosed.com/boot.html"||!Kt(t.entry)||!Array.isArray(t.resources)||t.resources.length<1||t.resources.length>4096)throw new Error("Invalid web app manifest");let e=t.encryption!==void 0;if(t.encoding!==void 0&&(!t.encoding||typeof t.encoding!="object"||Array.isArray(t.encoding)||Object.keys(t.encoding).some(a=>!["algorithm","key"].includes(a))||t.encoding.algorithm!=="AES-256-CTR"||typeof t.encoding.key!="string"||!Yt.test(t.encoding.key)))throw new Error("Invalid web app encoding");if(t.identity!==void 0&&(!t.identity||typeof t.identity!="object"||Array.isArray(t.identity)||Object.keys(t.identity).some(a=>!["title","icon"].includes(a))||typeof t.identity.title!="string"||!t.identity.title||t.identity.title.length>200||t.identity.icon!=="/amoosed.com/app/favicon.ico"))throw new Error("Invalid app identity");if(e&&(!t.encryption||typeof t.encryption!="object"||Array.isArray(t.encryption)||Object.keys(t.encryption).some(a=>!["algorithm","keyId"].includes(a))||t.encryption.algorithm!=="AES-256-GCM"||typeof t.encryption.keyId!="string"||!nc.test(t.encryption.keyId)))throw new Error("Invalid web app encryption");if(t.audioCarriers!==void 0){if(!t.audioCarriers||typeof t.audioCarriers!="object"||Array.isArray(t.audioCarriers)||Object.keys(t.audioCarriers).length>64)throw new Error("Invalid audio carrier map");for(let[a,s]of Object.entries(t.audioCarriers))if(!Vo.test(a)||!a.endsWith(".wav")||!s||s.format!=="amw.audio-carrier.v1"||!Number.isInteger(s.length)||s.length<1||s.length>4096||!Yt.test(s.sha256)||!Array.isArray(s.packets)||s.packets.length<1||s.packets.length>32||!Array.isArray(s.locations)||s.locations.length!==s.packets.length*3||s.packets.some((l,c)=>l.index!==c||!Number.isInteger(l.length)||l.length<1||l.length>128||!Yt.test(l.sha256))||s.packets.reduce((l,c)=>l+c.length,0)!==s.length||s.locations.some(l=>!Number.isInteger(l.packet)||l.packet<0||l.packet>=s.packets.length||!Number.isFinite(l.startSeconds)||l.startSeconds<0||!Number.isFinite(l.durationSeconds)||l.durationSeconds<=0))throw new Error("Invalid audio carrier map")}let r="",n=0,o=new Set;for(let a of t.resources){if(!a||typeof a!="object"||Array.isArray(a)||Object.keys(a).some(c=>!["path","mime","length","sha256","parts","access","delivery"].includes(c))||!Kt(a.path)||a.path<=r||a.access!==void 0&&(!e||!["public","members"].includes(a.access))||a.delivery!==void 0&&a.delivery!=="download"||typeof a.mime!="string"||!rc.test(a.mime)||!Number.isSafeInteger(a.length)||a.length<1||a.length>1024*1024*1024||typeof a.sha256!="string"||!Yt.test(a.sha256)||!Array.isArray(a.parts)||a.parts.length<1||a.parts.length>16384)throw new Error("Invalid web app resource");r=a.path;let s=st(t,a);s&&n++;let l=0;for(let c of a.parts){if(!c||typeof c!="object"||Array.isArray(c)||Object.keys(c).some(f=>!["url","offset","length","sha256","codec",...s?["nonce","plainLength"]:[]].includes(f))||typeof c.url!="string"||typeof c.sha256!="string"||!Yt.test(c.sha256)||!Vo.test(c.url)||c.url.slice(1).split("/").some(f=>!f||f==="."||f==="..")||c.url==="/favicon.ico"||c.url.startsWith("/amoosed.com/")||c.codec!==void 0&&!(c.codec==="png-lsb1"&&c.url.endsWith(".png")||c.codec==="wav-4fsk1"&&c.url.endsWith(".wav")&&t.audioCarriers?.[c.url]||["frame-luma1","frame-luma2"].includes(c.codec)&&c.url.endsWith(".png")&&c.offset===0&&c.length<=21)||!Number.isSafeInteger(c.offset)||c.offset<0||!Number.isSafeInteger(c.length)||c.length<1||c.length>4*1024*1024+(s?16:0)||s&&(typeof c.nonce!="string"||!/^[0-9a-f]{24}$/.test(c.nonce)||!Number.isSafeInteger(c.plainLength)||c.plainLength<1||c.plainLength>4*1024*1024||c.length!==c.plainLength+16))throw new Error("Invalid web app shard");if(s){if(o.has(c.nonce))throw new Error("Repeated web app nonce");o.add(c.nonce)}l+=s?c.plainLength:c.length}if(l!==a.length)throw new Error("Web app resource length mismatch")}if(e&&n===0)throw new Error("Encrypted app has no member resources");let i=t.resources.find(a=>a.path===t.entry);if(!i||!i.mime.startsWith("text/html"))throw new Error("Web app entry must be HTML");if(i.delivery==="download")throw new Error("Web app entry cannot be a download");if(t.identity){let a=t.resources.find(s=>s.path===t.identity.icon);if(!a||a.mime!=="image/x-icon"||st(t,a)||a.delivery==="download")throw new Error("App identity favicon must be public")}return t}var Ee=4096,ze=128,Qo=1,Zo=2,ei="AMW1DOC\0",ti="AMW1TAIL",Jo=new TextEncoder,Mr=new TextDecoder("utf-8",{fatal:!0}),Y=t=>(0,Xo.createHash)("sha256").update(t).digest(),Pr=t=>Buffer.from(t).toString("hex"),kt=t=>JSON.stringify(t,(e,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).sort(([n],[o])=>n<o?-1:n>o?1:0)):r),We=(t,e)=>Number(t.readBigUInt64LE(e)),qe=(t,e,r)=>t.writeBigUInt64LE(BigInt(e),r),Ge=(t,e)=>{if(!Number.isSafeInteger(t)||t<0)throw new Error(`Invalid ${e}`);return t};function Ye(t){Lr(t);let e=Jo.encode(kt(t.bootstrap??{title:t.title,blocks:t.blocks.slice(0,1)})),r=Jo.encode(kt(t)),n=[{id:"bootstrap",type:"amw.document.v1",bytes:e},{id:"document",type:"amw.document.v1",bytes:r}],o=Buffer.alloc(0),i;for(let l=0;l<20;l++){let c=Ee+o.length;i={format:"amw.sections.v1",sections:n.map(u=>{let h={id:u.id,type:u.type,offset:c,length:u.bytes.length,sha256:Pr(Y(u.bytes))};return c+=u.bytes.length,h})};let f=Buffer.from(kt(i));if(f.length===o.length){o=f;break}if(o=f,l===19)throw new Error("Manifest layout did not converge")}let a=Ee+o.length+n.reduce((l,c)=>l+c.bytes.length,0),s=Buffer.alloc(Ee);return s.write(ei,0,"ascii"),s.writeUInt16LE(Qo,8),s.writeUInt16LE(Ee,10),qe(s,a,16),qe(s,Ee,24),qe(s,o.length,32),qe(s,i.sections[0].offset,40),qe(s,e.length,48),Y(o).copy(s,56),Y(e).copy(s,88),Buffer.concat([s,o,...n.map(l=>l.bytes)])}function ri(t){let e=Buffer.from(t);if(e.length!==Ee||e.toString("ascii",0,8)!==ei)throw new Error("Invalid AMW header");if(e.readUInt16LE(8)!==Qo||e.readUInt16LE(10)!==Ee)throw new Error("Unsupported AMW version");if(e.subarray(12,16).some(Boolean)||e.subarray(120).some(Boolean))throw new Error("Nonzero reserved header bytes");let r={total:Ge(We(e,16),"total"),manifestOffset:Ge(We(e,24),"manifest offset"),manifestLength:Ge(We(e,32),"manifest length"),bootstrapOffset:Ge(We(e,40),"bootstrap offset"),bootstrapLength:Ge(We(e,48),"bootstrap length"),manifestHash:e.subarray(56,88),bootstrapHash:e.subarray(88,120)};if(r.manifestOffset!==Ee||r.manifestLength>1024*1024||r.total>1024*1024*1024)throw new Error("Invalid AMW bounds");return r}function me(t){let e=Buffer.from(t),r=ri(e.subarray(0,Ee));if(e.length!==r.total)throw new Error("AMW length mismatch");let n=e.subarray(r.manifestOffset,r.manifestOffset+r.manifestLength);if(n.length!==r.manifestLength||!Y(n).equals(r.manifestHash))throw new Error("Manifest integrity failure");let o=JSON.parse(Mr.decode(n));if(kt(o)!==Mr.decode(n)||o.format!=="amw.sections.v1"||!Array.isArray(o.sections))throw new Error("Invalid manifest");let i=Ee+r.manifestLength;for(let l of o.sections){if(!["bootstrap","document"].includes(l.id)||l.type!=="amw.document.v1"||l.offset!==i||!Number.isSafeInteger(l.length)||l.length<0||!/^[0-9a-f]{64}$/.test(l.sha256))throw new Error("Invalid section");let c=i+l.length;if(c>e.length||Pr(Y(e.subarray(i,c)))!==l.sha256)throw new Error("Section integrity failure");i=c}if(i!==e.length||o.sections.length!==2||o.sections[0].id!=="bootstrap"||o.sections[1].id!=="document"||o.sections[0].offset!==r.bootstrapOffset||o.sections[0].length!==r.bootstrapLength||!Y(e.subarray(r.bootstrapOffset,r.bootstrapOffset+r.bootstrapLength)).equals(r.bootstrapHash))throw new Error("Invalid bootstrap or layout");let a=JSON.parse(Mr.decode(e.subarray(o.sections[1].offset)));Lr(a);let s=JSON.parse(Mr.decode(e.subarray(o.sections[0].offset,o.sections[0].offset+o.sections[0].length)));if(Lr(s,!1),kt(s)!==kt(a.bootstrap??{title:a.title,blocks:a.blocks.slice(0,1)}))throw new Error("Bootstrap does not match document");return{header:r,manifest:o,document:a}}function ct(t,e){me(e);let r=Buffer.from(t),n=Buffer.from(e),o=ri(n.subarray(0,Ee)),i=Buffer.alloc(ze);return i.write(ti,0,"ascii"),i.writeUInt16LE(Zo,8),i.writeUInt16LE(ze,10),qe(i,r.length,16),qe(i,r.length,24),qe(i,n.length,32),Y(n).copy(i,40),Y(r).copy(i,72),Y(n.subarray(0,o.bootstrapOffset+o.bootstrapLength)).copy(i,104,0,24),Buffer.concat([r,n,i])}function oc(t,e){let r=Buffer.from(t),n=r.length===ze?r.readUInt16LE(8):0;if(r.length!==ze||r.toString("ascii",0,8)!==ti||![1,Zo].includes(n)||r.readUInt16LE(10)!==ze||r.subarray(12,16).some(Boolean)||n===1&&r.subarray(104).some(Boolean))throw new Error("Invalid AMW footer");let o={version:n,carrierLength:Ge(We(r,16),"carrier length"),payloadOffset:Ge(We(r,24),"payload offset"),payloadLength:Ge(We(r,32),"payload length"),payloadHash:r.subarray(40,72),carrierHash:r.subarray(72,104),bootstrapPrefixHash:n===2?r.subarray(104,128):null};if(o.carrierLength!==o.payloadOffset||o.payloadLength<Ee||o.payloadOffset+o.payloadLength+ze!==e)throw new Error("Invalid carrier layout");return o}function ge(t){let e=Buffer.from(t),r=oc(e.subarray(-ze),e.length),n=e.subarray(0,r.carrierLength),o=e.subarray(r.payloadOffset,-ze);if(!Y(n).equals(r.carrierHash)||!Y(o).equals(r.payloadHash))throw new Error("Carrier integrity failure");return me(o),{carrier:n,payload:o,footer:r}}function Lr(t,e=!0){let r=o=>typeof o=="string"&&/^#[0-9a-fA-F]{6}$/.test(o),n=t?.theme;if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(o=>!["title","blocks","theme",...e?["bootstrap","webApp","privateIndex"]:[]].includes(o))||typeof t.title!="string"||t.title.length>200||!Array.isArray(t.blocks)||t.blocks.length>1e4)throw new Error("Invalid document");if(t.privateIndex!==void 0){let o=t.privateIndex;if(!e||t.webApp!==void 0||t.bootstrap!==void 0||!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(i=>!["algorithm","url","offset","length","sha256","nonce","key"].includes(i))||o.algorithm!=="AES-256-GCM"||typeof o.url!="string"||!/^\/(?!\/)[A-Za-z0-9._/-]+$/.test(o.url)||o.url==="/favicon.ico"||o.url.startsWith("/amoosed.com/")||o.url.slice(1).split("/").some(i=>!i||i==="."||i==="..")||!Number.isSafeInteger(o.offset)||o.offset<0||!Number.isSafeInteger(o.length)||o.length<17||o.length>16*1024*1024+16||!/^[0-9a-f]{64}$/.test(o.sha256)||!/^[0-9a-f]{24}$/.test(o.nonce)||!/^[0-9a-f]{64}$/.test(o.key))throw new Error("Invalid private index locator")}if(n!==void 0&&(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).some(o=>!["background","foreground","accent"].includes(o)||!r(n[o]))))throw new Error("Invalid document theme");t.webApp!==void 0&<(t.webApp),t.bootstrap!==void 0&&Lr(t.bootstrap,!1);for(let o of t.blocks){if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(i=>!["type","text","href","style"].includes(i))||!["heading","paragraph","link","launch"].includes(o.type)||typeof o.text!="string"||o.text.length>1e4)throw new Error("Invalid document block");if(e&&o.type==="launch")throw new Error("Launch button belongs in the bootstrap");if(o.type==="link"?typeof o.href!="string"||!/^(?:https:\/\/|amw:\/\/|\/(?!\/)|\.{1,2}\/)/i.test(o.href):"href"in o)throw new Error("Invalid document link");if(o.type!=="launch"&&"style"in o)throw new Error("Only launch buttons may have styles");if(o.style!==void 0&&(!o.style||typeof o.style!="object"||Array.isArray(o.style)||Object.keys(o.style).some(i=>!["background","foreground","radius"].includes(i)||(i==="radius"?!Number.isInteger(o.style[i])||o.style[i]<0||o.style[i]>32:!r(o.style[i])))))throw new Error("Invalid launch style")}}var A=require("node:fs/promises"),he=require("node:fs"),to=require("node:stream/promises"),$a=require("node:stream"),C=require("node:path");var K=require("node:crypto");function ni(t,e){if(!Buffer.isBuffer(t)||!t.length||t.length>1024*1024)throw new Error("Invalid app favicon");let r=t.subarray(-128,-120).toString("ascii")==="AMW1TAIL"?ge(t).carrier:t;return ct(r,Ye({title:e,blocks:[]}))}async function Be(t,e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Invalid response limit");let r=t.headers.get("Content-Length");if(r!==null&&(!/^[0-9]+$/.test(r)||!Number.isSafeInteger(Number(r))||Number(r)>e))throw t.body&&await t.body.cancel().catch(()=>{}),new Error("Carrier response exceeds byte limit");if(!t.body)return new Uint8Array(0);let n=t.body.getReader(),o=[],i=0,a=!1;try{for(;;){let{done:c,value:f}=await n.read();if(c){a=!0;break}if(i+=f.byteLength,i>e)throw new Error("Carrier response exceeds byte limit");o.push(f)}}finally{a||await n.cancel().catch(()=>{}),n.releaseLock()}let s=new Uint8Array(i),l=0;for(let c of o)s.set(c,l),l+=c.byteLength;return s}var ft=4096,Ie=128,oi=1024*1024*1024,An=16*1024*1024,ic=new TextDecoder("utf-8",{fatal:!0}),Xt=(t,e)=>t.length===e.length&&t.every((r,n)=>r===e[n]),Jt=async t=>new Uint8Array(await crypto.subtle.digest("SHA-256",t)),Ke=(t,e)=>{let r=Number(t.getBigUint64(e,!0));if(!Number.isSafeInteger(r))throw new Error("Unsafe offset");return r},ii=(t,e)=>Xt(t.slice(0,8),new TextEncoder().encode(e)),xn=t=>JSON.parse(ic.decode(t));function ac(t){if(t.length!==ft||!ii(t,"AMW1DOC\0"))throw new Error("Invalid AMW header");let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(e.getUint16(8,!0)!==1||e.getUint16(10,!0)!==ft||t.slice(12,16).some(Boolean)||t.slice(120).some(Boolean))throw new Error("Unsupported AMW header");let r={total:Ke(e,16),manifestOffset:Ke(e,24),manifestLength:Ke(e,32),bootstrapOffset:Ke(e,40),bootstrapLength:Ke(e,48),manifestHash:t.slice(56,88),bootstrapHash:t.slice(88,120)};if(r.total>oi||r.total<ft||r.manifestOffset!==ft||r.manifestLength>1024*1024)throw new Error("Invalid AMW bounds");return r}function sc(t,e){if(t.length!==Ie||!ii(t,"AMW1TAIL"))throw new Error("No AMW footer");let r=new DataView(t.buffer,t.byteOffset,t.byteLength),n=r.getUint16(8,!0);if(![1,2].includes(n)||r.getUint16(10,!0)!==Ie||t.slice(12,16).some(Boolean)||n===1&&t.slice(104).some(Boolean))throw new Error("Unsupported footer");let o={version:n,carrierLength:Ke(r,16),payloadOffset:Ke(r,24),payloadLength:Ke(r,32),payloadHash:t.slice(40,72),bootstrapPrefixHash:n===2?t.slice(104,128):null};if(o.carrierLength!==o.payloadOffset||o.payloadLength>oi||o.payloadOffset+o.payloadLength+Ie!==e)throw new Error("Invalid carrier layout");return o}async function ai(t,{onBootstrap:e=()=>{},fetcher:r=fetch}={}){let n=new URL(t,globalThis.location?.href);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1"].includes(n.hostname)))throw new Error("HTTPS required");let o,i,a;return kn(async(l,c,f=!1)=>{if(a)return f?a.slice(-Ie):a.slice(l,c+1);let u=await r(n,{headers:{Range:f?`bytes=-${Ie}`:`bytes=${l}-${c}`,...i?{"If-Range":i}:{}},cache:"no-store",credentials:"omit",redirect:"error"});if(u.status===404||u.status===410)throw new Error("No AMW footer");if(u.status===200){let _=u.headers.get("Content-Length");if(_!==null&&(!/^[0-9]+$/.test(_)||!Number.isSafeInteger(Number(_))))throw new Error("Invalid full response length");if(a=await Be(u,An),a.length<Ie&&f)throw new Error("No AMW footer");if(_!==null&&a.length!==Number(_)||o!==void 0&&o!==a.length)throw new Error("Full response length changed");return o=a.length,f?a.slice(-Ie):a.slice(l,c+1)}if(u.status!==206)throw new Error("Host must support HTTP byte ranges");let h=/^bytes (\d+)-(\d+)\/(\d+)$/.exec(u.headers.get("Content-Range")||"");if(!h)throw new Error("Invalid Content-Range");let[p,d,g]=h.slice(1).map(Number);if(Number.isSafeInteger(g)&&g<Ie)throw new Error("No AMW footer");if(!Number.isSafeInteger(g)||o!==void 0&&o!==g||(f?d!==g-1||d-p+1!==Ie:p!==l||d!==c))throw new Error("Range changed or mismatched");let m=u.headers.get("ETag");if(i&&m&&m!==i)throw new Error("ETag changed during load");!i&&m&&!m.startsWith("W/")&&(i=m),o=g;let E=await Be(u,d-p+1);if(E.length!==d-p+1)throw new Error("Short range response");return E},()=>o,!n.pathname.endsWith(".amw"),e)}async function si(t,{onBootstrap:e=()=>{}}={}){let r=t instanceof Uint8Array?t:new Uint8Array(t);if(r.length<Ie||r.length>An)throw new Error("Invalid local index size");return kn(async(o,i,a=!1)=>a?r.slice(-Ie):r.slice(o,i+1),()=>r.length,!0,e)}async function li(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);if(e.length<ft||e.length>An)throw new Error("Invalid private index size");return kn(async(n,o)=>e.slice(n,o+1),()=>e.length,!1,()=>{})}async function kn(t,e,r,n){let o=r?sc(await t(0,0,!0),e()):null,i=o?.payloadOffset||0,a=await t(i,i+ft-1),s=ac(a);if(o&&s.total!==o.payloadLength)throw new Error("Payload length mismatch");if(!o&&e()!==s.total)throw new Error("AMW length mismatch");let l=await t(i+s.manifestOffset,i+s.manifestOffset+s.manifestLength-1);if(!Xt(await Jt(l),s.manifestHash))throw new Error("Manifest integrity failure");let c=xn(l);if(c.format!=="amw.sections.v1"||!Array.isArray(c.sections)||c.sections.length!==2)throw new Error("Invalid manifest");let f=ft+s.manifestLength;for(let m of c.sections){if(m.offset!==f||!Number.isSafeInteger(m.length)||m.length<1||!/^[0-9a-f]{64}$/.test(m.sha256))throw new Error("Invalid section layout");f+=m.length}if(f!==s.total||c.sections[0].id!=="bootstrap"||c.sections[1].id!=="document"||c.sections.some(m=>m.type!=="amw.document.v1")||c.sections[0].offset!==s.bootstrapOffset||c.sections[0].length!==s.bootstrapLength)throw new Error("Invalid section layout");let u=new Uint8Array(s.total);u.set(a,0),u.set(l,s.manifestOffset);let h=async m=>{let E=await t(i+m.offset,i+m.offset+m.length-1);if([...await Jt(E)].map(P=>P.toString(16).padStart(2,"0")).join("")!==m.sha256)throw new Error("Section integrity failure");return u.set(E,m.offset),E},p=await h(c.sections[0]);if(!Xt(await Jt(p),s.bootstrapHash))throw new Error("Bootstrap integrity failure");let d=xn(p);if(o?.version===2){let m=await Jt(u.subarray(0,s.bootstrapOffset+s.bootstrapLength));if(!Xt(m.subarray(0,24),o.bootstrapPrefixHash))throw new Error("Bootstrap prefix integrity failure");n(d)}let g=xn(await h(c.sections[1]));if(o&&!Xt(await Jt(u),o.payloadHash))throw new Error("Payload integrity failure");return(!o||o.version===1)&&n(d),g}var ci=/^[0-9a-f]{64}$/,lc=/^[0-9a-f]{24}$/,cc=16*1024*1024+16,fc=t=>[...t].map(e=>e.toString(16).padStart(2,"0")).join("");function Rr(t){if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(e=>!["algorithm","url","offset","length","sha256","nonce","key"].includes(e))||t.algorithm!=="AES-256-GCM"||typeof t.url!="string"||!/^\/(?!\/)[A-Za-z0-9._/-]+$/.test(t.url)||t.url==="/favicon.ico"||t.url.startsWith("/amoosed.com/")||t.url.slice(1).split("/").some(e=>!e||e==="."||e==="..")||!Number.isSafeInteger(t.offset)||t.offset<0||!Number.isSafeInteger(t.length)||t.length<17||t.length>cc||!ci.test(t.sha256)||!lc.test(t.nonce)||!ci.test(t.key))throw new Error("Invalid private index locator");return t}async function fi(t,e=fetch,r=location.origin){if(!t?.privateIndex)return t;if(t.webApp)throw new Error("Ambiguous index file");let n=Rr(t.privateIndex),o=new URL(n.url,r);if(o.origin!==r)throw new Error("Private index changed origin");let i=await e(o.href,{headers:{Range:`bytes=${n.offset}-${n.offset+n.length-1}`},cache:"no-store",credentials:"omit",redirect:"error"});if(!i.ok||new URL(i.url,r).origin!==r)throw new Error("Private index carrier unavailable");let a;if(i.status===206){let h=/^bytes (\d+)-(\d+)\/(\d+)$/.exec(i.headers.get("Content-Range")||"");if(!h||Number(h[1])!==n.offset||Number(h[2])!==n.offset+n.length-1||!Number.isSafeInteger(Number(h[3])))throw new Error("Private index range mismatch");a=await Be(i,n.length)}else if(i.status===200)a=(await Be(i,16777216)).slice(n.offset,n.offset+n.length);else throw new Error("Private index carrier needs byte ranges");if(a.length!==n.length||fc(new Uint8Array(await crypto.subtle.digest("SHA-256",a)))!==n.sha256)throw new Error("Private index integrity failure");let s=await crypto.subtle.importKey("raw",Uint8Array.from(n.key.match(/../g),h=>parseInt(h,16)),"AES-GCM",!1,["decrypt"]),l=Uint8Array.from(n.nonce.match(/../g),h=>parseInt(h,16)),c=new TextEncoder().encode(`AMW1-PRIVATE-INDEX\0${n.url}\0${n.offset}`),f;try{f=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:l,additionalData:c},s,a))}catch{throw new Error("Private index key or authentication failed")}let u=await li(f);if(u.privateIndex)throw new Error("Nested private index is not supported");return u}var hi="AMQ1",Or=93,ui=new TextEncoder,_n=new TextDecoder("utf-8",{fatal:!0});function vn(t){return Uint8Array.from(t.match(/../g),e=>Number.parseInt(e,16))}function In(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}function di(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function vt(t){let e=Rr(t),r=ui.encode(e.url);if(r.length>255)throw new Error("Private index carrier path is too long for a QR token");let n=new Uint8Array(Or+r.length);n.set(ui.encode(hi)),n[4]=r.length;let o=new DataView(n.buffer);return o.setBigUint64(5,BigInt(e.offset)),o.setUint32(13,e.length),n.set(vn(e.sha256),17),n.set(vn(e.nonce),49),n.set(vn(e.key),61),n.set(r,Or),di(n)}function ut(t){if(typeof t!="string"||!/^[A-Za-z0-9_-]{124,464}$/.test(t))throw new Error("Invalid Amoosed QR key");let e;try{e=Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),i=>i.charCodeAt(0))}catch{throw new Error("Invalid Amoosed QR key")}if(e.length!==Or+e[4]||_n.decode(e.subarray(0,4))!==hi||di(e)!==t)throw new Error("Invalid Amoosed QR key");let r=new DataView(e.buffer),n=Number(r.getBigUint64(5)),o={algorithm:"AES-256-GCM",url:_n.decode(e.subarray(Or)),offset:n,length:r.getUint32(13),sha256:In(e.subarray(17,49)),nonce:In(e.subarray(49,61)),key:In(e.subarray(61,93))};if(Rr(o),vt(o)!==t)throw new Error("Invalid Amoosed QR key");return o}function pi(t,e){ut(e);let r=new URL(t);if(r.username||r.password||!(r.protocol==="https:"||r.protocol==="http:"&&["localhost","127.0.0.1"].includes(r.hostname)))throw new Error("Unlock link requires a secure site origin");return r.pathname="/amoosed.com/boot.html",r.search="",r.hash=`amw-index=${e}`,r.href}function Nr(t){return ut(t),`AMWKEY1:${t}
|
|
16
|
-
`}function Ur(t){let e=typeof t=="string"?t:_n.decode(t),r=/^AMWKEY1:([A-Za-z0-9_-]{124,464})\r?\n?$/.exec(e);if(!r)throw new Error("Invalid Amoosed key file");return ut(r[1]),r[1]}var jr=require("node:fs/promises"),uc=Buffer.from("89504e470d0a1a0a","hex"),Dr=Buffer.from("amWd"),mi=Buffer.from("416d6f6f736564576562446174613031","hex"),Cn=t=>t==="png-chunk"?12:t==="mp4-uuid"?24:0;function It(t,e=4294967295){for(let r of t){e^=r;for(let n=0;n<8;n++)e=e>>>1^(e&1?3988292384:0)}return e>>>0}async function $r(t,e,r){let n=Buffer.alloc(r),{bytesRead:o}=await t.read(n,0,r,e);if(o!==r)throw new Error("Truncated media carrier");return n}async function Qt(t,e){let r=(await(0,jr.stat)(t)).size,n=await(0,jr.open)(t,"r");try{if(e==="png-chunk"){if(r<45||!(await $r(n,0,8)).equals(uc))throw new Error("PNG chunk mode requires a PNG image");let o=8,i=!0;for(;o+12<=r;){let a=await $r(n,o,8),s=a.readUInt32BE(0),l=a.toString("ascii",4,8);if(o+12+s>r)throw new Error("Invalid PNG chunk layout");if(i&&(l!=="IHDR"||s!==13))throw new Error("Invalid PNG IHDR");if(i=!1,l==="IEND"){if(s!==0||o+12!==r)throw new Error("PNG IEND must end the file");return{insertOffset:o,size:r}}o+=12+s}throw new Error("PNG IEND is missing")}if(e==="mp4-uuid"){let o=0,i=!0;for(;o+8<=r;){let a=await $r(n,o,8),s=a.readUInt32BE(0);if(s===1){if(o+16>r)throw new Error("Invalid MP4 box layout");let l=(await $r(n,o+8,8)).readBigUInt64BE();if(l>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("MP4 box is too large");s=Number(l)}if(i&&a.toString("ascii",4,8)!=="ftyp")throw new Error("MP4 UUID mode requires an ISO BMFF file");if(i=!1,s<8||o+s>r)throw new Error("Invalid MP4 box layout");o+=s}if(o!==r||i)throw new Error("Invalid MP4 box layout");return{insertOffset:r,size:r}}throw new Error(`Unsupported carrier mode: ${e}`)}finally{await n.close()}}function Zt(t,e=0){if(t==="png-chunk"){if(e>4294967295)throw new Error("PNG carrier data is too large");let r=Buffer.alloc(8);return r.writeUInt32BE(e,0),Dr.copy(r,4),r}if(t==="mp4-uuid"){if(e+24>4294967295)throw new Error("MP4 UUID box is too large");let r=Buffer.alloc(24);return r.writeUInt32BE(e+24,0),r.write("uuid",4,"ascii"),mi.copy(r,8),r}throw new Error(`Unsupported carrier mode: ${t}`)}var tr=require("node:crypto"),qn=En(Fr(),1),ua=Buffer.from("AMWPX1\0\0"),Me=44,fa=16*1024*1024,ha=16*1024*1024;function wf(t,e){for(;e;)[t,e]=[e,t%e];return t}function Gn(t){if(!Buffer.isBuffer(t)||t.length<33||!t.subarray(0,8).equals(Buffer.from("89504e470d0a1a0a","hex"))||t.toString("ascii",12,16)!=="IHDR")throw new Error("Expected a PNG image");let e=t.readUInt32BE(16),r=t.readUInt32BE(20);if(!e||!r||e*r>fa)throw new Error("PNG pixel count exceeds limit");let n=qn.PNG.sync.read(t,{checkCRC:!0}),o=n.width*n.height;if(!Number.isSafeInteger(o)||o<1||o>fa)throw new Error("PNG pixel count exceeds limit");let i=[];for(let l=0;l<o;l++)n.data[l*4+3]===255&&i.push(l);let a=i.length*3;if(a<Me*8)throw new Error("PNG has too few opaque pixels");let s=65537;for(;wf(s,a)!==1;)s+=2;return{png:n,opaque:Uint32Array.from(i),slots:a,stride:s}}function Wn(t,e,r){if(e.length*8>t.slots)throw new Error("Pixel carrier capacity exceeded");let n=0;for(let o=0;o<e.length;o++){let i=r?e[o]:0;for(let a=7;a>=0;a--){let s=t.opaque[Math.floor(n/3)]*4+n%3;r?t.png.data[s]=t.png.data[s]&254|i>>>a&1:i=i<<1|t.png.data[s]&1,n=(n+t.stride)%t.slots}r||(e[o]=i)}}function Hr(t){let e=Gn(t);return Math.max(0,Math.floor(e.slots/8)-Me)}function Bt(t,e){if(!Buffer.isBuffer(e)||e.length<1||e.length>ha)throw new Error("Invalid pixel payload");let r=Gn(t);if(e.length+Me>Math.floor(r.slots/8))throw new Error("Pixel carrier capacity exceeded");let n=Buffer.alloc(Me+e.length);return ua.copy(n),n.writeUInt32LE(e.length,8),(0,tr.createHash)("sha256").update(e).digest().copy(n,12),e.copy(n,Me),Wn(r,n,!0),qn.PNG.sync.write(r.png,{colorType:6,inputColorType:6,bitDepth:8})}function Ne(t){let e=Gn(t),r=Buffer.alloc(Me);if(Wn(e,r,!1),!r.subarray(0,8).equals(ua))throw new Error("No AmoosedWeb pixel payload");let n=r.readUInt32LE(8);if(n<1||n>ha||n+Me>Math.floor(e.slots/8))throw new Error("Invalid pixel payload length");let o=Buffer.alloc(Me+n);Wn(e,o,!1);let i=(0,tr.createHash)("sha256").update(o.subarray(Me)).digest();if(!(0,tr.timingSafeEqual)(i,r.subarray(12,44)))throw new Error("Pixel payload integrity failure");return o.subarray(Me)}var $e=require("node:crypto");var Tt=require("node:crypto"),da=Buffer.from("AMW-MEDIA-TRANSPORT-V1");function rr(t,e){if(!Buffer.isBuffer(t)||!Buffer.isBuffer(e)||e.length!==32)throw new Error("A 256-bit media key is required");let r=(0,Tt.randomBytes)(12),n=(0,Tt.createCipheriv)("aes-256-gcm",e,r);return n.setAAD(da),{bytes:Buffer.concat([n.update(t),n.final(),n.getAuthTag()]),encryption:{algorithm:"AES-256-GCM",nonce:r.toString("hex"),plainLength:t.length}}}function nr(t,e,r){if(!Buffer.isBuffer(t)||t.length<17||!Buffer.isBuffer(r)||r.length!==32||!e||e.algorithm!=="AES-256-GCM"||!/^[0-9a-f]{24}$/.test(e.nonce)||!Number.isSafeInteger(e.plainLength)||e.plainLength<1||e.plainLength!==t.length-16)throw new Error("Invalid media encryption metadata or key");try{let n=(0,Tt.createDecipheriv)("aes-256-gcm",r,Buffer.from(e.nonce,"hex"));return n.setAAD(da),n.setAuthTag(t.subarray(-16)),Buffer.concat([n.update(t.subarray(0,-16)),n.final()])}catch{throw new Error("Media key or authentication failed")}}function Mt(t,e){let{bytes:r,encryption:n}=rr(t,e);return Buffer.concat([Buffer.from(n.nonce,"hex"),r])}function Lt(t,e){if(!Buffer.isBuffer(t)||t.length<29)throw new Error("Invalid media envelope");return nr(t.subarray(12),{algorithm:"AES-256-GCM",nonce:t.subarray(0,12).toString("hex"),plainLength:t.length-28},e)}var pa=require("node:crypto"),ma=t=>(0,pa.createHash)("sha256").update(t).digest("hex");function Wr(t,e){let r=[];for(let n=0,o=0;n<t.length;n+=e,o++){let i=t.subarray(n,n+e);r.push({index:o,length:i.length,sha256:ma(i)})}return r}function qr(t,e){if(!Array.isArray(t.packets)||t.packets.length!==t.packetCount)throw new Error("Invalid ciphertext packet map");for(let[r,n]of t.packets.entries())if(!n||n.index!==r||n.length!==Math.min(e,t.length-r*e)||!/^[0-9a-f]{64}$/.test(n.sha256))throw new Error("Invalid ciphertext packet map")}function or(t,e){return t.length===e.length&&ma(t)===e.sha256}var Ue=16e3,ir=160,ga=1600,ya=[1e3,1500,2e3,2500],ar=Array.from({length:16},(t,e)=>e&1?3:0),Kn=Buffer.from("AWA1"),ae=128,Xe=54,dt=4096,yf=128*1024*1024,Pt=3,Rt=t=>(0,$e.createHash)("sha256").update(t).digest("hex");function bf(t,e,r){let n=t.subarray(e*ae,(e+1)*ae),o=Buffer.alloc(Xe+n.length);return Kn.copy(o),o.writeUInt32LE(t.length,4),o.writeUInt16LE(r,8),o.writeUInt16LE(e,10),o.writeUInt16LE(n.length,12),(0,$e.createHash)("sha256").update(t).digest().copy(o,14),(0,$e.createHash)("sha256").update(n).digest().copy(o,46,0,8),n.copy(o,Xe),o}function Yn(t){return ar.length+t.length*4}function Ef(t){let e=Buffer.alloc(44+t.length);e.write("RIFF",0),e.writeUInt32LE(e.length-8,4),e.write("WAVEfmt ",8),e.writeUInt32LE(16,16),e.writeUInt16LE(1,20),e.writeUInt16LE(1,22),e.writeUInt32LE(Ue,24),e.writeUInt32LE(Ue,28),e.writeUInt16LE(1,32),e.writeUInt16LE(8,34),e.write("data",36),e.writeUInt32LE(t.length,40);for(let r=0;r<t.length;r++)e[44+r]=Math.max(0,Math.min(255,Math.round(128+t[r]/256)));return e}function ba(t,e=null){let r=t.reduce((s,l)=>s+ga+Yn(l.bytes)*ir,0),n=e?xa(e):null;if(n&&n.samples.length/n.rate<r/Ue)throw new Error("Cover audio is shorter than the encoded track");let o=new Int16Array(n?Math.max(r,Math.floor(n.samples.length/n.rate*Ue)):r);if(n)for(let s=0;s<o.length;s++)o[s]=Math.round(n.samples[Math.floor(s*n.rate/Ue)]*.85*32767);let i=[],a=0;for(let s of t){a+=ga,i.push({packet:s.index,copy:s.copy,startSeconds:a/Ue,durationSeconds:Yn(s.bytes)*ir/Ue});let l=[...ar];for(let c of s.bytes)for(let f=6;f>=0;f-=2)l.push(c>>>f&3);for(let c of l){let f=ya[c];for(let u=0;u<ir;u++){let h=Math.min(1,u/16,(ir-u-1)/16),p=(e?.12:.55)*32767*h*Math.sin(2*Math.PI*f*u/Ue);o[a+u]=Math.max(-32768,Math.min(32767,Math.round(o[a+u]+p)))}a+=ir}}return{wav:Ef(o),locations:i}}function Ea(t,e=1,r,n=[]){if(!Buffer.isBuffer(t)||t.length<1||t.length>dt-16)throw new Error("Audio plaintext must be 1\u20134080 bytes");let{bytes:o,encryption:i}=rr(t,r),a=Math.ceil(o.length/ae);if(!Number.isInteger(e)||e<1||e>Math.min(32,a*Pt))throw new Error("Invalid audio clip count");if(!Array.isArray(n)||n.length&&n.length!==e)throw new Error("Provide one cover WAV per clip");let s=Array.from({length:e},()=>[]);for(let c=0;c<a;c++){let f=bf(o,c,a);for(let u=0;u<Pt;u++)s[(c*Pt+u)%e].push({bytes:f,index:c,copy:u})}let l=s.map((c,f)=>({file:`clip-${String(f+1).padStart(3,"0")}.wav`,...ba(c,n[f])}));return{manifest:{format:"amw.audio-transport.v1",algorithm:"4fsk-100hz-3x",length:o.length,sha256:Rt(o),encryption:i,packetBytes:ae,packetCount:a,packets:Wr(o,ae),clips:l.map(c=>({file:c.file,durationSeconds:(c.wav.length-44)/Ue,locations:c.locations}))},clips:l.map(({file:c,wav:f})=>({file:c,wav:f}))}}function xa(t){if(!Buffer.isBuffer(t)||t.length<44||t.length>yf||t.toString("ascii",0,4)!=="RIFF"||t.toString("ascii",8,12)!=="WAVE")throw new Error("Expected a bounded PCM WAV file");let e,r;for(let s=12;s+8<=t.length;){let l=t.toString("ascii",s,s+4),c=t.readUInt32LE(s+4);if(s+8+c>t.length)throw new Error("Invalid WAV chunk");l==="fmt "&&(e=t.subarray(s+8,s+8+c)),l==="data"&&(r=t.subarray(s+8,s+8+c)),s+=8+c+(c&1)}if(!e||e.length<16||!r||e.readUInt16LE(0)!==1||![1,2].includes(e.readUInt16LE(2))||![16e3,44100,48e3].includes(e.readUInt32LE(4))||![8,16].includes(e.readUInt16LE(14)))throw new Error("Expected 16/44.1/48 kHz 8/16-bit PCM");let n=e.readUInt16LE(2),o=e.readUInt32LE(4),i=e.readUInt16LE(14)/8;if(r.length%(n*i))throw new Error("Invalid WAV sample length");let a=new Float32Array(r.length/(n*i));for(let s=0;s<a.length;s++){let l=0;for(let c=0;c<n;c++){let f=(s*n+c)*i;l+=i===1?(r[f]-128)/128:r.readInt16LE(f)/32768}a[s]=l/n}return{samples:a,rate:o}}function xf(t,e,r,n){let o=r+Math.round(e*.001),i=r+Math.round(e*.009);if(o<0||i>=t.length)return-1;let a=0,s=0,l=2*Math.PI*n/e;for(let c=o;c<i;c++)a+=t[c]*Math.cos(l*(c-o)),s+=t[c]*Math.sin(l*(c-o));return a*a+s*s}function Aa(t,e,r){let n=-1,o=0;for(let i=0;i<4;i++){let a=xf(t,e,r,ya[i]);a>n&&(n=a,o=i)}return o}function wa(t,e,r,n){let o=Buffer.alloc(n),i=e/100;for(let a=0;a<n;a++)for(let s=0;s<4;s++)o[a]=o[a]<<2|Aa(t,e,Math.round(r+(ar.length+a*4+s)*i));return o}function zn(t,e,r,n){let o=e/100,i=-1,a=-1;for(let g=-2;g<=1;g+=.5){let m=r+Math.round(g*e/1e3);if(m<0)continue;let E=0;for(let _=0;_<ar.length;_++)Aa(t,e,Math.round(m+_*o))===ar[_]&&E++;E>a&&(a=E,i=m)}if(a<14)return null;let s=wa(t,e,i,Xe);if(!s.subarray(0,4).equals(Kn))return null;let l=s.readUInt32LE(4),c=s.readUInt16LE(8),f=s.readUInt16LE(10),u=s.readUInt16LE(12);if(l<1||l>dt||c!==Math.ceil(l/ae)||f>=c||u!==Math.min(ae,l-f*ae)||i+Yn(Buffer.alloc(Xe+u))*o>n+e*.004)return null;let p=wa(t,e,i,Xe+u).subarray(Xe),d=(0,$e.createHash)("sha256").update(p).digest().subarray(0,8);return(0,$e.timingSafeEqual)(d,s.subarray(46,54))?{total:l,count:c,index:f,sha256:s.subarray(14,46).toString("hex"),data:p}:null}function Vn(t,e=[]){let{samples:r,rate:n}=xa(t),o=Math.round(n/1e3),i=[];for(let c of e){if(!Number.isFinite(c.startSeconds)||c.startSeconds<0)continue;let f=Math.round(c.startSeconds*n);for(let u=-3;u<=3;u+=.5){let h=zn(r,n,f+Math.round(u*n/1e3),r.length);if(h&&h.index===c.packet){i.push(h);break}}}if(i.length===e.length&&e.length)return i;let a=!1,s=0,l=0;for(let c=0;c<r.length;c+=o){let f=0;for(let h=c;h<Math.min(c+o,r.length);h++)f+=r[h]*r[h];let u=f/o>.002;if(u&&!a?(a=!0,s=c,l=0):u?l=0:a&&l++,a&&l>=20){a=!1;let h=zn(r,n,s,c-19*o);h&&i.push(h)}}if(a){let c=zn(r,n,s,r.length);c&&i.push(c)}return i}function ka(t,e,r){if(!e||e.format!=="amw.audio-transport.v1"||e.algorithm!=="4fsk-100hz-3x"||!Number.isInteger(e.length)||e.length<1||e.length>dt||!/^[0-9a-f]{64}$/.test(e.sha256)||e.packetBytes!==ae||e.packetCount!==Math.ceil(e.length/ae)||!Array.isArray(e.clips)||e.clips.length<1||e.clips.length>32||e.clips.length!==t.length||e.clips.some(i=>!i||!Array.isArray(i.locations)||i.locations.length>e.packetCount*Pt||i.locations.some(a=>!a||!Number.isInteger(a.packet)||a.packet<0||a.packet>=e.packetCount||!Number.isFinite(a.startSeconds)||a.startSeconds<0||!Number.isFinite(a.durationSeconds)||a.durationSeconds<=0)))throw new Error("Invalid audio transport index");qr(e,ae);let n=new Map;for(let[i,a]of t.entries())for(let s of Vn(a,e.clips[i].locations))s.total!==e.length||s.count!==e.packetCount||s.sha256!==e.sha256||!or(s.data,e.packets[s.index])||n.has(s.index)||n.set(s.index,s.data);if(n.size!==e.packetCount)throw new Error(`Audio packet recovery incomplete: ${n.size}/${e.packetCount}`);let o=Buffer.concat(Array.from({length:e.packetCount},(i,a)=>n.get(a)));if(o.length!==e.length||Rt(o)!==e.sha256)throw new Error("Audio payload integrity failure");return nr(o,e.encryption,r)}function Jn(t,e){if(!Array.isArray(t)||!t.length||t.length>32||t.some(i=>!Buffer.isBuffer(i)||i.length<1||i.length>ae))throw new Error("Audio carrier needs 1\u201332 ciphertext shards of at most 128 bytes");let r=Buffer.concat(t);if(r.length>dt)throw new Error("Audio carrier payload exceeds 4 KiB");let n=[];for(let[i,a]of t.entries()){let s=Buffer.alloc(Xe+a.length);Kn.copy(s),s.writeUInt32LE(r.length,4),s.writeUInt16LE(t.length,8),s.writeUInt16LE(i,10),s.writeUInt16LE(a.length,12),(0,$e.createHash)("sha256").update(r).digest().copy(s,14),(0,$e.createHash)("sha256").update(a).digest().copy(s,46,0,8),a.copy(s,Xe);for(let l=0;l<Pt;l++)n.push({bytes:s,index:i,copy:l})}let o=ba(n,e);return{wav:o.wav,manifest:{format:"amw.audio-carrier.v1",length:r.length,sha256:Rt(r),packets:t.map((i,a)=>({index:a,length:i.length,sha256:Rt(i)})),locations:o.locations}}}function Gr(t,e){if(!e||e.format!=="amw.audio-carrier.v1"||!Number.isInteger(e.length)||e.length<1||e.length>dt||!/^[0-9a-f]{64}$/.test(e.sha256)||!Array.isArray(e.packets)||e.packets.length<1||e.packets.length>32||!Array.isArray(e.locations)||e.locations.length!==e.packets.length*Pt||e.locations.some(o=>!Number.isInteger(o.packet)||o.packet<0||o.packet>=e.packets.length||!Number.isFinite(o.startSeconds)||o.startSeconds<0))throw new Error("Invalid audio carrier manifest");let r=new Map;for(let o of Vn(t,e.locations))o.total!==e.length||o.count!==e.packets.length||o.sha256!==e.sha256||!or(o.data,e.packets[o.index])||r.has(o.index)||r.set(o.index,o.data);if(r.size!==e.packets.length)throw new Error("Audio carrier recovery incomplete");let n=Buffer.concat(e.packets.map((o,i)=>r.get(i)));if(n.length!==e.length||Rt(n)!==e.sha256)throw new Error("Audio carrier integrity failure");return n}function va(t,e){if(!Buffer.isBuffer(t)||t.length<1||t.length>dt-28)throw new Error("Standalone audio payload must be 1\u20134068 bytes");let r=Mt(t,e),n=Array.from({length:Math.ceil(r.length/ae)},(o,i)=>r.subarray(i*ae,(i+1)*ae));return Jn(n).wav}function Ia(t,e){let r=Vn(t).filter(i=>i.total>=29&&i.total<=dt&&i.count===Math.ceil(i.total/ae)),n=new Map;for(let i of r){let a=`${i.total}:${i.count}:${i.sha256}`;n.has(a)||n.set(a,{total:i.total,count:i.count,sha256:i.sha256,parts:new Map});let s=n.get(a);s.parts.has(i.index)||s.parts.set(i.index,i.data)}let o=[];for(let i of n.values()){if(i.parts.size!==i.count)continue;let a=Buffer.concat(Array.from({length:i.count},(s,l)=>i.parts.get(l)));a.length===i.total&&Rt(a)===i.sha256&&o.push(a)}if(o.length!==1)throw new Error("Standalone audio packet recovery incomplete or ambiguous");return Lt(o[0],e)}var Ba=require("node:crypto"),sr=En(Fr(),1);function Xn(t,e,r){let n=e*r;if(!Number.isSafeInteger(n)||e<256||r<128||n>16*1024*1024||t.length!==n*4)throw new Error("Invalid frame dimensions");let o=(f,u)=>{for(;u;)[f,u]=[u,f%u];return f},i=Math.floor(n*.61803398875)|1;for(;o(i,n)!==1;)i+=2;let a=((Math.imul(e,73856093)^Math.imul(r,19349663))>>>0)%n,s=new Uint32Array(768),l=f=>{let u=f*4;return(299*(t[u]&254)+587*(t[u+1]&254)+114*(t[u+2]&254))/1e3},c=f=>{let u=f%e,h=Math.floor(f/e),p=l(f),d=0;return u>0&&(d+=Math.abs(p-l(f-1))),u+1<e&&(d+=Math.abs(p-l(f+1))),h>0&&(d+=Math.abs(p-l(f-e))),h+1<r&&(d+=Math.abs(p-l(f+e))),d};for(let f=0,u=0;f<n&&u<s.length;){let h=-1,p=-1;for(let d=0;d<16&&f<n;d++,f++){let g=(a+f*i)%n;if(t[g*4+3]!==255)continue;let m=c(g);m>p&&(h=g,p=m)}if(h>=0&&(s[u++]=h),u===s.length)return s}throw new Error("Frame needs at least 768 opaque pixels")}var Ta=Buffer.from("AWF1"),se=8,_a=32,Ca=16,pt=11,Ae=32-pt,Qe=3,Ma=1024,Nt=t=>(0,Ba.createHash)("sha256").update(t).digest();function zr(t){if(!Buffer.isBuffer(t)||t.length<33||!t.subarray(0,8).equals(Buffer.from("89504e470d0a1a0a","hex"))||t.readUInt32BE(16)*t.readUInt32BE(20)>16*1024*1024)throw new Error("Expected a bounded PNG frame");let e=sr.PNG.sync.read(t,{checkCRC:!0});if(e.width<_a*se||e.height<Ca*se)throw new Error("Frame must be at least 256 x 128 pixels");for(let r=0;r<Ca*se;r++)for(let n=0;n<_a*se;n++)if(e.data[(r*e.width+n)*4+3]!==255)throw new Error("Frame data region must be opaque");return e}function Ot(t,e,r){let n=0;for(let o=0;o<se;o++)for(let i=0;i<se;i++){let a=((r+o)*t.width+e+i)*4;n+=(t.data[a]*299+t.data[a+1]*587+t.data[a+2]*114)/1e3}return n/(se*se)}function Sa(t,e,r,n){for(let o=0;o<se;o++)for(let i=0;i<se;i++){let a=((r+o)*t.width+e+i)*4;for(let s=0;s<3;s++)t.data[a+s]=Math.max(0,Math.min(255,Math.round(t.data[a+s]+n)))}}function La(t){let e=Math.floor(t/16);return[t%16*2*se,e*se]}function Af(t,e){for(let r=0;r<e.length*8;r++){let[n,o]=La(r),i=e[r>>>3]&1<<7-(r&7)?1:-1,a=i*(Ot(t,n,o)-Ot(t,n+se,o));if(a<40){let s=Math.min(72,(48-a)/2);Sa(t,n,o,i*s),Sa(t,n+se,o,-i*s)}if(i*(Ot(t,n,o)-Ot(t,n+se,o))<20)throw new Error("Cover frame is too saturated or high contrast for tile encoding")}}function Pa(t){let e=Buffer.alloc(32);for(let r=0;r<e.length*8;r++){let[n,o]=La(r);Ot(t,n,o)>Ot(t,n+se,o)&&(e[r>>>3]|=1<<7-(r&7))}return e}function Ra(t,e,r=30,n=1,o,i="pixel"){if(!Buffer.isBuffer(t)||t.length<1||t.length>Ma-16)throw new Error("Frame plaintext must be 1\u20131008 bytes");let{bytes:a,encryption:s}=rr(t,o);if(!Number.isInteger(r)||r<24||r>60||!Number.isInteger(n)||n<1||n>16)throw new Error("Invalid frame rate or clip count");if(!["pixel","luma"].includes(i))throw new Error("Invalid frame encoding mode");let l=i==="luma"?zr(e):null,c=Math.ceil(a.length/Ae);if(n>c*Qe)throw new Error("More clips than frame copies");let f=Array.from({length:n},(h,p)=>({id:`clip-${String(p+1).padStart(3,"0")}`,frames:[]})),u=[];for(let h=0;h<c;h++){let p=a.subarray(h*Ae,(h+1)*Ae),d=Buffer.alloc(32);Ta.copy(d),d.writeUInt16LE(h,4),d[6]=p.length,Nt(p).copy(d,7,0,4),p.copy(d,pt);for(let g=0;g<Qe;g++){let m=f[(h*Qe+g)%n],E=(m.frames.length+1)*r,_=`${m.id}-frame-${String(E).padStart(6,"0")}.png`,P;if(i==="pixel")P=Bt(e,d);else{let S=new sr.PNG({width:l.width,height:l.height});l.data.copy(S.data),Af(S,d),P=sr.PNG.sync.write(S,{colorType:6,inputColorType:6,bitDepth:8})}u.push({file:_,bytes:P}),m.frames.push({file:_,frameIndex:E,startSeconds:E/r,packet:h,copy:g})}}return{manifest:{format:"amw.frame-transport.v1",mode:i,fps:r,length:a.length,sha256:Nt(a).toString("hex"),encryption:s,packetBytes:Ae,packetCount:c,packets:Wr(a,Ae),clips:f},frames:u}}function Oa(t,e,r){if(!e||e.format!=="amw.frame-transport.v1"||!Number.isInteger(e.length)||e.length<1||e.length>Ma||!/^[0-9a-f]{64}$/.test(e.sha256)||!["pixel","luma"].includes(e.mode)||e.packetBytes!==Ae||e.packetCount!==Math.ceil(e.length/Ae)||!Number.isInteger(e.fps)||e.fps<24||e.fps>60||!Array.isArray(e.clips)||e.clips.length<1||e.clips.length>16||e.clips.some(i=>!i||!Array.isArray(i.frames)||i.frames.length>e.packetCount*Qe||i.frames.some(a=>!a||!Number.isInteger(a.packet)||a.packet<0||a.packet>=e.packetCount||!Number.isSafeInteger(a.frameIndex)||a.frameIndex<0)))throw new Error("Invalid frame transport index");qr(e,Ae);let n=new Map;for(let i of t){let a;try{a=e.mode==="pixel"?Ne(i):Pa(zr(i))}catch{continue}if(!a.subarray(0,4).equals(Ta))continue;let s=a.readUInt16LE(4),l=a[6];if(s>=e.packetCount||l!==Math.min(Ae,e.length-s*Ae))continue;let c=a.subarray(pt,pt+l);!Nt(c).subarray(0,4).equals(a.subarray(7,11))||!or(c,e.packets[s])||n.has(s)||n.set(s,c)}if(n.size!==e.packetCount)throw new Error(`Frame packet recovery incomplete: ${n.size}/${e.packetCount}`);let o=Buffer.concat(Array.from({length:e.packetCount},(i,a)=>n.get(a)));if(Nt(o).toString("hex")!==e.sha256)throw new Error("Frame payload integrity failure");return nr(o,e.encryption,r)}function Na(t,e){if(!Buffer.isBuffer(e)||e.length<1||e.length>Ae)throw new Error("Luminance frame shard must be 1\u201321 bytes");let r=zr(t),n=Buffer.alloc(32);Buffer.from("AWF2").copy(n),n.writeUInt16LE(0,4),n[6]=e.length,Nt(e).copy(n,7,0,4),e.copy(n,pt);let o=Xn(r.data,r.width,r.height);for(let i=0;i<256;i++)for(let a=0;a<Qe;a++){let s=o[i*Qe+a]*4;r.data[s]=r.data[s]&254|n[i>>>3]>>>7-(i&7)&1}return sr.PNG.sync.write(r,{colorType:6,inputColorType:6,bitDepth:8})}function lr(t){let e=zr(t),r=Xn(e.data,e.width,e.height),n=Buffer.alloc(32);for(let o=0;o<256;o++){let i=0;for(let a=0;a<Qe;a++)i+=e.data[r[o*Qe+a]*4]&1;i>=2&&(n[o>>>3]|=1<<7-(o&7))}return n.subarray(0,4).toString("ascii")!=="AWF2"?kf(e):Ua(n,"AWF2")}function kf(t){return Ua(Pa(t),"AWF1")}function Ua(t,e){if(t.subarray(0,4).toString("ascii")!==e||t.readUInt16LE(4)!==0||t[6]<1||t[6]>Ae)throw new Error("Invalid luminance frame payload");let r=t.subarray(pt,pt+t[6]);if(!Nt(r).subarray(0,4).equals(t.subarray(7,11)))throw new Error("Luminance frame integrity failure");return r}var ro="AMW1DATA",Le=128,vf=new Set([".html",".htm",".js",".mjs",".css",".json",".xml",".svg",".txt",".map",".php",".asp",".aspx",".jsp"]),je=t=>Pr(Y(t)),De=(t,e)=>{let r=(0,C.relative)(t,e);return!r||!r.startsWith("..")&&!r.includes(":")};async function Ut(t){try{return await(0,A.stat)(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function If(t,e,r,n,o="append",i=0){let a=Buffer.alloc(Le);return a.write(ro,0,"ascii"),a.writeUInt16LE(o==="append"?1:2,8),a.writeUInt16LE(Le,10),o!=="append"&&(a.writeUInt8(o==="png-chunk"?1:2,12),a.writeBigUInt64LE(BigInt(i),96)),a.writeBigUInt64LE(BigInt(t),16),a.writeBigUInt64LE(BigInt(e),24),r.copy(a,32),n.copy(a,64),a}function _f(t,e){if(t.length!==Le||t.toString("ascii",0,8)!==ro||![1,2].includes(t.readUInt16LE(8))||t.readUInt16LE(10)!==Le)throw new Error("Invalid data carrier footer");let r=t.readUInt16LE(8),n=r===1?"append":t[12]===1?"png-chunk":t[12]===2?"mp4-uuid":null;if(!n||(r===1?t.subarray(12,16).some(Boolean)||t.subarray(96).some(Boolean):t.subarray(13,16).some(Boolean)||t.subarray(104).some(Boolean)))throw new Error("Invalid data carrier footer");let o=Number(t.readBigUInt64LE(16)),i=Number(t.readBigUInt64LE(24)),a=r===2?Number(t.readBigUInt64LE(96)):o;if(!Number.isSafeInteger(o)||!Number.isSafeInteger(i)||!Number.isSafeInteger(a)||a>o||n==="mp4-uuid"&&a!==o||o+i+Cn(n)+Le!==e)throw new Error("Invalid data carrier layout");return{originalLength:o,dataLength:i,insertOffset:a,dataStart:a+(n==="append"?0:8+(n==="mp4-uuid"?16:0)),mode:n,originalHash:t.subarray(32,64),dataHash:t.subarray(64,96)}}async function Zn(t,e,r){let n=(0,K.createHash)("sha256");if(r)for await(let o of(0,he.createReadStream)(t,{start:e,end:e+r-1}))n.update(o);return n.digest()}async function eo(t,e=!1){let r=(await(0,A.stat)(t)).size,n=Buffer.alloc(0);if(r>=Le){let s=await(0,A.open)(t,"r");try{n=Buffer.alloc(Le);let{bytesRead:l}=await s.read(n,0,Le,r-Le);if(l!==Le)throw new Error("Incomplete data carrier footer")}finally{await s.close()}}if(n.toString("ascii",0,8)!==ro){if(!e)throw new Error("Invalid data carrier footer");return{originalLength:r,dataLength:0,mode:"append",originalHash:await Zn(t,0,r),packed:!1}}let o=_f(n,r),i=(0,K.createHash)("sha256"),a=o.mode==="png-chunk"?[[0,o.insertOffset],[o.dataStart+o.dataLength+4,o.originalLength-o.insertOffset]]:[[0,o.originalLength]];for(let[s,l]of a)if(l)for await(let c of(0,he.createReadStream)(t,{start:s,end:s+l-1}))i.update(c);if(!i.digest().equals(o.originalHash)||!(await Zn(t,o.dataStart,o.dataLength)).equals(o.dataHash))throw new Error("Data carrier integrity failure");if(o.mode!=="append"){let s=await(0,A.open)(t,"r");try{let l=Buffer.alloc(Cn(o.mode)-(o.mode==="png-chunk"?4:0));if(await s.read(l,0,l.length,o.insertOffset),!l.subarray(0,Zt(o.mode,o.dataLength).length).equals(Zt(o.mode,o.dataLength)))throw new Error("Embedded carrier header failure");if(o.mode==="png-chunk"){let c=It(Dr);if(o.dataLength)for await(let u of(0,he.createReadStream)(t,{start:o.dataStart,end:o.dataStart+o.dataLength-1}))c=It(u,c);let f=Buffer.alloc(4);if(await s.read(f,0,4,o.dataStart+o.dataLength),f.readUInt32BE()!==(c^4294967295)>>>0)throw new Error("PNG carrier chunk integrity failure")}}finally{await s.close()}}return{...o,packed:!0}}async function Qn(t,e){let r=await(0,A.lstat)(e);if(!r.isFile()||r.isSymbolicLink()||!De(t,(0,he.realpathSync)(e)))throw new Error(`Overlay file leaves its directory: ${e}`);return e}async function Cf(t,e){async function r(n){for(let o of await(0,A.readdir)(n,{withFileTypes:!0})){let i=(0,C.join)(n,o.name);if(o.isSymbolicLink())throw new Error(`Overlay contains a symlink: ${i}`);if(o.isDirectory())await r(i);else if(!o.isFile()||!e.delete((0,C.relative)(t,i).replaceAll("\\","/")))throw new Error(`Overlay contains a non-carrier file: ${i}`)}}if(await r(t),e.size)throw new Error(`Overlay is missing a carrier: ${[...e][0]}`)}async function Sf(t,e,r,n){let o=(0,K.createHash)("sha256");if(r){let i=new $a.Transform({transform(a,s,l){o.update(a),l(null,a)}});await(0,to.pipeline)((0,he.createReadStream)(t,{start:0,end:r-1}),i,(0,he.createWriteStream)(e,{flags:"wx"}))}else await(0,A.writeFile)(e,Buffer.alloc(0),{flag:"wx"});if(!o.digest().equals(n))throw new Error("Carrier changed while packing")}function Bf(t,e,r,n,o){let i=r,a;if(o){let s=Vt(t,e,r.length);a=(0,K.createHmac)("sha256",n.key).update("AMW1-NONCE\0").update(s).update(Y(r)).digest().subarray(0,12);let l=(0,K.createCipheriv)("aes-256-gcm",n.key,a);l.setAAD(s),i=Buffer.concat([l.update(r),l.final(),l.getAuthTag()])}return{chunk:i,nonce:a}}function Tf(t,e=null,r=null){let n=e?(0,K.createHmac)("sha256",e).update("AMW1-PRIVATE-ENCODING\0"):(0,K.createHash)("sha256").update("AMW1-SITE-ENCODING\0");r&&n.update(Buffer.from(r,"hex"));for(let o of[...t].sort((i,a)=>i.path<a.path?-1:i.path>a.path?1:0))n.update(o.path).update("\0").update(o.contentHash??je(o.bytes)).update(`
|
|
17
|
-
`);return n.digest()}function Mf(t,e,r,n,o,i){let a=Bf(t,e,r,n,o),s=Y(Buffer.from(`AMW1-SITE-CTR\0${t.path}\0${e}`)).subarray(0,16),l=(0,K.createCipheriv)("aes-256-ctr",i,s);return{chunk:Buffer.concat([l.update(a.chunk),l.final()]),nonce:a.nonce}}function Lf(t,e,r,n){if(!n)return r;let o=Y(Buffer.from(`AMW1-SITE-CTR\0${t.path}\0${e}`)).subarray(0,16),i=(0,K.createDecipheriv)("aes-256-ctr",n,o);return Buffer.concat([i.update(r),i.final()])}async function cr(t,e){let r=0;for(;r<e.length;){let n=await t.write(e,r,e.length-r,null);if(!n.bytesWritten)throw new Error("Incomplete carrier write");r+=n.bytesWritten}}async function Yr({siteDir:t,appDir:e,outDir:r,document:n,carriers:o,chunkSize:i,encryptionKey:a,keyId:s,protected:l,downloads:c,placements:f,indexDelivery:u="hosted",indexKey:h,encodingSalt:p}){if(t=(0,C.resolve)(t),e=(0,C.resolve)(e),r=(0,C.resolve)(r),!["hosted","external"].includes(u))throw new Error("Invalid index delivery");if(u==="external"&&(!Buffer.isBuffer(h)||h.length!==32))throw new Error("External index requires a random 256-bit index key");if(p!==void 0&&(!/^[0-9a-f]{64}$/.test(p)||u!=="hosted"))throw new Error("Hosted encoding salt must be 64 lowercase hex characters");if([t,e].some(w=>De(w,r)||De(r,w)))throw new Error("Overlay must be separate from inputs");if(await Ut(r))throw new Error("Overlay output already exists");if(!Array.isArray(o)||!o.length)throw new Error("Specify existing carrier paths");let d=o.map(w=>typeof w=="string"?{path:w,mode:"append"}:w);if(d.some(w=>!w||typeof w.path!="string"||!["append","png-chunk","mp4-uuid","png-pixels","wav-tones","frame-luma"].includes(w.mode)||w.maxChunks!==void 0&&(w.mode!=="wav-tones"||!Number.isInteger(w.maxChunks)||w.maxChunks<1||w.maxChunks>32))||new Set(d.map(w=>w.path)).size!==d.length)throw new Error("Specify unique carrier paths and valid modes");if(l!==void 0&&(!a||!Array.isArray(l)||!l.length||l.some(w=>typeof w!="string"||!w||w.startsWith("/")||w.includes("\\")||w.replace(/\/$/,"").split("/").some(T=>!T||T==="."||T===".."))))throw new Error("Invalid protected resource paths");if(c!==void 0&&(!Array.isArray(c)||new Set(c).size!==c.length||c.some(w=>typeof w!="string"||!Kt(`/amoosed.com/app/${w}`)||w==="index.html"||w==="favicon.ico")))throw new Error("Invalid download resource paths");let g=new Set(c),m=(0,he.realpathSync)(t),E=(0,C.join)(t,"favicon.ico");if((await(0,A.lstat)(E)).isSymbolicLink()||!De(m,(0,he.realpathSync)(E)))throw new Error("Favicon must be inside the site build");let _=await(0,A.readFile)(E),P=_.subarray(-128,-120).toString("ascii")==="AMW1TAIL"?ge(_).carrier:_,S=[];for(let{path:w,mode:T,maxChunks:oe}of d){if(typeof w!="string"||w.startsWith("/")||w.includes("\\")||w.split("/").some(M=>!M||M==="."||M==="..")||w==="favicon.ico"||w.startsWith("amoosed.com/")||vf.has((0,C.extname)(w).toLowerCase()))throw new Error(`Unsafe carrier path: ${w}`);if(["png-chunk","png-pixels","frame-luma"].includes(T)&&(0,C.extname)(w).toLowerCase()!==".png"||T==="mp4-uuid"&&![".mp4",".m4v"].includes((0,C.extname)(w).toLowerCase())||T==="wav-tones"&&(0,C.extname)(w).toLowerCase()!==".wav")throw new Error(`Carrier mode does not match media path: ${w}`);let D=(0,C.resolve)(t,w);if((await(0,A.lstat)(D)).isSymbolicLink()||!De(m,(0,he.realpathSync)(D)))throw new Error(`Carrier leaves site build: ${w}`);if(!(await(0,A.stat)(D)).isFile())throw new Error(`Carrier is not a file: ${w}`);let ve=await eo(D,!0);if(ve.packed&&ve.mode!=="append")throw new Error(`Use the original media file when rebuilding embedded carrier: ${w}`);let y=["append","png-pixels","wav-tones","frame-luma"].includes(T)?{insertOffset:ve.originalLength}:await Qt(D,T);if(T==="png-pixels"&&(await(0,A.stat)(D)).size>64*1024*1024)throw new Error(`Pixel carrier file is too large: ${w}`);let H;if(T==="png-pixels"){let M=await(0,A.readFile)(D);H=Hr(M);try{throw Ne(M),new Error(`Use the original PNG when rebuilding pixel carrier: ${w}`)}catch(ce){if(ce.message!=="No AmoosedWeb pixel payload")throw ce}}if(T==="frame-luma"){if((await(0,A.stat)(D)).size>64*1024*1024)throw new Error(`Frame carrier file is too large: ${w}`);try{throw lr(await(0,A.readFile)(D)),new Error(`Use the original PNG when rebuilding frame carrier: ${w}`)}catch(M){if(M.message.startsWith("Use the original PNG"))throw M}}S.push({url:`/${w}`,path:D,...ve,mode:T,insertOffset:y.insertOffset,...T==="png-pixels"?{capacity:H,pixelChunks:[],dataLength:0}:{}}),T==="wav-tones"&&Object.assign(S.at(-1),{audioChunks:[],dataLength:0,maxChunks:oe??32}),T==="frame-luma"&&Object.assign(S.at(-1),{frameChunk:null,dataLength:0})}if(u==="external"&&["png-pixels","wav-tones","frame-luma"].includes(S[0].mode))throw new Error("External index needs a byte-addressable first carrier");let v=[];async function R(w){for(let T of(await(0,A.readdir)(w,{withFileTypes:!0})).sort((oe,D)=>oe.name<D.name?-1:1)){if(T.isSymbolicLink())throw new Error("Symlinks are not allowed in app build");let oe=(0,C.join)(w,T.name);if(T.isDirectory())await R(oe);else if(T.isFile()){let D=(0,C.relative)(e,oe).replaceAll("\\","/");if(D.endsWith(".map"))throw new Error("Source maps are not allowed in app build");let ve=(0,C.extname)(D).slice(1).toLowerCase(),y={html:"text/html; charset=utf-8",css:"text/css; charset=utf-8",js:"text/javascript; charset=utf-8",mjs:"text/javascript; charset=utf-8",json:"application/json",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",ico:"image/x-icon",wasm:"application/wasm",woff:"font/woff",woff2:"font/woff2",zip:"application/zip",mp4:"video/mp4",m4v:"video/mp4"}[ve]||"application/octet-stream",H=l?.some(de=>de.endsWith("/")?D.startsWith(de):D===de),M=(await(0,A.stat)(oe)).size,ce=`/amoosed.com/app/${D}`;if(!Kt(ce)||!Number.isSafeInteger(M)||M<1||M>1024*1024*1024)throw new Error(`Invalid or empty app asset: ${D}`);v.push({name:D,source:oe,path:ce,mime:y,length:M,...g.has(D)?{download:!0}:{},...l?{protected:H}:{}})}}}if(await R(e),c?.some(w=>!v.some(T=>T.name===w)))throw new Error("Download resource path matches no asset");let $={title:n.title,icon:"/amoosed.com/app/favicon.ico"},j=v.find(w=>w.path===$.icon);if(j&&l?.some(w=>w==="favicon.ico"))throw new Error("App favicon must be public");let ne=ni(j?await(0,A.readFile)(j.source):P,$.title);if(j?(j.bytes=ne,j.length=ne.length,j.protected=a?!1:void 0):v.push({name:"favicon.ico",path:$.icon,mime:"image/x-icon",length:ne.length,bytes:ne,...a?{protected:!1}:{}}),v.sort((w,T)=>w.name<T.name?-1:w.name>T.name?1:0),v.length<1||v.length>4096||!v.some(w=>w.path==="/amoosed.com/app/index.html"))throw new Error("Invalid app asset list");if(f!==void 0&&(f===null||typeof f!="object"||Array.isArray(f)||Object.entries(f).some(([w,T])=>!v.some(oe=>oe.name===w)||typeof T!="string"||!S.some(oe=>oe.url===`/${T}`))))throw new Error("Placement must map an app asset to a selected carrier");if(l?.some(w=>!v.some(T=>w.endsWith("/")?T.path.slice(17).startsWith(w):T.path===`/amoosed.com/app/${w}`)))throw new Error("Protected resource path matches no assets");let W=a?{key:a,keyId:s}:null;for(let w of v)w.contentHash=w.bytes?je(w.bytes):(await Zn(w.source,0,w.length)).toString("hex");let le=Tf(v,u==="external"?h:null,p),G=i??1024*1024;if(!Number.isSafeInteger(G)||G<1||G>4*1024*1024||W&&(!Buffer.isBuffer(W.key)||W.key.length!==32||typeof W.keyId!="string"||!/^[A-Za-z0-9._-]{1,64}$/.test(W.keyId)))throw new Error("Invalid content key, key ID, or chunk size");await(0,A.mkdir)((0,C.dirname)(r),{recursive:!0});let Q=await(0,A.mkdtemp)((0,C.join)((0,C.dirname)(r),".amw-stage-")),z=[];try{if(!De((0,C.dirname)(r),Q)||Q===(0,C.dirname)(r))throw new Error("Unsafe staging path");let w=[],T=0;for(let y of v){let H=f?.[y.name],M=!!W&&y.protected!==!1,ce=(0,K.createHash)("sha256"),de=[],pe=y.bytes?null:await(0,A.open)(y.source,"r");try{for(let Oe=0,Br=0;Oe<y.length;Br++){let I;for(let fe=0;fe<(H?1:S.length);fe++){let be=H?S.find(Kl=>Kl.url===`/${H}`):S[T++%S.length];if(!(y.path===$.icon&&["wav-tones","frame-luma"].includes(be.mode))&&(!["png-pixels","wav-tones","frame-luma"].includes(be.mode)||be.mode==="png-pixels"&&be.capacity-be.dataLength>(M?16:0)||be.mode==="wav-tones"&&be.audioChunks.length<be.maxChunks&&4096-be.dataLength>(M?16:0)||be.mode==="frame-luma"&&!be.frameChunk&&21>(M?16:0))){I=be;break}}if(!I)throw new Error(H?`Pinned carrier capacity exhausted: ${y.name} \u2192 ${H}`:"Media carrier capacity exhausted");let zl=I.mode==="png-pixels"?I.capacity-I.dataLength-(M?16:0):I.mode==="wav-tones"?Math.min(128,4096-I.dataLength)-(M?16:0):I.mode==="frame-luma"?21-(M?16:0):G,ye=Buffer.alloc(Math.min(G,zl,y.length-Oe)),at=0;for(;at<ye.length;){let{bytesRead:fe}=pe?await pe.read(ye,at,ye.length-at,Oe+at):{bytesRead:y.bytes.copy(ye,at,Oe+at,Oe+ye.length)};if(!fe)throw new Error(`App asset changed while packing: ${y.name}`);at+=fe}ce.update(ye);let{chunk:Z,nonce:Tr}=Mf(y,Br,ye,W,M,le);if(Oe+=ye.length,I.mode==="png-pixels"){let fe=I.dataLength;I.pixelChunks.push(Z),I.dataLength+=Z.length,z.includes(I)||z.push(I),de.push({url:I.url,codec:"png-lsb1",offset:fe,length:Z.length,sha256:je(Z),...M?{nonce:Tr.toString("hex"),plainLength:ye.length}:{}});continue}if(I.mode==="wav-tones"){let fe=I.dataLength;I.audioChunks.push(Z),I.dataLength+=Z.length,z.includes(I)||z.push(I),de.push({url:I.url,codec:"wav-4fsk1",offset:fe,length:Z.length,sha256:je(Z),...M?{nonce:Tr.toString("hex"),plainLength:ye.length}:{}});continue}if(I.mode==="frame-luma"){I.frameChunk=Z,I.dataLength=Z.length,z.push(I),de.push({url:I.url,codec:"frame-luma2",offset:0,length:Z.length,sha256:je(Z),...M?{nonce:Tr.toString("hex"),plainLength:ye.length}:{}});continue}if(!I.output){let fe=(0,C.join)(Q,I.url.slice(1));await(0,A.mkdir)((0,C.dirname)(fe),{recursive:!0}),I.mode==="append"?await Sf(I.path,fe,I.originalLength,I.originalHash):(await(0,to.pipeline)((0,he.createReadStream)(I.path,{start:0,end:I.insertOffset-1}),(0,he.createWriteStream)(fe,{flags:"wx"})),await(0,A.appendFile)(fe,Zt(I.mode)),I.crc=I.mode==="png-chunk"?It(Dr):void 0),I.output=await(0,A.open)(fe,"a"),I.dataHash=(0,K.createHash)("sha256"),I.dataLength=0,I.dataStart=I.insertOffset+(I.mode==="append"?0:I.mode==="png-chunk"?8:24),z.push(I)}let Yl=I.dataStart+I.dataLength;await cr(I.output,Z),I.dataHash.update(Z),I.mode==="png-chunk"&&(I.crc=It(Z,I.crc)),I.dataLength+=Z.length,de.push({url:I.url,offset:Yl,length:Z.length,sha256:je(Z),...M?{nonce:Tr.toString("hex"),plainLength:ye.length}:{}})}if(pe&&(await pe.stat()).size!==y.length)throw new Error(`App asset changed while packing: ${y.name}`)}finally{pe&&await pe.close()}let Yo=ce.digest("hex");if(Yo!==y.contentHash)throw new Error(`App asset changed while packing: ${y.name}`);if(w.push({path:y.path,mime:y.mime,length:y.length,sha256:Yo,...y.protected===void 0?{}:{access:M?"members":"public"},...y.download?{delivery:"download"}:{},parts:de}),y.path===$.icon){let Oe=S.findIndex(Br=>["wav-tones","frame-luma"].includes(Br.mode));Oe>=0&&(T=Oe)}}w.sort((y,H)=>y.path<H.path?-1:y.path>H.path?1:0);let oe={};for(let y of z.filter(H=>H.mode==="wav-tones")){if((await(0,A.stat)(y.path)).size>128*1024*1024)throw new Error("Audio cover file is too large");y.audioResult=Jn(y.audioChunks,await(0,A.readFile)(y.path)),oe[y.url]=y.audioResult.manifest}let D={launch:"/amoosed.com/boot.html",entry:"/amoosed.com/app/index.html",resources:w,identity:$,encoding:{algorithm:"AES-256-CTR",key:le.toString("hex")},...Object.keys(oe).length?{audioCarriers:oe}:{},...W?{encryption:{algorithm:"AES-256-GCM",keyId:W.keyId}}:{}};lt(D);let ve;if(u==="external"){let y=z[0],H=Ye({...n,webApp:D});if(H.length>16*1024*1024)throw new Error("Private index is too large");let M=y.dataStart+y.dataLength,ce=(0,K.createHmac)("sha256",h).update("AMW1-INDEX-NONCE\0").update(y.url).update("\0").update(String(M)).update("\0").update(Y(H)).digest().subarray(0,12),de=(0,K.createCipheriv)("aes-256-gcm",h,ce);de.setAAD(Buffer.from(`AMW1-PRIVATE-INDEX\0${y.url}\0${M}`));let pe=Buffer.concat([de.update(H),de.final(),de.getAuthTag()]);await cr(y.output,pe),y.dataHash.update(pe),y.mode==="png-chunk"&&(y.crc=It(pe,y.crc)),y.dataLength+=pe.length,ve=ct(P,Ye({title:n.title,blocks:[],privateIndex:{algorithm:"AES-256-GCM",url:y.url,offset:M,length:pe.length,sha256:je(pe),nonce:ce.toString("hex"),key:h.toString("hex")}}))}else ve=ct(P,Ye({...n,webApp:D}));for(let y of z){if(y.mode==="png-pixels"){await(0,A.writeFile)((0,C.join)(Q,y.url.slice(1)),Bt(await(0,A.readFile)(y.path),Buffer.concat(y.pixelChunks)),{flag:"wx"});continue}if(y.mode==="wav-tones"){await(0,A.writeFile)((0,C.join)(Q,y.url.slice(1)),y.audioResult.wav,{flag:"wx"});continue}if(y.mode==="frame-luma"){if((await(0,A.stat)(y.path)).size>64*1024*1024)throw new Error("Frame carrier file is too large");await(0,A.writeFile)((0,C.join)(Q,y.url.slice(1)),Na(await(0,A.readFile)(y.path),y.frameChunk),{flag:"wx"});continue}if(y.mode==="png-chunk"){let H=Buffer.alloc(4);H.writeUInt32BE((y.crc^4294967295)>>>0),await cr(y.output,H);let M=await(0,A.open)(y.path,"r");try{let ce=Buffer.alloc(y.originalLength-y.insertOffset);await M.read(ce,0,ce.length,y.insertOffset),await cr(y.output,ce)}finally{await M.close()}}if(await cr(y.output,If(y.originalLength,y.dataLength,y.originalHash,y.dataHash.digest(),y.mode,y.insertOffset)),await y.output.close(),y.output=null,y.mode!=="append"){let H=await(0,A.open)((0,C.join)(Q,y.url.slice(1)),"r+");try{await H.write(Zt(y.mode,y.dataLength),0,y.mode==="png-chunk"?8:24,y.insertOffset)}finally{await H.close()}}}if(u==="hosted"&&await(0,A.writeFile)((0,C.join)(Q,"favicon.ico"),ve),await Ut(r))throw new Error("Overlay output already exists");return await(0,A.rename)(Q,r),{webApp:D,carrierCount:z.length,indexBytes:ve}}finally{await Promise.allSettled(z.filter(w=>w.output).map(w=>w.output.close())),De((0,C.dirname)(r),Q)&&Q!==(0,C.dirname)(r)&&await Ut(Q)&&await(0,A.rm)(Q,{recursive:!0,force:!0})}}async function fr(t,{key:e,collectResources:r=!0,onChunk:n,carrierOnly:o=!1,indexBytes:i,indexToken:a}={}){if(i&&a)throw new Error("Supply only one index credential");let s=(0,he.realpathSync)(t),l;if(a)l={privateIndex:ut(a)};else{let u=i??await(0,A.readFile)(await Qn(s,(0,C.join)(s,"favicon.ico"))),{payload:h}=ge(u);l=me(h).document}if(l.privateIndex){let u=l.privateIndex,h=await Qn(s,(0,C.join)(s,u.url.slice(1))),p=await eo(h);if(u.offset<p.dataStart||u.offset+u.length>p.dataStart+p.dataLength)throw new Error("Private index outside carrier data");let d=await(0,A.open)(h,"r"),g=Buffer.alloc(u.length);try{let m=0;for(;m<g.length;){let{bytesRead:E}=await d.read(g,m,g.length-m,u.offset+m);if(!E)throw new Error("Private index is incomplete");m+=E}}finally{await d.close()}if(je(g)!==u.sha256)throw new Error("Private index integrity failure");try{let m=(0,K.createDecipheriv)("aes-256-gcm",Buffer.from(u.key,"hex"),Buffer.from(u.nonce,"hex"));m.setAAD(Buffer.from(`AMW1-PRIVATE-INDEX\0${u.url}\0${u.offset}`)),m.setAuthTag(g.subarray(-16));let E=Buffer.concat([m.update(g.subarray(0,-16)),m.final()]);l=me(E).document}catch{throw new Error("Private index key or authentication failed")}if(l.privateIndex)throw new Error("Nested private index is not supported")}let c=lt(l.webApp);if(e&&(!Buffer.isBuffer(e)||e.length!==32))throw new Error("Invalid content key");let f=new Map;try{for(let d of c.resources.flatMap(g=>g.parts)){if(f.has(d.url))continue;let g=await Qn(s,(0,C.join)(s,d.url.slice(1)));if(d.codec==="png-lsb1"){if((await(0,A.stat)(g)).size>64*1024*1024)throw new Error("Pixel carrier file is too large");f.set(d.url,{pixelData:Ne(await(0,A.readFile)(g))})}else if(d.codec==="wav-4fsk1"){if((await(0,A.stat)(g)).size>128*1024*1024)throw new Error("Audio carrier file is too large");f.set(d.url,{audioData:Gr(await(0,A.readFile)(g),c.audioCarriers?.[d.url])})}else if(d.codec==="frame-luma1"||d.codec==="frame-luma2"){if((await(0,A.stat)(g)).size>64*1024*1024)throw new Error("Frame carrier file is too large");f.set(d.url,{frameData:lr(await(0,A.readFile)(g))})}else{let m=await eo(g);f.set(d.url,{...m,file:await(0,A.open)(g,"r")})}}o&&await Cf(s,new Set([...i||a?[]:["favicon.ico"],...[...f.keys()].map(d=>d.slice(1))]));let u=r?new Map:null,h=0,p=0;for(let d of c.resources){let g=st(c,d);g&&h++;let m=r?[]:null,E=c.identity?.icon===d.path?[]:null,_=(0,K.createHash)("sha256"),P=0;for(let[S,v]of d.parts.entries()){let R=f.get(v.url),$;if(["png-lsb1","wav-4fsk1","frame-luma1","frame-luma2"].includes(v.codec)){let W=v.codec==="png-lsb1"?R.pixelData:v.codec==="wav-4fsk1"?R.audioData:R.frameData;if(!W||v.offset+v.length>W.length)throw new Error("Part outside media payload");$=W.subarray(v.offset,v.offset+v.length)}else{let{dataStart:W,dataLength:le,file:G}=R,Q=v.offset-W;if(Q<0||Q+v.length>le)throw new Error("Part outside appended data");$=Buffer.alloc(v.length);let z=0;for(;z<$.length;){let{bytesRead:w}=await G.read($,z,$.length-z,v.offset+z);if(!w)throw new Error("Part outside appended data");z+=w}}if(je($)!==v.sha256)throw new Error("Part integrity failure");let j=Lf(d,S,$,c.encoding&&Buffer.from(c.encoding.key,"hex")),ne;if(g&&e)try{let W=Buffer.from(v.nonce,"hex"),le=(0,K.createDecipheriv)("aes-256-gcm",e,W);if(le.setAAD(Vt(d,S,v.plainLength)),le.setAuthTag(j.subarray(-16)),ne=Buffer.concat([le.update(j.subarray(0,-16)),le.final()]),ne.length!==v.plainLength)throw new Error("Plaintext length mismatch")}catch{throw new Error("Content key or authentication failed")}else g||(ne=j);ne&&(_.update(ne),P+=ne.length,m&&m.push(ne),E&&E.push(ne),n&&await n(d,ne,S))}if(!(g&&!e)){if(P!==d.length||_.digest("hex")!==d.sha256)throw new Error("Resource integrity failure");if(E){let S=me(ge(Buffer.concat(E)).payload).document;if(S.title!==c.identity.title||S.webApp)throw new Error("App favicon identity mismatch")}p++,u&&u.set(d.path,Buffer.concat(m))}}return{document:l,resources:u?.size?u:null,encrypted:!!c.encryption,resourceCount:c.resources.length,protectedCount:h,verifiedCount:p}}finally{await Promise.all([...f.values()].filter(u=>u.file).map(u=>u.file.close()))}}async function ja(t,e,{key:r,indexBytes:n,indexToken:o}={}){if(e=(0,C.resolve)(e),await Ut(e))throw new Error("Unpack output already exists");await(0,A.mkdir)((0,C.dirname)(e),{recursive:!0});let i=await(0,A.mkdtemp)((0,C.join)((0,C.dirname)(e),".amw-unpack-"));try{if(!De((0,C.dirname)(e),i)||i===(0,C.dirname)(e))throw new Error("Unsafe staging path");let a=await fr(t,{key:r,indexBytes:n,indexToken:o,collectResources:!1,carrierOnly:!0,onChunk:async(s,l,c)=>{let f=(0,C.join)(i,s.path.slice(17));c===0?(await(0,A.mkdir)((0,C.dirname)(f),{recursive:!0}),await(0,A.writeFile)(f,l,{flag:"wx"})):await(0,A.appendFile)(f,l)}});if(a.protectedCount&&!r)throw new Error("Content key required to unpack encrypted bundle");if(await Ut(e))throw new Error("Unpack output already exists");return await(0,A.rename)(i,e),a.verifiedCount}finally{De((0,C.dirname)(e),i)&&i!==(0,C.dirname)(e)&&await Ut(i)&&await(0,A.rm)(i,{recursive:!0,force:!0})}}var Kr=require("node:fs/promises"),ur=require("node:path");async function Pf(t,e){let r=e&&new Set(e);if(r&&r.size!==e.length)throw new Error("Duplicate release file rule");async function n(o){for(let i of await(0,Kr.readdir)(o,{withFileTypes:!0})){let a=(0,ur.join)(o,i.name);if(i.isSymbolicLink())throw new Error(`Release contains a symlink: ${a}`);if(i.isDirectory())await n(a);else{if(!i.isFile())throw new Error(`Release contains a non-file: ${a}`);if(i.name.toLowerCase().endsWith(".map"))throw new Error(`Release contains a source map: ${a}`);if(r&&!r.delete((0,ur.relative)(t,a).replaceAll("\\","/")))throw new Error(`Unexpected release file: ${a}`)}}}if(await n(t),r?.size)throw new Error(`Missing release file: ${[...r][0]}`)}async function Vr(t,e,{indexBytes:r,indexToken:n}={}){let o=await fr(t,{collectResources:!1,indexBytes:r,indexToken:n});for(let i of o.document.webApp.resources){let a=(0,ur.join)(t,i.path.slice(1));try{throw await(0,Kr.lstat)(a),new Error(`App resource was deployed as a separate file: ${i.path}`)}catch(s){if(s.code!=="ENOENT")throw s}}return await Pf(t,e),o.resourceCount}var b=require("node:fs/promises"),x=require("node:path"),Ka=require("node:zlib"),mt=require("node:crypto"),$t=require("node:child_process");var Da="AMM1",no=new TextDecoder("utf-8",{fatal:!0}),Fa=/^[a-z0-9][a-z0-9._-]{0,63}$/i;function Ha(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function hr(t,e){if(typeof t!="string"||!Fa.test(t)||!(e instanceof Uint8Array)||e.length!==32)throw new Error("Invalid Amoosed member credential");let r=new TextEncoder().encode(t),n=new Uint8Array(37+r.length);return n.set(new TextEncoder().encode(Da)),n[4]=r.length,n.set(e,5),n.set(r,37),Ha(n)}function dr(t){if(typeof t!="string"||!/^[A-Za-z0-9_-]{51,135}$/.test(t))throw new Error("Invalid Amoosed member key");let e;try{e=Uint8Array.from(atob(t.replaceAll("-","+").replaceAll("_","/")),o=>o.charCodeAt(0))}catch{throw new Error("Invalid Amoosed member key")}if(e.length<38||e.length!==37+e[4]||no.decode(e.subarray(0,4))!==Da||Ha(e)!==t)throw new Error("Invalid Amoosed member key");let r=no.decode(e.subarray(37)),n=e.slice(5,37);if(!Fa.test(r))throw new Error("Invalid Amoosed member key");return{keyId:r,key:n}}function pr(t){return dr(t),`AMWMEMBER1:${t}
|
|
18
|
-
`}function mr(t){let e=typeof t=="string"?t:no.decode(t),r=/^AMWMEMBER1:([A-Za-z0-9_-]{51,135})\r?\n?$/.exec(e);if(!r)throw new Error("Invalid Amoosed member key file");return dr(r[1]),r[1]}function Wa(t,e,r){dr(e);let n=new URL(t);if(n.username||n.password||!(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1"].includes(n.hostname)))throw new Error("Unlock link requires a secure site origin");if(typeof r!="string"||!/^\/amoosed\.com\/app\/[a-zA-Z0-9._~!$&'()+,;=:@/-]+$/.test(r)||r.includes("..")||r.includes("//"))throw new Error("Invalid protected app path");return n.pathname="/amoosed.com/boot.html",n.search=new URLSearchParams({return:r}).toString(),n.hash=`amw-member=${e}`,n.href}var Rf=String.raw`// Copyright (c) 2026 Juhapekka Piiroinen <jp@1337.fi>
|
|
19
|
-
// All Rights Reserved.
|
|
20
|
-
// AmoosedWeb project: https://amoosed.com
|
|
21
|
-
import { existsSync, readdirSync } from 'node:fs';
|
|
22
|
-
import { spawnSync } from 'node:child_process';
|
|
23
|
-
import { dirname, join, resolve } from 'node:path';
|
|
24
|
-
import { fileURLToPath } from 'node:url';
|
|
25
|
-
import { createInterface } from 'node:readline/promises';
|
|
26
|
-
|
|
27
|
-
const root = dirname(fileURLToPath(import.meta.url));
|
|
28
|
-
const namePattern = /^[a-z0-9][a-z0-9-]*$/;
|
|
29
|
-
const branchPattern = /^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;
|
|
30
|
-
|
|
31
|
-
function usage() {
|
|
32
|
-
console.log('Usage: build | release PAGES_PROJECT | publish PAGES_PROJECT [production-branch]');
|
|
33
|
-
console.log('Windows: build.cmd, release.cmd, publish.cmd');
|
|
34
|
-
console.log('macOS/Linux: sh build.sh, sh release.sh, sh publish.sh');
|
|
35
|
-
console.log('Set AMW_CLI to the compiler path if it is not installed or beside this project.');
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function run(command, args, options = {}) {
|
|
39
|
-
const result = spawnSync(command, args, { cwd: root, stdio: 'inherit',
|
|
40
|
-
shell: process.platform === 'win32' && /\.cmd$/i.test(command), ...options });
|
|
41
|
-
if (result.error || result.status !== 0)
|
|
42
|
-
throw new Error(command + ' failed: ' + (result.error?.message || 'exit ' + result.status));
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function compiler() {
|
|
46
|
-
const selected = process.env.AMW_CLI;
|
|
47
|
-
const local = selected ? resolve(root, selected) : [join(root, 'amw.cjs'), join(root, '..', 'amw.cjs')]
|
|
48
|
-
.find(existsSync);
|
|
49
|
-
if (selected && !existsSync(local)) throw new Error('AMW_CLI does not exist: ' + local);
|
|
50
|
-
if (local) return { command: /\.[cm]?js$/i.test(local) ? process.execPath : local,
|
|
51
|
-
prefix: /\.[cm]?js$/i.test(local) ? [local] : [] };
|
|
52
|
-
return { command: process.platform === 'win32' ? 'amw.cmd' : 'amw', prefix: [] };
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function amw(args) {
|
|
56
|
-
const cli = compiler();
|
|
57
|
-
run(cli.command, [...cli.prefix, ...args]);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function nextOutput(parent, prefix) {
|
|
61
|
-
const directory = join(root, parent);
|
|
62
|
-
const existing = existsSync(directory) ? new Set(readdirSync(directory)) : new Set();
|
|
63
|
-
for (let n = 1; n < 10000; n++) {
|
|
64
|
-
const name = prefix + '-' + String(n).padStart(4, '0');
|
|
65
|
-
if (!existing.has(name)) return parent + '/' + name;
|
|
66
|
-
}
|
|
67
|
-
throw new Error('No unused output directory is available');
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
function currentBranch() {
|
|
71
|
-
const result = spawnSync('git', ['branch', '--show-current'], { cwd: root, encoding: 'utf8' });
|
|
72
|
-
return result.status === 0 && result.stdout.trim() || 'main';
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
async function projectExists(projectName) {
|
|
76
|
-
console.log('\nChecking Cloudflare Pages projects...');
|
|
77
|
-
try { run(process.platform === 'win32' ? 'npx.cmd' : 'npx', ['wrangler', 'pages', 'project', 'list']); }
|
|
78
|
-
catch {
|
|
79
|
-
console.log('Project listing failed. Sign in to Cloudflare in the browser Wrangler opens.');
|
|
80
|
-
run(process.platform === 'win32' ? 'npx.cmd' : 'npx', ['wrangler', 'login']);
|
|
81
|
-
run(process.platform === 'win32' ? 'npx.cmd' : 'npx', ['wrangler', 'pages', 'project', 'list']);
|
|
82
|
-
}
|
|
83
|
-
if (!process.stdin.isTTY) throw new Error('Publishing needs an interactive terminal for Pages project confirmation');
|
|
84
|
-
const input = createInterface({ input: process.stdin, output: process.stdout });
|
|
85
|
-
try {
|
|
86
|
-
while (true) {
|
|
87
|
-
const answer = (await input.question('Is "' + projectName + '" listed above? [y/n] ')).trim().toLowerCase();
|
|
88
|
-
if (answer === 'y') return true;
|
|
89
|
-
if (answer === 'n') return false;
|
|
90
|
-
}
|
|
91
|
-
} finally { input.close(); }
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
async function main() {
|
|
95
|
-
const [mode, projectName, requestedBranch, extra] = process.argv.slice(2);
|
|
96
|
-
if (mode === '--help' || mode === '-h') { usage(); return; }
|
|
97
|
-
if (mode === 'build' && !projectName) {
|
|
98
|
-
const output = nextOutput('builds', 'local');
|
|
99
|
-
console.log('Building ' + output + '...');
|
|
100
|
-
amw(['build-project', '.', output]);
|
|
101
|
-
// build-project verifies the merged site, including an external index when present.
|
|
102
|
-
console.log('Ready to preview. Run: amw serve ' + output);
|
|
103
|
-
return;
|
|
104
|
-
}
|
|
105
|
-
if ((mode !== 'release' && mode !== 'publish') || !namePattern.test(projectName || '') || extra ||
|
|
106
|
-
mode === 'release' && requestedBranch) {
|
|
107
|
-
usage(); throw new Error('Expected a Pages project name using lowercase letters, numbers, and hyphens');
|
|
108
|
-
}
|
|
109
|
-
const branch = requestedBranch || currentBranch();
|
|
110
|
-
if (!branchPattern.test(branch) || branch.split('/').some(part => part === '.' || part === '..'))
|
|
111
|
-
throw new Error('Invalid production branch: ' + branch);
|
|
112
|
-
const output = nextOutput('distribution', 'release');
|
|
113
|
-
console.log('Packaging ' + output + ' for Pages project ' + projectName + '...');
|
|
114
|
-
amw(['package-pages', '.', output, projectName]);
|
|
115
|
-
amw(['verify-managed', output]);
|
|
116
|
-
amw(['verify-backup', output]);
|
|
117
|
-
console.log('Verified release: ' + output + '/pages');
|
|
118
|
-
console.log('Private snapshot and credentials remain outside pages/.');
|
|
119
|
-
if (mode === 'release') {
|
|
120
|
-
console.log('No upload was started. Read ' + output + '/DEPLOY.txt or run publish.');
|
|
121
|
-
return;
|
|
122
|
-
}
|
|
123
|
-
if (!await projectExists(projectName)) {
|
|
124
|
-
console.log('Creating Pages project ' + projectName + ' with production branch ' + branch + '...');
|
|
125
|
-
run(process.platform === 'win32' ? 'npx.cmd' : 'npx',
|
|
126
|
-
['wrangler', 'pages', 'project', 'create', projectName, '--production-branch', branch]);
|
|
127
|
-
}
|
|
128
|
-
console.log('Deploying verified pages/ on branch ' + branch + '...');
|
|
129
|
-
amw(['deploy-pages', output, projectName, branch]);
|
|
130
|
-
console.log('Published. Check the deployment and custom domain in Cloudflare Pages.');
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
main().catch(error => { console.error('Stopped: ' + error.message); process.exitCode = 1; });
|
|
134
|
-
`,Of=t=>`@echo off\r
|
|
135
|
-
rem Copyright (c) 2026 Juhapekka Piiroinen <jp@1337.fi>\r
|
|
136
|
-
rem All Rights Reserved.\r
|
|
137
|
-
rem AmoosedWeb project: https://amoosed.com\r
|
|
138
|
-
node "%~dp0amw-pipeline.mjs" ${t} %*\r
|
|
139
|
-
exit /b %errorlevel%\r
|
|
140
|
-
`,Nf=t=>`#!/bin/sh
|
|
141
|
-
# Copyright (c) 2026 Juhapekka Piiroinen <jp@1337.fi>
|
|
142
|
-
# All Rights Reserved.
|
|
143
|
-
# AmoosedWeb project: https://amoosed.com
|
|
144
|
-
exec node "$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)/amw-pipeline.mjs" ${t} "$@"
|
|
145
|
-
`,qa={"amw-pipeline.mjs":Rf,...Object.fromEntries(["build","release","publish"].flatMap(t=>[[t+".cmd",Of(t)],[t+".sh",Nf(t)]]))};var Uf=["boot.html","boot.js","boot.css","sw.js","download.js"],Ga=(t,e)=>{let r=(0,x.relative)(t,e);return!r||!r.startsWith("..")&&!r.includes(":")};async function q(t){try{return await(0,b.stat)(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function $f(t){let e=4294967295;for(let r of t){e^=r;for(let n=0;n<8;n++)e=e>>>1^(e&1?3988292384:0)}return(e^4294967295)>>>0}function oo(t,e){let r=Buffer.concat([Buffer.from(t,"ascii"),e]),n=Buffer.alloc(r.length+8);return n.writeUInt32BE(e.length,0),r.copy(n,4),n.writeUInt32BE($f(r),n.length-4),n}function so(){let r=Buffer.alloc(172960);for(let o=0;o<160;o++)for(let i=0;i<360;i++){let a=o*1081+1+i*3;r[a]=Math.min(255,22+(i>>2)),r[a+1]=Math.min(255,11+(o>>3)),r[a+2]=8,Math.abs(o-(112-16*Math.sin(i/55)))<3&&(r[a]=255,r[a+1]=146,r[a+2]=57)}let n=Buffer.alloc(13);return n.writeUInt32BE(360,0),n.writeUInt32BE(160,4),n[8]=8,n[9]=2,Buffer.concat([Buffer.from("89504e470d0a1a0a","hex"),oo("IHDR",n),oo("IDAT",(0,Ka.deflateSync)(r)),oo("IEND",Buffer.alloc(0))])}function Va(){let t=Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/l9sAAAAASUVORK5CYII=","base64"),e=Buffer.alloc(22);return e.writeUInt16LE(1,2),e.writeUInt16LE(1,4),e[6]=1,e[7]=1,e.writeUInt16LE(1,10),e.writeUInt16LE(32,12),e.writeUInt32LE(t.length,14),e.writeUInt32LE(22,18),Buffer.concat([e,t])}var Ja={"site/index.html":`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>My regular website</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f3eee7;color:#21180f;font:18px system-ui}main{max-width:720px;padding:40px}h1{font:700 64px Georgia,serif}img{width:100%;border-radius:12px}</style><main><p>ORDINARY WEBSITE</p><h1>My regular website</h1><p>This page stays available to every visitor. Amoosed mode is an optional second experience.</p><img src="/media/scene.png" alt="Orange line on a dark background"></main></html>
|
|
146
|
-
`,"site/robots.txt":`User-agent: *
|
|
147
|
-
Allow: /
|
|
148
|
-
`,"app/index.html":`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Hello from Amoosed mode</title><link rel="stylesheet" href="style.css"><main><p class="eyebrow">AMOOSED MODE</p><h1>Hello, world!</h1><p>This is a small second website. Its HTML, CSS, and JavaScript are carried by the ordinary site\u2019s image file.</p><button id="hello">Say hello</button><p id="result" role="status"></p><p><a href="members/index.html">Visit the members-only example \u2192</a></p></main><script type="module" src="main.js"></script></html>
|
|
149
|
-
`,"app/style.css":`:root{color-scheme:dark}body{margin:0;min-height:100vh;display:grid;place-items:center;background:#080807;color:#f5eee5;font:18px/1.6 system-ui}main{max-width:720px;padding:40px}.eyebrow{color:#ff9a3d;font-size:12px;font-weight:800;letter-spacing:.2em}h1{font:600 clamp(52px,8vw,90px) Georgia,serif}button{padding:14px 20px;border:0;border-radius:6px;background:#ff9a3d;color:#17100b;font:700 15px system-ui;cursor:pointer}
|
|
150
|
-
`,"app/main.js":`document.querySelector("#hello").addEventListener("click",()=>{document.querySelector("#result").textContent="Hello from a carrier-backed JavaScript file!";});
|
|
151
|
-
`,"app/members/index.html":`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Members-only Hello World</title><link rel="stylesheet" href="../style.css"><main><p class="eyebrow">MEMBERS ONLY</p><h1>Welcome, member.</h1><p>This page is encrypted inside the media carrier. Its source is not served as an ordinary website file.</p><p><a href="../index.html">\u2190 Back to the public example</a></p></main></html>
|
|
152
|
-
`,"document.json":JSON.stringify({title:"My Amoosed mode",theme:{background:"#080807",foreground:"#f5eee5",accent:"#ff9a3d"},bootstrap:{title:"Opening my Amoosed mode",theme:{background:"#080807",foreground:"#f5eee5",accent:"#ff9a3d"},blocks:[{type:"heading",text:"Opening the second website"},{type:"paragraph",text:"Loading verified content from existing site media."}]},blocks:[{type:"heading",text:"My Amoosed mode"},{type:"paragraph",text:"A second website carried by existing media files."}]},null,2)+`
|
|
153
|
-
`,"bundle.json":JSON.stringify({document:"document.json",carriers:["media/scene.png"],chunkSize:65536,keyId:"hello-members",protected:["members/"]},null,2)+`
|
|
154
|
-
`,".gitignore":`.amw/
|
|
155
|
-
public/
|
|
156
|
-
builds/
|
|
157
|
-
distribution/
|
|
158
|
-
`,...qa,"README.txt":`MY AMOOSED MODE PROJECT
|
|
159
|
-
|
|
160
|
-
This folder is its own Git repository. The compiler created it with
|
|
161
|
-
git init. Commit the editable source files; .gitignore excludes .amw/
|
|
162
|
-
private keys, public/ outputs, and distribution/ outputs. Never commit
|
|
163
|
-
private keys or a published build as a substitute for source.
|
|
164
|
-
|
|
165
|
-
EDIT: site/ (ordinary site and original binary carriers), app/ (Amoosed
|
|
166
|
-
mode application), document.json (bootstrap), bundle.json (carrier and
|
|
167
|
-
access rules). Keep .amw-template.json under Git but do not hand-edit it;
|
|
168
|
-
it tracks starter file versions for safe template upgrades.
|
|
169
|
-
|
|
170
|
-
After installing a newer compiler, commit or stash all local changes,
|
|
171
|
-
then run: amw update-project .
|
|
172
|
-
The command checks Git and key ignore rules. It updates only unchanged
|
|
173
|
-
starter files, preserving your edited site and app files. Review the Git
|
|
174
|
-
diff, commit the upgrade, and build a NEW distribution directory. Runtime
|
|
175
|
-
files come from the installed compiler on each build. Old compiled output
|
|
176
|
-
is immutable; never patch carrier bytes or runtime files in place.
|
|
177
|
-
|
|
178
|
-
1. Run: amw build-project . public
|
|
179
|
-
2. Run: amw serve public
|
|
180
|
-
3. Open the local site in Chrome and use the Amoosed extension's moose button.
|
|
181
|
-
4. In Amoosed mode, click Say hello. This proves the app JavaScript ran.
|
|
182
|
-
5. Click the members-only link. Enter the content key when asked.
|
|
183
|
-
|
|
184
|
-
EASY BUILD AND RELEASE (Node.js 22 or newer):
|
|
185
|
-
Windows: build.cmd | release.cmd YOUR_PAGES_PROJECT
|
|
186
|
-
macOS/Linux: sh build.sh | sh release.sh YOUR_PAGES_PROJECT
|
|
187
|
-
Build creates a fresh builds/local-0001/ and verifies the site. Preview it
|
|
188
|
-
with: amw serve builds/local-0001
|
|
189
|
-
Release creates a fresh distribution/release-0001/pages/ and verifies both
|
|
190
|
-
the published-file inventory and private source-and-key snapshot. It does
|
|
191
|
-
not upload anything. Later runs use the next free number; old releases stay
|
|
192
|
-
available locally. To publish and get guided Cloudflare login/project setup:
|
|
193
|
-
Windows: publish.cmd YOUR_PAGES_PROJECT [production-branch]
|
|
194
|
-
macOS/Linux: sh publish.sh YOUR_PAGES_PROJECT [production-branch]
|
|
195
|
-
The default branch is this project's current Git branch. For an existing
|
|
196
|
-
Pages project with another production branch, pass it explicitly. These
|
|
197
|
-
scripts look for amw.cjs in this folder or its parent, then for an installed
|
|
198
|
-
amw command. Set AMW_CLI to the compiler path if it is elsewhere. Only the
|
|
199
|
-
verified pages/ folder is uploaded. Configure a custom domain in Cloudflare.
|
|
200
|
-
|
|
201
|
-
To prepare a Cloudflare Pages Direct Upload distribution, run:
|
|
202
|
-
amw package-pages . distribution YOUR_PAGES_PROJECT
|
|
203
|
-
amw verify-managed distribution
|
|
204
|
-
amw verify-backup distribution
|
|
205
|
-
amw deploy-pages distribution YOUR_PAGES_PROJECT
|
|
206
|
-
This makes distribution/pages/ with only verified public site files and
|
|
207
|
-
distribution/DEPLOY.txt with Wrangler login, project creation, and deploy
|
|
208
|
-
commands. Upload ONLY distribution/pages/. The guide stays on your own
|
|
209
|
-
computer. The private keys and shareable credential files remain under
|
|
210
|
-
.amw/, outside the distribution. Use a NEW distribution folder for each
|
|
211
|
-
release. Cloudflare Pages limits each uploaded file to 25 MiB; the
|
|
212
|
-
compiler checks this before the distribution is finalized.
|
|
213
|
-
MANAGED-FILES.json stays beside pages/ and records hashes of every
|
|
214
|
-
generated file. Do not edit any file in pages/; verify-managed and
|
|
215
|
-
deploy-pages reject changes, missing files, and extra files.
|
|
216
|
-
The compiler also snapshots site/, app/, configuration, and current keys
|
|
217
|
-
under ignored .amw/release-snapshots/. BACKUP-RECEIPT.json stays beside
|
|
218
|
-
pages/; deploy-pages verifies the matching local backup before publishing.
|
|
219
|
-
The snapshot contains bearer keys: never publish or commit it. Keep a
|
|
220
|
-
second encrypted offline copy. Set AMW_RELEASE_BACKUP_DIR to another
|
|
221
|
-
protected local folder if this project directory is not a safe location.
|
|
222
|
-
|
|
223
|
-
site/ is the normal website. Its favicon.ico carries the index, and its
|
|
224
|
-
media/scene.png carries the example app. Replace site/ with an existing
|
|
225
|
-
static website build if you like, while retaining a valid favicon.ico.
|
|
226
|
-
|
|
227
|
-
app/ contains the Amoosed mode source. app/index.html and app/main.js are
|
|
228
|
-
public; app/members/index.html is encrypted because bundle.json lists
|
|
229
|
-
"protected": ["members/"]. Add HTML, CSS, JavaScript, images, fonts,
|
|
230
|
-
WASM, and downloadable files here. List existing binary carrier paths in
|
|
231
|
-
bundle.json. document.json controls the small bootstrap introduction.
|
|
232
|
-
|
|
233
|
-
On the FIRST successful build, the compiler generates a random 256-bit
|
|
234
|
-
content key using the operating system's cryptographic random source.
|
|
235
|
-
It saves 64 hexadecimal characters to .amw/keys/hello-members.hex,
|
|
236
|
-
outside public/. Keep this file private and back it up. Do not commit or
|
|
237
|
-
publish it. Later builds reuse the same key, so members retain access.
|
|
238
|
-
The build prints the key file path, never the key itself. The owner can
|
|
239
|
-
share the 64-character key privately with members. They can enter it in
|
|
240
|
-
the Amoosed extension's Advanced panel or a private boot URL fragment.
|
|
241
|
-
The build also writes .amw/keys/hello-members.amwmember. Share this
|
|
242
|
-
small file instead when you want the recipient to select a local file
|
|
243
|
-
on the member unlock page. It contains the same bearer key and edition
|
|
244
|
-
ID; keep it out of public/ and source control.
|
|
245
|
-
|
|
246
|
-
To make a private member QR or link, run:
|
|
247
|
-
amw member-link .amw/keys/hello-members.amwmember https://your-site.example /amoosed.com/app/members/index.html member.svg
|
|
248
|
-
The QR opens the protected page through the site boot route. It carries
|
|
249
|
-
the member key and can be copied by anyone who sees it. You can also
|
|
250
|
-
generate the file from an existing hex key with:
|
|
251
|
-
amw member-file hello-members path/to/key.hex member.amwmember
|
|
252
|
-
|
|
253
|
-
To rotate just the member key, run:
|
|
254
|
-
amw rotate-project . members
|
|
255
|
-
amw build-project . public-next
|
|
256
|
-
This generates a new key ID, hex key, and .amwmember file while keeping
|
|
257
|
-
the old files privately for recovery. Share only the new member file.
|
|
258
|
-
To rotate the site-wide key instead, choose "site"; choose "both" to
|
|
259
|
-
rotate both. For a hosted index, the site-wide key is PUBLIC encoding,
|
|
260
|
-
so rotating it does not revoke access. For an external index, "site"
|
|
261
|
-
rotates its private index key and backs up the previous one under
|
|
262
|
-
.amw/rotations/. Build to a fresh folder, verify it, then replace the
|
|
263
|
-
published carrier release together and remove old published snapshots.
|
|
264
|
-
An external index build gets a new locator and key file even when only
|
|
265
|
-
members were rotated; distribute that updated index credential too.
|
|
266
|
-
Old downloaded plaintext or complete old releases cannot be revoked.
|
|
267
|
-
For automated builds, set the
|
|
268
|
-
AMW_CONTENT_KEY_HEX environment variable to a 64-character hex value;
|
|
269
|
-
it is used without saving it in the project. Never put keys in bundle.json.
|
|
270
|
-
|
|
271
|
-
To keep the app index off the ordinary website, set
|
|
272
|
-
"indexDelivery": "external" in bundle.json and build to a NEW public/
|
|
273
|
-
folder. The ordinary favicon remains unchanged. The encrypted index goes
|
|
274
|
-
inside media/scene.png, while the compiler prints a separate
|
|
275
|
-
.amw/indexes/favicon-<digest>.ico key file. Share that ICO privately; a
|
|
276
|
-
recipient chooses it on the site's Amoosed boot page. The compiler also
|
|
277
|
-
prints .amw/indexes/key-<digest>.amwkey, a compact text key file that
|
|
278
|
-
unlocks the same edition without the ICO. The first build
|
|
279
|
-
also saves a random index key in .amw/keys/index.hex for repeatable
|
|
280
|
-
builds. Keep both files out of public/ and back up the saved key.
|
|
281
|
-
An automated build may supply AMW_INDEX_KEY_HEX instead. The index key
|
|
282
|
-
opens the whole Amoosed app; the members key remains separate. You can
|
|
283
|
-
email the intact ICO with a design brief or question, including after a
|
|
284
|
-
manual purchase. Anyone the recipient forwards it to gets the same
|
|
285
|
-
access. For a second paid tier, share the members key separately; neither
|
|
286
|
-
key provides individual subscriptions or revocation.
|
|
287
|
-
|
|
288
|
-
For a short QR unlock link, run:
|
|
289
|
-
amw key-link .amw/indexes/key-<digest>.amwkey https://your-site.example event.svg
|
|
290
|
-
The QR opens the site's /amoosed.com/boot.html with a compact key in its
|
|
291
|
-
URL fragment. The boot page checks the carrier and saves the key for this
|
|
292
|
-
site in browser storage before opening the app. Put the QR on an event
|
|
293
|
-
poster or business card only if everyone who sees it may get access.
|
|
294
|
-
The URL and QR image carry the key: do not put them in a public build
|
|
295
|
-
for a paid or private edition.
|
|
296
|
-
|
|
297
|
-
The public/ output contains the ordinary site and compiled app bytes in
|
|
298
|
-
its carriers. It does not contain loose app/ source or the key. Upload
|
|
299
|
-
the contents of public/ to a compatible static HTTPS host. See the
|
|
300
|
-
AmoosedWeb SITE-INTEGRATION.md guide for existing sites and WordPress.
|
|
301
|
-
`};async function lo(t){let e=(0,x.resolve)(t);if(await q(e))throw new Error("Project directory already exists");await(0,b.mkdir)((0,x.join)(e,"site/media"),{recursive:!0}),await(0,b.mkdir)((0,x.join)(e,"app"),{recursive:!0}),await(0,b.mkdir)((0,x.join)(e,"app/members"),{recursive:!0});for(let[n,o]of Object.entries(Ja))await(0,b.writeFile)((0,x.join)(e,n),o,{flag:"wx",mode:n.endsWith(".sh")?493:420});await(0,b.writeFile)((0,x.join)(e,"site/favicon.ico"),Va(),{flag:"wx"}),await(0,b.writeFile)((0,x.join)(e,"site/media/scene.png"),so(),{flag:"wx"}),await jf(e);let r=(0,$t.spawnSync)("git",["init","-b","main",e],{encoding:"utf8"});if(r.error||r.status!==0)throw new Error(`Project created but Git initialization failed: ${r.error?.message||r.stderr?.trim()}`);return e}var za=t=>t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");async function Xa(t,e){if(!Array.isArray(e)||!e.length||e.length>4092)throw new Error("Choose between 1 and 4092 files to share");let r=[],n=0;for(let f of e){let u=(0,x.resolve)(f),h=await(0,b.lstat)(u),p=(0,x.basename)(u);if(!h.isFile()||h.isSymbolicLink()||!h.size||h.size>1024*1024*1024)throw new Error(`Share inputs must be nonempty regular files of at most 1 GiB: ${f}`);if(/[\x00-\x1f\x7f]/.test(p))throw new Error(`File name contains control characters: ${f}`);if(n+=h.size,n>4*1024*1024*1024)throw new Error("Share inputs exceed the 4 GiB starter limit");r.push({source:u,name:p,size:h.size})}let o=await lo(t),i=(0,x.join)(o,"app/files");await(0,b.mkdir)(i);let a=[],s=[];for(let[f,u]of r.entries()){let h=`files/file-${String(f+1).padStart(4,"0")}.bin`;await(0,b.copyFile)(u.source,(0,x.join)(o,"app",h)),a.push(h),s.push(`<li><span><strong>${za(u.name)}</strong><small>${u.size.toLocaleString("en-US")} bytes</small></span><a href="${h}" download="${za(u.name)}">Download</a></li>`)}let l=Math.ceil(n/(16*1024*1024)),c=["media/scene.png"];for(let f=2;f<=l;f++){let u=`media/share-${String(f).padStart(3,"0")}.png`;await(0,b.writeFile)((0,x.join)(o,"site",u),so()),c.push(u)}return await(0,b.writeFile)((0,x.join)(o,"bundle.json"),JSON.stringify({document:"document.json",carriers:c,chunkSize:65536,indexDelivery:"external",downloads:a},null,2)+`
|
|
302
|
-
`),await(0,b.writeFile)((0,x.join)(o,"document.json"),JSON.stringify({title:"Shared files",bootstrap:{title:"Opening shared files",blocks:[{type:"heading",text:"Opening shared files"},{type:"paragraph",text:"Loading and checking the carrier files."}]},blocks:[{type:"heading",text:"Shared files"}]},null,2)+`
|
|
303
|
-
`),await(0,b.writeFile)((0,x.join)(o,"site/index.html"),`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Shared files</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#0b0908;color:#f5eee5;font:18px/1.6 system-ui}main{max-width:640px;padding:32px}h1{font:600 52px Georgia,serif;color:#ff9a3d}</style><main><h1>Shared files</h1><p>This site also has an Amoosed mode. Open the private key you received from its owner to view the file list.</p></main></html>
|
|
304
|
-
`),await(0,b.writeFile)((0,x.join)(o,"app/index.html"),'<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Shared files</title><link rel="stylesheet" href="style.css"><main><p class="eyebrow">AMOOSED MODE</p><h1>Shared files</h1><p>Choose a file to download. Original sizes are shown below.</p><ul>'+s.join("")+`</ul><p id="status" role="status"></p></main><script type="module" src="main.js"></script></html>
|
|
305
|
-
`),await(0,b.writeFile)((0,x.join)(o,"app/style.css"),`:root{color-scheme:dark}body{margin:0;background:#090807;color:#f5eee5;font:17px/1.6 system-ui}main{max-width:900px;margin:auto;padding:72px 28px}.eyebrow{color:#ff9a3d;font-size:12px;font-weight:800;letter-spacing:.2em}h1{font:600 clamp(48px,7vw,80px) Georgia,serif}ul{list-style:none;margin:38px 0;padding:0}li{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:20px 0;border-top:1px solid #4b3222}small{display:block;color:#b6a89c}a{padding:10px 18px;border-radius:5px;background:#ff9a3d;color:#18100b;font-weight:700;text-decoration:none}a:focus-visible{outline:3px solid white}#status{color:#ffba7a}@media(max-width:500px){li{align-items:flex-start;flex-direction:column}}
|
|
306
|
-
`),await(0,b.writeFile)((0,x.join)(o,"app/main.js"),`document.querySelectorAll("a[download]").forEach(link=>link.addEventListener("amw:download-error",event=>{document.querySelector("#status").textContent="Download failed: "+event.detail;}));
|
|
307
|
-
`),await(0,b.rm)((0,x.join)(o,"app/members/index.html")),await(0,b.rmdir)((0,x.join)(o,"app/members")),await(0,b.writeFile)((0,x.join)(o,"README.txt"),`AMOOSEDWEB FILE SHARE
|
|
308
|
-
|
|
309
|
-
This is an independent Git project. It contains ${r.length} original file(s),
|
|
310
|
-
totaling ${n.toLocaleString("en-US")} bytes. The normal site has a generic landing
|
|
311
|
-
page. The private Amoosed app lists each original filename and exact byte
|
|
312
|
-
size, with a Download button. The copied files are app/files/file-*.bin;
|
|
313
|
-
these are source inputs, not loose website files. bundle.json marks them
|
|
314
|
-
as downloads, so the site worker serves attachments after verifying chunks.
|
|
315
|
-
|
|
316
|
-
EDITING
|
|
317
|
-
Replace or add files under app/files/, then update app/index.html and the
|
|
318
|
-
downloads array in bundle.json. Keep the display names and sizes accurate.
|
|
319
|
-
site/media/ contains unlinked image carriers. The normal HTML does not fetch
|
|
320
|
-
them; Amoosed fetches chunks only after a recipient supplies the key.
|
|
321
|
-
Carrier URLs are still public to anyone who knows or guesses them; the
|
|
322
|
-
private index key controls decoding, not HTTP access to carrier bytes.
|
|
323
|
-
Do not edit carrier bytes inside builds/ or distribution/. document.json controls the loading intro.
|
|
324
|
-
Keep .amw-template.json in Git; it records starter versions for upgrades.
|
|
325
|
-
Before amw update-project ., commit or stash your changes. The updater
|
|
326
|
-
preserves edited starter files and refuses tracked private .amw/ files.
|
|
327
|
-
|
|
328
|
-
BUILD AND PUBLISH (Node.js 22 or newer)
|
|
329
|
-
Windows: build.cmd
|
|
330
|
-
macOS/Linux: sh build.sh
|
|
331
|
-
Each build creates and verifies a new builds/local-NNNN/ folder. Preview it
|
|
332
|
-
with amw serve builds/local-0001 (use the path printed by the script).
|
|
333
|
-
To package without uploading: release.cmd PAGES_PROJECT or
|
|
334
|
-
sh release.sh PAGES_PROJECT. To package and publish with guided Wrangler
|
|
335
|
-
login and project creation: publish.cmd PAGES_PROJECT [production-branch]
|
|
336
|
-
or sh publish.sh PAGES_PROJECT [production-branch]. The default branch is
|
|
337
|
-
the current Git branch. The scripts look for amw.cjs in this folder or its
|
|
338
|
-
parent, then for an installed amw. Set AMW_CLI if the compiler is elsewhere.
|
|
339
|
-
Each release uses a new distribution/release-NNNN/ folder. Only its pages/
|
|
340
|
-
folder is uploaded. Set your custom domain in Cloudflare Pages.
|
|
341
|
-
|
|
342
|
-
PRIVATE ACCESS
|
|
343
|
-
The index is external. The first build creates a random index key under
|
|
344
|
-
.amw/keys/ and a shareable .amwkey and ICO under .amw/indexes/. The compiler
|
|
345
|
-
prints their paths. Give a friend ONE of the shareable files, not the saved
|
|
346
|
-
key or source snapshot. The recipient imports it on the site's Amoosed boot
|
|
347
|
-
page. To make a QR after the site URL is known, run:
|
|
348
|
-
amw key-link .amw/indexes/key-<digest>.amwkey https://your-site.example/ invitation.svg
|
|
349
|
-
The QR, URL, .amwkey, and ICO are transferable bearer keys. Anyone who copies
|
|
350
|
-
one can open this release. Never upload them with the website. The compiler
|
|
351
|
-
saves a private source-and-key snapshot under .amw/release-snapshots/ and
|
|
352
|
-
verifies it before deployment; keep an encrypted offline copy too.
|
|
353
|
-
|
|
354
|
-
LIMITS
|
|
355
|
-
Cloudflare Pages allows 25 MiB per uploaded file. This starter spreads
|
|
356
|
-
chunks over roughly 16 MiB image carriers. The current format limits each
|
|
357
|
-
resource to 1 GiB; this starter accepts at most 4 GiB in total. A browser
|
|
358
|
-
assembles each download in memory before saving it, so test large files on
|
|
359
|
-
your target devices. Use a regular download host for larger games until
|
|
360
|
-
streaming downloads are implemented.
|
|
361
|
-
`),{root:o,files:r.length,total:n,carrierCount:c.length}}var Jr=1,Qa=".amw-template.json",Za=()=>({...Ja,"site/favicon.ico":Va(),"site/media/scene.png":so()}),io=t=>Y(t).toString("hex");async function jf(t){let e={};for(let[r,n]of Object.entries(Za()))e[r]=io(n);await(0,b.writeFile)((0,x.join)(t,Qa),JSON.stringify({schema:1,templateVersion:Jr,files:e,notice:"Compiler-owned upgrade record. Do not edit; update with amw update-project."},null,2)+`
|
|
362
|
-
`)}async function es(t){let e=(0,x.resolve)(t);if(!await q((0,x.join)(e,"bundle.json"))||!await q((0,x.join)(e,"site"))||!await q((0,x.join)(e,"app")))throw new Error("Not an AmoosedWeb project (expected bundle.json, site/, and app/)");let r=(0,$t.spawnSync)("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8"});if(r.error||r.status!==0||(0,x.resolve)(r.stdout.trim()).toLowerCase()!==e.toLowerCase())throw new Error("Update requires the project to be the root of its own Git repository");if((0,$t.spawnSync)("git",["check-ignore","--quiet","--no-index",".amw/keys/secret.hex"],{cwd:e}).status!==0)throw new Error("Private .amw/keys/ files must be covered by the project .gitignore");let o=(0,$t.spawnSync)("git",["ls-files","--cached","--",".amw"],{cwd:e,encoding:"utf8"});if(o.error||o.status!==0)throw new Error("Could not inspect tracked private key files");if(o.stdout.trim())throw new Error("Private .amw/ files are tracked by Git; remove them from the index before updating");let i=(0,$t.spawnSync)("git",["status","--porcelain","--untracked-files=all"],{cwd:e,encoding:"utf8"});if(i.error||i.status!==0)throw new Error("Could not inspect project Git status");if(i.stdout.trim())throw new Error("Commit or stash uncommitted and untracked project files before update-project");let a=(0,x.join)(e,Qa),s=await q(a)?JSON.parse(await(0,b.readFile)(a,"utf8")):null;if(s&&(s.schema!==1||!s.files||typeof s.files!="object"||!Number.isSafeInteger(s.templateVersion)||s.templateVersion>Jr))throw new Error("Unsupported project template version");let l={schema:1,templateVersion:Jr,files:{},notice:"Compiler-owned upgrade record. Do not edit; update with amw update-project."},c=[],f=[],u=[];for(let[p,d]of Object.entries(Za())){let g=(0,x.join)(e,p),m=io(d);if(!await q(g)){f.push(p);continue}let E=io(await(0,b.readFile)(g)),_=s?.files?.[p];_&&E===_&&E!==m?(await(0,b.writeFile)(g,d),c.push(p),l.files[p]=m):E===m?(l.files[p]=m,_||u.push(p)):(f.push(p),_&&(l.files[p]=_))}let h=JSON.stringify(l,null,2)+`
|
|
363
|
-
`;return(!await q(a)||await(0,b.readFile)(a,"utf8")!==h)&&await(0,b.writeFile)(a,h),{root:e,updated:c,preserved:f,adopted:u,templateVersion:Jr}}async function ao(t,e){for(let r of await(0,b.readdir)(t,{withFileTypes:!0})){let n=(0,x.join)(t,r.name),o=(0,x.join)(e,r.name);if(r.isSymbolicLink()||!r.isFile()&&!r.isDirectory())throw new Error("Project contains unsupported file type or symlink");r.isDirectory()?(await(0,b.mkdir)(o,{recursive:!0}),await ao(n,o)):await(0,b.copyFile)(n,o)}}async function Df(){let t=[typeof __dirname=="string"?(0,x.join)(__dirname,"runtime/amoosed.com"):null,(0,x.join)((0,x.dirname)(process.execPath),"runtime/amoosed.com"),(0,x.resolve)("release/pages/amoosed.com")];for(let e of t)if(e&&await q((0,x.join)(e,"boot.html")))return e;throw new Error("Runtime package not found beside the compiler; from source, run npm run build:release first")}async function Ya(t,e){let r=await q(t)?await(0,b.readFile)(t,"utf8"):"";await(0,b.writeFile)(t,r+(r&&!r.endsWith(`
|
|
364
|
-
`)?`
|
|
365
|
-
`:"")+e)}async function Xr(t,e,{runtimeDir:r}={}){let n=(0,x.resolve)(t),o=(0,x.resolve)(e),i=(0,x.join)(n,"site"),a=(0,x.join)(n,"app");if(!await q(i)||!await q(a))throw new Error("Project needs site/ and app/ folders");if(Ga(i,o)||Ga(a,o)||await q(o))throw new Error("Output must be new and separate from site/ and app/");let s=JSON.parse(await(0,b.readFile)((0,x.join)(n,"bundle.json"),"utf8"));if("encryptionKey"in s||"key"in s)throw new Error("Do not put content keys in bundle config");if(s.indexDelivery!==void 0&&!["hosted","external"].includes(s.indexDelivery))throw new Error("Invalid index delivery");if(s.keyId&&!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(s.keyId))throw new Error("Invalid content key ID");if(typeof s.document!="string"||s.document.includes("..")||s.document.startsWith("/")||s.document.includes("\\"))throw new Error("Invalid document path");let l=JSON.parse(await(0,b.readFile)((0,x.join)(n,s.document),"utf8")),c=s.keyId?(0,x.join)(n,".amw","keys",`${s.keyId}.hex`):null,f=s.keyId?(0,x.join)(n,".amw","keys",`${s.keyId}.amwmember`):null,u=process.env.AMW_CONTENT_KEY_HEX;if(u!==void 0&&!/^[0-9a-fA-F]{64}$/.test(u))throw new Error("AMW_CONTENT_KEY_HEX must contain 64 hex characters");let h=c&&await q(c)?(await(0,b.readFile)(c,"utf8")).trim():null;if(h!==null&&!/^[0-9a-fA-F]{64}$/.test(h))throw new Error("Saved content key is invalid");if(h&&u&&h.toLowerCase()!==u.toLowerCase())throw new Error("Supplied content key differs from the saved key; rotate deliberately");let p=!!(c&&!h&&!u),d=c?Buffer.from(u||h||(0,mt.randomBytes)(32).toString("hex"),"hex"):void 0,g=s.indexDelivery==="external"?(0,x.join)(n,".amw","keys","index.hex"):null,m=process.env.AMW_INDEX_KEY_HEX;if(m!==void 0&&!/^[0-9a-fA-F]{64}$/.test(m))throw new Error("AMW_INDEX_KEY_HEX must contain 64 hex characters");let E=g&&await q(g)?(await(0,b.readFile)(g,"utf8")).trim():null;if(E!==null&&!/^[0-9a-fA-F]{64}$/.test(E))throw new Error("Saved index key is invalid");if(E&&m&&E.toLowerCase()!==m.toLowerCase())throw new Error("Supplied index key differs from the saved key; rotate deliberately");let _=!!(g&&!E&&!m),P=g?Buffer.from(m||E||(0,mt.randomBytes)(32).toString("hex"),"hex"):void 0,S=r?(0,x.resolve)(r):await Df();await(0,b.mkdir)((0,x.dirname)(o),{recursive:!0});let v=await(0,b.mkdtemp)((0,x.join)((0,x.dirname)(o),".amw-project-"));try{let R=(0,x.join)(v,"site"),$=(0,x.join)(v,"overlay");if(await(0,b.mkdir)(R),await ao(i,R),await q((0,x.join)(R,"amoosed.com")))throw new Error("Site already has an amoosed.com runtime route");let j=await Yr({...s,document:l,encryptionKey:d,indexKey:P,siteDir:i,appDir:a,outDir:$});await ao($,R),await(0,b.mkdir)((0,x.join)(R,"amoosed.com"));for(let G of Uf)await(0,b.copyFile)((0,x.join)(S,G),(0,x.join)(R,"amoosed.com",G));await Ya((0,x.join)(R,"_redirects"),`/amoosed.com/app /amoosed.com/boot.html 200
|
|
366
|
-
/amoosed.com/app/ /amoosed.com/boot.html 200
|
|
367
|
-
/amoosed.com/app/* /amoosed.com/boot.html 200
|
|
368
|
-
`);let ne=s.carriers.map(G=>typeof G=="string"?G:G.path);if(await Ya((0,x.join)(R,"_headers"),`/*.ico
|
|
369
|
-
Cache-Control: no-store
|
|
370
|
-
/amoosed.com/*
|
|
371
|
-
Cache-Control: no-store
|
|
372
|
-
`+ne.map(G=>`/${G}
|
|
373
|
-
Cache-Control: no-store
|
|
374
|
-
`).join("")),await Vr(R,void 0,s.indexDelivery==="external"?{indexBytes:j.indexBytes}:{}),await q(o))throw new Error("Output directory already exists");if(p&&(await(0,b.mkdir)((0,x.dirname)(c),{recursive:!0}),await(0,b.writeFile)(c,d.toString("hex")+`
|
|
375
|
-
`,{flag:"wx",mode:384})),f){let G=pr(hr(s.keyId,d));if(await(0,b.mkdir)((0,x.dirname)(f),{recursive:!0}),!await q(f))await(0,b.writeFile)(f,G,{flag:"wx",mode:384});else if(await(0,b.readFile)(f,"utf8")!==G)throw new Error("Saved member key file conflicts with this build")}_&&(await(0,b.mkdir)((0,x.dirname)(g),{recursive:!0}),await(0,b.writeFile)(g,P.toString("hex")+`
|
|
376
|
-
`,{flag:"wx",mode:384}));let W,le;if(s.indexDelivery==="external"){let G=Y(j.indexBytes).toString("hex").slice(0,16);if(W=(0,x.join)(n,".amw","indexes",`favicon-${G}.ico`),le=(0,x.join)(n,".amw","indexes",`key-${G}.amwkey`),await(0,b.mkdir)((0,x.dirname)(W),{recursive:!0}),!await q(W))await(0,b.writeFile)(W,j.indexBytes,{flag:"wx",mode:384});else if(!(await(0,b.readFile)(W)).equals(j.indexBytes))throw new Error("External index file conflicts with this build");let Q=me(ge(j.indexBytes).payload).document.privateIndex,z=Nr(vt(Q));if(!await q(le))await(0,b.writeFile)(le,z,{flag:"wx",mode:384});else if(await(0,b.readFile)(le,"utf8")!==z)throw new Error("External key file conflicts with this build")}return await(0,b.rename)(R,o),{output:o,keyPath:c,memberKeyPath:f,keyCreated:p,keySource:u?"environment":c?"saved-file":null,indexKeyPath:g,indexKeyCreated:_,externalIndexPath:W,externalKeyPath:le}}finally{await q(v)&&await(0,b.rm)(v,{recursive:!0,force:!0})}}async function ts(t,e){if(!["members","site","both"].includes(e))throw new Error("Choose members, site, or both");let r=(0,x.resolve)(t),n=(0,x.join)(r,"bundle.json"),o=await(0,b.readFile)(n,"utf8"),i=JSON.parse(o),a=e!=="site",s=e!=="members";if(a&&(!i.keyId||!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(i.keyId)))throw new Error("This project has no valid member key ID");if(a&&process.env.AMW_CONTENT_KEY_HEX!==void 0)throw new Error("Remove AMW_CONTENT_KEY_HEX before rotating the project member key");if(s&&i.indexDelivery==="external"&&process.env.AMW_INDEX_KEY_HEX!==void 0)throw new Error("Remove AMW_INDEX_KEY_HEX before rotating the project index key");let l=(0,x.join)(r,".amw","keys"),c=a?(0,x.join)(l,`${i.keyId}.hex`):null,f=s&&i.indexDelivery==="external"?(0,x.join)(l,"index.hex"):null;if(a&&!await q(c))throw new Error("Build this project before rotating its member key");if(f&&!await q(f))throw new Error("Build this project before rotating its external index key");if(a&&!/^[0-9a-fA-F]{64}\s*$/.test(await(0,b.readFile)(c,"utf8")))throw new Error("Saved member key is invalid");if(f&&!/^[0-9a-fA-F]{64}\s*$/.test(await(0,b.readFile)(f,"utf8")))throw new Error("Saved index key is invalid");if(s&&i.indexDelivery!=="external"&&i.encodingSalt!==void 0&&!/^[0-9a-f]{64}$/.test(i.encodingSalt))throw new Error("Saved encoding salt is invalid");let u=(0,mt.randomBytes)(8).toString("hex"),h=a?`${i.keyId.slice(0,46)}-r${u}`:null,p=a?(0,x.join)(l,`${h}.hex`):null,d=a?(0,x.join)(l,`${h}.amwmember`):null,g=f?(0,x.join)(r,".amw","rotations",`index-${Date.now()}-${u}.hex`):null,m=(0,x.join)(r,`bundle.json.amw-${u}.tmp`),E=f?(0,x.join)(l,`index.hex.amw-${u}.tmp`):null,_=f?await(0,b.readFile)(f):null,P=a?(0,mt.randomBytes)(32):null;a&&(i.keyId=h),s&&!f&&(i.encodingSalt=(0,mt.randomBytes)(32).toString("hex"));let S=!1,v=!1,R=!1,$=!1;try{a&&(await(0,b.writeFile)(p,P.toString("hex")+`
|
|
377
|
-
`,{flag:"wx",mode:384}),R=!0,await(0,b.writeFile)(d,pr(hr(h,P)),{flag:"wx",mode:384}),$=!0),f&&(await(0,b.mkdir)((0,x.dirname)(g),{recursive:!0}),await(0,b.writeFile)(g,_,{flag:"wx",mode:384}),await(0,b.writeFile)(E,(0,mt.randomBytes)(32).toString("hex")+`
|
|
378
|
-
`,{flag:"wx",mode:384})),await(0,b.writeFile)(m,JSON.stringify(i,null,2)+`
|
|
379
|
-
`,{flag:"wx"}),f&&(await(0,b.rename)(E,f),S=!0),await(0,b.rename)(m,n),v=!0}catch(j){throw S&&await(0,b.writeFile)(f,_),v&&await(0,b.writeFile)(n,o),$&&await(0,b.rm)(d),R&&await(0,b.rm)(p),j}finally{for(let j of[m,E])j&&await q(j)&&await(0,b.rm)(j)}return{scope:e,keyId:h,memberPath:p,memberFilePath:d,archivePath:g,siteKeyKind:s?f?"private index":"public encoding":null}}var re=require("node:fs/promises"),X=require("node:path");var rs=require("node:crypto"),ns=require("node:fs"),Ze=require("node:fs/promises"),Ce=require("node:path"),os="MANAGED-FILES.json";async function is(t){let e={};async function r(n){for(let o of(await(0,Ze.readdir)(n,{withFileTypes:!0})).sort((i,a)=>i.name.localeCompare(a.name))){let i=(0,Ce.join)(n,o.name),a=await(0,Ze.lstat)(i);if(a.isSymbolicLink())throw new Error(`Managed release contains a symlink: ${i}`);if(a.isDirectory())await r(i);else if(a.isFile()){let s=(0,rs.createHash)("sha256");for await(let l of(0,ns.createReadStream)(i))s.update(l);e[(0,Ce.relative)(t,i).replaceAll("\\","/")]=s.digest("hex")}else throw new Error(`Managed release contains unsupported file: ${i}`)}}return await r(t),e}async function as(t,e){let r=(0,Ce.resolve)(t),n=(0,Ce.join)(r,"pages"),o={schema:1,managedDirectory:"pages",description:e,notice:"GENERATED. Do not edit, delete, rename, optimize, or append to these files. Edit the project source and build a new distribution.",files:await is(n)},i=(0,Ce.join)(r,os);return await(0,Ze.writeFile)(i,JSON.stringify(o,null,2)+`
|
|
380
|
-
`),i}async function jt(t){let e=(0,Ce.resolve)(t),r=JSON.parse(await(0,Ze.readFile)((0,Ce.join)(e,os),"utf8"));if(r.schema!==1||r.managedDirectory!=="pages"||!r.files||typeof r.files!="object"||Array.isArray(r.files))throw new Error("Invalid managed release manifest");let n=r.files;if(Object.keys(n).some(a=>a.startsWith("/")||a.includes("\\")||a.split("/").some(s=>!s||s==="."||s==="..")||!/^[0-9a-f]{64}$/.test(n[a])))throw new Error("Invalid managed release file entry");let o=await is((0,Ce.join)(e,"pages")),i=new Set([...Object.keys(n),...Object.keys(o)]);for(let a of[...i].sort()){if(!n[a])throw new Error(`Unlisted managed file: ${a}`);if(!o[a])throw new Error(`Missing managed file: ${a}`);if(n[a]!==o[a])throw new Error(`Modified managed file: ${a}`)}return{files:i.size,root:e}}var gr=require("node:crypto"),cs=require("node:fs"),O=require("node:fs/promises"),L=require("node:path"),co=require("node:child_process");var gt="0.21.0";var fs="BACKUP-RECEIPT.json",ss={project:["site","app","document.json","bundle.json","README.txt",".gitignore",".amw-template.json"],repository:["src","tools","web","webapp","extension","demo","test","package.json","package-lock.json","AGENTS.md","README.md","FORMAT.md","WEBAPP.md","SITE-INTEGRATION.md","PORTFOLIO-RELEASE.md","COPYRIGHT.txt"]},Dt=(t,e)=>{let r=(0,L.relative)(t,e);return!r||!r.startsWith("..")&&!r.includes(":")};async function Qr(t){try{return await(0,O.lstat)(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function wt(t){let e=(0,gr.createHash)("sha256");for await(let r of(0,cs.createReadStream)(t))e.update(r);return e.digest("hex")}async function ls(t){if(process.platform!=="win32"){await(0,O.chmod)(t,448);return}let e=(0,co.spawnSync)("whoami.exe",["/user","/fo","csv","/nh"],{encoding:"utf8"}),r=e.stdout?.match(/,"(S-1(?:-\d+)+)"\s*$/)?.[1];if(e.error||e.status!==0||!r)throw new Error("Cannot identify the local user for release backup ACL");let n=(0,co.spawnSync)("icacls.exe",[t,"/grant:r",`*${r}:(OI)(CI)F`,"/inheritance:r"],{encoding:"utf8"});if(n.error||n.status!==0)throw new Error(`Cannot secure local release backup ACL: ${n.error?.message||n.stderr?.trim()}`)}async function fo(t,e,r,n=""){let o=await(0,O.lstat)(t);if(o.isSymbolicLink())throw new Error(`Release snapshot refuses a symlink: ${t}`);if(o.isDirectory()){await(0,O.mkdir)(e,{recursive:!0,mode:448});for(let i of(await(0,O.readdir)(t,{withFileTypes:!0})).sort((a,s)=>a.name.localeCompare(s.name)))i.name===".git"||i.name===".amw"||await fo((0,L.join)(t,i.name),(0,L.join)(e,i.name),r,n?`${n}/${i.name}`:i.name)}else if(o.isFile())await(0,O.copyFile)(t,e),r[n]=await wt(e);else throw new Error(`Release snapshot refuses an unsupported file: ${t}`)}async function us(t,e,r="project"){if(!ss[r])throw new Error("Invalid release snapshot kind");let n=(0,L.resolve)(t),o=(0,L.resolve)(e);if(process.env.AMW_RELEASE_BACKUP_DIR&&!(0,L.isAbsolute)(process.env.AMW_RELEASE_BACKUP_DIR))throw new Error("AMW_RELEASE_BACKUP_DIR must be an absolute local path");let i=(0,L.resolve)(process.env.AMW_RELEASE_BACKUP_DIR||(0,L.join)(n,".amw","release-snapshots"));if(Dt(o,i)||Dt(i,o)||Dt((0,L.join)(n,"site"),i)||Dt((0,L.join)(n,"app"),i))throw new Error("Release backup must be outside the distribution and source input directories");await jt(o);let a=await wt((0,L.join)(o,"MANAGED-FILES.json"));if(await(0,O.mkdir)(i,{recursive:!0,mode:448}),(await(0,O.lstat)(i)).isSymbolicLink())throw new Error("Release backup directory must not be a symlink");await ls(i);let s=await(0,O.mkdtemp)((0,L.join)(i,".snapshot-")),l=`${new Date().toISOString().replace(/[-:.TZ]/g,"")}-${a.slice(0,12)}-${(0,gr.randomBytes)(4).toString("hex")}`,c=(0,L.join)(i,l);try{await ls(s);let f={},u={};for(let _ of ss[r]){let P=(0,L.join)(n,_);if(await Qr(P))await fo(P,(0,L.join)(s,"source",_),f,_);else if(["site","app","document.json","bundle.json","package.json"].includes(_))throw new Error(`Release snapshot is missing required source: ${_}`)}let h=(0,L.join)(n,".amw");for(let _ of["keys","indexes","rotations"]){let P=(0,L.join)(h,_);await Qr(P)&&await fo(P,(0,L.join)(s,"private",_),u,_)}for(let[_,P]of[["AMW_CONTENT_KEY_HEX","environment-content.hex"],["AMW_INDEX_KEY_HEX","environment-index.hex"]]){let S=process.env[_];if(S===void 0)continue;if(!/^[0-9a-fA-F]{64}$/.test(S))throw new Error(`Invalid ${_} for release backup`);let v=(0,L.join)(s,"private",P);await(0,O.mkdir)((0,L.dirname)(v),{recursive:!0,mode:448}),await(0,O.writeFile)(v,S.toLowerCase()+`
|
|
381
|
-
`,{flag:"wx",mode:384}),u[P]=await wt(v)}let p={schema:1,id:l,kind:r,compilerVersion:gt,createdAt:new Date().toISOString(),releaseManifestSha256:a,sourceFiles:f,privateFiles:u,notice:"PRIVATE LOCAL BACKUP. Contains source and may contain bearer keys. Never publish or commit."},d=(0,L.join)(s,"SNAPSHOT.json");await(0,O.writeFile)(d,JSON.stringify(p,null,2)+`
|
|
382
|
-
`,{flag:"wx",mode:384});let g=await wt(d);await(0,O.rename)(s,c);let m={schema:1,backup:c,releaseManifestSha256:a,snapshotSha256:g},E=(0,L.join)(o,`.backup-receipt-${(0,gr.randomBytes)(8).toString("hex")}.tmp`);try{await(0,O.writeFile)(E,JSON.stringify(m,null,2)+`
|
|
383
|
-
`,{flag:"wx",mode:384}),await(0,O.rename)(E,(0,L.join)(o,fs))}finally{await Qr(E)&&await(0,O.rm)(E)}return{backup:c,sourceCount:Object.keys(f).length,privateCount:Object.keys(u).length}}finally{Dt(i,s)&&s!==i&&await Qr(s)&&await(0,O.rm)(s,{recursive:!0,force:!0})}}async function Zr(t){let e=(0,L.resolve)(t),r=JSON.parse(await(0,O.readFile)((0,L.join)(e,fs),"utf8"));if(r.schema!==1||!(0,L.isAbsolute)(r.backup)||!/^[0-9a-f]{64}$/.test(r.releaseManifestSha256)||!/^[0-9a-f]{64}$/.test(r.snapshotSha256)||Dt(e,r.backup))throw new Error("Invalid release backup receipt");let n=await wt((0,L.join)(e,"MANAGED-FILES.json"));if(n!==r.releaseManifestSha256)throw new Error("Release backup does not match this distribution");let o=(0,L.join)(r.backup,"SNAPSHOT.json");if(await wt(o)!==r.snapshotSha256)throw new Error("Release backup record was modified");let i=JSON.parse(await(0,O.readFile)(o,"utf8"));if(i.schema!==1||i.releaseManifestSha256!==n||!i.sourceFiles||!i.privateFiles)throw new Error("Invalid release backup record");for(let[a,s]of[["source",i.sourceFiles],["private",i.privateFiles]])for(let[l,c]of Object.entries(s)){if(l.startsWith("/")||l.includes("\\")||l.split("/").some(u=>!u||u==="."||u==="..")||!/^[0-9a-f]{64}$/.test(c))throw new Error("Invalid release backup file record");let f=(0,L.join)(r.backup,a,l);if((await(0,O.lstat)(f)).isSymbolicLink()||await wt(f)!==c)throw new Error(`Release backup file was modified: ${a}/${l}`)}return{backup:r.backup,sourceCount:Object.keys(i.sourceFiles).length,privateCount:Object.keys(i.privateFiles).length}}var Ff=2e4,Hf=25*1024*1024;async function en(t){try{return await(0,re.stat)(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function uo(t){let e=0;async function r(n){for(let o of await(0,re.readdir)(n,{withFileTypes:!0})){let i=(0,X.join)(n,o.name),a=await(0,re.lstat)(i);if(a.isSymbolicLink())throw new Error(`Pages distribution contains a symlink: ${i}`);if(a.isDirectory())await r(i);else if(a.isFile()){if(e++,e>Ff)throw new Error("Pages distribution exceeds 20,000 files");if(a.size>Hf)throw new Error(`Pages asset exceeds 25 MiB: ${(0,X.relative)(t,i)}`);if(o.name.toLowerCase().endsWith(".map"))throw new Error(`Pages distribution contains a source map: ${i}`)}else throw new Error(`Pages distribution contains an unsupported file: ${i}`)}}if(await r(t),!await en((0,X.join)(t,"index.html"))||!(await(0,re.stat)((0,X.join)(t,"index.html"))).isFile())throw new Error("Pages distribution needs an index.html file");return e}function Wf(t,e,r){let n=t??"YOUR_PAGES_PROJECT";return`AMOOSEDWEB CLOUDFLARE PAGES DISTRIBUTION
|
|
384
|
-
|
|
385
|
-
Upload ONLY the pages/ folder. DEPLOY.txt is for the site owner and is not published.
|
|
386
|
-
Verified assets: ${e}. The build checked the carrier index and resource hashes,
|
|
387
|
-
rejected source maps, and checked Cloudflare Pages' 25 MiB per-file and 20,000-file limits.
|
|
388
|
-
The build also saved a PRIVATE source and key snapshot under .amw/release-snapshots/
|
|
389
|
-
or AMW_RELEASE_BACKUP_DIR. Keep it off the website, out of Git, and on a protected local disk.
|
|
390
|
-
BACKUP-RECEIPT.json stays beside pages/; amw deploy-pages verifies that snapshot.
|
|
391
|
-
|
|
392
|
-
1. Install Node.js and authenticate with Cloudflare through Wrangler:
|
|
393
|
-
npx wrangler login
|
|
394
|
-
|
|
395
|
-
2. Create a Direct Upload Pages project once, if it does not exist:
|
|
396
|
-
npx wrangler pages project create ${n}
|
|
397
|
-
|
|
398
|
-
3. From this distribution folder, deploy the exact pages/ directory:
|
|
399
|
-
npx wrangler pages deploy ./pages --project-name ${n}
|
|
400
|
-
If Wrangler detects a different Git branch, add --branch YOUR_PRODUCTION_BRANCH
|
|
401
|
-
to target the production branch selected when the Pages project was created.
|
|
402
|
-
Or from the project root run: amw deploy-pages distribution ${n}
|
|
403
|
-
This checks MANAGED-FILES.json before calling Wrangler.
|
|
404
|
-
|
|
405
|
-
4. For later releases, build a fresh distribution folder and repeat step 3.
|
|
406
|
-
Configure the custom domain in Cloudflare Pages if desired. Test the deployed
|
|
407
|
-
favicon and carrier byte ranges; disable transformations that change media bytes.
|
|
408
|
-
After key rotation, publish all changed carriers and index as one release and
|
|
409
|
-
clear stale CDN copies before distributing new credentials.
|
|
410
|
-
|
|
411
|
-
${r?`This build has an EXTERNAL index. Its .amwkey/ICO and member credentials remain under the project .amw/ folder; share them privately, never upload them with pages/.
|
|
412
|
-
|
|
413
|
-
`:`Member credentials remain under the project .amw/ folder; never upload them with pages/.
|
|
414
|
-
|
|
415
|
-
`}Cloudflare guide: https://developers.cloudflare.com/pages/get-started/direct-upload/
|
|
416
|
-
Wrangler command reference: https://developers.cloudflare.com/workers/wrangler/commands/pages/
|
|
417
|
-
`}async function hs(t,e,r,n={}){if(r!==void 0&&!/^[a-z0-9][a-z0-9-]*$/.test(r))throw new Error("Pages project name must use lowercase letters, numbers, and hyphens");let o=(0,X.resolve)(t),i=(0,X.resolve)(e);if(await en(i))throw new Error("Distribution folder already exists; use a new path");await(0,re.mkdir)((0,X.dirname)(i),{recursive:!0});let a=await(0,re.mkdtemp)((0,X.join)((0,X.dirname)(i),".amw-pages-"));try{let s=(0,X.join)(a,"pages"),l=await Xr(o,s,n),c=await uo(s);await(0,re.writeFile)((0,X.join)(a,"DEPLOY.txt"),Wf(r,c,!!l.externalKeyPath),{mode:384}),await as(a,"AmoosedWeb Pages project distribution");let f=await us(o,a);if(await en(i))throw new Error("Distribution folder was created during build");return await(0,re.rename)(a,i),{distribution:i,pages:(0,X.join)(i,"pages"),guide:(0,X.join)(i,"DEPLOY.txt"),files:c,keyPath:l.keyPath,memberKeyPath:l.memberKeyPath,externalKeyPath:l.externalKeyPath,externalIndexPath:l.externalIndexPath,backup:f.backup}}finally{let s=(0,X.dirname)(i),l=(0,X.relative)(s,a);if(!l||l.startsWith("..")||l.includes(":"))throw new Error("Unsafe Pages staging path");await en(a)&&await(0,re.rm)(a,{recursive:!0,force:!0})}}var tn=require("node:path"),ds=require("node:child_process");var qf=t=>typeof t=="string"&&/^[a-z0-9][a-z0-9-]*$/.test(t),Gf=t=>typeof t=="string"&&/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(t)&&!t.split("/").some(e=>e==="."||e==="..");async function ps(t,e,r,n=ds.spawnSync){if(!qf(e))throw new Error("Pages project name must use lowercase letters, numbers, and hyphens");if(r!==void 0&&!Gf(r))throw new Error("Invalid Pages branch name");let o=(0,tn.resolve)(t);await jt(o),await Zr(o),await uo((0,tn.join)(o,"pages"));let i=["wrangler","pages","deploy","./pages","--project-name",e,...r?["--branch",r]:[]],a=process.platform==="win32"?"npx.cmd":"npx",s=n(a,i,{cwd:o,stdio:"inherit",shell:process.platform==="win32"});if(s.error||s.status!==0)throw new Error(`Wrangler deploy failed: ${s.error?.message||`exit ${s.status}`}`);return{root:o,projectName:e,branch:r}}var gs=[["Start a project",[["init","<project-dir>","Create an AmoosedWeb starter site."],["init-share","<project-dir> <file> [file...]","Create a private file-sharing site."],["update-project","<project-dir>","Update unchanged starter files."],["build-project","<project-dir> <output-dir>","Compile the ordinary and Amoosed sites."],["serve","<site-dir> [port]","Preview a static site locally."]]],["Release to Cloudflare Pages",[["package-pages","<project-dir> <distribution-dir> [pages-project-name]","Build and verify a Pages distribution."],["verify-managed","<distribution-dir>","Check the managed release file hashes."],["verify-backup","<distribution-dir>","Check the private source-and-key snapshot."],["deploy-pages","<distribution-dir> <pages-project-name> [branch]","Deploy a verified release with Wrangler."],["rotate-project","<project-dir> <members|site|both>","Rotate member or site keys."]]],["Read a published site",[["remote-list","<site-url> [key.amwkey|index.ico]","List verified app files and metadata."],["remote-get","<site-url> <resource-path> <output> [key.amwkey|index.ico]","Download one verified app file."],["remote-pull","<site-url> <output-dir> [key.amwkey|index.ico]","Download all accessible app files."]]],["Exchange files through media",[["media-key","<private-out.hex>","Generate a private media key."],["audio-encode","<file-or-folder> <output-dir> [--dry-run]","Encode files into numbered WAV tracks."],["audio-decode","<parts-dir> <output-dir>","Restore files from WAV tracks."],["video-encode","<file-or-folder> <cover.mp4> <output-dir> [--dry-run]","Encode files into playable MP4 copies."],["video-decode","<parts-dir> <output-dir>","Restore files from MP4 copies."]]],["Keys and invitations",[["key-link","<index.ico|key.amwkey> <site-url> [qr-out.svg]","Make an index unlock URL or QR code."],["member-file","<key-id> <key.hex> <out.amwmember>","Create a portable member key file."],["member-link","<key.amwmember> <site-url> <protected-app-path> [qr-out.svg]","Make a member unlock URL or QR code."]]],["Advanced carrier tools",[["bundle","<config.json> <site-build-dir> <app-build-dir> <overlay-dir> [index-out.ico|key.amwkey]","Compile an app into selected carriers."],["verify-bundle","<overlay-dir> [index.ico|key.amwkey]","Verify a carrier-only overlay."],["verify-site","<site-build-dir> [index.ico|key.amwkey]","Verify a merged static site."],["unpack-bundle","<overlay-dir> <app-out-dir> [index.ico|key.amwkey]","Recover verified app resources."],["compile","<document.json> <output.amw>","Compile a binary bootstrap document."],["pack","<carrier> <payload.amw> <output>","Append a document to an opaque carrier."],["unpack","<packed> <carrier-out> <payload-out>","Separate a universal carrier and document."],["verify","<file>","Verify an AMW document or carrier."]]],["Experimental pixel, audio, and frame tools",[["pixel-capacity","<image.png>","Estimate lossless PNG pixel capacity."],["pixel-encode","<image.png> <payload> <output.png>","Encode encrypted data into PNG pixels."],["pixel-decode","<image.png> <output>","Extract and verify PNG pixel data."],["audio-encode-set","<payload> <output-dir> [clip-count] [cover-wav-dir]","Encode a small indexed WAV packet set."],["audio-decode-set","<index.json> <output>","Recover an indexed WAV packet set."],["frame-encode-set","<payload> <cover.png> <output-dir> [fps] [clip-count] [pixel|luma]","Write numbered replacement PNG frames."],["frame-decode-set","<index.json> <output>","Recover an indexed frame packet set."]]]],ms={init:"Next: edit the site/ and app/ folders, then run amw build-project.","init-share":"The starter includes a private index key; keep it out of the published site.","package-pages":"This creates local files and a private backup. It does not deploy.","deploy-pages":"Requires a verified distribution and Wrangler access to the project.","audio-encode":"Set AMW_MEDIA_KEY_HEX first. --dry-run estimates part count and output size without writing.","audio-decode":"Set the same AMW_MEDIA_KEY_HEX and supply every numbered WAV part.","video-encode":"Set AMW_MEDIA_KEY_HEX first. The MP4 data requires byte-preserving transfer; transcoding may remove it.","video-decode":"Set the same AMW_MEDIA_KEY_HEX and supply every numbered MP4 part.","remote-get":"For member content, set AMW_MEMBER_KEY_FILE or AMW_CONTENT_KEY_HEX.","remote-pull":"For member content, set AMW_MEMBER_KEY_FILE or AMW_CONTENT_KEY_HEX."},zf=gs.flatMap(([,t])=>t);function ws(){let t=[`AmoosedWeb CLI v${gt}`,"Build a second, carrier-backed experience for a website.","","Quick start"," amw init my-site"," amw build-project my-site my-site/public"," amw serve my-site/public",""];for(let[e,r]of gs){t.push(e);for(let[n,,o]of r)t.push(` ${n.padEnd(22)}${o}`);t.push("")}return t.push('Run "amw help <command>" for arguments and notes.'),t.push('Run "amw --version" to check which compiler you have.'),t.push("Guide: https://amoosed.com/compiler.html"),t.join(`
|
|
418
|
-
`)}function rn(t){let e=zf.find(([i])=>i===t);if(!e)throw new Error(`Unknown command "${t}". Run "amw help" to list commands.`);let[r,n,o]=e;return[`AmoosedWeb CLI v${gt}`,"",`Usage: amw ${r} ${n}`,"",o,...ms[r]?["",ms[r]]:[],"","Guide: https://amoosed.com/compiler.html"].join(`
|
|
419
|
-
`)}var ys=require("node:http"),wr=require("node:fs/promises"),et=require("node:path"),Yf={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".txt":"text/plain; charset=utf-8",".json":"application/json",".ico":"image/x-icon",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".svg":"image/svg+xml",".wasm":"application/wasm",".zip":"application/zip",".amw":"application/octet-stream"};function bs(t,e=4173){let r=(0,et.resolve)(t);if(!Number.isInteger(e)||e<1||e>65535)throw new Error("Invalid port");let n=(0,ys.createServer)(async(o,i)=>{try{if(o.method!=="GET"&&o.method!=="HEAD"){i.writeHead(405),i.end();return}let a=decodeURIComponent(new URL(o.url,"http://localhost").pathname),s=(0,et.resolve)(r,`.${a==="/"?"/index.html":a}`);if(!s.startsWith(r+et.sep))throw new Error("Outside root");let l;try{l=await(0,wr.stat)(s)}catch(u){if(u.code!=="ENOENT"||a!=="/amoosed.com/app"&&!a.startsWith("/amoosed.com/app/")&&a!=="/amoosed.com/boot")throw u;s=(0,et.resolve)(r,"amoosed.com/boot.html"),l=await(0,wr.stat)(s)}if(!l.isFile())throw new Error("Not a file");let c=await(0,wr.readFile)(s);i.setHeader("Content-Type",Yf[(0,et.extname)(s)]||"application/octet-stream"),i.setHeader("Accept-Ranges","bytes"),i.setHeader("Cache-Control","no-store"),i.setHeader("X-Content-Type-Options","nosniff");let f=/^bytes=(\d*)-(\d*)$/.exec(o.headers.range||"");if(o.headers.range&&!f){i.writeHead(416),i.end();return}if(f){let u=f[1]?Number(f[1]):Math.max(0,c.length-Number(f[2])),h=f[1]&&f[2]?Number(f[2]):c.length-1;if(!Number.isSafeInteger(u)||!Number.isSafeInteger(h)||u>h||h>=c.length){i.writeHead(416,{"Content-Range":`bytes */${c.length}`}),i.end();return}i.writeHead(206,{"Content-Range":`bytes ${u}-${h}/${c.length}`,"Content-Length":h-u+1}),o.method==="HEAD"?i.end():i.end(c.subarray(u,h+1))}else i.writeHead(200,{"Content-Length":c.length}),o.method==="HEAD"?i.end():i.end(c)}catch{i.writeHead(404),i.end("Not found")}});return n.listen(e,"127.0.0.1",()=>console.log(`Demo: http://127.0.0.1:${e}/ (serving ${r})`)),n}var Fe=require("node:crypto"),Se=require("node:fs/promises"),xs=require("node:fs"),Pe=require("node:path");var Kf=16*1024*1024,Vf=t=>(0,Fe.createHash)("sha256").update(t).digest("hex"),Es=t=>Buffer.from(t,"hex");function Jf(t){let e=new URL(t);if(e.username||e.password||!(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1"].includes(e.hostname)))throw new Error("Remote site requires HTTPS or local HTTP");return e.origin}async function Xf(t,e,r){let n=new URL(e.url,t.origin);if(n.origin!==t.origin)throw new Error("Carrier changed origin");let o=e.codec==="png-lsb1"?["pixel",64*1024*1024]:e.codec==="wav-4fsk1"?["audio",128*1024*1024]:["frame-luma1","frame-luma2"].includes(e.codec)?["frame",64*1024*1024]:null;if(o){if(!r.has(e.url)){let l=await t.fetcher(n,{cache:"no-store",credentials:"omit",redirect:"error"});if(l.status!==200||new URL(l.url,t.origin).origin!==t.origin)throw new Error(`${e.url}: media carrier unavailable`);let c=Buffer.from(await Be(l,o[1])),f=o[0]==="pixel"?Ne(c):o[0]==="audio"?Gr(c,t.app.audioCarriers?.[e.url]):lr(c);r.set(e.url,f)}return r.get(e.url).subarray(e.offset,e.offset+e.length)}let i=e.offset+e.length-1,a=await t.fetcher(n,{headers:{Range:`bytes=${e.offset}-${i}`},cache:"no-store",credentials:"omit",redirect:"error"});if(![200,206].includes(a.status)||new URL(a.url,t.origin).origin!==t.origin)throw new Error(`${e.url}: carrier unavailable`);if(a.status===206){let l=/^bytes (\d+)-(\d+)\/(\d+)$/.exec(a.headers.get("Content-Range")||"");if(!l||Number(l[1])!==e.offset||Number(l[2])!==i||!Number.isSafeInteger(Number(l[3])))throw new Error(`${e.url}: invalid range`);return Buffer.from(await Be(a,e.length))}return Buffer.from(await Be(a,Kf)).subarray(e.offset,i+1)}function Qf(t,e,r,n,o){if(o.length!==n.length||Vf(o)!==n.sha256)throw new Error(`${n.url}: chunk integrity failure`);let i=o;if(t.app.encoding){let a=(0,Fe.createHash)("sha256").update(`AMW1-SITE-CTR\0${e.path}\0${r}`).digest().subarray(0,16),s=(0,Fe.createDecipheriv)("aes-256-ctr",Es(t.app.encoding.key),a);i=Buffer.concat([s.update(i),s.final()])}if(st(t.app,e)){if(!t.contentKey)throw new Error("Member content key required");try{let a=(0,Fe.createDecipheriv)("aes-256-gcm",t.contentKey,Es(n.nonce));if(a.setAAD(Vt(e,r,n.plainLength)),a.setAuthTag(i.subarray(-16)),i=Buffer.concat([a.update(i.subarray(0,-16)),a.final()]),i.length!==n.plainLength)throw new Error("Plaintext length mismatch")}catch{throw new Error("Member key or chunk authentication failed")}}return i}async function As(t,{credential:e,indexKeyFile:r,contentKey:n,memberKeyFile:o,fetcher:i=fetch}={}){let a=Jf(t);if(e&&r||n&&o)throw new Error("Supply one source for each key");if(r){let f=await(0,Se.readFile)(r);e=f.subarray(0,8).toString("ascii")==="AMWKEY1:"?{indexToken:Ur(f)}:{indexBytes:f}}let s;if(o){let f=await(0,Se.readFile)(o),u=f.toString("utf8").trim();if(/^[0-9a-fA-F]{64}$/.test(u))n=Buffer.from(u,"hex");else{let h=dr(mr(f));s=h.keyId,n=Buffer.from(h.key)}}if(n&&(!(n instanceof Uint8Array)||n.length!==32))throw new Error("Invalid member content key");let l;e?.indexToken?l={privateIndex:ut(e.indexToken)}:e?.indexBytes?l=await si(e.indexBytes):l=await ai(`${a}/favicon.ico`,{fetcher:i}),l=await fi(l,i,a);let c=lt(l.webApp);if(s&&c.encryption?.keyId!==s)throw new Error("Member key belongs to another edition");return{origin:a,app:c,contentKey:n&&Buffer.from(n),fetcher:i}}function ks(t){return t.app.resources.map(e=>({path:e.path,bytes:e.length,sha256:e.sha256,mime:e.mime,access:st(t.app,e)?"members":"public",delivery:e.delivery||"app"}))}async function ho(t,e,r){let n=t.app.resources.find(f=>f.path===e);if(!n)throw new Error("Resource is absent from the verified index");let o=(0,Pe.resolve)(r);await(0,Se.mkdir)((0,Pe.dirname)(o),{recursive:!0});let i=(0,Pe.resolve)((0,Pe.dirname)(o),`.amw-download-${(0,Fe.randomBytes)(12).toString("hex")}`),a=await(0,Se.open)(i,"wx",384),s=(0,Fe.createHash)("sha256"),l=new Map,c=0;try{try{for(let[f,u]of n.parts.entries()){let h=Qf(t,n,f,u,await Xf(t,u,l));s.update(h),c+=h.length;let p=0;for(;p<h.length;){let{bytesWritten:d}=await a.write(h,p,h.length-p,null);if(!d)throw new Error("Incomplete local write");p+=d}}}finally{await a.close()}if(c!==n.length||s.digest("hex")!==n.sha256)throw new Error("Resource integrity failure");return await(0,Se.copyFile)(i,o,xs.constants.COPYFILE_EXCL),{path:o,bytes:c,sha256:n.sha256}}finally{await(0,Se.unlink)(i).catch(f=>{if(f.code!=="ENOENT")throw f})}}async function vs(t,e){let r=(0,Pe.resolve)(e),n=[];for(let o of t.app.resources){let i=o.path.slice(17),a=(0,Pe.resolve)(r,i),s=(0,Pe.relative)(r,a);if(!s||s.startsWith("..")||s.includes(":"))throw new Error("Unsafe resource output path");n.push(await ho(t,o.path,a))}return n}var nn=require("node:crypto"),te=require("node:fs/promises"),we=require("node:path");var Is=Buffer.from("AMXS1"),_s=Buffer.from("AMXA1"),po=Buffer.from("416d6f6f7365645472616e7366657231","hex"),Ft=69,Cs=4068-Ft,Ss=8*1024*1024,on=t=>(0,nn.createHash)("sha256").update(t).digest();async function Bs(t){let e=(0,we.resolve)(t),r=[];async function n(i,a){let s=await(0,te.lstat)(i);if(s.isSymbolicLink())throw new Error("Symbolic links are not supported in exchanges");if(s.isDirectory())for(let l of(await(0,te.readdir)(i)).sort())await n((0,we.join)(i,l),a?`${a}/${l}`:l);else if(s.isFile())r.push({path:i,name:a,bytes:s.size});else throw new Error("Only regular files and directories are supported")}let o=await(0,te.lstat)(e);if(await n(e,o.isDirectory()?"":(0,we.basename)(e)),!r.length)throw new Error("The input contains no files");return r}function Zf(t){let e=t.map(r=>({name:r.name,bytes:r.bytes,sha256:"0".repeat(64)}));return 9+Buffer.byteLength(JSON.stringify(e))+t.reduce((r,n)=>r+n.bytes,0)}async function eu(t){let e=await Promise.all(t.map(async o=>{let i=await(0,te.readFile)(o.path);if(i.length!==o.bytes)throw new Error(`Input changed while encoding: ${o.name}`);return{...o,data:i,sha256:on(i).toString("hex")}})),r=Buffer.from(JSON.stringify(e.map(({name:o,bytes:i,sha256:a})=>({name:o,bytes:i,sha256:a})))),n=Buffer.alloc(9);return _s.copy(n),n.writeUInt32BE(r.length,5),Buffer.concat([n,r,...e.map(o=>o.data)])}function tu(t){return typeof t=="string"&&t.length>0&&!t.includes("\\")&&t.split("/").every(e=>e&&e!=="."&&e!==".."&&!e.includes(":")&&!e.includes("\0"))}function ru(t){if(t.length<9||!t.subarray(0,5).equals(_s))throw new Error("Invalid exchange archive");let e=t.readUInt32BE(5);if(e>t.length-9)throw new Error("Truncated exchange archive");let r=JSON.parse(t.subarray(9,9+e).toString("utf8"));if(!Array.isArray(r)||!r.length)throw new Error("Invalid exchange file list");let n=new Set,o=[],i=9+e;for(let a of r){if(!tu(a.name)||n.has(a.name)||!Number.isSafeInteger(a.bytes)||a.bytes<0||!/^[0-9a-f]{64}$/.test(a.sha256)||a.bytes>t.length-i)throw new Error("Invalid exchange file entry");n.add(a.name);let s=t.subarray(i,i+a.bytes);if(on(s).toString("hex")!==a.sha256)throw new Error(`Exchange file integrity failure: ${a.name}`);o.push({name:a.name,data:s}),i+=a.bytes}for(let a of n)for(let s of n)if(a!==s&&a.startsWith(`${s}/`))throw new Error("Conflicting exchange file paths");if(i!==t.length)throw new Error("Exchange archive has trailing bytes");return o}function nu(t,e,r,n,o){let i=t.subarray(r*o,(r+1)*o),a=Buffer.alloc(Ft);return Is.copy(a),e.copy(a,5),a.writeUInt32BE(r,21),a.writeUInt32BE(n,25),a.writeBigUInt64BE(BigInt(t.length),29),on(t).copy(a,37),Buffer.concat([a,i])}function ou(t){if(!t.length)throw new Error("No exchange files found");let e=new Map,r;for(let i of t){if(i.length<Ft||!i.subarray(0,5).equals(Is))throw new Error("Invalid exchange shard");let a=i.subarray(5,21).toString("hex"),s=i.readUInt32BE(21),l=i.readUInt32BE(25),c=Number(i.readBigUInt64BE(29)),f=i.subarray(37,69).toString("hex");if(!Number.isSafeInteger(c)||c<1||l<1||s>=l)throw new Error("Invalid exchange shard map");let u=`${a}:${l}:${c}:${f}`;if(r&&r!==u||e.has(s))throw new Error("Mixed or duplicate exchange shards");r=u,e.set(s,i.subarray(Ft))}let n=t[0].readUInt32BE(25);if(e.size!==n)throw new Error(`Exchange set incomplete: ${e.size}/${n} files`);let o=Buffer.concat(Array.from({length:n},(i,a)=>e.get(a)));if(o.length!==Number(t[0].readBigUInt64BE(29))||on(o).toString("hex")!==t[0].subarray(37,69).toString("hex"))throw new Error("Exchange set integrity failure");return ru(o)}function iu(t){let e=t+28,r=44;for(let n=0;n<e;n+=128){let o=Math.min(128,e-n);r+=3*(1600+(16+(54+o)*4)*160)}return r}async function mo(t,e,r){let n=await Bs(t),o=Zf(n),i=e==="audio"?Cs:Ss;if(!["audio","video"].includes(e))throw new Error("Unknown exchange medium");let a=Math.ceil(o/i);if(a>4294967295)throw new Error("Too many output files for exchange v1");let s=0;if(e==="audio")for(let l=0;l<a;l++)s+=iu(Ft+Math.min(i,o-l*i));else{let l=(await Qt(r,"mp4-uuid")).size;s=a*(l+24+Ft+28)+o}return{files:n.length,inputBytes:n.reduce((l,c)=>l+c.bytes,0),archiveBytes:o,outputs:a,estimatedOutputBytes:s}}async function go(t,e,r,n,o){let i=await Bs(t),a=await eu(i),s=e==="audio"?Cs:Ss;if(!["audio","video"].includes(e))throw new Error("Unknown exchange medium");let l=Math.ceil(a.length/s);if(l>4294967295)throw new Error("Too many output files for exchange v1");let c=e==="video"?await(0,te.readFile)(o):null;if(c&&await Qt(o,"mp4-uuid"),c?.includes(po))throw new Error("Cover MP4 already contains a standalone exchange box");await(0,te.mkdir)(r);let f=(0,nn.randomBytes)(16),u=[];for(let h=0;h<l;h++){let p=nu(a,f,h,l,s),d;if(e==="audio")d=va(p,n);else{let m=Mt(p,n),E=Buffer.alloc(24);E.writeUInt32BE(24+m.length,0),E.write("uuid",4),po.copy(E,8),d=Buffer.concat([c,E,m])}let g=`part-${String(h+1).padStart(5,"0")}.${e==="audio"?"wav":"mp4"}`;await(0,te.writeFile)((0,we.join)(r,g),d,{flag:"wx"}),u.push(g)}return{outputs:u,sourceFiles:i.length}}function au(t,e){let r=0,n=null;for(;r+8<=t.length;){let o=t.readUInt32BE(r),i=8;if(o===1){if(r+16>t.length)throw new Error("Invalid MP4 exchange carrier");o=Number(t.readBigUInt64BE(r+8)),i=16}if(!Number.isSafeInteger(o)||o<i||r+o>t.length)throw new Error("Invalid MP4 exchange carrier");if(t.toString("ascii",r+4,r+8)==="uuid"&&o>=i+16&&t.subarray(r+i,r+i+16).equals(po)){if(n)throw new Error("Duplicate exchange box");n=t.subarray(r+i+16,r+o)}r+=o}if(r!==t.length||!n)throw new Error("Missing MP4 exchange box");return Lt(n,e)}async function wo(t,e,r,n){let o=e==="audio"?"wav":e==="video"?"mp4":null;if(!o)throw new Error("Unknown exchange medium");let i=(await(0,te.readdir)(t)).filter(l=>/^part-\d{5,}\.(wav|mp4)$/.test(l));if(!i.length||i.some(l=>!l.endsWith(`.${o}`)))throw new Error("No matching exchange parts found");let a=[];for(let l of i.sort()){let c=(0,we.join)(t,l);if(!(await(0,te.lstat)(c)).isFile())throw new Error("Exchange parts must be regular files");let f=await(0,te.readFile)(c);a.push(e==="audio"?Ia(f,n):au(f,n))}let s=ou(a);await(0,te.mkdir)(r);for(let l of s){let c=(0,we.resolve)(r,...l.name.split("/"));if(!c.startsWith((0,we.resolve)(r)+we.sep))throw new Error("Unsafe extraction path");await(0,te.mkdir)((0,we.resolve)(c,".."),{recursive:!0}),await(0,te.writeFile)(c,l.data,{flag:"wx"})}return{files:s.length,parts:i.length}}var ql=require("node:crypto");var Gl=En(Wl(),1),U=require("node:path");async function yh(){let[t,...e]=process.argv.slice(2),r=()=>{let l=process.env.AMW_CONTENT_KEY_HEX;if(l!==void 0){if(!/^[0-9a-fA-F]{64}$/.test(l))throw new Error("AMW_CONTENT_KEY_HEX must contain 64 hex characters");return Buffer.from(l,"hex")}},n=()=>{let l=process.env.AMW_MEDIA_KEY_HEX;if(!l||!/^[0-9a-fA-F]{64}$/.test(l))throw new Error("Set AMW_MEDIA_KEY_HEX to a private 64-character hexadecimal key");return Buffer.from(l,"hex")},o=async l=>{let c=await(0,B.readFile)(l);return c.subarray(0,8).toString("ascii")==="AMWKEY1:"?{indexToken:Ur(c)}:{indexBytes:c}},i=async()=>{if(process.env.AMW_MEMBER_KEY_FILE&&process.env.AMW_CONTENT_KEY_HEX)throw new Error("Supply one member key source");if(process.env.AMW_MEMBER_KEY_FILE){let l=await(0,B.readFile)(process.env.AMW_MEMBER_KEY_FILE),c=l.toString("utf8").trim();if(/^[0-9a-fA-F]{64}$/.test(c))return{key:Buffer.from(c,"hex")};let f=mr(l),u=decodeMemberToken(f);return{key:Buffer.from(u.key),keyId:u.keyId}}return{key:r()}},a=async(l,c)=>{let f=await i(),u=await As(l,{contentKey:f.key,...c?{credential:await o(c)}:{}});if(f.keyId&&u.app.encryption?.keyId!==f.keyId)throw new Error("Member key belongs to another edition");return u},s=async(l,c)=>{if(c){if(!c.toLowerCase().endsWith(".svg"))throw new Error("QR output must be an SVG file");await(0,B.writeFile)(c,await Gl.default.toString(l,{type:"svg",errorCorrectionLevel:"M",margin:4,width:768}),{flag:"wx",mode:384}),console.log(`QR saved: ${(0,U.resolve)(c)}`)}};try{if(!t||(t==="--help"||t==="help")&&e.length===0)console.log(ws());else if((t==="--help"||t==="help")&&e.length===1)console.log(rn(e[0]));else if(e.length===1&&e[0]==="--help")console.log(rn(t));else if(t==="--version"&&e.length===0)console.log(gt);else if(t==="init"&&e.length===1)console.log(`Created ${await lo(e[0])}`);else if(t==="init-share"&&e.length>=2){let l=await Xa(e[0],e.slice(1));console.log(`Created file-share project ${l.root} with ${l.files} files across ${l.carrierCount} carriers`)}else if(t==="update-project"&&e.length===1){let l=await es(e[0]);console.log(`Template v${l.templateVersion}: updated ${l.updated.length}, preserved ${l.preserved.length} edited or missing files.`);for(let c of l.preserved)console.log(`Preserved: ${c}`)}else if(t==="build-project"&&e.length===2){let l=await Xr(e[0],e[1]);console.log(`Built ${l.output}`),l.keyCreated?console.log(`Generated member key: ${l.keyPath} (keep private; 64 hexadecimal characters)`):l.keyPath&&console.log(l.keySource==="environment"?"Member key supplied by AMW_CONTENT_KEY_HEX":`Reused member key: ${l.keyPath}`),l.memberKeyPath&&console.log(`Share this member key file privately: ${l.memberKeyPath}`),l.externalIndexPath&&console.log(`Share this index file outside the website: ${l.externalIndexPath}`),l.externalKeyPath&&console.log(`Or share this compact key file: ${l.externalKeyPath}`),l.indexKeyCreated&&console.log(`Generated private index key: ${l.indexKeyPath} (back up; the shared favicon contains it)`)}else if(t==="package-pages"&&(e.length===2||e.length===3)){let l=await hs(e[0],e[1],e[2]);console.log(`Cloudflare Pages assets (${l.files} files): ${l.pages}`),console.log(`Wrangler release steps: ${l.guide}`),l.memberKeyPath&&console.log(`Keep member credential private: ${l.memberKeyPath}`),l.externalKeyPath&&console.log(`Keep external index credential private: ${l.externalKeyPath}`),console.log(`Private source and key snapshot: ${l.backup}`)}else if(t==="verify-managed"&&e.length===1){let l=await jt(e[0]);console.log(`Verified ${l.files} managed Pages files in ${l.root}`)}else if(t==="verify-backup"&&e.length===1){let l=await Zr(e[0]);console.log(`Verified private release snapshot: ${l.backup} (${l.sourceCount} source files, ${l.privateCount} private files)`)}else if(t==="deploy-pages"&&(e.length===2||e.length===3)){let l=await ps(e[0],e[1],e[2]);console.log(`Deployed verified Pages distribution from ${l.root}`)}else if(t==="rotate-project"&&e.length===2){let l=await ts(e[0],e[1]);console.log(`Rotated ${l.scope}; build a new output folder and replace the published carrier release as one set.`),l.memberPath&&console.log(`New member key ID: ${l.keyId}; share only the new private file: ${l.memberFilePath}`),l.siteKeyKind&&console.log(`Rotated ${l.siteKeyKind} key${l.archivePath?`; previous index key backed up at ${l.archivePath}`:""}.`)}else if(t==="serve"&&(e.length===1||e.length===2))bs(e[0],Number(e[1]||4173));else if(t==="remote-list"&&(e.length===1||e.length===2))console.log(JSON.stringify(ks(await a(e[0],e[1])),null,2));else if(t==="remote-get"&&(e.length===3||e.length===4))console.log(JSON.stringify(await ho(await a(e[0],e[3]),e[1],e[2])));else if(t==="remote-pull"&&(e.length===2||e.length===3))console.log(JSON.stringify(await vs(await a(e[0],e[2]),e[1]),null,2));else if(t==="compile"&&e.length===2){let l=JSON.parse(await(0,B.readFile)(e[0],"utf8"));await(0,B.writeFile)(e[1],Ye(l))}else if(t==="pack"&&e.length===3)await(0,B.writeFile)(e[2],ct(await(0,B.readFile)(e[0]),await(0,B.readFile)(e[1])));else if(t==="unpack"&&e.length===3){let{carrier:l,payload:c}=ge(await(0,B.readFile)(e[0]));await(0,B.writeFile)(e[1],l),await(0,B.writeFile)(e[2],c)}else if(t==="verify"&&e.length===1){let l=await(0,B.readFile)(e[0]),c;try{c=me(l)}catch{c=me(ge(l).payload)}console.log(`OK: ${c.document.title} (${c.manifest.sections.length} sections)`)}else if(t==="pixel-capacity"&&e.length===1)console.log(`${Hr(await(0,B.readFile)(e[0]))} bytes`);else if(t==="pixel-encode"&&e.length===3)await(0,B.writeFile)(e[2],Bt(await(0,B.readFile)(e[0]),Mt(await(0,B.readFile)(e[1]),n())),{flag:"wx"}),console.log(`Wrote pixel carrier: ${(0,U.resolve)(e[2])}`);else if(t==="pixel-decode"&&e.length===2)await(0,B.writeFile)(e[1],Lt(Ne(await(0,B.readFile)(e[0])),n()),{flag:"wx"}),console.log(`Verified pixel payload: ${(0,U.resolve)(e[1])}`);else if(t==="media-key"&&e.length===1)await(0,B.writeFile)(e[0],`${(0,ql.randomBytes)(32).toString("hex")}
|
|
420
|
-
`,{flag:"wx",mode:384}),console.log(`Private media key saved: ${(0,U.resolve)(e[0])}`);else if(t==="audio-encode"&&(e.length===2||e.length===3&&e[2]==="--dry-run"))e[2]==="--dry-run"?console.log(JSON.stringify(await mo(e[0],"audio"),null,2)):console.log(JSON.stringify(await go(e[0],"audio",e[1],n()),null,2));else if(t==="audio-decode"&&e.length===2)console.log(JSON.stringify(await wo(e[0],"audio",e[1],n()),null,2));else if(t==="video-encode"&&(e.length===3||e.length===4&&e[3]==="--dry-run"))e[3]==="--dry-run"?console.log(JSON.stringify(await mo(e[0],"video",e[1]),null,2)):console.log(JSON.stringify(await go(e[0],"video",e[2],n(),e[1]),null,2));else if(t==="video-decode"&&e.length===2)console.log(JSON.stringify(await wo(e[0],"video",e[1],n()),null,2));else if(t==="audio-encode-set"&&e.length>=2&&e.length<=4){let l=e[2]===void 0?1:Number(e[2]);if(!Number.isInteger(l)||l<1||l>32)throw new Error("Invalid audio clip count");let c=e[3]?await Promise.all(Array.from({length:l},(u,h)=>(0,B.readFile)((0,U.resolve)(e[3],`clip-${String(h+1).padStart(3,"0")}.wav`)))):[],f=Ea(await(0,B.readFile)(e[0]),l,n(),c);await(0,B.mkdir)(e[1]);for(let u of f.clips)await(0,B.writeFile)((0,U.resolve)(e[1],u.file),u.wav,{flag:"wx"});await(0,B.writeFile)((0,U.resolve)(e[1],"index.json"),`${JSON.stringify(f.manifest,null,2)}
|
|
421
|
-
`,{flag:"wx"}),console.log(`Wrote ${f.clips.length} audio clips and transport index: ${(0,U.resolve)(e[1])}`)}else if(t==="audio-decode-set"&&e.length===2){let l=JSON.parse(await(0,B.readFile)(e[0],"utf8"));if(!Array.isArray(l.clips)||l.clips.some(f=>!/^clip-\d{3}\.wav$/.test(f.file)))throw new Error("Unsafe audio clip filename");let c=await Promise.all(l.clips.map(f=>(0,B.readFile)((0,U.resolve)((0,U.dirname)((0,U.resolve)(e[0])),f.file))));await(0,B.writeFile)(e[1],ka(c,l,n()),{flag:"wx"}),console.log(`Verified audio payload: ${(0,U.resolve)(e[1])}`)}else if(t==="frame-encode-set"&&e.length>=3&&e.length<=6){let l=Ra(await(0,B.readFile)(e[0]),await(0,B.readFile)(e[1]),e[3]===void 0?30:Number(e[3]),e[4]===void 0?1:Number(e[4]),n(),e[5]??"pixel");await(0,B.mkdir)(e[2]);for(let c of l.frames)await(0,B.writeFile)((0,U.resolve)(e[2],c.file),c.bytes,{flag:"wx"});await(0,B.writeFile)((0,U.resolve)(e[2],"index.json"),`${JSON.stringify(l.manifest,null,2)}
|
|
422
|
-
`,{flag:"wx"}),console.log(`Wrote ${l.frames.length} replacement frames and transport index: ${(0,U.resolve)(e[2])}`)}else if(t==="frame-decode-set"&&e.length===2){let l=JSON.parse(await(0,B.readFile)(e[0],"utf8"));if(!Array.isArray(l.clips)||l.clips.some(u=>!Array.isArray(u.frames)||u.frames.some(h=>!/^clip-\d{3}-frame-\d{6}\.png$/.test(h.file))))throw new Error("Unsafe frame filename");let c=l.clips.flatMap(u=>u.frames.map(h=>h.file)),f=await Promise.all(c.map(u=>(0,B.readFile)((0,U.resolve)((0,U.dirname)((0,U.resolve)(e[0])),u))));await(0,B.writeFile)(e[1],Oa(f,l,n()),{flag:"wx"}),console.log(`Verified frame payload: ${(0,U.resolve)(e[1])}`)}else if(t==="key-link"&&(e.length===2||e.length===3)){let l=await o(e[0]),c=l.indexToken??vt(me(ge(l.indexBytes).payload).document.privateIndex),f=pi(e[1],c);await s(f,e[2]),console.log(`Unlock URL (bearer key; share privately unless intended for everyone): ${f}`)}else if(t==="member-file"&&e.length===3){if(!e[2].toLowerCase().endsWith(".amwmember"))throw new Error("Member output must be an .amwmember file");let l=(await(0,B.readFile)(e[1],"utf8")).trim();if(!/^[0-9a-fA-F]{64}$/.test(l))throw new Error("Member key file must contain 64 hex characters");let c=hr(e[0],Buffer.from(l,"hex"));await(0,B.writeFile)(e[2],pr(c),{flag:"wx",mode:384}),console.log(`Member key file saved: ${(0,U.resolve)(e[2])}`)}else if(t==="member-link"&&(e.length===3||e.length===4)){let l=mr(await(0,B.readFile)(e[0])),c=Wa(e[1],l,e[2]);await s(c,e[3]),console.log(`Member unlock URL (bearer key; share privately): ${c}`)}else if(t==="bundle"&&(e.length===4||e.length===5)){let l=JSON.parse(await(0,B.readFile)(e[0],"utf8"));if("encryptionKey"in l||"key"in l)throw new Error("Do not put content keys in bundle config");typeof l.document=="string"&&(l.document=JSON.parse(await(0,B.readFile)((0,U.resolve)((0,U.dirname)((0,U.resolve)(e[0])),l.document),"utf8")));let c=l.keyId?r():void 0;if(l.keyId&&!c)throw new Error("Encrypted bundle requires AMW_CONTENT_KEY_HEX");if(l.indexDelivery==="external"!=(e.length===5))throw new Error("External index delivery requires a separate index-out.ico path");if(e[4]){let h=(0,U.resolve)(e[4]),p=d=>{let g=(0,U.relative)((0,U.resolve)(d),h);return!g||!g.startsWith("..")&&!g.includes(":")};if([e[1],e[2],e[3]].some(p))throw new Error("External index output must stay outside site, app, and carrier overlay")}let f=process.env.AMW_INDEX_KEY_HEX;if(f!==void 0&&!/^[0-9a-fA-F]{64}$/.test(f))throw new Error("AMW_INDEX_KEY_HEX must contain 64 hex characters");if(l.indexDelivery==="external"&&!f)throw new Error("External bundle requires AMW_INDEX_KEY_HEX");let u=await Yr({...l,encryptionKey:c,indexKey:f?Buffer.from(f,"hex"):void 0,siteDir:e[1],appDir:e[2],outDir:e[3]});if(e[4]){let p=e[4].toLowerCase().endsWith(".amwkey")?Nr(vt(me(ge(u.indexBytes).payload).document.privateIndex)):u.indexBytes;await(0,B.writeFile)(e[4],p,{flag:"wx",mode:384})}console.log(`OK: ${u.webApp.resources.length} app resources across ${u.carrierCount} existing carriers`)}else if(t==="verify-bundle"&&(e.length===1||e.length===2)){let l=await fr(e[0],{key:r(),collectResources:!1,carrierOnly:!0,...e[1]?await o(e[1]):{}});console.log(`OK: ${l.resourceCount} integrity-checked app resources; ${l.verifiedCount} plaintext resources verified${l.protectedCount&&!r()?"; member ciphertext checked without a content key":""}`)}else if(t==="verify-site"&&(e.length===1||e.length===2))console.log(`OK: ${await Vr(e[0],void 0,e[1]?await o(e[1]):{})} carrier-backed app resources in site build`);else if(t==="unpack-bundle"&&(e.length===2||e.length===3))console.log(`OK: ${await ja(e[0],e[1],{key:r(),...e[2]?await o(e[2]):{}})} unpacked app resources`);else throw new Error(`Invalid arguments.
|
|
423
|
-
|
|
424
|
-
${rn(t)}`)}catch(l){console.error(l.message),process.exitCode=1}}yh();
|